myfavoritemovies.us

September 26, 2008

? and ?? feature in C#

Filed under: C# 3.0 — @ 1:47 pm

In C# 3.0 there is a new feature assign and check the null values that lot of people doesn’t know it even exists. Well I didn’t know till couple of months ago. Even though I knew, there were couple of good circumstances I could have used it but never used it. So yesterday I decided to look at the code and see if I can save some typing by using this operators.

Lets jump into an example and look at the operator in action. I like examples more than theory so here it goes…

? is currently used as a trinary operator as we all know. Good example would be

string resturnResult = (value == null)?””:value;

in the previous statement, we are first checking to see if the value is null then assign an empty string to the returnResult else just assign the value in the value variable.

Now the use of ?? operator. The same statement we look at before would be

string returnResult = value ?? “”;

It does the same thing as the earlier statement we look at.  ?? operator will check and see if the value string is null and if it is null then it will assign the value to its right, else assign the value. Isn’t it elegant? I like this code better than the earlier one. We can argue about readability but once you start using it you will learn to read it as well.

Now going back to one other operator ‘?’ Currently it is used in the trinary operator, now it is a new face as well. Something like the following

int? age;

This basically says, the integer variable age could take null value. Why would someone want to do that, to be honest I haven’t used it. So in my limited knowledge on this subject, I could see the use in database side. You might run a stored proc and get user information from table and assign values to these variable which could take null values. If some rows doesn’t have age value set in the columns, that could come as null. So when the value is retrieved and it could be assigned to age variable without throwing an exception. Even though that is the intend, I haven’t sold on this idea yet. So if you any of you have used this operator, please drop me a note.

Thanks and happy coding…

September 3, 2008

Some cool string manipulation in C#

Filed under: C# 3.0 — @ 2:04 am

Today I was writing a simple code which would readin a commandline parameters like

name param1=value1 param2=value2 param3=value

from the values it is very obivious the frst parameter is a individual name and others are named parameters with associated values. If we could do it in our normal mode, we would first assign the first parameter to the unique name field and then we would split each following arguments and put it in a array or arraylist or some sort.

Since it is key value pair the best bet would be Dictionary or Hash and I prefer Dictionary. For some reason I never came across a situation I had to use hash yet. Anyway, so I was going to write the split code and method and then I realised I could do the split and assign it o an arry in single statement and here is how I did it.

string[][] pharsed = argument.Skip(1).Select(s => s.split(‘=’)).ToArray();

IDictionary<string, string> dictionary = new Dictionary<string, string>();

foreach(string[] vaue in pharsed)

{

     dictionary.add(vaue[0], vaue[1]);

}

Thats it, what I liked was the ease to skip and split on the fly. I haven’t figured out, how to create Dictionary on the fly in that single statement. Once I find out how to do it, I will update it in here for my notes…

Have fun.

Powered by Qumana

September 2, 2008

Factory pattern through reflection.

Last week I came across a situation where, I need to implement bunch of classes which perform same task differently when it is called. (Simply put, factory pattern). So I thought, based on GOF it is a simple implementation.

Create a abstract factory class and then create sealed worker class which implement the actual task. Simple enough. In the main program have a switch which checks the incoming parameter and based on the parameter, we create instance of a proper worker class and vola we got the implementation done.

Now the point to remember here is, if we need to add a new worker class, what are all the elements involved? First you need to add a new case statement for the new worker class initation and then add the new worker class itself. Two code changes. Not a big deal. But if you happen to have too many implementation or in other words too many worker implementation then your switch statement could grow larger and larger.

This limiation forced me to think if there is any other way of creating classes on the fly. I talked to one my collegue and he pointed me to one his implementation he is currently using that is using reflection. So here is how it is implemented.

First create the interface you would like the factory workers to implement. Something like the following;

IWorker.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TraditionalFactory
{
public interface IWorker
{
void SayName(string name);
}
}

You can see all we are trying to implement is a ‘SayHello’ method. Following two are two worker implementation of the Factory Interface;

Worker1.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TraditionalFactory
{
public class Worker1:IWorker
{
#region IWorker Members

public void SayName(string name)
{
Console.WriteLine("Name from first worker is {0}", name);
}

#endregion
}
}

Worker2.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TraditionalFactory
{
public class Worker2:IWorker
{
#region IWorker Members

public void SayName(string name)
{
Console.WriteLine("Name from second worker {0}", name);
}

#endregion
}
}

Based on the interface and the worker implementation there is nothing new. The code that make this one work without big switch statement is in the main program.

Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TraditionalFactory
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Which worker to run (Worker1 or Worker2?");
string workerName = Console.ReadLine();
Type workerType = Type.GetType("TraditionalFactory."+workerName);
IWorker worker = (IWorker)Activator.CreateInstance(workerType);
worker.SayName("data passed");
Console.ReadKey();
}
}
}

This factory model implementation compltly depends on the reflection feature of C#. This also depends on the the consumer to this program aware of which worker they need to consume by name or you need to create a dictionary mapping of the user input to worker class mapping of some sort. For this implementation I am assuming the consumer knows which worker to use.

The point of interests are, first creating the type of the class we are going to instantiate. In our class we are going to find the factory interface type of execuing assembly using ‘Type.GetType’ method call. Which looks at the executing assembly or clr to see if it finds matching type. If you look at the code closely, since we already know which worker that we are interested to consume based on ‘workerName’, we look for the namespace + workerName in the GetType. (This is where reflection come into get the type of the class we are trying to consume). Once the type identified, we call in the ‘Activator.CreateInstance’ method to create the instance of the worker class through the interface and then execute the public method from the interface. Thats it, we got ourself Factory pattern implemented.

The benefit of this implementation is that, when you want to add a new worker class, you simply add the worker class, compile it and deliver the exe. No more main program change. One code change and you are done.

The problems I see with the implementation is that, you need agree on how the consumers are going to consume the worker class and make appropriate mapping before hand or make the consure to call in with appropriate worker name explicitly (like the example below).

One for my notes….

June 22, 2008

Handling Resources in C#

Filed under: C# 3.0 — @ 12:41 am

Most of the people use resources when they want localize a product. Some other uses would be to use static reference files etc., For a month or two I have been use ResourceManager for one of my project. The requirement is very simple, I need to create a resource with bunch of files and then later build the same resource file into a C# project which when running would extract the files from the resource which was build in the previous step. Like any other simple C# coder, I approached the problem with our ResourceReader and ResourceWriter.

I first created a class called Writer as shown below, 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
using System.IO;
 
namespace ResourceBuilder
{
    public class Writer
    {
        public void WriteFile(string resourceName, string fileName)
        {
            ResourceWriter writer = new ResourceWriter(resourceName);
            CreateFile(fileName);
            byte[] file = File.ReadAllBytes(fileName);
            writer.AddResource(fileName, file);
            writer.Generate();
            writer.Close();
        }
 
        private void CreateFile(string name)
        {
            using (StreamWriter wr = new StreamWriter(name))
            {
                for (int i = 0; i < 5; i++)
                    wr.WriteLine(i.ToString());
            }
        }
    }
}

 
Writer class has one method called WriteFile, which creates a simple resource file and then populate the resource with one text file. The text file is created dynamically.
 
Next I created a class called Reader which does nothing but read the information from the resource file and creates output file. There are two ways you can read the resource file and I created two separate methods to extract in both ways as shown below.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
using System.IO;
using System.Reflection;
using System.Collections;
 
namespace ResourceBuilder
{
    public class Reader
    {
        public string ReadFiles(string resourceName, string fileName)
        {
            string outFile = "file1.txt";
            ResourceReader reader = new ResourceReader(resourceName);
            string resourceType;
            byte[] resourceData;
            reader.GetResourceData(fileName, out resourceType, out resourceData);
            File.WriteAllBytes(outFile, resourceData);
            return outFile;
        }
 
        public string ReadWithDictionary(string resourceName, string fileName)
        {
            string outFile = "file2.txt";
            string name;
            object value;
            ResourceReader myReader = new ResourceReader(resourceName);
            IDictionaryEnumerator readerWalker = myReader.GetEnumerator();
            while (readerWalker.MoveNext())
            {
                name = (string)(readerWalker.Key);
                if (name.Equals(fileName))
                {
                    value = readerWalker.Value;
                    File.WriteAllBytes(outFile, (byte[])value);
                    return outFile;
                }
            }
            return "";
        }
    }
}

The first read method ReadFile is the straight opposite of write method. This basically opens the resource file in resource reader mode and fetches the file we are interested in and write it out to a file.

The second method is little different. This still opens the resource file in resource reader mode and then instead of fetching object directory, cast it to IDictionaryEnumurator so that we can traverse the resource file to find out what are all the objects the current resource file has. So if you get a resource file and you would like to find out all the resources in the file, all you have to do is implement the second method, whola, now you can traverse the resource file and get the object by dictionary look up.

Now lets look at the main code which uses the reader and writer together to put all together.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace ResourceBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            Program pg = new Program();
            pg.CreateAndCompareResources();            
        }
 
        private void CreateAndCompareResources()
        {
            string resourceName = "temp.resource";
            string fileName = "file.txt";
            Writer wr = new Writer();
            wr.WriteFile(resourceName, fileName);
            Reader rd = new Reader();
            string outfile = rd.ReadFiles(resourceName, fileName);
            string outfile1 = rd.ReadWithDictionary(resourceName, fileName);
 
            string[] infilea = File.ReadAllLines(fileName);
            string[] outfilea = File.ReadAllLines(outfile);
            string[] outfile1a = File.ReadAllLines(outfile1);
            
            Console.WriteLine("First Match using ResourceReader/Writer is {0}", CompareArrays(infilea, outfilea));
            Console.WriteLine("First Match using ResourceReader/Writer is {0}", CompareArrays(infilea, outfile1a));
            Console.ReadKey();
        }
 
        private bool CompareArrays(string[] infile, string[] outfile)
        {
            if (infile.Length == outfile.Length)
            {
                for (int i = 0; i < infile.Length; i++)
                {
                    if (!infile[i].Equals(outfile[i]))
                        return false;
                }
                return true;
            }
            return false;
        }
    }
}

Now lets go through the program and see what are we trying to do;

1. We create Writer and request it to create a resource file called "temp.resource" and create a file called "file.txt" with following content

0

1

2

3

4

in it and then insert this file into the resource file.

2. We Create a reader class and then we call the first reader method to extract the "file.txt" from "temp.resource" and write the extracted content into a file called "file1.txt".

3. Then we call the same reader class but use the second extract method to extract the "file.txt" from "temp.resource" and write the extracted content into a file called "file2.txt".

4. Next we compare "file.txt" against "file1.txt" and write the match result.

5. Compare "file.txt" against "file2.txt" and write the match result.

Based on the documentation, (4) and (5) should return true.

Now if we run this program the result show be something like the following

image

To our surprise the first match returned false, if you would debug the code and see the content in the "file1.txt", the first four bytes are the size of the file and the "file2.txt" does not have the size of the file in it. That is the difference.  So beware of this difference.

I will research more on this to see why the first method put the size of the file in the beginning. If you know the answer, please post it here or send me a note at ksunair at yahoo.com

I developed the code on XP SP3 using Visual Studio 2008 Express for C# 3.0.

Thanks and happy coding…

April 29, 2008

C# 3.0

Filed under: C# 3.0 — Tags: , , — @ 2:51 am

Recently I started using C#3.0 and I am loving all the new features MS has added to this fantastic language. One thing I was trying to do over time was to learn the functional programming. As you can imagine it is completely different paradigm shift. When I switched from COBOL to C++, I had to go through the same. Jumping from procedural to object oriented concept. It looks like with 3.0 there will be another shift I am very happy to do, jumping to functional programming, it is going to happen sometime soon for me. I wanted to learn functional programming while I thought it is going to take some extra effort from my side, C#3.0 kind of made my life easy by adding Lambda expressions in its arsenals. Now you all know why I am so hyped about 3.0. Enough said, let me go through what are the main new concepts added in 3.0

(more…)

Powered by WordPress