While using LINQ, you may want to choose unique items in a list with the DISTINCT clause. To use this clause with your objects or projections or an object that represents stored proc. results, you will need to provide the logic used to compare 2 object instances and return if they are equal or not. This is because .NET does not inherently know how to compare these objects.

Lets say you have a Person class:

public class Person {
    public long ID;
    public string firstName;
    public string lastName;
}

The comparison logic is defined in a class PersonComparer needs to implement the IEqualityComparer interface that has 2 methods as shown.

public class PersonComparer : IEqualityComparer<Person>
{
    #region IEqualityComparer<Person> Members

    public bool Equals(Person object1, Person object2)
    {

        //return true if equal
        return object1.firstName.Equals(object2.firstName)
               && object1.lastName.Equals(object2.lastName);

    }

    public int GetHashCode(Person obj)
    {
        return obj.ID.GetHashCode();
    }

    #endregion
}

Now to use this, let’s say we have a list of Person objects IEnumerable<Person> lstPerson, and we want to get unique objects in this.

Declare an instance of your Comparer object

PersonComparer myComparer = new PersonComparer();

and then use it with the Distinct clause

IEnumerable<Person> lstPersonDistinct = lstPerson.Distinct(myComparer)

 If you want to go deeper, Distinct is defined in the .NET framework as an extension on class Enumerable.

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);

So essentially, the interface (IEqualityComparer) of myComparer is used in your Distinct call.

Hope this post helps you to implement Distinct for your objects.

As you know, data operations on a database that need to execute together should always be in a transaction, in order to maintain data integrity.

LINQ automatically uses database transactions.
So, when you call UpdateChanges(), all LINQ operations done from creation of the data context or the last UpdateChanges are executed within a database Transaction.

Unlike what many developers think, you do not need to use TransactionScope if you just use a single call to UpdateChanges(), after a number of InsertOnSubmit(), DeleteOnSubmit(), etc..

If you do use multiple UpdateChanges(), you will need to manually handle the transactions by wrapping the Operations in a TransactionScope block. My previous post has a scenario in which you would need to do this.

Contrary to what you might think, SQL that gets executed on a database as a result of LINQ operations, might not be in the order of your LINQ calls.

Let’s consider a scenario in which Customer data needs to be updated. You’d like to delete the old row and then insert the new data rather than an Update, because of some triggers which run some complex business logic.

Unfortunately, a sequence of an Insert followed by a Delete does not execute on SQL Server like you would expect. For some reason, LINQ always executes the DELETE operation at the end, no matter where it was in the execution sequence.
So, a Delete and Insert in your LINQ would execute as an Insert and a Delete on SQL Server. This could cause problems like Primary key violations, depending on your table design.
There is no way to get around this, except by calling SubmitChanges() after the different Operations.
So, you would have Delete, DataContext.SubmitChanges and then Insert and DataContext.SubmitChanges. This would preserve the sequence of Deleting before an Insert.

To maintain data integrity, the executions should be in a Transaction. Since you call SubmitChanges() more than once, you need to manually create/manage the Transaction.

This is done by enclosing the operations in a block:


using (var ts = new TransactionScope())
{
    try {
   …
   ts.Complete();   //commit the transaction

    }
    catch
    {
         ts.Dispose();   //rollback
     }
}

Note: To use TransactionScope, you need to reference System.Transactions.

If you are using SQL Profiler to watch the SQL being executed, note that you will always see the Update and Insert statements irrespective of whether the Transaction was rolled back or not, because SQL Profiler does not indicate Transactions, but let that not confuse you. The data will not be affected in case of a Rollback.

Just thought I’d write a quick post with some extension methods that you can use for cleaning up strings.

The core of these extension methods are regular expressions, and if you understand how they work, you can roll your own using this pattern.
If you don’t, you should read these:
http://msdn.microsoft.com/en-us/library/hs600312.aspx
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

I feel that mastering Regular Expressions is very important for string manipulation.

Let’s take the example of an application which provides a text-box for phone numbers, where the user can enter a phone-number in any format and then you would just like to extract the numbers to do a search.
It boils down to stripping the input of non-numeric characters.

I would write an extension method like this:


namespace String.Util
{
    public static class Extensions
    {

        public static string StripNonNumbers(this string input)
       {
             //strip out non-numeric chars from input
            string stripped = Regex.Replace(input, "[^0-9]", "");
            return stripped;
      }

.
.
.

The Regular Expression above essentially matches non-numeric characters and replaces them with an empty string, so you get a resulting string containing only numbers.

You could tweak this with some really powerful expressions for your purpose.
For e.g. In place of [^0-9], use [^a-zA-Z] to remove non-alpha characters or [0-9] to replace numeric characters

Then you just reference String.Util in your target module with a Using statement and invoke it like:


string cleanPhone = phone.StripNonNumbers();

Notice the down-arrow in the Intellisense for a string’s methods, which indicates that it’s an extension method.

If you’re not already familiar with Extension methods, they are a cleaner, functional programming way of writing Helper methods. They are not more efficient necessarily but make the code much cleaner and I would encourage you to use them when possible.

A good practice for a web service is to provide and store data in a locale agnostic way, e.g. timestamps should be stored as UTC and the data should also be returned/serialized in an agnostic way, so the client can apply localization settings, user preferences, etc. This is a good practice so that servers are location agnostic and the client does the lifting.

In the past, I returned a DateTime with the specification that it was UTC, so the client blindly localized it.
I recently ran into a problem where our Flex/Flash client used the UTC indicator to localize instead of blindly doing it, which meant that my method had to return timestamps marked as UTC, i.e. with a “z” at the end. There is an issue with that if you use .NET to write your web service because the XmlSerializer cannot just take a Datetime type and serialize it as UTC.

In fact, .NET framework 1.1 had no way to designate a timestamp as UTC or local and this messed up web service designs and frustrated developers because data had to be converted to a locale before it was returned/serialized in a web service.
This issue was addressed in .NET framework 2.0 by adding a DateKind flag to a DateTime type. So, to serialize (and mark) a DateTime as UTC, you use:

DateTime dt = new DateTime(timestamp, DateTimeKind.Utc)

Now, if you are like me, you think it might be easier to add an extension method to a DateTime type in your service layer (or lower layers, if you really need it there), so you could provide the synctactic sugar elegantly write

DateTime dt = timestamp.UTCKind

But, unfortunately that does not work…
Why not?

From what I understand, extension methods are implemented in .NET as delegates with currying, which limits the first parameter (of a delegate) to be a reference type – ergo you cannot extend a value type or, in the case of Datetime, a struct.

So, what is currying? Is it dinner time yet? (if you like Indian or Thai food)

Going further down the rabbit-hole of functional programming, currying is “transforming a function that takes n arguments into a function that takes only one argument and returns a curried function of n – 1 arguments”.
In layman terms, when you curry a function, you return a lambda expression which is then used in the “higher” calling function.

A good explanation here: http://blogs.msdn.com/ericlippert/archive/2009/06/25/mmm-curry.aspx
and here: http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx

Origins of its name: http://c2.com/cgi/wiki?CurryingSchonfinkelling

Here are some related articles:

http://stackoverflow.com/questions/1016033/extension-methods-defined-on-value-types-cannot-be-used-to-create-delegates-why

http://blogs.msdn.com/sreekarc/archive/2007/05/01/extension-methods-and-delegates.aspx

So, ultimately, I created a utility method that takes in a DateTime and returns a UTC type DateTime, i.e. its kind is set to UTC.

public static DateTime UTCKind(DateTime dt)
{
    return DateTime.SpecifyKind(dt, DateTimeKind.Utc); //set time as UTC
}

This is a confusing error if you’re busy coding away and don’t step back to think about it.
In a nutshell, you are providing access to an object, and the access scope on that object does not match (aka is inconsistent) that of the providing method.

For e.g. if you define an interface IFoo and forget to mark it as public, and create a public Factory method returning an object implementing IFoo, you will get an “Inconsistent Accessibility” error at compile time.
It is pretty obvious if you think about it; the Factory method is public but the Interface is not, and you are returning a private (aka inaccessible) object via a public accessor, which doesn’t make sense.

So, to resolve it, start where the error occurs (by double-clicking the error) and then start drilling down the object hierarchy to see where the access changes from open to more restrictive, e.g. public to private.

Hope that helps…