mardi 4 août 2015

Parse SQL INSERT-statement with RegEx

I need to parse SQL to get all:

  • Table names after INSERT clause,
  • Tables after FROM, JOINs (including CROSS JOIN as comma ',' operator) clauses,
  • The same with OPENQUERY or any other subqueries.

Each statement is one-liner SQL, without any extra spaces, comments, or new lines. Each query is INSERT-statement.

I have almost working regex: http://ift.tt/1HoUetJ.

But it has a problem: regex cathes only first FROM/JOIN statement. Or only last if I apply greedy quantificators.

Ideal result is syntax tree. But simple list of named group will be sufficient.



via Chebli Mohamed

DocumentDb write within a transactionscope

I am trying to use a DocumentDb write as a part of a transaction like below -

using (var scope = new TransactionScope)
{
//first transaction

//write to document db

//third transaction
}

I observed that if the third transaction fails, documentDb write is not rolled back and I still see the document in the collection. The first transaction (NEventStore in this case) rolls back perfectly. Does anyone know if DocumentDb supports TrnasactionScope. What if I have a nested transaction?

Thanks!



via Chebli Mohamed

Determine if anonymous type's property is a generic collection

I need a method to cycle through each object's properties and log the property name and value. On occasion, however, I hit a property that is a list object and the whole thing crashes. I've gather the condition below from various SO posts but it returns false every time. Wondering how to test if your method property is a generic collection type?

Class Definition

public class DtccProducer
{
    public string ProducerDateOfBirth { get; set; }
    public string ProducerGender { get; set; }
    public string TransactionType { get; set; }
    public List<BigAddress> Addresses { get; set; }
    public List<BigCommunicationItem> Communications { get; set; }
}

Method

    private static void ParseProducer(object obj)
    {
        StringBuilder s = new StringBuilder();
        Type objType = obj.GetType();

        foreach (PropertyInfo info in objType.GetProperties())
        {
            string key = info.Name;

            Type propType = info.PropertyType;

            if (propType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(propType.GetGenericTypeDefinition()))
            {
                // This condition never passes - always evaluates to false
            }
            else
            {
                string value = (string) info.GetValue(obj, null);
                _sb.AppendLine(key + ": " + value);                    
            }
        }
    }



via Chebli Mohamed

AutoMapper: Map null source object to decimal

I need to map an object of type PriceValue to a decimal value and I have the following mapping configured:

public class PriceValue
{
    public decimal Value { get; set; }
    ...
}

...

Mapper.CreateMap<PriceValue, decimal>()
    .ConvertUsing(src => src.Value);

The problem is when src is null an exception is thrown.

What's the best way to configure the mapping so a default(decimal) is returned instead?



via Chebli Mohamed

C# reflection and Func

I have 3 classes, each have same function names:

class A {Func<sampleobject,bool> alpha = c=>c.some1 == something;Func<object,bool> beta= c=>c.some1 == something;}
class B {Func<sampleobject,bool> alpha = c=>c.some1 == something;Func<sampleobject,bool> beta= c=>c.some1 == something;}
class C{Func<sampleobject,bool> alpha = c=>c.some1 == something;Func<sampleobject,bool> beta= c=>c.some1 == something;}

I have a factory that will get me the proper class. there's also another property that will determine which function of the class gets called.

dbcontext.sampleobjects.where(Factory(class).ReflectionFunction(memberName));

I was able to use reflection to get the member name via:

var prop = this.GetType().GetMember("alpha");

I just don't know how to use this or what to call to be able to be used in the "WHERE" statement like if I would call it directly.

dbcontext.sampleobjects.where(instanceofA.alpha);



via Chebli Mohamed

Convert a literal improperly encoded string (e.g., "ñ") to ISO-8859-1 (Latin1) H

Without going into too much detail, I have a C# WCF application that is a wrapper for an XML based API I am calling. That API returns a string, which is really just an XML document. I then parse that XML, and return it. That returned information is displayed in the browser as JSON.

A bit confusing, but here is some sampled code:

[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Json, UriTemplate = "/TestGetUser")]
TestGetUserResponse TestGetUser();

/* ... */

[DataContract(Namespace = "http://ift.tt/1P4PaB1", Name = "TestGetUser")]
public class TestGetUserResponse
{
    [DataMember]
    public User User { get; set; }
    [DataMember]
    public Error Error { get; set; }
}

And TestGetUser being:

public TestGetUserResponse TestGetUser() {
    WebClient client = getCredentials(domain); //Defined elsewhere

    string apiUrl = "http://ift.tt/1IWjVJs";
    string apiRequest = "<?xml version='1.0' encoding='utf-8' ?><test>My XML Request Lives Here</test>";

    string result = client.UploadString(apiUrl, apiRequest);

    XmlDocument user = new XmlDocument();
    user.LoadXml(result);

    userNode = user.SelectSingleNode("/my[1]/xpath[1]/user[1]");

    return new TestGetUserResponse {
        Error = new Error(),
        User = new User {
            Name = userNode.SelectSingleNode("name[1]").InnerText,
            Email = userNode.SelectSingleNode("email[1]").InnerText,
            ID = System.Convert.ToInt32(userNode.SelectSingleNode("id[1]").InnerText)
        }
    };
}

So, when I hit my URL from a browser, it returns a JSON string, like below:

{
    "Error": {
        "ErrorCode": 0,
        "ErrorDetail": null,
        "ErrorMessage":"Success"
    },
    "User": {
        "Name": "John Smith",
        "Email": "john.smith@example.com",
        "ID": 12345
    }
}

Now, my problem is, sometimes the string that is returned (directly from the API) is a badly encoded UTF-8 string (I think? I could be getting this a bit wrong). For example, I may get back:

{
    "Error": {
        "ErrorCode": 0,
        "ErrorDetail": null,
        "ErrorMessage":"Success"
    },
    "User": {
        "Name": "Jose Nuñez",
        "Email": "jose.nunez@example.com",
        "ID": 54321
    }
}

Notice the ñ in the Name property under the User object.

My question is, how can I convert this improperly encoded string to a ñ, which is what it should be?

I've found a bunch of posts

But none seem to be exactly what I need, or trying to borrow from those posts have failed.

So, to make my question as possible,

If I have a variable in a C# (.NET 3.5) application that when I write it out to the screen get's written as 'ñ', how can I "re-encode" (may be wrong word) so that it outputs as 'ñ'?

Thanks in advance.



via Chebli Mohamed

Fresh Install Visual Studio 2013

I am getting an error message that reads as follows when I try to create a new emty web project:

"Configuring IIS Express failed with the following error:

Unable to access the IIS metabase. You do not have sufficient privilege to access IIS web sites on your machine."

I am an Administrator account, and run VS2013 as administrator I tried the fix found at this link

Error - Unable to access the IIS metabase

I didn't understand the answer and don't have enough rep to comment and ask. When Altron suggests how to fix it, I clicked through the folders, and said continue, but I don't understand what he meant by "Changing the shortcut back to "Run as me"". This might not be my issue, but if it is can someone please clarify for me what he means or how to fix this? Thank you



via Chebli Mohamed