Wednesday, August 24, 2011

C# Yield statement

I came across “Yield” statement in C# 2.0 very recently. I haven’t heard about this and so thought of exploring it a bit. This seems to be handy if you want to generate a list of items. To illustrate this let us consider a Fibonacci series generator example, first without using “Yield” and then using “Yield”.

Fibonacci generator without Yield:

    private IEnumerable<int> getFibonacciList(int num)
        {
            List<int> list = new List<int>();
            int prev = -1;
            int curr = 1;
            for (int i = 0; i < num; i++)
            {
                int next = prev + curr;
                list.Add(next);
                prev = curr;
                curr = next;
            }

            return list;
        }

This method takes an integer as parameter to indicate the length of the Fibonacci series to be generated. As you can see above, we need to create a List<int> and then add the elements to it.

Now, let us see the “Yield” statement version:

        public IEnumerable<int> generate(int num)
        {
            int prev = -1;
            int curr = 1;
            for (int i = 0; i < num; i++)
            {
                int next = prev + curr;
                yield return next;
                prev = curr;
                curr = next;
            }
        }

The above code doesn’t need any List<int> to be created. On first thought, it looks like the compiler generates the additional line of code to declare a List<int>. But in reallity there is lot more than this. If you view the compiled code in .NET Reflector tool you will find lot more code generated.

Now consider the following code that calls the above function:
           
foreach (int i in generate(10))
            {
                Console.WriteLine(i);
            }

When you step through the code in VS debugger, you will find “generate” method is being called 10 times (the value of the passed parameter). What happens is for each iteration of foreach loop, “generate” is called and this method returns as soon as it reaches “yield return”. During the next iteration the execution resumes from the line after “yield return”. This  means that C# maintains the state (like values of variable prev, curr, in our example) for each call (something like closures in javascript).

I am not clear on the real time usage of “Yield” statement. I am planning to read more on this in coming days and hopefully be in better position to list the pros/cons and usages of “Yield” in another post.

Happy coding!!

Thursday, August 4, 2011

Javascript : Call Vs Apply (Part 2)

This is part 2 of JavaScript Call Vs Apply.

Part 1 explained bit about of switching context in JavaScript and its uses. This part explains how to use Call and Apply for this and what is the difference between Call and Apply.

The only difference between Call and Apply is in how they handle the arguments. In Call you need to pass the arguments (as you do for normal function calls). In Apply you need to pass the arguments as an array. To see this in action, I am going to modify the function used in Part 1 by adding additional arguments:

function displayDetails(argOne, argTwo)
{
          alert(argOne + ‘:’ + argTwo);
}

Following is the syntax to invoke the above function using Call and Apply:

displayDetails.call(object, ‘one’, ’two’);
displayDetails.apply(object, [‘one’,’two’]);

As you could see from above, the only difference is the arguments in Call are sent separately but in Apply it is sent as an array.

One scenario where Apply could be preferred over Call is when you need to pass all the arguments of the parent function to the target function. For example, consider the following code:

function test(testOne, testTwo)
{
          displayDetails.call(this, testOne, testTwo); //works as expected.
displayDetails.apply(this, arguments); //works as expected.
}

Both the lines in the above function work correctly. It you are going to add another parameter to “test” function, then you would need to modify the first line (Call) but not the second (Apply).

function test(testOne, testTwo, testThree)
{
          displayDetails.call(this, testOne, testTwo, testThree); //need to add the additional parameter.
displayDetails.apply(this, arguments); //no changes required.
}

Hope this post was useful.

Happy coding!!

Friday, July 29, 2011

How to generate barcodes in C#?


Generating barcode is surprisingly very easy (at least in C#). Barcodes are another representation of the data (characters, numbers,etc) in a different font. To generate barcodes in your application you need to just display data in barcode fonts. There are number of free barcode fonts available. One such font is available here http://www.squaregear.net/fonts/free3of9.shtml. You could use your custom font as well.

From here I assume you have downloaded (and extracted) the above font files in F:\Downloads\free3of9 folder. I will be using the extended font in this example (fre3of9x.ttf). Also I assume you are using a windows form (C#) with a label named label1.

1.    First you need to create a font object in C# by loading the downloaded font into a font collection:

System.Drawing.Text.PrivateFontCollection fontCollection = new    System.Drawing.Text.PrivateFontCollection();

            fontCollection.AddFontFile(@"F:\Downloads\free3of9\fre3of9x.ttf");                        
FontFamily family = new FontFamily("Free 3 of 9 Extended", fontCollection);

Please note that “Free 3 of 9 Extended” is the typeface name of the barcode font downloaded from the url that I have mentioned above. You need to find out the typeface name for the barcode font that you download for your use. Specifying any other name will throw “Font cannot be found.” exception.

2.    Next you need to generate the barcode by setting the font of the label as below:
      Font font3of9 = new Font(family, 30);
            label1.Text = "This is a bar code font";
      label1.Font = font3of9;

Following is the entire barcode generation code in C#:

      private void Form1_Load(object sender, EventArgs e)
      {
System.Drawing.Text.PrivateFontCollection fontCollection = new
System.Drawing.Text.PrivateFontCollection();
fontCollection.AddFontFile(@"F:\Downloads\free3of9\fre3of9x.ttf");
FontFamily family = new FontFamily("Free 3 of 9 Extended", fontCollection);
Font font3of9 = new Font(family, 30);
           label1.Text = "This is a bar code font";
label1.Font = font3of9;
       }

The output will be as below:




Hope this post will be useful for someone as a starting point to generate barcode in C#.

Happy coding!!

Wednesday, July 20, 2011

Download image url to file

Recently, in one of my personal projects, I wanted to provide an option to save (or download) a png image url to the disk. First, as most of us do, I Googled it and found lot of solutions. But I was not able to use any snippet readily without any modifications. May be no one has encountered this scenario (as you could easily use browse “save as” functionality for this). [Updated on July 21st - I found a very elegant solution here which I have also updated at the end of this post). In interest of others who might someday need this functionality, I am providing the code snippet that I used to achieve this.

public void saveAsFile(string link)
{
          /*Get the name of the image from the link by finding the last '/' */           
          string name = link.Split('/')[link.Split('/').Length - 1];

          /*save the file with the same name in the current base directory */
          string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name);
           
          System.Net.WebRequest request = System.Net.WebRequest.Create(link);            
          System.Net.WebResponse response = request.GetResponse();
          System.IO.Stream stream = response.GetResponseStream();
           
          //convert the response stream into an image object.
          System.Drawing.Image image = System.Drawing.Image.FromStream(stream);

//save the image to a file.
          image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);           
 }

Note that I have used ImageFormat.Png as my need is to save only PNG files. You need to change this format based  on what type of image (gif,bmp,etc) you want to save.

Happy coding!!

Updated on July 21st - Looks like I am not good in Googling. I found a very elegant solutions here. I have updated the code based on this:



       public void saveAsFile(string link)
       {
         /*Get the name of the image from the link by finding the last '/' */
          string name = link.Split('/')[link.Split('/').Length - 1];

          /*save the file with the same name in the current base directory */
          string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name);

           System.Net.WebClient client = new System.Net.WebClient();
           client.DownloadFile(link, filePath);
        }

Saturday, July 16, 2011

"Default" property in C#?

I came across the "Default" keyword in VB.NET that seems to be handy in many cases. Following is the excerpt from msdn:

"A property that accepts arguments can be declared as the default property for a class. A default property is the property that Visual Basic will use when no specific property has been named for an object. Default properties are useful because they allow you to make your source code more compact by omitting frequently used property names."

I thought it would also be available in C# so that I can assign something like this: 

MyClass a = new MyClass();
a = "test";

I created a class and decorated with "DefaultProperty":

DefaultProperty("MyDefaultProperty")]
public class MyClass
{
    public string MyDefaultProperty;
}    

Now I created an instance of MyClass and assigned a string to the instance as below:

MyClass a = new MyClass();
a = "test";

But this gave me compilation error "Cannot implicitly convert type 'string' to MyClass'". Looks like there is no way to implement the "Default" behavior in C#!!

We could use operator overloading, which comes somewhat close, but it has its own disadvantage. Let us first use operator overloading and see what happens:

public class MyClass
{
           public string MyDefaultProperty;
           public string AnotherProperty;
           public static implicit operator MyClass(string value)
          {
             MyClass t = new MyClass();
             t.MyDefaultProperty = value;
           }
       }

The above  class has 2 properties, one of which is the default property. Now I don't get any compilation error when I use:

MyClass a = new MyClass();
a = "test";

This assigns the value "test" to "MyDefaultProperty" and so is equivalent to:

MyClass a = new MyClass();
a.MyDefaultProperty = “test”;

Have we achieved what we wanted? No!!  As I had mentioned earlier, this comes close to what we want and has its limitations. Now consider the following:

MyClass  a = new MyClass();
a.AnotherProperty = "another property";
a = "test";
What should be the value of a.AnotherProperty after line 3? It should be the string "another property". But as a new instance is created in the overloaded operator, the state of the object is gone and we get a brand new instance with only the default property set!!  

Is there any reason for not implementing this behavior in C# while it is available in VB.NET? It would be great if anyone throws some light on this.

Happy coding!!

Tuesday, July 12, 2011

Javascript : Call Vs Apply (Part 1)

I have been using Javascript extensively for quiet some time. It is almost impossible for me to write a Javascript app without using either of the two (Call/Apply).IMHO, these are very powerful functions in Javascript.

Both does the same (i.e. change the context) but with subtle difference in terms of how they handle the arguments. But first, why do you need to change the context of a function and what is it exactly??

Ok, now consider the following two functions (or objects as all functions in Javascript are actually objects)

function Dolphin()
{
 this.details = "I am a Mammal!!";

 this.canSwim = "Yes";
 this.canFly = "No";
}


function Shark()
{
  this.details = "I am a Fish!!";

  this.canSwim = "Yes";
  this.canFly = "No";
}


Now instantiate these objects:
var d = new Dolphin();
var s = new Shark();


If I want to add a method to display the details of these objects then we would write a generic function and pass the details as arguments as shown below:

function displayDetails(details)
{
 alert(details);
}


displayDetails(d.details); //this displays "I am a Mammal!!"
displayDetails(s.details); //this displays "I am a Fish!!"

But what if "displayDetails" needs to be extended to show other details (like "can fly", "can swim" etc)? Then we have to add more arguments to "displayDetails" as below:

function displayDetails(details, canSwim, canFly)
{
 alert(details + ':' + canSwim + ':' + canFly);
}


and pass the additional arguments:

displayDetails(d.details, d.canSwim, d.canFly); //this displays "I am a Mammal!!:Yes:No"
displayDetails(s.details, s.canSwim, s.canFly); //this displays "I am a Fish!!:Yes:No"

As you can see from above code, it is more prudent to pass the entire object to "displayDetails" as below:

function displayDetails(animal)
{
 alert(animal.details + ':' + animal.canSwim + ':' + animal.canFly);
}


and call this as follows:

displayDetails(d); //this displays "I am a Mammal!!:Yes:No"
displayDetails(s); //this displays "I am a Fish!!:Yes:No"

Won't it be nice if we can call "displayDetails" as a function of the object Dolphin or Shark so that we could invoke "displayDetails" as:

d.displayDetails();
s.displayDetails();


call/apply functions does the same thing but with different syntax:

displayDetails.call(d); //this displays "I am a Mammal!!:Yes:No"
displayDetails.call(s); //this displays "I am a Fish!!:Yes:No"


But we need to make couple of changes (remove param and use "this" instead of param) to displayDetails as below:

function displayDetails()
{
 alert(this.details + ':' + this.canSwim + ':' + this.canFly);
}


As you can see from above, we are changing what "this" means inside the function "displayDetails". When a "Dolphin" object is passed, "this" refers to "Dolphin" object. When "Shark" object is passed, "this" refers to "Shark" object. What we have done is changed the context in which "displayDetails" executes.

It has been rather long blog than I anticipated. So I will move the remaining to Part 2.

Happy coding!!

Thursday, July 7, 2011

C# "using" statement - a small caveat

I was thinking the "using" statement will always ensure the enveloped object is disposed safely. And it does so except in one scenario. When an error occurs in the constructor of the enveloped object, the dispose method is not at all called.

I have read in many sites that

using (ConcreteDispose c = new ConcreteDispose())
{
   c.yourMethod();
}

roughly transalates to

ConcreteDispose c = new ConcreteDispose ();
try
{
   c.yourMethod();
}
finally
{
  c.Dispose();
}

After looking into the above code snippet again, it dawned on me that this issue is because finally block will not be exectued (when exception is thrown in the constructor) as the instance is created before the try block. I thought this could be easily solved if the translated code is something like below

ConcreteDispose c;

try
{
   c = new ConcreteDispose ();
   c.yourMethod();
}
finally
{
  if (c != null) 
    c.Dispose();
}

This will exectue the finally clause but the instance is not created (when constructor throws exception) and so the dispose method will not be called at all.

Although doing too much work in the constructor is not recommended, but if you are doing it for some reason then keep this in mind....

Happy coding :-)