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 . “);
}
}
}

How to Transform A DataSet using Xml and Xslt in .Net 2.0

// Creating DOM Document
XmlDocument doc = new XmlDocument();

// Get hold of the XML string from the dataset
doc.LoadXml(ds.GetXml());

//Load XSL and Tranform
XslCompiledTransform myXslTrans = new XslCompiledTransform();
string path = Directory.GetCurrentDirectory();
myXslTrans.Load(path + @”PrintView.xslt“);

// Using a StringWriter for Streaming part
StringWriter stringWriter = new StringWriter();

// The actual transformation
myXslTrans.Transform(doc.DocumentElement, null, stringWriter);
stringWriter.Flush();

// Consuming the transformed results
webBrowser1.Document.Write(stringWriter.ToString());

//doc.Save(“Example.xml”);

Merging Menu and Toolbar to MDI Form

I have a form that it is used both stand alone and within an MDI from. When used in an MDI form I wanted to move the menu’s and toolbars to the shared placed on the MDI form whereas using it on a standalone case I had no option than having it on the owner form.

To establish this behavior I had to implement the activate and deactivate methods to make the toolstrip and menu strip, which hold the toolbar items and menu items, invisible and move the items to the new container. This is a stait forward solution as illustrated below:


private void OnFormActivate(object sender, EventArgs e)
{
try
{
// Get the parent
Form parent = this.MdiParent;
if (parent == null)
return;

// Get the toolbar on the parent by name
string targetToolbar = "toolStrip"; // using the name of the control
if (!parent.Controls.ContainsKey(targetToolbar))
return;
ToolStrip target
= parent.Controls[targetToolbar] as ToolStrip;
if (target == null)
return;

ToolStripManager.Merge(
this.toolStrip1, target);

// Hide the original container
this.toolStrip1.Visible = false;
this.menuStrip1.Visible = false;
SetToolbarCaption();
}
catch { } // Any exception will cause the toolbar to remain on its oroginal parent
}
private void OnFormDeactivate(object sender, EventArgs e)
{
try
{
// Get the parent
Form parent = this.MdiParent;
if (parent == null)
return;

// Get the toolbar on the parent by name
string targetToolbar = "toolStrip";
if (!parent.Controls.ContainsKey(targetToolbar))
return;

// Double check
ToolStrip target = parent.Controls[targetToolbar] as ToolStrip;
if (target == null)
return;

// Actual Merge Revert of the contents of the toolStrip
ToolStripManager.RevertMerge(target, this.toolStrip1);

// Keep hiding the original container
this.toolStrip1.Visible = false;
}
catch { }
}

All I need to do next is to wire these events to the propper events: FormActivate and Deactivate.

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.