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