Tuesday, October 17, 2006

Remoting vs XML Web Services


So which to use?

They share alot of similarities but also alot of differences.

XML Web services built using cross-platform standards based on xml messaging. The are execute by the ASP.NET runtime thus gaining ASP.NET features like output caching. An important point is that it is fundamentally stateless. The best uses for XML web services is when cross platform boundaries or trust boundaries are required.

Remoting is a .NET specific technology for building distributed objects. It supperceeds DCOM. Perfect for in-house systems that need to communicate and are built using the same .NET platform. It allows for different types of communication, such as sharing binary messages to lean TCP/IP connections. If you want stateful objects and bidirectional communication via callbacks then this is your technology. It also allows you to send custom .NET objects over the wire.
Object Instantiation with Reflection


So i need to instantiate objects at runtime. Whats the best way of doing this? Reflection !

What you need to do is obtain the Type object representing the type of object you want to instantiate then call the Type.GetConstructor method. This will give you the System.Reflection.ConstructorInfo that represents the constructor you want to use. Then execute the ConstructorInfo.Invoke method.


Code : sample

----Type type = typeof(StringBuilder);
----Type[] argTypes = new Type[] {typeof(System.String), typeof(System.Int32);}

----ConstructorInfo cInfo = type.GetConstructor(argTypes);

----object[] argVals = new object[] {"something", 30};
----StringBuilder sb = (StringBuilder) cInfo.Invoke(argVals);
Application Domain Creation



This feature lets you isolate your application safely from others. Load assemblies into your application domain and if it dies it wont kill anything else!

Use SystemAppDomain.CreateDomain.

Sample Code:

----AppDomainSetup sup = new AppDomainSetup();

----sup.ApplicationBase = @"c:\RootDir";
----sup.ConfigurationFile = "test.Config";
----sup.PrivateBinPath = "bin;external;";

----AppDomain newDom = AppDomain.CreateDomain("A new domain", null, setupInfo);


** Once you've created the application domain you need to keep a reference to it as there is no known method of getting a list of created application domains.
Serializable object to a file


Simple steps, take a deep breath and follow this list carefully. Its not as hard as it may sound!

Use a formatter to serialize the object and write it to the System.IO.FileStream object.

formaters available:

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
System.Runtime.Serialization.Formatters.Soap.SoapFormatter

example:

public static void BinarySerialization(ArrayList list){
--using (FileStream str = File.Create("stuff.bin")){
----BinaryFormatter bf = new BinaryFormatter();
----bf.Serialize(str, list);
--}
}


public static ArrayList BinaryDeserialization(){
--ArrayList stuff = null;
--using (FileStream str = File.OpenRead("stuff.bin")){
----BinaryFormatter bf = new BinaryFormatter();
----stuff = (ArrayList)bf.Deserialize(str);
--}
--return stuff ;
}
Sorting an Array/ArrayList


So you have an array with alpha elements that you want sorted?

Use the ArrayList.Sort or Array.Sort its that simple

As long as the array contains elements that are of datatypes that implement the IComparable interface then it can be sorted. The basic datatypes all support this interface!

So what happens if some of the elements don't support this interface? You must pass the Sort method to an object that implements the System.Collections.IComparer interface.
Manipulating a string into a DateTime


This is a common requirement in any application, this is what ive come across on my projects!

Date manipulation is very sensitive, there will always be the exception to the rules where a querky solution is required however ill list what worked for me..

Example dates "1/6/2005", "6/1/2005", "1-Jun-2005", "1st June 2005"

I use the DateTime.Parse function. Its a cool function but it does substitute current date values for missing or erroneous values. eg. if your missing the year it will use the current year. The default missing/eroneous time elements default to 12:00:00am. It is a flexible function that makes assumptions...

If you want to be specific and not use the defaults then use the DateTime.ParseExact. The IFormatProvider parameter is used to provide culture-specific information. If the IFormatProvider is null then it uses the current threads culture information.

If there is a format issue it will throw the System.FormatException


Code: Sample

DateTime dt1 = DateTime.Parse("Sep 2005");

DateTime dt2 = DateTime.ParseExact("Mon, 05 Sep 2005 14:13:30 GMT", ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", null);
Convert to a Byte Array

If you need to convert a basic value type to a byte array then you've come to the right place..

The System.BitConverter class provides a cool mechanism for this conversion process.

The exception is the decimal value type, use the System.IO.MemoryStream object.

System.BitConverter.GetBytes returns the conversion as an array of bytes. It is overloaded to take many datatypes. It also contains static methods to convert from a byte array to a datatype.

For decimals --> ByteArray use System.IO.BinaryWriter then use the MemoryStream.ToArray.

For ByteArray --> Decimal use the System.IO.BinaryReader



Code : Decimal to ByteArray


public static byte[] ConvertDecimalToByteArray(decimal src){
--using(MemoryStream stream = new MemoryStream()){
----using(BinaryWriter writer = new BinaryWriter(stream)){
------writer.Write(src);
------return stream.ToArray();
----}
--}
}


Code: ByteArray to Decimal

public static decimal ConvertByteArrayToDecimal(byte[] src){
--using(MemoryStream stream = new MemorStream(stc)){
----using (BinaryReader reader = new BinaryReader(stream)){
------return reader.ReadDecimal();
----}
--}
}


Code: Other Datatypes to Byte Array

byte[] b =null;

b=BitConverter.GetBytes("THIS IS A STRING");
BitConverter.ToString(b);
Reverse String Function


This is a simple reverse string function that uses the StringBuilder class optimizing resources..



public static string ReverseString(string str){

if(str == null str.Length <= 1){
return str;
}

StringBuilder revStr = new StringBuilder(str.Length);

for(int count=str.Length-1; count>-1;count--){
revStr.Append(str[count]);
}

return revStr.ToString();

}
Efficient String Content Manipulation


Abstract

String objects are immutable which means that manipulations of such objects results in automatic string creations (huge memory overheads).

To overcome this overhead use the System.Text.StringBuilder class for string manipulations then when your done convert the result to a String object using the StringBuilder.ToString().

Detail

Immutable String objects mean that once created their content cannot be changed.

eg. concatenating String objects results in new String objects created whenever new elements are added to the existing string.

The overhead can exponentially increase as the number of string manipulations goes up.

The StringBuilder class offers a solution by providing a "buffer of characters" allowing you to do complex manipulations without the need for new objects being created.

Capacity tells us the size of the buffer

Length tells us the length of the current content.

If the length of the data where manipulating exceeds the capacity then a new buffer needs to be allocated. This can negate the benefits of the StringBuilder class, so take care in defining the capacity. [Default capacity is 16]

MaxCapacity tells us the maximum size of allocation. There may be issues if the size is greater than 2GB. Ensure that the Capacity does not exceed the MaxCapacity.


TIPS

Capacity is set to less than Length, System.ArgumentOutOfRangeException is thrown.

Capacity is set to something greater than MaxCapacity, System.ArgumentOutOfRangeException is thrown

Length is set to something less than the current content then the content is truncated.

Length is set to something greater than the current content then buffer is padded with spaces to meet the length.

Length is set to something greater than the Capacity then Capacity is automatically reset to the new value. Capacity will equal Length.