Monday, 27 February 2012

Regular Expression in LINQ

string[] companies = { "microsoft", "IBM", "oracle", "google", "apple", "facebook", "RIM" };
//wildcard search to "%o%o%"
Regex regex = new Regex("oo");
var oo = companies.Where(c => Regex.IsMatch(c, "o.*o")).Select(c => c);
var oo1 = from c in companies
		  where (Regex.IsMatch(c, "o.*o"))
		  select c;
oo1.Write();


Here we are searching for company names containing two “o”, need not be consecutive.

How to use LIKE, IN - in LINQ

How do we use LIKE (from SQL) in LINQ?

One option:
-> use string.Contains() method

string[] companies = { "microsoft", "IBM", "oracle", "google", "apple", "facebook" };
//get companies which have 'oo' in them
IEnumerable<string> companiesWithAnO = (from c in companies
                 where c.Contains("oo")
                 select c).ToArray();


Also we can use string.StartsWith() and EndsWith().

-> Second option: This is only if we are using LINQ To SQL.

string[] companies = { "microsoft", "IBM", "oracle", "google", "apple", "facebook" };
//get companies which have 'oo' in them
IEnumerable<string> companiesWithAnO = from c in companies
             where SqlMethods.Like(c,"%oo%")
             select c;

The IN operator is also quite easy.

string orangeFruit = "orange";
string[] fruitBasket = {"apple","orange","mango","leechy" };
//check orange is in the fruit basket
bool orangeFound = fruitBasket.Contains(orangeFruit);

“Contains” is the extension method in the IEnumerable<T> class.

Sunday, 26 February 2012

LINQ: Differed Queries

LINQ queries, by default, are differed. It means that the original source collection is accessed only when the collection containing the LINQ output is enumerated. Let us see an example.
string[] companies = { "microsoft", "IBM", "oracle", "google", "apple", "facebook" };
//get companies which have 'oo' in them
IEnumerable<string> companiesWithAnO = from c in companies
           where c.Contains("oo")
           select c;
foreach (var item in companiesWithAnO)
{
 Console.WriteLine(item);
}


Output: google, facebook.

Let’s add a new line after the LINQ query.
try
{
 string[] companies = { "microsoft", "IBM", "oracle", "google", "apple", "facebook" };
 //get companies which have 'oo' in them
 IEnumerable<string> companiesWithAnO = from c in companies
       where c.Contains("oo")
       select c;
 //set IBM string to null
 companies[5] = null;
 foreach (var item in companiesWithAnO)
 {
  Console.WriteLine(item);
 }
}
catch (Exception ex)
{
 Console.WriteLine(ex.ToString());
}

O/P: Google, System.NullReferenceException…

So the first string “Google” is printed, but the next one gives error. Why? The reason is: when the LINQ query output variable – companiesWithAnO is enumerated, it accesses the original source collection – companies to get the results.

Let us check what the variable companiesWithAnO contains after the LINQ query but before the loop. Now we could check the companiesWithAnO.Count(), but this will give the output as 2, because running Count() will enumerate the collection – we need to prove that the collection companiesWithAnO hasn’t been enumerated and the original source not accessed yet.

We can try to have a look at the variable in debug mode, a breakpoint is set before the foreach loop.

image
The ‘Results View’ is not shown as it not yet enumerated. We change the query and add a ToArray().
IEnumerable<string> companiesWithAnO = (from c in companies
     where c.Contains("oo")
     select c).ToArray();

image

So the collection companiesWithAnO contains the values in this case.

Well we know now that LINQ queries are differed queries, except when we use ToArray() or ToList() or ToLookUp(). But why? We shall try that in next post.

Tuesday, 21 February 2012

LINQ: Extension Methods for Console apps

When designing Console apps for Windows, we usually write a lot of message to the console. It is a pain to write “Console.WriteLine(“xxxxxx”)” every time.

So let’s use extension methods to ease the pain.

Step 1> Create a Library project, add a class:

namespace LINQ.ExtensionMethods
{
    public static class MExtensions
    {
        public static void Write(this string s)
        {
            Console.WriteLine(s);
        }
    }
}


Step 2> Create a Console project, in the Main method:

        static void Main(string[] args)
        {
            "Welcome to Console project".Write();
        }


image



Let’s do this for a collection, no more writing loops or calling a method to iterate. Here we write an extension method for IEnumerable<T> in the class MExtensions above.

  public static void Write<T>(this IEnumerable<T> c)
        {
            Console.WriteLine();
            foreach (var item in c)
            {
                Console.WriteLine(item);
            }
        }

And to call:

    string[] games = { "Soccer", "Football", "Rugby" };
    var items = games.Select(p => new { p, p.Length });
    items.Write();

image

How to check when a machine was restarted?

Yesterday evening one of our test servers automatically rebooted. And today morning we found out that the last night’s test run was interrupted. Checking the logs and stuff, found out this was the case. So took on the task to find out what happened.

The best friend is Windows Event Logs – it is a reliable source to check computer’s history. (What happens in case of hibernate? #to-find)

Shutdown or reboot could happen because of various reasons and for each reason we could get a different Event ID. So we need is a quick way to find out the boot time . There are few events we can trust, the events logged by Event Logging service – that it is starting or shutting down. Very rarely would some one disable this service or start/stop it. The logs logged by Event Log Service are:

6005: logged at boot time, when the service starts
6006: at shutdown, that the service is stopping

The Date/Time of entries with these IDs can be taken as a rough idea when the computer stopped and booted.

In our case, we found that half an hour before a shutdown log – there was a log event (Event ID = 22, Category = Installation, Source = Windows Update Agent) logged by Windows Update – saying that the computer will be rebooted within 30 minutes.

More info: http://support.microsoft.com/kb/196452

C# Reactive Extensions - Buffer and Window

I was going through Buffer and Window in RX, thought a few examples would help clear the differences. First create a buffer of even numbe...