Dec 1, 2008

Dynamically creating types using reflection and setting properties using Reflection.Emit.

I came across a requirement where we needed to create types dynamically based on XML Configuration files, so that in the furture new types are required we dont need to update the application again by creating a new class.
The additional requirement was to populate the property names of the class based on the Cml configuration and its values using the Querystring values from the HttpWebRequest.
I earlier thought about using Dynamic methods from .NET Framework 2.0, but that did not fit my purpose since I didn't need to execute methods from the dynamic type that was created.

So here is the code:
I created three helper methods
1. Generates the AssemblyBuilder and Module Builder objects
2. Generates the TypeBuilder object.. which will be used for generating an instance of the dynamic type using Activator.CreateInstance
3. Create properties using Relection.Emit
   1: public class DynamicType
   2: {
   3:  
   4:     public static AssemblyBuilder asmBuilder = null;
   5:     public static ModuleBuilder modBuilder = null;
   6:     public static void GenerateAssemblyAndModule()
   7:     {
   8:         if (asmBuilder == null)
   9:         {
  10:             AssemblyName assemblyName = new AssemblyName();
  11:             assemblyName.Name = "DWBeacons";
  12:             AppDomain thisDomain = Thread.GetDomain();
  13:             asmBuilder = thisDomain.DefineDynamicAssembly(
  14:                          assemblyName, AssemblyBuilderAccess.Run);
  15:             modBuilder = asmBuilder.DefineDynamicModule(
  16:                          asmBuilder.GetName().Name, false);
  17:         }
  18:     }
  19:  
  20:     public static TypeBuilder CreateType(ModuleBuilder modBuilder, string typeName)
  21:     {
  22:         TypeBuilder typeBuilder = modBuilder.DefineType(typeName,
  23:                     TypeAttributes.Public |
  24:                     TypeAttributes.Class |
  25:                     TypeAttributes.AutoClass |
  26:                     TypeAttributes.AnsiClass |
  27:                     TypeAttributes.BeforeFieldInit |
  28:                     TypeAttributes.AutoLayout,
  29:                     typeof(object));
  30:         return typeBuilder;
  31:     }
  32:  
  33:  
  34:     public static void CreateProperty(TypeBuilder t, string name, Type typ)
  35:     {
  36:         string field = "_" + name.ToLower();
  37:         FieldBuilder fieldBldr = t.DefineField(field, typ, FieldAttributes.Private);
  38:         PropertyBuilder propBldr = t.DefineProperty(name, PropertyAttributes.HasDefault, typ, null);
  39:         MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  40:  
  41:         MethodBuilder getPropBldr = t.DefineMethod("get_" + name, getSetAttr, typ, Type.EmptyTypes);
  42:  
  43:         ILGenerator getIL = getPropBldr.GetILGenerator();
  44:         getIL.Emit(OpCodes.Ldarg_0);
  45:         getIL.Emit(OpCodes.Ldfld, fieldBldr);
  46:         getIL.Emit(OpCodes.Ret);
  47:  
  48:         MethodBuilder setPropBldr = t.DefineMethod("set_" + name, getSetAttr, null, new Type[] { typ });
  49:  
  50:         ILGenerator setIL = setPropBldr.GetILGenerator();
  51:  
  52:         setIL.Emit(OpCodes.Ldarg_0);
  53:         setIL.Emit(OpCodes.Ldarg_1);
  54:         setIL.Emit(OpCodes.Stfld, fieldBldr);
  55:         setIL.Emit(OpCodes.Ret);
  56:  
  57:         propBldr.SetGetMethod(getPropBldr);
  58:         propBldr.SetSetMethod(setPropBldr);
  59:  
  60:     }
  61:  
  62: }



Then to use these helper methods from the Main program I used the following:

   1: if (DynamicType.asmBuilder == null)
   2:     DynamicType.GenerateAssemblyAndModule();
   3: finalType = DynamicType.modBuilder.GetType("Beacon11");
   4:  
   5: TypeBuilder tb = DynamicType.CreateType(DynamicType.modBuilder, typeName);
   6:  
   7: foreach (XElement e in beaconNode.Descendants())
   8: {
   9:     string pname = e.Attribute("qs").Value;
  10:     string ptype = e.Attribute("type").Value;
  11:     DynamicType.CreateProperty(tb, pname, Type.GetType(ptype));
  12: }
  13: finalType = tb.CreateType();
  14:  
  15: Object obj = Activator.CreateInstance(finalType);
  16: // this sets the properties of the just instantiated class
  17: finalType.InvokeMember("bv", BindingFlags.SetProperty, null, data, new object[] { 1.0 });
  18: finalType.InvokeMember("tp", BindingFlags.SetProperty, null, data, new object[] { 2.0 });
  19: //this sets the properties of the type by using values from the querystring
  20: foreach (XElement e in beaconNode.Descendants())
  21: {
  22:     string pname = e.Attribute("qs").Value;
  23:     object value = context.Request.QueryString[pname];
  24:     finalType.InvokeMember(pname, BindingFlags.SetProperty, null, data, new object[] { value });
  25: }


For more information visit : msdn - PropertyBuilder

kick it on DotNetKicks.com

Nov 18, 2008

Schedule a task using C# code

I needed to schedule a task to run every day at 9:00 p.m. in the night. I had an addition al requirement that the task be scheduled only if the FileSystemwatcher alerts us of new files being available for processing.

Thus the files could be recieved anytime during the day, but despite that the task should be schduled to run exactly at 9:00 p.m. in the night.

So I used the following code to schedule a task(using System.Threading.Timer and TimeSpan classes)

DateTime d = DateTime.Now;

timer = new Timer(new TimerCallback(Update), null,
TimeSpan.FromMinutes(21 * 60 - (d.Hour * 60 + d.Minute)),
TimeSpan.FromMilliseconds(-1));


Note I used TimeSpan.FromMillisecnods(-1) to disable periodic signalling

kick it on DotNetKicks.com

Nov 13, 2008

Compare 2 SQL queries for equality

DECLARE @check1 bigint
DECLARE @check2 bigint

Select @check1 = CHECKSUM_AGG(CHECKSUM(*))
FROM
(
SELECT *
FROM dbo.Orders (nolock)
)
AS Source

Select @check2 = CHECKSUM_AGG(CHECKSUM(*))
FROM
(
SELECT *
FROM dbo.Orders (nolock)
WHERE IsSuccessful = 1
)
As Comparison

IF @check1 = @check2
PRINT 'Queries are Equal'
ELSE
PRINT 'Queries are NOT Equal'


Note:
If order of rows is different it will not effect the result
It does not do execution plan comparisons, simply checks if the rows returned by the two queries are the same or not

More info

kick it on DotNetKicks.com

Nov 12, 2008

Converting SQL2005 DBTimeStamp to Long for Comparison (Convert from Hex to long and decimal to Hex)

If you need to Convert SQL 2005 DB TimeStamp values to Long then follow these steps:
1. Retrieve the DB TimeStamp value in a Byte Array (8 bytes long).
2. Convert the byte array into a Hexadecimal string
3. Convert the hexadecimal string to a long
private long BytesToLong(byte[] bytes)
{
string ts = null;
foreach (byte b in bytes)
ts += b.ToString("X").PadLeft(2,Convert.ToChar("0"));
return Convert.ToInt64(ts, 16);
}


There is another method to convert the DBTimeStamp to Long, but I dont prefer this method since it can return negative values. The method is:

1. Retrieve the DB TimeStamp value in a Byte Array (8 bytes long).
2. Use BitConverter class to convert the byte array into long
long result = BitConverter.ToInt64(dbTimestamp, 0); 

Inorder to remedy this use the following to generate the same long value as in step 1:


public static long FromDbTimestamp(byte[] dbTimestamp)
{
long result = 0;
if (dbTimestamp != null)
{
Array.Reverse(dbTimestamp);
result = BitConverter.ToInt64(dbTimestamp, 0);
}

return result;
}

Finally to convert a long into the correct DBTimeStamp use this:

public static byte[] ToDbTimestamp(long timestamp)
{
byte[] result = BitConverter.GetBytes(timestamp);
Array.Reverse(result);
return result;
}

kick it on DotNetKicks.com

Oct 13, 2008

Passing state to threads via anonymous calls

We already know that we can pass state into to Threads in 2 ways:

1. using ParameterizedThreadStart delegate

2.using global variables(reference or value types) accessible to the main thread as well the instantiated thread. This is also the way to share data amonst multiple threads. Infact the most common way to share data between threads is using static variables where application wide scope is desired.

3.using Thread.QueueUserWorkItem ... This differs from Parameterized ThreadStart delegate since it uses threads from a preconfigured ThreadPool instead of manually creating threads

There is another cool method to pass information to threads is via anonymous methods. For e.g.
static void Main
{
string mainMessage = "Hello from Main !!!";
Thread t = new Thread(delegate() { Print(mainMessage);});
t.Start();
}
static void Print(string message)
{
Console.Writeline(message);
}

Advantage of using this technique is that, it provides strongly typed access to the parameters passed to the thread. The Target Method can accept any number of arguments, and no casting is required (unlike Parameterized Start where the passed state is an “object”) . The flip side, though, is that you must keep outer-variable semantics in mind

kick it on DotNetKicks.com

Sep 26, 2008

Method Hiding... Polymorphism in C#

In the following code:

interface IBand
{
int ID {get;set;}
string Name {get;set;}
void GetStatus();
}
public class Band : IBand
{
public int ID { get; set; }
public string Name { get; set; }

public Band()
{
GetStatus();
}
public void GetStatus()
{
ID = 555;
Name = "Ring";
Console.WriteLine("Base Class Called");
}
}

public class ABand : Band, IBand
{
public string Update { get; set; }

public ABand() : base() {}

public new void GetStatus()
{
ID = 655;
Name = "TEsst";
Update = "ddd";
Console.WriteLine("Derived class Called");
}
}
class Program
{
static void Main(string[] args)
{
IBand band = new ABand();
band.GetStatus();
}

}

We have 2 classes, Band and ABand which implement the IBand interface explicitly.

Now the call to band.GetStatus in Main will display "Derived class called". This will only happen if the Derived class (ABand) also implements the interface IBand explicitly (not in the literal sense in that it does not implement the methods using the IBand.GetStatus syntax)

If the ABand class does not implement the IBand interface explicitly (but implicitly since it inherits from Band which implements IBand) then the above code will output "Base class called"

However note one thing, that when the CTor for ABand is invoked it will invoke the ctor Band class and which will call GetStatus() method from within Band class hence this will output "Base class called" even though the ABand class has implemented the IBand interface explicilty.

kick it on DotNetKicks.com

Sep 9, 2008

Linq To XML : Check for existence of an element

var bookQuery = 
from book in bookXml.Descendants("Item")

let attributes = book.Element("ItemAttributes")

let price = Decimal.Parse((
book.Elements("OfferSummary").Any()
&& book.Element("OfferSummary").Elements("LowestNewPrice").Any()
? book.Element("OfferSummary").Element("LowestNewPrice").Element("Amount").Value
: (attributes.Elements("ListPrice").Any()
? attributes.Element("ListPrice").Element("Amount").Value
: "0"))) / 100

select new {Price = price};


The trick is to use the Elements(“node”) instead of Element(“node”) and then use the Any() function which will return true if an element of that name exists.

Some other LINQ tips:

Some of the extensions that one can use are Intersect,Union && Except
var list1 = new List<int> { 2, 4, 9, 11, 3, 6 };
var list2 = new List<int> { 3, 8, 4, 30, 9, 16 };
var newlist = list1.Intersect(list2);

This returns : 3,4,9
newlist = list1.Union(list2);
this returns : 2,3,4,6,8,9,11,16,30. finally
newlist = list1.Except(list2);
returns : 2,11,6

kick it on DotNetKicks.com

Aug 26, 2008

Convert Array of Ints into bytes

Here is the code to convert array of Ints to bytes:

int[] source = ids.ToArray();
int length = source.Length * 4;
byte[] dest = new byte[length];
System.Buffer.BlockCopy(source, 0, dest, 0, dest.Length);

kick it on DotNetKicks.com

Jul 25, 2008

Alternating styles in ListView- without AlternatingItemTemplate

From within any template, you have access to the current index of the row within the whole data set, using Container.DataItemIndex, and within the currently displayed items, using Container.DisplayIndex. This gives us an easy way to alternate styles:

<ItemTemplate>
<li class="<%# Container.DisplayIndex % 2 == 0 ? "even" : "odd" %>">
<%# Eval("Name") %>
</li>
</ItemTemplate>


Just define the even and odd classes in your stylesheet and you're pretty much done.

kick it on DotNetKicks.com

Jul 24, 2008

Batch Inserts to SQL Server- Stored procedure method

To do batch Updates to SQL server

  • Create DataTable or DataSet and populate it with required rows
  • Next Create a SqlCommand and SqlDataAdapter using that SqlCommand
  • Remember to set the UpdateRowSource property on the Command the the appropriate value
  • Set the UpdateBatchSize Property on the SqlDataAdapter
  • then call SqlDataAdapter.Update(dt) to push the updates to SQL server
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("asin"));
dt.Columns.Add(new DataColumn("trackasin"));
dt.Columns.Add(new DataColumn("isrc"));
for(int i =0; i < 2000;i++)
{
DataRow dr = dt.NewRow();
dr["asin"] = asin;
dr["trackasin"] = trackasin;
dr["isrc"] = isrc;
//dr.RowState = DataRowState.Added;
dt.Rows.Add(dr);
}
------------------------------------------------
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MySpaceMusic"].ConnectionString))
{
SqlCommand command = new SqlCommand(INSERT_TRACK, connection);
command.CommandType = CommandType.StoredProcedure;
command.UpdatedRowSource = UpdateRowSource.None;
command.CommandTimeout = commandTimeout;

command.Parameters.Add("@asin", SqlDbType.VarChar, 255, dt.Columns[0].ColumnName);
command.Parameters.Add("@trackAsin", SqlDbType.VarChar, 255, dt.Columns[1].ColumnName);
command.Parameters.Add("@isrc", SqlDbType.VarChar, 600, dt.Columns[2].ColumnName);

SqlDataAdapter adpt = new SqlDataAdapter();

adpt.InsertCommand = command;
adpt.UpdateBatchSize = batchSize;
try
{
connection.Open();
int recordsInserted = adpt.Update(dt);
}
finally
{
adpt.Dispose();
}
}


kick it on DotNetKicks.com

Jul 3, 2008

क्यूट सोंग .. नानी तेरी मोरनी को मोर ले गए

Naani Teri Morni Ko Mor Le Gaye
Baaki Jo Bacha Tha Kaale Chor Le Gaye

Khaake Peeke Mote Hoke,
Chor Baithe Rail Mein
Choron Vaala Dibba Kat Ke, Pahuncha Seedhe Jail Mein

Naani Teri Morni Ko...

Un Choron Ki Khoob Khabar Li,
Mote Thaanedaar Ne
Moron Ko Bhi Khoob Nachaaya,
Jungal Ki Sarkaar Ne

Naani Teri Morni Ko...
Achhi Naani Pyaari Naani,
Roosa-Roosi Chhod De Jaldi Se Ek Paisa De De,
Tu Kanjoosi chod de...

Nani teri morni ko chor le gaye
baaki jo bacha tha kaale chor le gaye

kick it on DotNetKicks.com

May 6, 2008

Unity Application block and Generic Singleton

Here are some features of the Unity Application block. (Note there is overhead in using this block… i.e. overhead while creating instances of objects that have dependent objects)

http://msdn.microsoft.com/en-us/library/cc440954.aspx

  Highlights of the Unity Application Block

The Unity Application Block includes the following features:

· It provides a mechanism for building (or assembling) instances of objects, which may contain other dependent object instances.

· It exposes RegisterType methods that support configuring the container with type mappings and objects (including singleton instances) and Resolve methods that return instances of built objects that can contain any dependent objects.

· It provides inversion of control (IoC) functionality by allowing injection of preconfigured objects into classes built by the application block. Developers can specify an interface or class type in the constructor (constructor injection) or apply to properties and methods attributes to initiate property injection and method call injection.

· It supports a hierarchy for containers. A container may have child container(s), allowing object location queries to pass from the child out through the parent container(s).

· It can read configuration information from standard configuration systems, such as XML files, and use it to configure the container( The Unity Container which hold references to the objects built using Resolve method).

· It makes no demands on the object class definition. There is no requirement to apply attributes to classes (except when using property or method call injection), and there are no limitations on the class declaration.

· It supports custom container extensions that developers can implement; for example, methods to allow additional object construction and container features such as caching.

And here is the code for the Generic Singleton:

/// <summary>
/// Provides a Singleton implementation using Generics.
/// </summary>
/// <typeparam name="T">Type of singleton instance</typeparam>
public sealed class Singleton<T> where T : new()
{
Singleton() { }
public static T Instance
{
get
{ return Nested.instance; }
}

class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() { }
internal static readonly T instance = new T();
}
}


The code for returning the instance then becomes:



        public static BlogSettings Instance
{
get
{
return Utils.Singleton<BlogSettings>.Instance;
}
}

You have to also change the constructor for BlogSettings to public to allow this this to work

kick it on DotNetKicks.com

Apr 30, 2008

Debugging Win Service

For debugging a Startup of Windows Service add the call to the Method Debugger.Launch or Debugger.Break. This call can be placed in the Constructor of the Service.cs or in the first line of the OnStart() method.

Calling Debugger.Launch() or Debugger.Break() in your code allow you to debug such problems.

For debugging an already running WindowService, simply attach the Debugger to to an existing process using "Debug\Attach to Process" menu item in VS 2005/VS 2008.


Visual Linq is a tool to visually create your Linq to SQL queries: http://code.msdn.microsoft.com/vlinq


A Primer on WCF :

It is all about Service Contracts, Operation Contracts, Data Contracts and Fault Contracts and other type of Contracts

Contracts usually enforced on Interfaces and the Classes then implement these interfaces.

If Service Contract, Operation Contract attributes are applied to classes then we have an additional advantage that the methods can be marked private and can still be accessed by WCF clients.

DataContracts are used to create .NET objects that can be sent to/fro between the client and the WCF Service. thus the DataMember attribute tells the runtime which properties need to be serialized/deserialized by the framework before being passed onto the network.

We dont need DataContracts for Intrinsic objects like Int32, string etc since they are natively serializable

FaultContracts can be applied to methods and can be used by the Client to determine what exceptions occurred at the server during processing of the request. Thus .NET exceptions are converted to FaultExceptions which are then sent over the wire as SOAP faults and then the client can reconstruct them to extract the Fault Detail from the FaultException

A good introduction to WCF can be found here: David Chappell's intro to WCF

Bindings and endpoints form the heart of WCF, we can have different kinds of bindings,

  • BasicHTTPBinding which allows Http and HTTPS access.
  • WSHttpBinding which adds the WS specifications to the binding to provide for reliability, transactions, security and other features.
  • WSDualHttpBinding: use this for two-way communication between client and service, only HTTP is supported
  • FederatedBinding: which means that if authenticated by one of the services, then the same ticket can be used to authenticate the client to other WCF/Java services
  • NETTCPBinding : used when communicating using TCP protocol as the transport
  • NamedPipeBinding: used within the local machine for inter process communication on the same machine.

Endpoints define how the service can be accessed by the client. Each WCF Service exposes endpoints to clients to publicize their services. Specify a different endpoint for each binding used by your service, thus the same machine can expose the service over HTTP and TCP using basicHttpBinding and NetTcpBinding respoectively and thus exposing endpoints for each of them. Endpoints consist of address, behavior etc

John Sharp's WCF Step by Step from Microsoft Press is an excellent book to get started.

kick it on DotNetKicks.com

Apr 6, 2008

Get back almost 1GB of free disk space after Vista SP1 installation

If you have installed SP1 of Vista you certainly recognized that your drive lost around 1Gb of free space.

The solution is to use a tool that comes with the SP1 to recover your free space at the price of not being able to come back and uninstall the SP1.

This tool is vsp1cln.exe that you can run like this:

vistasp1

kick it on DotNetKicks.com

Mar 27, 2008

Add Windows Explorer to your Visual Studio tools menu

.NET Tip of The Day: Add Windows Explorer to your Visual Studio tools menu

kick it on DotNetKicks.com

Mar 3, 2008

Concurrency and Co-ordination Runtime - CCR

Pretty cool Library from Microsoft for performing concurrent operations like multithreading operations and async tasks. Essenitally you get a guide to migrate all your APM ( Asynchronous Programming Model) tasks to the CCR tasks so that synchronization and co-ordination issues are automatically handled for you behind the scenes.

Some of the good links on CCR are:

kick it on DotNetKicks.com

Feb 8, 2008

ASP.NET State Server and Load Balancer

These are great links:
ASP.NET load balancing and ASP.NET state server (aspnet_state)

Session state ...State Server

kick it on DotNetKicks.com

Jan 9, 2008

How to check email works with no SMTP

There is a way to send e-mails with no SMTP server set up. Just configure your .NET application to drop e-mails into a specified folder instead of sending them via SMTP server


  <system.net>

    <mailSettings>

      <smtp deliveryMethod="SpecifiedPickupDirectory">

        <specifiedPickupDirectory pickupDirectoryLocation="c:\Rohit\" />

      </smtp>

    </mailSettings>

  </system.net>



This will instruct SmtpClient class to generate mail message, save it as .eml file and drop it into c:\Test\ folder

kick it on DotNetKicks.com

Jan 8, 2008

Using CompareValidator for just Data Validation

A simple method to validate an integer, double, date, or currency values entered into a textbox on ASP.NET page

Normally the CompareValidator is used to check one value against another on ASP.NET page. However it also can be used to ensure user has entered data in a correct format. (Data Validation)

Here's how it works:

  • Set the ControlToValidate property to the ID of the TextBox.
  • Set the Operator property to DataTypeCheck.
  • Assign a ValidationDataType enumeration member to the Type property, which includes either one of the following : String, Integer, Double, Date, and Currency.

kick it on DotNetKicks.com

Jan 3, 2008

using FOR XMLPATH to concat multiple row values

The need is to concatenate multiple row values from a table
The following TSQL in SQL 2005 can assist in returning values

Following is the input table
ID Value
---------
1 '-'
1 'C'
1 'B'
1 'A'
2 '='
2 'G'
2 'D'
=======
Expected output :
ID Concat
1 '-CBA'
2 '=GD'
=================

TSQL for this :
select Distinct ID, o.List
from
#t1 A
CROSS APPLY
(
select Val as [text()] from #t1 B
where B.ID = A.ID
FOR XML PATH('')
) o (List)

kick it on DotNetKicks.com