Linq: Group by and sort

The following LINQ statement was the first one I wrote:


var hsQ = from hspt in hospitals
orderby hspt.County, hspt.City
group hspt by hspt.County;

It obviously groups by country and then sorts by city.

However, I found the following even better as it groups first by country, sorts by country and then sorts within the group by city:


var hsQ = from hspt in hospitals
orderby hspt.City
group hspt by hspt.County into hsptGroup
orderby hsptGroup.First().County
select hsptGroup;

C# Warning CS0067: The event ‘event’ is never used

In my current project I am using a library that is delivered to me. The API in this library provide an interface that is a bit big! The interface requires my class to implement two events as follows:


#region INotifyPropertyChanged Members
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

#endregion
#region INotifyPropertyChanging Members
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;

These two events have no meaning in my class and I just have to implement them for the sake of the interface.

As I start to compile my code I see the Warning CS0067 that indicates that my events are not used anywhere, which is true.

As usual, I don’t want my code gets spoiled with warnings en I would like to sort out ALL MY WARNINGS. So I came across some options:

  • Ignoring this warnig throughout the project.

    This is too much, I don’t want to avoid the benefit of getting this nice warning that just highlighted my problem. But if I would like to do so I need to put the number 0067 in the project properties page in Build tab onder the Supress warnings

  • The less wide solution would be to ignore this warning only in that file and I could do this by putting the code just before my declaration:
    #pragma warning disable 0067

    and then restore it after my declaration using

    #pragma warning restore 0067

  • The last option I just found from MSDN which seems a neat solution is to tell the compiler that I am deliberately not supporting this event and even if it would be called at runtime that would be a mistake.

    To do so I need to throw an exception as follows:

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged
    {
    add { throw new NotSupportedException(); }
    remove { }
    }

    public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging
    {
    add { throw new NotSupportedException(); }
    remove { }
    }

Using brackets after any if statement

In my new assignment, where we use .NET 3.5 I got the chance to use the ReSharper extensively. One of the new features I was surprised with is the usage of brackets after every if and else even when they contain simply one statement.
It occurred to me that the debugger stops on the brackets as a step in the processing cycle. So I decided to see what is the difference in the compiled IL code. Therefore I wrote the following code:


public class SeeTheDifference
{
public void Test1()
{
for (int i = 0; i < 10; i++)
{
TestMethod();
}
}
public void Test2()
{
for (int i = 0; i < 10; i++)
TestMethod();
}
private void TestMethod()
{
Debug.WriteLine("test");
}
}

And compiled in both Debug and in Release configuration. The result is the following snapshot in the Reflector:

.method public hidebysig instance void Test1() cil managed
{
.maxstack 2
.locals init (
[0] int32 i,
[1] bool CS$4$0000)
L_0000: nop
L_0001: ldc.i4.0
L_0002: stloc.0
L_0003: br.s L_0012
L_0005: nop
L_0006: ldarg.0
L_0007: call instance void Knowledgebase.SeeTheDifference::TestMethod()
L_000c: nop
L_000d: nop
L_000e: ldloc.0
L_000f: ldc.i4.1
L_0010: add
L_0011: stloc.0
L_0012: ldloc.0
L_0013: ldc.i4.s 10
L_0015: clt
L_0017: stloc.1
L_0018: ldloc.1
L_0019: brtrue.s L_0005
L_001b: ret
}
.method public hidebysig instance void Test2() cil managed
{
.maxstack 2
.locals init (
[0] int32 i,
[1] bool CS$4$0000)
L_0000: nop
L_0001: ldc.i4.0
L_0002: stloc.0
L_0003: br.s L_0010
L_0005: ldarg.0
L_0006: call instance void Knowledgebase.SeeTheDifference::TestMethod()
L_000b: nop
L_000c: ldloc.0
L_000d: ldc.i4.1
L_000e: add
L_000f: stloc.0
L_0010: ldloc.0
L_0011: ldc.i4.s 10
L_0013: clt
L_0015: stloc.1
L_0016: ldloc.1
L_0017: brtrue.s L_0005
L_0019: ret
}

As it is visible in this IL code, there are two nop commands as results of the bracket pair. According to Reflector “nop (0x0000): fills space if bytecodes are patched. No meaningful operation is performed although a processing cycle can be consumed.”

Another peace of code that I don’t want to rewrite it again (and again)

using System;
using System.Collections.Generic;

/// <summary>
/// This class uses XmlSerializer to do both sides of conversion to xml string
/// </summary>
/// <typeparam name="T">any Serializable class</typeparam>
public class Serializer<T>
{
/// <summary>
/// Convert an instance to XML string
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public string Serialize(T item)
{

MemoryStream ms
= new MemoryStream();
XmlTextWriter writer
= new XmlTextWriter(ms, Encoding.Unicode);

XmlSerializer serializer
= new XmlSerializer(typeof(T));
serializer.Serialize(writer, item);

writer.Flush();
ms.Position
= 0;

StreamReader reader
= new StreamReader(ms);
return reader.ReadToEnd();

}
/// <summary>
/// another version, could be better
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private string GetSerialize2(T item)
{
StringWriter wr
= new StringWriter(new StringBuilder());

XmlSerializer serializer
= new XmlSerializer(typeof(T));
serializer.Serialize(wr, item);

wr.Close();
return wr.GetStringBuilder().ToString();
}

/// <summary>
/// Convert the XML string to an instance of an object
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public T Deserialize(string xml)
{
XmlTextReader stream
= new XmlTextReader(new StringReader(xml));
XmlSerializer serializer
= new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stream);
}
}

Sorting Generic List in C#

You can sort a generic List in C# using different methods. Here I cover only two options which I found them most handy. The third option is to put the method into a class that implements the IComparer interface.

using System;
using System.Collections.Generic;

public class SortingList
{
/// <summary>
/// SortingList: This snippet code demonstrates the delegate method of sorting lists
/// I define an Item type having some fields and sort based on a preferred field
/// To do so I need to implement a method would be called during the sort action for each pair.
///
/// NOTE: You could also create a class implementing IComparer and use the class to pass to the Sort method.
///
/// Asghar Panahy
/// 07-12-2007
/// </summary>
public static void Main()
{
List
<Item> list = new List<Item>();

// Adding some dummy items
list.Add(new Item("6", " Asghar 1"));
list.Add(
new Item("5", " Asghar 2"));
list.Add(
new Item("3", " Asghar 3"));
list.Add(
new Item("4", " Asghar 4"));
list.Add(
new Item("2", " Asghar 5"));
list.Add(
new Item("1", " Asghar 6"));

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Sorting it by ID
list.Sort(SortByID);

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Second Option, using anonimous methods
// Sorting it by Birthday
list.Sort(
delegate (Item i1, Item i2)
{
return i1.Birthday.CompareTo(i2.Birthday);
}
);

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Wait for response before closing it
Console.ReadLine();

}
public static int SortByID(Item s1, Item s2)
{
return s1.ID.CompareTo(s2.ID);
}

public static void DumpList(List<Item> list)
{
foreach(Item l in list)
{
Console.WriteLine(l);
}
}

}

// Sample Class
public class Item
{
public Item(string id, string name)
{
this.ID = id;
this.Name = name;
this.Birthday = DateTime.Now;
}
public string Name;
public string ID;
public DateTime Birthday;
public override string ToString()
{
return String.Format("{0} is born on {1}", this.Name, this.Birthday.ToLocalTime());
}
}
}

Anonimous Functions in C# 3.0

These parts are coming from the Language Specification document:

x => x + 1 // Implicitly typed, expression body
x => { return x + 1; } // Implicitly typed, statement body
(int x) => x + 1 // Explicitly typed, expression body
(int x) => { return x + 1; } // Explicitly typed, statement body
(x, y) => x * y // Multiple parameters
() => Console.WriteLine() // No parameters
delegate (int x) { return x + 1; } // Anonymous method expression
delegate { return 1 + 1; } // Parameter list omitted

// Example:
delegate bool Filter(int i);
void F() {
Filter f = (int n) => n < 0;
list.FindAll(f);
}

delegate void D();
void F() {
int n;
D d = () => { n = 1; };
d();

// Error, n is not definitely assigned
Console.WriteLine(n);
}

Zip a folder using SharpZipLib assembly in C#

There are several ways of zipping files. One way I started was to copy the files in the folder into an already existing zip file using a vb script. This was going fine until we had the request to delete the files when the process is done. Unfortunately the zip process thought it was completed and so the delete could start which caused the files be removed before taking the chance to be zipped.

My second attempt is this small c# script that is runnable in both frameworks 1.1 and 2.0. It uses a free open software called ZipLib that I have downloaded it from their website.

In this library they have several ways of doing the same thing. Adding files one by one was my preferred option for this particular problem but I had an issue with Windows XP not willing to show the content of the zip file whislt the file is unzippable. So I had to come up with this fast solution.

This small program is using a fast class for doing regular things like I wanted.

using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

namespace ZipFolder
{
/// <summary>
/// This small program is a command line application that takes two parameters.
/// If you don’t provide any parameter it will then show the syntax.
/// The aim of this class is to zip a folder with all its contents into a small zip file.
/// Notice that you can call it to zip the current folder but the destination may not be
/// within the source folder.
///
/// By Asghar Panahy
/// 25-oct-2007
///
/// </summary>
class Program
{
/// <summary>
/// Expects exactly zero or two parameters
/// </summary>
[STAThread]
static void Main(string[] args)
{
if (args.Length <2)
{
DumpSyntaxt();
return;
}

// Get the parameters
string fileName = args[0];
string path = args[1];

Console.Write(String.Format(“Searching for files in {0}“, path));

FastZip fZip = new FastZip();
fZip.CreateZip(fileName, path, true, “”);// Still need to figure out how
he filter works!?!?!
}

private static void DumpSyntaxt()
{
Console.WriteLine(“Syntaxt: Zipper.exe <zipFile>
lt;FolderPath>
“);
Console.WriteLine(“Exemple: Zipper.exe ..test.zip . “);
}
}
}

Abstract versus Interface

An article on the MSDN describes a summary of both the definitions. Although the article is a bit old (2003) and it compares C# with C++ it still provides a good start.

On the Code Project I found a nice article written by Rahman Mahmoodi where her has a nice comparisson for these two definitions. Another article on the Code Project which seems even more in dept about abstract class is written by Jayababu.

Some important points about Abstract classes

· In contrary to other object oriented languages like JAVA, you can not inherit from more than one abstract class

· you can not instanciate them or you get a Compiler Error

· An abstract class may have a non-abstract constructor implementation.

· they might have (also) non-abstract methods having implementation. these non-abstract methods are callable from the

abstract class AbstractClass
{
public void NonAbstractMethod()
{
Console.WriteLine(“
You can call a non-abstract method which is implemented within the abstract method.“);
}
}

· You can reimplement the non-abstract method but it would be called by the class internally or any object of that type. If you define an object of abstract type and you instanciate the derived class you still call the implementation within the abstract class. To get the reimplementation you need to instanciate the class using a reference of type of the derived class. For example defining the following in the derived class:

public new void NonAbstractMethod()
{
Console.WriteLine(“
This is new implementation of the non-abstract method.“);
}

and calling it like this

// Will call the original implementation
AbstractClass obj = new InheritedClass();
obj.NonAbstractMethod();

// Will call the re-implementation
InheritedClass obj2 = new InheritedClass();
obj2.NonAbstractMethod();

· In your derrived class you need to ovreride all the abstract methods.

public override void OverrideThis()
{
Console.WriteLine(“
You have to implement an abstract method using the override key“);
}

· An abstract method can not be marked as static, compile error.

· You can have static and non-static fields in an abstract class:

public static int count = 1;
public int InstCount = 1;

public
AbstractClass()
{
count++;
InstCount++;
}

but when instanciating two objects of the derived class and verify the value of the fields:

Console.WriteLine(“Static field is ” + AbstractClass.count);
Console.WriteLine(“
Instance counter is ” + obj1.InstCount);
Console.WriteLine(“
Instance counter is ” + obj2.InstCount);

output:

Static field is 3
Instance counter is 2
Instance counter is 2

The Differences

· An inheritted class cannot have multiple base classes: compiler error.

· An abstract class can define a default implementation (using a non-abstract method) and that will not force the derived classes to reimplement it whereas an interface can not have any implementation at all.

· Interfaces can not contain fields; compile error.

· An interface is like a contract. Once the contract changes all the classes implementing it need to change whereas an abstract class is like a common code for all the classeds and you might introduce the new method as a non-abstract method and give a default implementation. This could be seen as a pro or con. In some situations it is required to force all the contract holders to apply on the new method and in other cases you want to have this new feature for some of the types while the rest migh follow later. (a good question would be why is the new method part of the abstract class and not introduced as a new contract)

·

Asynchronous Invocation Using BackgroundWorker / Threading / C#

Sample Image

Introduction

When you have a function that takes a long time and it freezes the screen, the user gets nervous. They simply don’t like to lose the control. It would give a friendly impression when they can still click on the form while the application is busy with getting the information, for example. When you start implementing asynchronous methods, you will wonder which technique is best suitable for your application. Would you use a Timer class or a Thread class or a BackgroundWorker? This article uses a BackgroundWorker class to show how easy it is, and where you need to pay attention when using it.

Background

I have tried to compare different methods of implementing Asynchronous Invocation in my weblog. With Microsoft Visual Studio 2005 , I discovered this class which is new to me.

Using the code

I have put extra comments everywhere possible, to make the sample a snippet of code you can use to start your own implementation. The code implements a very simple action, which is finding files in a directory to simulate the time consuming action. This is the place where you need to change. For the rest, the skeleton should be kept the same.

The background worker is able to send an event to the called thread to change the screen appearance. That is very easy, and I thought it would be easy for everyone to discover. But what if that is not enough and you would like to send other messages back to the caller? So I used BeginInvoke to invoke a call on the caller thread.

I have two delegates used from the sub thread, to call the method implemented in the main thread.

private delegate  void PaintMessage(TreeNode root,                                     string childText); private PaintMessage myAddNode = null;

The OnPaontMessage implements the adding of a newly found file into an existing (given) root. This is called when the sub-thread finds a new item.

private  delegate void EnableCancel(bool enabled); private EnableCancel myEnableCancel = null;

The second delegate is to indicate that the thread has been started and that it could be stopped. It is implemented by the main thread to enable the Cancel button.

Starting the action will be done by calling the RunWorkerAsync method on the worker.

this.backgroundWorker1.RunWorkerAsync(treeView1.Nodes[path]);

When a sub-folder is found, I send a notification to the main thread to create a node for the sub-folder. Then, I use that node to create a file node in it. But the dilemma is that I can not proceed with filling the file, if the main thread didn’t get the chance to create the sub folder. Thus, I need to wait and let the main application take the chance to create it. One simple way to do this is the following loop:

// Create a folder node before proceeding IAsyncResult ar = BeginInvoke(myAddNode, new object[]                   { root, di.Name }); // Update the screen  // Wait until the folder has been created before // proceeding with the content of the folde while (!ar.IsCompleted) {     Application.DoEvents();     ar.AsyncWaitHandle.WaitOne(-1, false); }

First, I invoke the delegate and I keep the reference to it. I use the reference to see if it has been completed. And in the loop, I let the application take the chance and do its events. Meanwhile, I tell my sub-thread to wait a bit.

Binding Data To The User Interface

This is not the very first time I am digging this subject but this is the first time I feel like I don’t know nothing. I am going to start from scratch and explore different technics on this subject…and again, I will use Amit Kalani’s book. This book will help me explore the following concepts :

  • Simple Data Binding
  • Complex Data Binding
  • One-way and two-way Data Binding
  • The BindingContext object
  • The Data Form Wizard

Simple Data Binding

Simple data binding means connecting a single value from the data model to a single property of a control. For example, you might bind the Vendor object name from a list of vendors to the Text property of a TextBox control.

private void SimpleBindingForm_Load(object sender, System.EventArgs e)
{
// Create an array of vendor names
String [] astrVendorNames = {"Microsoft", "Rational", "Premia"};

// Bind the array to the text box
txtVendorName.DataBindings.Add("Text", astrVendorNames, "");
}

The Binding class can accept many other types of data sources, including the following:

  • An instance of any class that implements the IBindingList or ITypedList interface, including the DataSet, DataTable, DataView, and DataViewManager classes.
  • An instance of any class that implements the IList interface on an indexed collection of objects. In particular, this applies to classes that inherit from System.Array, including C# arrays.
  • An instance of any class that implements the IList interface on an indexed collection of strongly typed objects. For example, you can bind to an array of Vendor objects

Binding to a collection of strongly typed objects is a convenient way to handle data from an object-oriented data model.

private void SimpleBindingForm_Load(object sender, System.EventArgs e)
{
// Initialize the vendors array
aVendors[0] = new Vendor("Microsoft");
aVendors[1] = new Vendor("Rational");
aVendors[2] = new Vendor("Premia");
// Bind the array to the textbox
txtVendorName.DataBindings.Add("Text", aVendors, "VendorName");
}

Navigating through data, using BindingContext :

private void btnPrevious_Click(object sender, System.EventArgs e)
{
// Move to the previous item in the data source
this.BindingContext[aVendors].Position -= 1;
}
private void btnNext_Click(object sender, System.EventArgs e)
{
// Move to the next item in the data source
this.BindingContext[aVendors].Position += 1;
}

Complex Data Binding

In complex data binding, you bind a user interface control to an entire collection of data, rather than to a single data item. A good example of complex data binding involves the DataGrid control. Obviously, complex data binding is a powerful tool for transferring large amounts of data from a data model to a user interface.code

private void ComplexBindingForm_Load(object sender, System.EventArgs e)
{
// Create an array of exams
Exam[] aExams =
{
new Exam("315", "Web Applications With Visual C# .NET"),
new Exam("316", "Windows Applications With Visual C# .NET"),
new Exam("320", "XML With Visual C# .NET"),
new Exam("305", "Web Applications With VB.NET"),
new Exam("306", "Windows Applications With VB.NET"),
new Exam("310", "XML With VB.NET")
};

// Bind the array to the list box
lbExams.DataSource = aExams;
lbExams.DisplayMember = "ExamName";
lbExams.ValueMember = "ExamNumber";
// Create an array of candidates
Candidate[] aCandidates = {
new Candidate("Bill Gates", "305"),
new Candidate("Steve Ballmer", "320")};
// Bind the candidates to the text boxes
txtCandidateName.DataBindings.Add( "Text", aCandidates, "CandidateName");
txtExamNumber.DataBindings.Add( "Text", aCandidates, "ExamNumber");

// And bind the exam number to the list box value
lbExams.DataBindings.Add( "SelectedValue", aCandidates, "ExamNumber");

In this example Exam class could be any user defined type you can think of, as long as it supports String properties ExamNumber and ExamName like this one:

public class Exam
{
private String examNumber;
private String examName;

public String ExamNumber
{
get{ return examNumber;}
}
public String ExamName
{
get{ return examName;}
}
public Exam(String strExamNumber, String strExamName)
{
examNumber = strExamNumber;
examName = strExamName;
}

}
And Candidate is also something similar to the following:

public class Candidate
{
private string examNumber;
private string candidateName;
public string ExamNumber
{
get {return examNumber;}
set {examNumber = value;}
}
public string CandidateName
{
get {return candidateName;}
set {candidateName = value;}
}
public Candidate(String strCandidateName, String strExamNumber)
{
this.CandidateName = strCandidateName;
this.ExamNumber = strExamNumber;
}
}

Filtering With DataView Objects
A DataSet object contains two collections. The Tables collection is made up of DataTable objects, each of which represents a single table in the data source. The Relatios collection is made up of DataRelation objects, each of whic represents the relationship between two DataTable objects.
A DataView represents a bindable, customized view of a DataTable object.You can sort them or filter the records of a DataTable object to build a DataView Object.
private void FilterGridView_Load(object sender, System.EventArgs e)
{
// Move the data from the database to the DataSet
sqlDataAdapter1.Fill(dsCustomers1, "Customers");
// Create a dataview to filter the Customers table
System.Data.DataView dvCustomers = new System.Data.DataView(dsCustomers1.Tables["Customers"]);

// Apply a sort to the dataview
dvCustomers.Sort = "ContactName";

// Apply a filter to the dataview
dvCustomers.RowFilter = "Country = 'France'";
// and bind the results to the grid
dgCustomers.DataSource = dvCustomers;
}

This way of retrieving data is consuming lots of network resources and to bring all the records of a table to the client prior to filtering it doesn’t seem an efficient way of using (available?) resources. Therefor it is wise to create the view and on the database server and filter it before sending it to client.
A very nice example of binding is to bind a textbox to the collection within the combobox. This dead-easy sample is binding the text property of the TextBox to a combobox using its SelectedObject attribute. txtRAM.DataBindings.Add(“Text”, cmbComputers, “SelectedValue”);

Currency Manager

One new challenge I was face with recently is ability of dinamically load a grid based on the selection on one other grid. This is usefull when for example you have to tables loaded and you want to be able to navigate the first table and when move the cursor from one record to the other, the second grid which is related by a foreign key to the first one, gets filtered.This can be achieved in several ways. I just found one very easy way using the BindingContext and CurrencyManager.Let’s say you have a data view keeping the data about the parent relation and you will assign a grid to it like this:
DataView dvParent = base.DataSet.Tables[0].DefaultView ;
...
dgCodeGroup.DataSource = dvParent ;

What you need to do here is to get a reference to the ContextManager which is available through the BindingContext:

myCurrencyManager = (CurrencyManager)this.BindingContext[dvParent];
Then you subscribe to its PositionChanged event to get a notification when user moves from one record to the other on the grid:

myCurrencyManager.PositionChanged +=new EventHandler(OnCurrencyManager_PositionChanged);
Now all you need to do is to filter your second grid based on the selection. And the selection is easy to find:

DataRowView drv = (DataRowView) myCurrencyManager.Current ;

This is a collection of fields in that row. So you can use it to get into the fields and build your second data view.
Navigating the Current Position
This is where the CurrencyManager comes very handy. It has a property called Position which you can access to figure out the index and you can also assign a value to reposition it. Also the Count property is very handy to avoid moving out of boundries.

private void MoveNext(CurrencyManager myCurrencyManager)
{
if(myCurrencyManager.Count == 0)
{
Console.WriteLine("No records to move to."); return;
}
if (myCurrencyManager.Position == myCurrencyManager.Count - 1)
{ Console.WriteLine("You're at end of the records"); }
else
{ myCurrencyManager.Position += 1; }
}
private void MoveFirst(CurrencyManager myCurrencyManager)
{ if(myCurrencyManager.Count == 0)
{ Console.WriteLine("No records to move to.");
return;
}
myCurrencyManager.Position = 0;}
private void MovePrevious(CurrencyManager myCurrencyManager)
{ if(myCurrencyManager.Count == 0)
{ Console.WriteLine("No records to move to.");
return;
}
if(myCurrencyManager.Position == 0)
{ Console.WriteLine("You're at the beginning of the records."); }
else{ myCurrencyManager.Position -= 1; }}private void MoveLast(CurrencyManager myCurrencyManager){ if(myCurrencyManager.Count == 0) { Console.WriteLine("No records to move to.");
return;
}
myCurrencyManager.Position = myCurrencyManager.Count - 1;}