Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for January, 2011

Zipping and Emailing Project – Using DotNetZip

Posted by JP on January 30, 2011

What about having a utility that zips and emails your project folder content? I agree that the source control tools provides backup. But this utility can be used to easily take the backup of your private projects at home.

The Challenge

The project folder usually contains many other folders and with different file extensions. The .Net inbuilt zipping library can be used to compress a file. But not the entire file/folder structure like winzip. There are multiple choces for creating zip files like using J#/ZipPackage/Third Party/DotNetZip framework.

The Solution

My chosen solution to zip entire folder content can be the use of DotNetZip which is an open source library for zipping. There are numerous examples available in the DotNetZip download, but we trying to create a utility that will do zipping and emailing of the given folder. This project should be extensible too.

You can download the library from url: http://dotnetzip.codeplex.com/

The Design

The project has been divided into the following parts:

  • The Application UI

clip_image002

  • The Core Library (containing folder searching, zipping, emailing classes)

clip_image004

TDD

The development of the project was gone through Test Driven Development. You can examine the unit tests generated.

Classes Explained

The core class involved here is the Zipper class:

clip_image006

The Zipper class consists of the properties:

Property

Description

Folder

The folder to zip for

ExcludeFolders

Exclude the folders from zipping

ExcludeFileExtensions

Exclude the following file extensions from zipping

AfterZipActions

Contains the action items to be performed after ipping

The Zipper class contains the Zip() method which is the core one:

The Zip() method performs the following actions:

  • Searches the Folder recursively and creates all files/folders list
  • Zip the file/folder list to a temporary file using DotNetZp
  • Performs the actions on zip file like Email, Copy etc.
  • Deletes the temporary zip file
  • Returns the size of the zip file

public bool Zip()

{

// Ensure valid folder is specified

if (!Directory.Exists(Folder))

throw new ArgumentException("Invalid Folder!");

// Get the files

var files = _searcher.GetFiles(Folder, ExcludeFolders, ExcludeFileExtensions);

// Perform zip

using (ZipFile zipFile = new ZipFile())

{

foreach (string file in files)

zipFile.AddFile(file);

// Create output zip file path

GenerateZipFilePath();

if (File.Exists(ZipFilePath))

File.Delete(ZipFilePath);

zipFile.Save(ZipFilePath);

}

// Perform actions assigned (email, copy to folder etc.)

foreach (IAction action in this.AfterZipActions)

action.Perform(this);

// Set file size for later reference

FileSize = new FileInfo(ZipFilePath).Length;

// Delete the original zip file

File.Delete(ZipFilePath);

// Return true

return true;

}

The DotNetZip’s ZipFile class is used to do the zipping operation. The associated dll can be found in the project’s Library folder.

The Extensibility Factor

The Zipper class is designed in such a way that in future the developer wanted to add a new action – it can be easily incorporated. For this purpose the IAction interface is used.

clip_image008

The interface contains the Perform() method. The IAction interface is implemented by the Emailer and Copier classes. So in future a new action is required, we can create the new class implementing the IAction interface and add to the AfterZipActions list property of the Zipper class.

Gmail for Sending Mails

As gmail is supporting smtp service, if the user is having a gmail account it would be really easier. Anyway other mail services are also supported as the mail parameters can be changed over the screen. The changes will be saved to config file back when the application exits.

Saving user preferences

The config file contains default values which can be overridden by the end user.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="LatestFolder" value=""/>

<add key="ExcludeFolders" value="obj,bin;TestResults"/>

<add key="ExcludeFileExtensions" value="*.suo;*.zip"/>

<!–Email Options–>

<add key="SenderEmail" value=""/>

<add key="SenderPassword" value=""/>

<add key="SMTPServer" value="smtp.gmail.com"/>

<add key="Recipients" value=""/>

<!–Copy Options–>

<add key="DestinationFolder" value=""/>

</appSettings>

</configuration>

The recommended usage of the utility is to add to the Visual Studio Tools>External Tools menu. This would be lot easier in zipping the project while after development.

Advertisements

Posted in WinForms | Tagged: , , | 2 Comments »

Saving an embedded file in C#

Posted by JP on January 19, 2011

Suppose you are working on an application – which needs to extract another application on runtime.  How to achieve the same?

We can start with the steps below:

Step 1: Create a new Console Application

image

Step 2: Embed an exe file inside it

For this – right click on the solution explorer window and choose “Add existing item”

image

In the appearing dialog box – type c:\windows\system32\regedt32.exe

For convenience I am using the registry editor utility of windows.

(note: if your windows folder is in different drive you have to change the above path)

image

Now you can see the file added to solution explorer.

Choose the properties of file and change the Build Action property to Embedded Resource.

image

Now build your project – if successful you are ready with an exe embedded.

Step 3: Get the embedded resource name

Now our goal is to save the embedded exe in runtime to the same application folder.  For achieving this we have to first get the embedded name of the exe file.

The embedded name of the resource file would be in the format ApplicationNameSpace.ResourceName.

In our case it is: EmbedExe.regedt32.exe

You can use the method

Assembly.GetExecutingAssembly().GetManifestResourceNames()

to get all the resource names in the assembly.

Step 4: Save the embedded resource

In this final step we are retrieving the bytes of assembly and saving into a file stream.  For this we are using Stream, FileStream classes.

The code is given below:

Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(“EmbedExe.regedt32.exe”);
            FileStream fileStream = new FileStream(“new.exe”, FileMode.CreateNew);
            for (int i = 0; i < stream.Length; i++)
                fileStream.WriteByte((byte)stream.ReadByte());
            fileStream.Close();

We can see in the output folder that the new.exe is created

image

 

Posted in C# | Tagged: , , , , | 6 Comments »

Manually install .Net 4.0 application pools

Posted by JP on January 17, 2011

If you are working in old version of IIS, you may not find the latest application pools for .Net 4.0.  This small article provides to install the missing .Net 4.0 application pools.

Manually install the .Net 4.0 Application Pools

Step 1: Open command prompt and locate the 4.0 folder

image

Step 2: Use the command “aspnet_regiis.exe –i”

image

Wait for the installation to complete.

image

Step 3: Open IIS Manager to view the pools

You can click on the Application Pools link on the left to view the installed .Net 4.0 pools

image

Posted in ASP.NET, IIS | Tagged: , , | Leave a Comment »

How to edit app.config file?

Posted by JP on January 13, 2011

The application configuration file provides flexibility in reading application settings.  But once in a while it is needed to change the settings programmatically. 

We can see how it is made possible.

Step 1: Create new Windows Forms application

Create a new windows forms application and add a config file into it.

Step 2: Add reference to System.Configuration

Add reference to System.Configuration namespace

Step 3: Add code to edit config

System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            configuration.AppSettings.Settings.Remove(“font”);
            configuration.AppSettings.Settings.Add(“font”, “Calibri”);

            configuration.Save(ConfigurationSaveMode.Modified);

Summary

For editing an existing appSettings key – we have deleted and added the key.

Posted in WinForms | Tagged: , , , , | Leave a Comment »

ColorComboBox to pick colors

Posted by JP on January 12, 2011

In this short article, I am trying to create a ColorComboBox control which allows the user to select colors from System.Drawing.Color struct. From Mahesh Chand’s color code snippet, I was inspired about the idea of listing color using reflection. So I thought it would be good if we can convert the code into a control.

Snapshot

The end control is shown in the snap shot below:

clip_image002

Steps involved in creating Control

The article is been subdivided into creating the custom combobox class and implementing the draw events.

Part 1: Create Custom ColorComboBox

For this, we have to create a new class and change the base class to ComboBox.

public class ColorComboBox : ComboBox

Part 2: Modify the constructor

We need to modify the constructor to fill the ComboBox with colors and change the draw mode.

public ColorComboBox()

{

FillColors();

// Change DrawMode for custom drawing

this.DrawMode = DrawMode.OwnerDrawFixed;

this.DropDownStyle = ComboBoxStyle.DropDownList;

}

Part 3: Implement the FillColors() method

For loading the combobox with color items, we need to use .Net Reflection. Following is the code to get all Color properties from struct Color.

private void FillColors()

{

this.Items.Clear();

// Fill Colors using Reflection

foreach (Color color in typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public).Where(c => c.PropertyType == typeof(Color)).Select(c => (Color)c.GetValue(c, null)))

{

this.Items.Add(color);

}

}

For reduction of code I have used Lambda Expressions. Basically the code will iterate through all the properties which are static and public, then the Where() method will filter them by type of Color. The Select() method converts the PropetyInfo to Color object using c.GetValue() method.

Part 4: Custom Draw the control

Now we are good with the entire color items in the list. The next challenge is to display the item with the actual color filled in a rectangle and showing the color name next to it.

For this we have to override the OnDrawItem method of combobox.

protected override void OnDrawItem(DrawItemEventArgs e)

{

if (e.Index >= 0)

{

Color color = (Color)this.Items[e.Index];

int nextX = 0;

e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);

DrawColor(e, color, ref nextX);

DrawText(e, color, nextX);

}

else

base.OnDrawItem(e);

}

Whenever the ComboBox item is painted the above OnDrawItem() method will be called. We basically checks whether the e.Index >= 0 to ensure there is a valid item in the list and do the custom drawing.

The drawing is divided into 3 steps.

1. Paint the Background

2. Draw the Color

3. Draw the Text (color name)

Part 5: Add Property to get selected color

Now we need to add a new property to get/set the selected color.

public Color Color

{

get

{

if (this.SelectedItem != null)

return (Color)this.SelectedItem;

return Color.Black;

}

set

{

int ix = this.Items.IndexOf(value);

if (ix >= 0)

this.SelectedIndex = ix;

}

}

The above get code will return the selected color by converting selected item into Color struct.

The set code will allow us to set the selected color by taking the set value and iterating through the items in the combobox.

Using the Code

The attachment contains the ColorComboBox as well as the test form. For reusing the control, one may take the ColorComboBox file alone and can be integrated to other projects.

Posted in C# | Tagged: , , , | Leave a Comment »

What is Host Header and how to configure it?

Posted by JP on January 11, 2011

 

Host Header is a third piece of information to identify a web site.

Thus the web site can be identified by using the following:

    • IP Address
    • Port
    • Host Header

Host Headers was introduced in HTTP 1.1

Eg: http://www.google.com

www.google.com is the host header

Configuration in IIS

We can configure host header in IIS using inetmgr application.

After configuration we need to publish the host header in the WINS (Windows Name Service) or DNS (Domain Name Service) depending on the site is an intranet or internet site.

Posted in ASP.NET, IIS | Tagged: , , | Leave a Comment »

Serialize and Zip in one step

Posted by JP on January 1, 2011

Once in a while it is needed that we need to serialize a particular object and zip it.  Here I am combining both the operations into one method.  The associated unit tests are also provided.

Source

public class SerializeNZip
{
    public void SerializeAndZip(object obj, string zipFileName)
    {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());
        MemoryStream stream = new MemoryStream();
        serializer.Serialize(stream, obj);
        stream.Position = 0;

        FileStream fileStream = File.Create(zipFileName);
        GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

        byte[] buffer = new byte[4096];
        int numRead;
        while ((numRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            gzipStream.Write(buffer, 0, numRead);
        }

        gzipStream.Dispose();
        fileStream.Dispose();
    }

    public T UnzipAndDeserialize<T>(string zipFileName)
    {
        FileStream compressedStream = new FileInfo(zipFileName).OpenRead();
        MemoryStream destinationStream = new MemoryStream();
        GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress);
        byte[] buffer = new byte[4096];

        int numRead;

        while ((numRead = gzipStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            destinationStream.Capacity += numRead;
            destinationStream.Write(buffer, 0, numRead);
        }

        gzipStream.Dispose();
        compressedStream.Dispose();

        destinationStream.Position = 0;

        XmlSerializer deserializer = new XmlSerializer(typeof(T));
        T result = (T)deserializer.Deserialize(destinationStream);

        return result;
    }
}

Invoking

[TestMethod()]
public void UnzipAndDeserialize_List_Test()
{
    SerializeNZip target = new SerializeNZip();
    List<Person> list = new List<Person>();
    list.Add(new Person() { Id = 1, Name = "TestName1" });
    list.Add(new Person() { Id = 2, Name = "TestName2" });

    target.SerializeAndZip(list, "c:\\ser2.zip");

    List<Person> actual = target.UnzipAndDeserialize<List<Person>>("c:\\ser2.zip");

    Assert.IsNotNull(actual);
    Assert.AreEqual(2, actual.Count);
    Assert.AreEqual(1, actual[0].Id);
    Assert.AreEqual(2, actual[1].Id);
    Assert.AreEqual("TestName1", actual[0].Name);
    Assert.AreEqual("TestName2", actual[1].Name);
}

public class Person
{
    public int Id
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

Posted in C# | Tagged: , , , | Leave a Comment »