Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
# Friday, February 01, 2008
I wrote an article about this topic a few months ago but I wanted to explain it a little further in this article by showing real-world scenarios on when and how to use this feature. So what does Extension Method mean? According to MSDN: "Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type." Now that we have that settled lets look at a good scenario that depicts a great time when to use an Extension Method.
Friday, February 01, 2008 9:15:19 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Fun Stuff | Tutorial
# Monday, January 28, 2008
Woohoo! That was a great Code Camp. Thanks to Woody and the gang for making this event happen. It was a fun and knowledge-filled event. I even got swags (a few books, a shirt, a small bag and a gym cup from Avanade)...
Monday, January 28, 2008 6:03:49 PM (GMT Standard Time, UTC+00:00)  #    Comments [1] -
.NET | All about Keith | Life | Rant | Tech News and Issues | Code Camp
# Saturday, January 26, 2008

Me and my wife will be at the Code Camp in Fullerton tommorow and we are excited. Code Camp is a great time to get together, learn new things about technology and network with people with the same mindset about technology and that is passion for learning and enriching knowledged. We are driving tonight to Fullerton so that we can be early tommorow.

There are already a few sessions that I am eyeing to go to. One of them is the session of John Bowen regarding WPF DataBinding and WPF controls. I met John Bowen 3 years ago in the .NET Rocks roadshow bus. I think this session is going to be awesome. I've been playing with alot of WPF lately and I'm interested in seeing and learning cool things about this technology.

Another session I'd love to see is the topic "Branching and Merging Guidance for VSTS 2008 and Team Foundation Server" presented by Mickey Williams. I haven't done anything with VSTS before but I know its going to be a great primer for me because merging and branching is one of the things that happens alot when you are in a team development environment.

Oh boy! This is going to be a great Code Camp. Time to go home and get ready for this event. See you there!

Saturday, January 26, 2008 1:17:37 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | All about Keith | Fun Stuff | Life | Tech News and Issues | Your Career | Code Camp
# Friday, January 25, 2008

I encountered a problem today with one of my projects. The problem was about a third-party application choking when it encounters files greater than 20MB. I have a Windows Service that creates PDFs of KPIs for around 150 users and each of the file that I generate is around 25MB each. I can compress the PDF file to lower resolution format but the management decided that we shouldn't trade quality over speed so I was stuck thinking of a different solution.

Then it came to me that I can zip the files so that I get a smaller file.

I started evaluating C# zip libraries and ended up choosing #ZipLib from the creators of SharpDevelop because of it's simplicity and robustness. The only thing I didn't like was the fact that I wasn't find a great documentation about the library. I ended up fiddling with it. It wasn't hard but you need to play with it alot to understand whats happening in the background.

Ok, now lets start by identifying what we need to create a zip file with SharpZipLib. The first thing that you need to do is download the binaries from the #ZipLib website and reference that DLL in your project.

Now that is done you need to add the ICSharpCode.SharpZipLib namespace in you source file to be able to start creating zip files using the #ZipLib library.

To start creating a zip file, all you need to do is to initialize a ZipFile object.

//initialize the file so that it can accept updates
ZipFile z = ZipFile.Create(filename);

The code above creates a new zip file with the specified filename. Next we need to call the BeginUpdate method of the ZipFile object to tell it that we are going to do some modifications to that file.

//initialize the file so that it can accept updates
z.BeginUpdate();

At this stage we can now add files to our zip file.

//add your file e.g "c:\reports\gummywhammyyummy.pdf"
z.Add(<Your file to add including it's path>);

Once you are done you need to commit  your changes and close the file.

//commit the update once we are done
z.CommitUpdate();
//close the file
z.Close();

Done. Now you have created your first zip file using #ZipLib. Neat! Below is the complete code listing of what we did above

/// <summary>
/// A method that creates a zip file
/// </summary>
/// <param name="zipFileStoragePath">the storage location</param>
/// <param name="zipFileName">the zip file name</param>
/// <param name="fileToCompress">the file to compress</param>
private void CreateZipFile(string zipFileStoragePath
    , string zipFileName
    , string fileToCompress)
{
    //create our zip file
    ZipFile z = ZipFile.Create(zipFileStoragePath + zipFileName);

    //initialize the file so that it can accept updates
    z.BeginUpdate();

    //add the file to the zip file
    z.Add(fileToCompress);

    //commit the update once we are done
    z.CommitUpdate();
    //close the file
    z.Close();
}

But what if you want to add a directory to your zip file? The ZipFile object provides a method called AddDirectory() that accepts a parameter directoryName. The problem with this method is that it doesn't add the files inside the specified directory but instead just creates a directory inside the zip file. To make this work, you need to get the files inside that directory by looping thru all objects in that directory and adding them one at a time. I was able to accomplish this task by creating a recursive function that drills through the whole directory structure of the folder you want to zip. Below is a snippet of the function.

/// <summary>
/// Creates a zip file
/// </summary>
/// <param name="zipFileStoragePath">where to store the zip file</param>
/// <param name="zipFileName">the zip file filename</param>
/// <param name="fileToZip">the file to zip</param>
/// <returns>indicates whether the file was created successfully</returns>
private bool CreateZipFile(string zipFileStoragePath
    , string zipFileName
    , FileInfo fileToZip)
{
    return CreateZipFile(   zipFileStoragePath
                        ,   zipFileName
                        ,   (FileSystemInfo)fileToZip);
}

/// <summary>
/// Creates a zip file
/// </summary>
/// <param name="zipFileStoragePath">where to store the zip file</param>
/// <param name="zipFileName">the zip file filename</param>
/// <param name="directoryToZip">the directory to zip</param>
/// <returns>indicates whether the file was created successfully</returns>
private bool CreateZipFile(string zipFileStoragePath
    , string zipFileName
    , DirectoryInfo directoryToZip)
{
    return CreateZipFile(   zipFileStoragePath
                        ,   zipFileName
                        ,   (FileSystemInfo)directoryToZip);
}

/// <summary>
/// Creates a zip file
/// </summary>
/// <param name="zipFileStoragePath">where to store the zip file</param>
/// <param name="zipFileName">the zip file filename</param>
/// <param name="fileSystemInfoToZip">the directory/file to zip</param>
/// <returns>indicates whether the file was created successfully</returns>
private bool CreateZipFile(string zipFileStoragePath
    , string zipFileName
    , FileSystemInfo fileSystemInfoToZip)
{
    return CreateZipFile(   zipFileStoragePath
                        ,   zipFileName
                        ,   new FileSystemInfo[] 
                            { 
                                fileSystemInfoToZip 
                            });
}

/// <summary>
/// A function that creates a zip file
/// </summary>
/// <param name="zipFileStoragePath">location where the file should be created</param>
/// <param name="zipFileName">the filename of the zip file</param>
/// <param name="fileSystemInfosToZip">an array of filesysteminfos that needs to be added to the file</param>
/// <returns>a bool value that indicates whether the file was created</returns>
private bool CreateZipFile(string zipFileStoragePath
    , string zipFileName
    , FileSystemInfo[] fileSystemInfosToZip)
{
    // a bool variable that says whether or not the file was created
    bool isCreated = false;

    try
    {
        //create our zip file
        ZipFile z = ZipFile.Create(zipFileStoragePath + zipFileName);
        //initialize the file so that it can accept updates
        z.BeginUpdate();
        //get all the files and directory to zip
        GetFilesToZip(fileSystemInfosToZip, z);
        //commit the update once we are done
        z.CommitUpdate();
        //close the file
        z.Close();
        //success!
        isCreated = true;
    }
    catch (Exception ex)
    {
        //failed
        isCreated = false;
        //lets throw our error
        throw ex;
    }
 
    //return the creation status
    return isCreated;
}

/// <summary>
/// Iterate thru all the filesysteminfo objects and add it to our zip file
/// </summary>
/// <param name="fileSystemInfosToZip">a collection of files/directores</param>
/// <param name="z">our existing ZipFile object</param>
private void GetFilesToZip(FileSystemInfo[] fileSystemInfosToZip, ZipFile z)
{
    //check whether the objects are null
    if (fileSystemInfosToZip != null && z != null)
    {
        //iterate thru all the filesystem info objects
        foreach (FileSystemInfo fi in fileSystemInfosToZip)
        {
            //check if it is a directory
            if (fi is DirectoryInfo)
            {
                DirectoryInfo di = (DirectoryInfo)fi;
                //add the directory
                z.AddDirectory(di.FullName);
                //drill thru the directory to get all
                //the files and folders inside it.
                GetFilesToZip(di.GetFileSystemInfos(), z);
            }
            else
            {
                //add it
                z.Add(fi.FullName);
            }
        }
    }
}

A sample usage of this function would be like this:

//sample usage for zipping a file
private void zipItButton_Click(object sender, EventArgs e)
{
    string fileToZip = fileToZipTextBox.Text;
    string zipFilename = Guid.NewGuid() + ".zip";

    //zip a file
    bool isCreated = CreateZipFile(
                                        CONST_ZIP_FILE_STORAGE
                                    ,   zipFilename
                                    ,   new FileInfo(fileToZip) );

    if (isCreated) {
        MessageBox.Show(zipFilename);
    }
    else {
        MessageBox.Show("Failed");
    }
}

//sample usage for zipping a directory
private void zipFolderButton_Click(object sender, EventArgs e)
{
    string directoryToZip = whereToZipTextBox.Text;
    string zipFilename = Guid.NewGuid() + ".zip";

    //zip a directory
    bool isCreated = CreateZipFile(
                            CONST_ZIP_FILE_STORAGE
                        , zipFilename
                        , new DirectoryInfo(directoryToZip) );

    if (isCreated){
        MessageBox.Show("Created " + zipFilename);
    }
    else{
        MessageBox.Show("Failed");
    }
}

And that's it. I hope i was able to shed light on you can create zip files in few easy steps with C#. If you are interested you can checkout this sample application that I built to demonstrate how to create zip files with C# and SharpZipLib.

Download the source code here. KeithRull.CreatingZipFiles.zip (19.15 KB)

Friday, January 25, 2008 8:59:16 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Fun Stuff | Tutorial
# Wednesday, January 23, 2008

Yesterday I wrote an article explaning what var means in .NET 3.x. Today lets talk about Anonymous Types.

Anonymous Types as describe by the C# 3.0 specification are tuple types automatically inferred and created from object initializers. Anonymous Types allows the new operator to be used with an anonymous object initializer to create an object at compile time. The format for an anonymous type declaration is a follows

var v = new { p1 = e1 , p2 = e2 , ... px = ex }

where v is the var variable, px denotes the property name and ex is equaivalent value.

Enough with the theory and lets look at some actual code. Lets assume that I have a class called Person with the following properties:

public class Person
{
    private string _name;
    private int _age;
    private bool _believesInJesus;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    public bool BelievesInJesus
    {
        get { return _believesInJesus; }
        set { _believesInJesus = value; }
    }
}

Let's say that I want to create an Anonymous Type that has a similar structure from what we have above, all I need to do is make this call:

var human = new { Name = "Keith", Age = 25, BelievesInJesus = true };

What happens in compile time is that the .NET compiler generates a class that represents the structure of your Anonymous Type.

public class __Anonymous1
{
    private string _name;
    private int _age;
    private bool _believesInJesus;

    public string Name { get { return _name; } set { _name = value; } }
    public int Age { get { return _age; } set { _age = value; } }
    public bool BelievesInJesus { get { return _believesInJesus; } set { _believesInJesus = value; } }
}

It's an  "Anonymous Type" because it a nameless class, it's generated by the compiler for you and it directly inherits from object.

To prove this let's look at this example:

class Program
{
    static void Main(string[] args)
    {
        var person = new { Name = "Keith", Age = 25, BelievesInJesus = true };

        Console.WriteLine(person.Name);
        Console.WriteLine(person.GetType());
        Console.ReadLine();
    }
}

Hovering at the person variable would give us some information about it's type:

The code above will have this output:

As you can see, the compiler created an Anonymous Type Called <>f__AnonymousType0`3. One thing to note about Anonymous Types is that the compiler is smart enough to figure out if an Anonynous Type has already been declared that meets the schema requirement of your new Anonymous Type.

    class Program
    {
        static void Main(string[] args)
        {
            var person1 = new { Name = "Keith", Age = 25, BelievesInJesus = true };
            var person2 = new { Name = "Charissa", Age = 23, BelievesInJesus = true };
            var person3 = new { Name = "Peter", Age = 23};

            Console.WriteLine(person1.Name);
            Console.WriteLine(person1.GetType());
            Console.WriteLine(person2.Name);
            Console.WriteLine(person2.GetType());
            Console.WriteLine(person3.Name);
            Console.WriteLine(person3.GetType());
            Console.ReadLine();
        }
    }

The result would be:

I hope I was able to show you what Anonymous Types are in C#. Next up is Extension Methods.

Wednesday, January 23, 2008 7:58:09 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Fun Stuff | Tutorial
Archive
<February 2008>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
2425262728291
2345678
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Keith Rull
Sign In
Statistics
Total Posts: 271
This Year: 0
This Month: 0
This Week: 0
Comments: 182
Themes
Pick a theme:
All Content © 2010, Keith Rull
DasBlog theme 'Business' created by Christoph De Baene (delarou)