Monday, 7 April 2008

WPF and Silverlight to the rescue

At last WPF and Silverlight technologies are giving some lights to web devs. It was always a challenge to develop rich media enabled applications using Microsoft technologies. Although Adobe flash was quite popular, but using ASP.NET to develop rich and interactive applications was always a challenging task. Thanks to WPF, Silverlight and AJAX technologies, which have changed the way how the web applications are developed.

Infragistics have developed a sample WPF app called NetAdvantage. Give it a go.. it's worth trying the app online. Truly a different experience.

http://xamples.infragistics.com/2007.2/xamShowcase.xbap 

Some screen shots running in IE and Firefox.

image

image

Saturday, 5 April 2008

Tuesday, 25 March 2008

Singleton pattern in C# 3.0

While I was going through some of the new features of C# 3.0, I thought why not implement Singleton pattern using automatic properties. Honestly, I hated declaring private fields and then encapsulate those vars in public properties. Automatic properties makes life easier and moreover a good readable code base with no cluttered private fields and public properties tied around.

The example shown below is an implementation of Singleton pattern in C# 3.0 specifically uses automatic properties.

public sealed class Singleton
{
public static Singleton Instance
{
get; private set;
}

static Singleton()
{
Instance = new Singleton();
}

private Singleton() { }

public void InstanceMethod()
{
Console.Write("Instance method invoked on type {0}", Instance.ToString());
Console.WriteLine("Are objects equal: {0} ", this == Instance);
}
}

Automatic properties: see the new feature and syntax in action. I have declared a static Instance property which doesn't use any underlying private field. The C# compiler takes care of generating the old style getter and setters. Note that I have used private access modifier for setter. A constraint on automatic properties is to define both get and set, otherwise the compiler will not be happy. Ok we can define that but I don't want my clients to use my setter, so I can specify the private access modifier and so only I can consume within the class scope.

Saturday, 22 March 2008

Compression and Base64 Encoding in .NET 2.0 and Java platforms.

Introduction

Distributed Enterprise applications typically involve heterogeneous platforms where different layers would be developed using heterogeneous technologies and frameworks. The co-existence and communication between the layers adds to the complexity of the application being developed. The applications will suffer from poor performance when huge amount of data is transferred across layers. This article discusses the usage of message compression technology that can be used in .NET 2.0 and Java based applications to decrease the size of message transferred which increases the overall performance and response time.

Distributed scenario

In this article we will consider a scenario where the client application is a .NET 2.0 smart client which forms the presentation layer. The business layer is developed using the Java technology which includes any business logic required by the presentation layer. The Business Service layer is responsible for responding to .NET client application queries. The Business Service receives requests from the client in the form of Xml messages, performs the necessary processing which may involve interaction with the database and sends the results back to the client in the form of xml messages. The data is transferred across the layers in the form of Xml messages.

The pictorial representation of this scenario is shown below:

Picture-1

Figure - 1

The key factor here is to define the contract between the Client and the Business Service and both parties can understand what each other are talking about. This can be achieved with the help of Xml schema where we define the strict contract for request and response messages.

Request and Response Interface

We will define a simple request and response interface schema that will be used by the .NET client and the Java Business service to construct the Xml data. Both request and response interfaces defines CompressedBase64Clob which is a xs:base64Binary data type. This clob structure holds compressed and base 64 encoded data that can be transferred across layers.

The schema representation is shown below:

Picture-2

Figure - 2

The code snippets for compression and decompression further described in this article don’t consider the intricacies of populating and reading Xml files. An Xml interface is defined in order to give an overall picture and the practical scenario where the message compression can be used.

Compression and Encoding stuffs

Both and .NET and Java have defined Compression packages as part of their libraries which can be used in client and server applications. This article describes compression and decompression of data using GZip implementation. The .NET has implemented GZip in System.IO.Compression.GZipStream class and the Java counter part is present in java.util.zip package. The description of how the GZip algorithm and any implementation are outside the scope of this article.

Encoding is the process of transforming information from one format into another. The opposite operation is called decoding [source: Wikipedia]. In this article we will be using Base64 encoding before the data is being transferred from the client to the Business service and vice versa.

The term "Base64" refers to a specific MIME content transfer encoding. It is also used as a generic term for any similar encoding scheme that encodes binary data by treating it numerically and translating it into a base 64 representation. The particular choice of base is due to the history of character set encoding: one can choose 64 characters that are both part of the subset common to most encodings, and also printable. This combination leaves the data unlikely to be modified in transit through systems, such as email, which were traditionally not 8-bit clean. MIME Base64 uses A–Z, a–z, and 0–9 for the first 62 digits [source: Wikipedia].

Both .NET and Java have standard way of converting to and from Base64 representation.

.NET 2.0 way of Compression and Decompression with Base64 encoding

System.IO.Compression namespace defines GZipStream class which consists of methods and properties to compress and decompress streams. In this article a utility class NCompressor is defined which exposes methods to compress and decompress the data in base64 encoded format.

Class Diagram

The class diagram for NCompressor is given below:

Picture-3

Figure - 3

NCompressor is a static class which exposes methods CompressToBase64String() and DecompressFromBase64String() for compressing and decompressing data.

CompressToBase64String

The code snippet shown below details compressing a string and then encoding the compressed byte array in Base64 format.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Compression
{
public static class NCompressor
{
private static int MAX_BUFFER_SIZE = 1024;

private static byte[] Compress(byte[] byteArray)
{
MemoryStream inputMemoryStream = new MemoryStream(byteArray);
MemoryStream outputMemoryStream = new MemoryStream();;
byte[] compressedBuffer = null;

using (GZipStream outputGZipStream = new GZipStream(outputMemoryStream, CompressionMode.Compress))
{
byte[] buffer = new byte[MAX_BUFFER_SIZE];
int bytesRead = -1;

while ((bytesRead = inputMemoryStream.Read(buffer, 0, MAX_BUFFER_SIZE)) > 0)
{
outputGZipStream.Write(buffer, 0, bytesRead);
}
}
compressedBuffer = outputMemoryStream.ToArray();

if (outputMemoryStream != null) { outputMemoryStream.Close(); }
if (inputMemoryStream != null) { inputMemoryStream.Close(); }

return compressedBuffer;
}

public static string CompressToBase64String(string data)
{
return Convert.ToBase64String(Compress(Encoding.UTF8.GetBytes(data)));
}
}
}

Code snippet - 1

CompressToBase64String() is a public method which accepts the data in string format. This method calls the private Compress() method to actually compress the byte stream. The string can be converted to byte stream using the Encoding class and with the appropriate encoding that is used in the application. In this instance, I have used UTF8 encoding since the xml data by default uses UTF8 encoding.

Once we have the byte representation of the string, the MemoryStreams are used in order to read and write the compressed data to and from memory. This can be easily tweaked to write into any other stream but this example uses memory stream for illustrative purpose. Create an instance of the GZipStream class pointing to the output memory stream with the Compress as its mode which indicates that the byte array must be compressed. Read the byte array in chunks of 1024 bytes from the InputMemoryStream and write it to the GZipStream which will be stored in the OutputMemoryStream and can be accessed later once the GZipStream is finalised. Once we’re done with reading and writing the source byte array, the compressed buffer can be retrieved from the OutputMemoryStream after the GZipStream is closed. Note that without closing the GZipStream, if any attempt is made to retrieve the compressed byte array would result in invalid data being read which can’t be decompressed later. This is behaviour is by design and Microsoft BCL team claims that the required footer information would be written and the compression will be finalised only after the GZipStream is closed. Finally, the compressed buffer is converted to Base64 representation using Convert.ToBase64String().

DecompressFromBase64String

This process is the reverse of compression where the compressed base64 string representation is passed to retrieve the original string data. The code snippet for decompression is shown below:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Compression
{
public static class NCompressor
{
private static int MAX_BUFFER_SIZE = 1024;

private static byte[] Decompress(byte[] byteArray)
{
MemoryStream inputMemoryStream = new MemoryStream(byteArray);
MemoryStream outputMemoryStream = new MemoryStream();
byte[] decompressedBuffer = null;

using (GZipStream inputGZipStream = new GZipStream(inputMemoryStream, CompressionMode.Decompress))
{
byte[] buffer = new byte[MAX_BUFFER_SIZE];
int bytesRead = -1;

while ((bytesRead = inputGZipStream.Read(buffer, 0, MAX_BUFFER_SIZE)) > 0)
{
outputMemoryStream.Write(buffer, 0, bytesRead);
}
}

decompressedBuffer = outputMemoryStream.ToArray();

if (inputMemoryStream != null) { inputMemoryStream.Close(); }
if (outputMemoryStream != null) { outputMemoryStream.Close(); }

return decompressedBuffer;
}

public static string DecompressFromBase64String(string base64String)
{
return Encoding.UTF8.GetString(Decompress(Convert.FromBase64String(base64String)));
}
}
}

Code snippet - 2

DecompressFromBase64String() is a public method which accepts the compressed and base64 encoded string. This method calls the private Decompress() method by passing the byte array from the base64 string. This uses Convert.FromBase64String() to convert the base64 representation to the byte array format.

Similarly how the compression makes use of MemoryStreams and GZipStream, the decompression method also uses memory and GZip stream in the same way except that it tells the GZipStream to decompress the data instead of compressing it.

Java way of Compression and Decompression with Base64 encoding

Package java.util.zip defines GZIPInputStream and GZIPOutputStream classes which exposes methods to compress and decompress streams. In this article a utility class JCompressor is defined which exposes methods to compress and decompress the data in base64 encoded format.

Class Diagram

The class diagram for JCompressor is given below:

Picture-4

Figure - 4

This example uses Base64 class which is defined in java.util.prefs package. This class is not visible outside the package but the source code is available which can be included in applications. However, make sure no copy right being violated before copying the source code. Any similar implementation of Base64 should also serve the purpose.

compressAndBase64Encode

The code snippet shown below details compressing a string and then encoding the compressed byte array in Base64 format.

package Compression;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public final class JCompressor {

private static final int MAX_BUFFER_SIZE = 1024;

private JCompressor() {
// Prevent instantiation
}

public static String compressAndBase64Encode(String data) throws IOException {
byte[] unCompressedBytes = data.getBytes();
byte[] compressedBytes = compress(unCompressedBytes);
String base64EncodedString = Base64.byteArrayToBase64(compressedBytes);

return base64EncodedString;
}

private static byte[] compress(byte[] unCompressedBytes) throws IOException {

ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream out = new GZIPOutputStream(bos);

ByteArrayInputStream in = new ByteArrayInputStream(unCompressedBytes);

byte[] buf = new byte[MAX_BUFFER_SIZE];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();

out.finish();
out.close();

byte[] compressedBytes = bos.toByteArray();
return compressedBytes;
}
}

Code snippet - 3

compressAndBase64Encode() is a public method which accepts the data in string format. This method calls the private compress() method to actually compress the byte stream. The string can be converted to byte stream using the getBytes() method from the String class.

This piece of code looks very similar to the compression code written in .NET except that we have different streams for writing and reading the compressed data. ByteArrayOutputStream and GZipOutputStream combination is used to compress the data. Once we have the compressed buffer, Base64.byteArrayToBase64() method is used to convert the compressed byte array into Base64 string representation.

base64DecodeAndUncompress

The code snippet shown below details decompressing a compressed base64 string and then encoding the compressed byte array in string format.

package Compression;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public final class JCompressor {

private static final int MAX_BUFFER_SIZE = 1024;

private JCompressor() {
// Prevent instantiation
}

public static String base64DecodeAndUncompress(String base64EncodedCompressedString) throws IOException {

byte[] compressedBytes;
compressedBytes = Base64.base64ToByteArray(base64EncodedCompressedString);
byte[] unCompressedBytes = unCompress(compressedBytes);

return new String(unCompressedBytes);
}

private static byte[] unCompress(byte[] compressedBytes) throws IOException {

ByteArrayInputStream instream = new ByteArrayInputStream(compressedBytes);

GZIPInputStream in = new GZIPInputStream(instream);
ByteArrayOutputStream out = new ByteArrayOutputStream();

byte[] buf = new byte[MAX_BUFFER_SIZE];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();

out.close();

// turn the compressed stream into a string
byte[] unCompressedBytes = out.toByteArray();
return unCompressedBytes;
}
}

Code snippet - 4

base64DecodeAndUncompress() is a public method which accepts the compressed base64 string parameter. This method calls the private unCompress() method to actually decompress the byte stream. The base64 string is converted to byte stream using the Base64.base64ToByteArray() method from the Base64 class.

This piece of code looks very similar to the decompression code written in .NET except that we have different streams for writing and reading the decompressed data. ByteArrayInputStream and GZipInputStream combination is used to decompress the data. Once we have the decompressed buffer, a new string representation is constructed from the decompressed buffer before returning to the caller.

Conclusion

The compression and decompression solution can be implemented in distributed scenarios where we can avoid huge amount of data being transferred across the network clogging most of the bandwidth. Also if there are any messaging frameworks like MSMQ or JMS involved in transferring the messages, they suffer from performance problems in transferring huge amount of data across the network. By compressing the required data we can achieve performance improvements and reduce bandwidth usage considerably. The approach described in this article uses memory streams for compressing and decompressing the data. If the request and response Xml messages are huge, server side applications may suffer from memory related issues and hence memory stream approach may not be the optimal one. Any alternate approach which involves storing/flushing the data to the disk at appropriate intervals may need to be considered. The environment, data size and any constraints must be thoroughly analysed before implementing this solution.

Custom Configuration Sections in .NET 2.0

Introduction

This article details how to create custom configuration sections in Microsoft .NET Framework 2.0 based applications. .NET 2.0 introduces a new namespace System.Configuration to handle application configuration files. This namespace exposes several classes to work with configuration files. The ConfigurationManager is a static class in the System.Configuration namespace which is most widely used to access any application settings, connection strings, section groups and custom sections. This also exposes methods to open and access configuration files other than the default application configuration file (ie .exe.config, .dll.config, web.config).

Configuration File

A sample configuration file snippet is shown below. This article describes how to build custom configuration section for the configuration file shown below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="application">
<section name="settings" type="Configurator.BaseConfigurationSection, Configurator"/>
</sectionGroup>
</configSections>

<application>
<settings description="Key value pair settings">
<keys>
<add key="key1" value="value1"/>
<add key="key2" value="value2"/>
<add key="key3" value="value3"/>
<add key="key4" value="value4"/>
<add key="key5" value="value5"/>
</keys>
</settings>
</application>
</configuration>

Code snippet - 1

Class design

The class diagram shown below gives a high level picture of the classes involved in creating the custom configuration section. The inheritance hierarchy is also shown to highlight all the participant classes from the System.Configuration namespace and their usage whilst creating the class model.

clip_image002[4]
Figure - 1

A typical configuration file will have the following structure.

<sectionGroup>
<section atribute=”id>
<element1/>
<element2/>
<element3/>
</section>
</sectionGroup>

Code snippet - 2

A sectionGroup element groups all the custom section entries. It can have multiple sections for which the section handler has to be defined in the code in order to access individual section entries. Based on the application’s requirement one has to judge the groupings and the hierarchies that should go within the configuration file. A typical section group would include application level settings. Eg: application constants, User interface mappings, file paths etc.

The primary concentration here is to create a custom configuration section and how to access it from the application. The above configuration file snippet provides the structure for a configuration section. It can have attributes and nested elements as part of the declaration.

Class Definition

System.Configuration namespace has an abstract class ConfigurationElement which represents a configuration element within a configuration file. Both ConfigurationSection and ConfigurationElementCollection abstract classes inherit from ConfigurationElement class. The following configuration entry can be represented as an instance of a class derived from the ConfigurationElement.

<add key="key1" value="value1"/&gt

Code snippet - 3

We can define the following class structure to represent the above configuration snippet.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace Configurator
{
public class BaseConfigurationElement : ConfigurationElement
{
public BaseConfigurationElement() : base() { }

[ConfigurationProperty("key", IsRequired = true)]
public string Key
{
get { return (string) base["key"]; }
}

[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)base["value"]; }
}
}
}

Code snippet - 4

The BaseConfigurationElement class inherits the ConfigurationElement abstract class. This class exposes two properties which represents key and value attributes which are declared as part of the <add/> element. The mapping between the property name and the actual configuration file entry is established by declarative attribute attached to the property. This tells the run time that the property Key must be associated to the xml attribute key from the configuration file.

We have now defined the ConfigurationElement which holds key value pairs. What if we need to hold to multiple key value pairs? This can be achieved with the help of collection classes. ConfigurationElementCollection class is an abstract class within the System.Configuration namespace which represents the collection of configuration entries. Since this is an abstract class, we need to inherit from this class and provide definition for the protected members and associate the collection to the configuration element.

Configuration collection snippet:

<keys>
<add key="key1" value="value1"/>
<add key="key2" value="value2"/>
<add key="key3" value="value3"/>
<add key="key4" value="value4"/>
<add key="key5" value="value5"/>
</keys>

Code snippet - 5

To represent the above structure, we need to create collection class which holds <add> elements. The class definition is shown below:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace Configurator
{
public class BaseConfigurationElementCollection<T> : ConfigurationElementCollection where T : ConfigurationElement, new()
{
public BaseConfigurationElementCollection() : base() {}

public T this[int index]
{
get { return (T) base.BaseGet(index); }
}

protected override ConfigurationElement CreateNewElement()
{
return new T();
}

protected override object GetElementKey(ConfigurationElement element)
{
return (T)element;
}
}
}

Code snippet - 6

The BaseConfigurationElementCollection<T> is defined as a class which accepts T as its generic parameter and inherits from the ConfigurationElementCollection abstract class. Note that the base class is not a generic type and we are introducing the generic type T which represents the ConfigurationElement. This also defines constraint on T that it should be of any type derived from the ConfigurationElement and must define a public parameterless constructor. This class provides an indexer to access ConfigurationElement objects from the collection. Methods CreateNewElement() and GetElementKey() must be overridden and the definition has to be provided; otherwise this class also becomes an abstract class which can’t be instantiated directly. The reason for introducing the genric type T is to ensure that we can use the same collection class for representing collection of elements which are derived from the ConfigurationElement.

Now, we are done with our collection class and let’s use this collection within in a section class. ConfigurationSection is an abstract class defined in the System.Configuration namespace which represents a configuration section. We are defining the BaseConfigurationSection class which inherits the ConfigurationSection abstract class. The BaseConfigurationSection exposes properties to access data defined within this section.

The configuration file and the class definition snippets are shown below:

<settings description="Key value pair settings">
<keys>
<add key="key1" value="value1"/>
<add key="key2" value="value2"/>
<add key="key3" value="value3"/>
<add key="key4" value="value4"/>
<add key="key5" value="value5"/>
</keys>
</settings>

Code snippet - 7

The class definition for BaseConfigurationSection is shown below:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace Configurator
{
public class BaseConfigurationSection : ConfigurationSection
{
public BaseConfigurationSection() : base() {}
[ConfigurationProperty("description")]
public string Description
{
get { return (string) this["description"]; }
}

[ConfigurationProperty("keys")]
public BaseConfigurationElementCollection<BaseConfigurationElement> Keys
{
get
{
return (BaseConfigurationElementCollection<BaseConfigurationElement>) this["keys"];
}
}
}
}

Code snippet - 8

The BaseConfigurationSection exposes properties to read the collection of key value pairs and the attribute which is declared as part of the section element in the configuration file. Note the association of these properties to the actual configuration entries is established through the declarative ConfigurationProperty attribute.

We are now done with our infrastructure required to access the custom configuration entry. We’ll now define the main program to read these values and display on the console.

The main program:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace Configurator
{
class Program
{
static void Main(string[] args)
{
BaseConfigurationSection settings = (BaseConfigurationSection)ConfigurationManager.GetSection("application/settings");

Console.WriteLine(settings.Description);
foreach(BaseConfigurationElement element in settings.Keys)
{
Console.WriteLine("Key: {0} Value: {1}", element.Key, element.Value);
}

Console.ReadKey();
}
}
}

Code snippet - 9

The console output:
clip_image002

Figure - 2

Conclusion

The Microsoft .NET Framework 2.0 has rich infrastructure to work with application configuration files. The custom configuration section handlers can be defined to read and write the data from the configuration sections. I have tried to make these classes as generic classes and so if there is any requirement to define multiple section groups and sections, these classes can be used as base classes to further provide the appropriate functionality.

Friday, 14 March 2008

My first blog entry :)