Tuesday, October 30, 2007

Cannot modify members of 'item' because it is a 'foreach iteration variable'

 I had a compile time issue with using my custom list. The code simply looks like the following:


foreach (ItemType item in listOfItems)

    item.CustomAccessor = "value";


And compiler complains with error:

            Cannot modify members of 'item' because it is a 'foreach iteration variable'


This is because the ItemType is defined as a  struct and not as a class. Doing so the iteration of foreach will result to some copies of the heap that are not reflecting the real objects. The question that has often been asked is why did you define your ItemType as struct and not as a class.... which I will answer it in other discussion.


Thursday, October 25, 2007

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>
static void Main(string[] args)
if (args.Length <2)

// 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>
Console.WriteLine("Exemple: Zipper.exe ..\test.zip . ");

Thursday, October 18, 2007

Abstract versus Interface

An article on the MSDN describes a summary of both the definitions. Although the article is a bit old (2003) and it compares C# with C++ it still provides a good start.

On the Code Project I found a nice article written by Rahman Mahmoodi where her has a nice comparisson for these two definitions. Another article on the Code Project which seems even more in dept about abstract class is written by Jayababu.

Some important points about Abstract classes

· In contrary to other object oriented languages like JAVA, you can not inherit from more than one abstract class

· you can not instanciate them or you get a Compiler Error

· An abstract class may have a non-abstract constructor implementation.

· they might have (also) non-abstract methods having implementation. these non-abstract methods are callable from the

abstract class AbstractClass
public void NonAbstractMethod()
You can call a non-abstract method which is implemented within the abstract method.");

· You can reimplement the non-abstract method but it would be called by the class internally or any object of that type. If you define an object of abstract type and you instanciate the derived class you still call the implementation within the abstract class. To get the reimplementation you need to instanciate the class using a reference of type of the derived class. For example defining the following in the derived class:

public new void NonAbstractMethod()
This is new implementation of the non-abstract method.");

and calling it like this

// Will call the original implementation
AbstractClass obj = new InheritedClass();

// Will call the re-implementation
InheritedClass obj2 = new InheritedClass();

· In your derrived class you need to ovreride all the abstract methods.

public override void OverrideThis()
You have to implement an abstract method using the override key");

· An abstract method can not be marked as static, compile error.

· You can have static and non-static fields in an abstract class:

public static int count = 1;
public int InstCount = 1;


but when instanciating two objects of the derived class and verify the value of the fields:

Console.WriteLine("Static field is " + AbstractClass.count);
Instance counter is " + obj1.InstCount);
Instance counter is " + obj2.InstCount);


Static field is 3
Instance counter is 2
Instance counter is 2

The Differences

· An inheritted class cannot have multiple base classes: compiler error.

· An abstract class can define a default implementation (using a non-abstract method) and that will not force the derived classes to reimplement it whereas an interface can not have any implementation at all.

· Interfaces can not contain fields; compile error.

· An interface is like a contract. Once the contract changes all the classes implementing it need to change whereas an abstract class is like a common code for all the classeds and you might introduce the new method as a non-abstract method and give a default implementation. This could be seen as a pro or con. In some situations it is required to force all the contract holders to apply on the new method and in other cases you want to have this new feature for some of the types while the rest migh follow later. (a good question would be why is the new method part of the abstract class and not introduced as a new contract)


Tuesday, October 16, 2007

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

//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);

// Consuming the transformed results


Attributes to consider applying when writing a custom control

The original author published this : Eilon Lipton's Blog


Almost every custom control has at least one additional public property, and that public property as well as the control itself should probably have at least a few attributes applied to them. Attributes tell the designer host (Visual Studio) or the parser (ASP.NET) interesting things about your control that might not be evident from just its name and its type. Launch any decent class browser tool and you'll see that every control that shipped in ASP.NET and ASP.NET AJAX has several attributes on it as well as their properties and events.

By applying the proper set of attributes you can significantly increase the usefulness of your control in several ways. For example, the DescriptionAttribute provides helpful text to the person designing the page. The ValidationPropertyAttribute is required when the person designing the page wants to validate the value of your control. Following is a list of the most useful and important attributes you can apply to your control and its properties and events.

Control attributes:

  • ControlValueProperty
     - Used by data source parameters to get the "intrinsic" value of the control. For example, DropDownList's "intrinsic" value is its SelectedValue property.
  • DefaultEvent
     - Set the event for which to create an event handler when double clicking the control in the designer.
  • DefaultProperty
     - Set the default selected property in the designer's property grid.
  • NonVisualControl
     - Hide the control at design time when "Non Visual Controls" is unchecked from the View menu.
  • ParseChildren
     - The full name is really "parse children as properties".
     - Set to true if the inner contents of the control represent properties as opposed to child controls.
     - True by default on controls deriving from WebControl; false by default otherwise.
  • PersistChildren
     - The full name is really "persist child controls".
     - Set to true if the designer should persist child controls as the inner contents.
     - False by default on controls deriving from WebControl; true by default otherwise.
     - 99.9% of the time PersistChildren has the opposite value of ParseChildren.
  • SupportsEventValidation
     - Indicates that the control's client-side calls to __doPostBack() should be validated on the server for security purposes.
  • Themable
     - Indicates that by default all the control's properties can be customized via themes. Individual properties can also be marked with this attribute to override the behavior.
     - True by default for controls that derive from WebControl.
  • ValidationProperty
     - Required when a control can be validated.
     - Somewhat similar to the ControlValueProperty in that they often point at the same property.
  • ViewStateModeById
     - Indicates that viewstate should be loaded based on control IDs as opposed to being loaded based on the index of the control in the child controls collection.

Property attributes:

  • Bindable
     - Indicates at design time only whether the property should appear by default in the Edit Databindings dialog.
  • Browsable
     - Indicates whether the property is visible in the property grid at design time.
  • Category
     - Determines in which category the property will appear when the property grid is in category mode.
  • DefaultValue
     - Get-only property: Since get-only properties are never persisted anyway, no default value is needed.
     - Get/Set value type property: Must be set.
     - Get/Set reference type property: Must be null so that it shows up as non-bold in the property grid.
  • Description
     - Determines the help text that will show in the property grid's lower help panel.
  • DesignerSerializationVisibility
     - Controls whether the property is persisted in the markup (see also PersistenceMode).
     - Use this to prevent get/set properties from being persisted at all.
  • EditorBrowsable
     - Affects whether the property appears in Intellisense.
  • IDReferenceProperty
     - Specifies that the property represents a control ID, and optionally the type of the target control. Not used by Visual Studio 2005.
  • MergableProperty
     - Affects whether the property shows up in the property grid when multiple controls are selected.
     - If the property is Browsable and is a reference type then set Mergable=false (except immutable reference types, such as string).
  • PersistenceMode
     - Controls how the property is persisted in the markup.
     - Simple-valued properties should use the default, which is Attribute.
     - Collection, template, and complex (e.g. styles) should use InnerProperty.
     - InnerDefaultProperty should never be used since it causes compatibility problems. For example, if in the next version of your control you want another inner property, it won't work properly.
     - EncodedInnerDefaultProperty should also rarely be used for similar reasons as InnerDefaultProperty.
     - In ASP.NET 2.0 support was added for strings to be InnerProperties, which is good for large multi-line string values, such as XmlDataSource's Data property.
  • Themable
     - Overrides the value of the attribute on the control to determine whether the property can be customized via themes.

Event attributes:

  • Browsable
     - Same as properties.
  • Category
     - Same as properties.
  • Description
     - Same as properties.
  • EditorBrowsable
     - Same as properties.