Blog Archives

TPL Task Parrallel Library .net 4.0 parallel programming multi thread threading task queue user work item

//simple parallel function call
Parallel.Invoke(() => somefunc1(), () => somefunc2());

//parallel foreach with two lists
new List<List> tasks = new List<List>()
{
  new List() { new DataSource1ProcessorA() },
  new List() { new DataSource2ProcessorA(), new DataSource2ProcessorB() }
}

Parallel.ForEach(tasks, (items) =>
{
    foreach (var item in items)
    {
        item.GetData();
        item.Process();
    }
});

//new task static factory method approach
Task.Factory.StartNew(() => { data.GetData(); data.Process(); })
.ContinueWith(t => Logger.Error("An exception occurred while processing. Check the inner exception for details", t.Exception),
TaskContinuationOptions.OnlyOnFaulted);

//explicit object oriented
   // Create a task and supply a user delegate by using a lambda expression. 
        Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
        // Start the task.
        taskA.Start();
        // Output a message from the calling thread.
        Console.WriteLine("Hello from thread '{0}'.", 
                          Thread.CurrentThread.Name);
        taskA.Wait();

//using task run
  Thread.CurrentThread.Name = "Main";
      // Define and run the task.
      Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA."));
      // Output a message from the calling thread.
      Console.WriteLine("Hello from thread '{0}'.", 
                          Thread.CurrentThread.Name);
      taskA.Wait();

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

(added 20121023 good comprehensive resource with illustrative examples)
http://www.codeproject.com/Articles/362996/Multi-core-programming-using-Task-Parallel-Library

http://www.codeproject.com/KB/threads/ParallelTasks.aspx

Optimize Managed Code For Multi-Core Machines
http://msdn.microsoft.com/en-us/magazine/cc163340.aspx

good blog
http://www.codethinked.com/net-40-and-systemthreadingtasks

queueuserworkitem
http://msdn.microsoft.com/en-us/library/4yd16hza.aspx

threadpool class
http://msdn.microsoft.com/en-us/library/y5htx827.aspx

task class
http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx

task parrallelism
http://msdn.microsoft.com/en-us/library/dd537609.aspx

How to: Use Parallel.Invoke to Execute Parallel Operations
http://msdn.microsoft.com/en-us/library/dd460705.aspx

C# Event Handlers and Delegates in ASP .Net with Web User Controls

This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.

Dilemma:
Page contains user control which has some methods and functionality built in. When a particular button click or other generic event is fired in the user control, it needs to call back to the parent page.

Solution:
Create event handlers and their delegates in the user control, fire them from the methods tied to the internal controls protected events, and define the methods that will handle the new events in the page (see code below).

C# (with some VB notes):

//delegate declaration not necessary in VB
 public delegate void MyCustomHandler(object sender, EventArgs e);
    public event MyCustomHandler SomethingClicked;

    protected void btnButton1_Click(object sender, EventArgs e)
    {
//tell our parent page which is listening for the event that something was clicked
//this null check and method invoke is the equivalent of raise event in VB
        if (SomethingClicked != null)
        {
            SomethingClicked(sender, e);
        }

//do some other work specific to this button in the user control
    }


That’s the code for your user control, now for the page.

 protected void Page_Load(object sender, EventArgs e)
    {

        MyUserControl1.SomethingClicked += new MyUserControl1.MyCustomHandler(MyUserControl1_SomethingClicked);
        

        if (!Page.IsPostBack)
        {
            //do my other normal work
        }

    }

    protected void MyUserControl1_SomethingClicked(object sender, EventArgs e)
    {
//voila! clicking on the button in your user control will fire this method on the parent page!
    }

Alternatively instead of declaring your own delegate, you can also simply use:

//in control
public event EventHandler SomethingClicked;

//and in page load
MyUserControl1.SomethingClicked+= new EventHandler(MyUserControl1_SomethingClicked);

If you have no need for custom arguments, this a good quick alternative that may be well liked by VB users where delegate declaration is optional.

References
DeveloperFusion, http://www.developerfusion.com/article/2137/event-handling-in-net-using-c/3/
VBForums, http://www.vbforums.com/showthread.php?t=521089
MSDN (events and delegates), http://msdn.microsoft.com/en-us/library/17sde2xt%28v=vs.71%29.aspx
MSDN (dynamically bind event handlers), http://msdn.microsoft.com/en-us/library/t3d01ft1%28v=vs.80%29.aspx
MSDN (which control raised an event), http://msdn.microsoft.com/en-us/library/zk6b17bs%28v=vs.80%29.aspx
ASP.Net (blog), http://weblogs.asp.net/rweigelt/archive/2005/01/14/353333.aspx
TechRepublic, http://www.techrepublic.com/article/simplify-net-class-communication-with-delegates/1050214
Akadia, http://www.akadia.com/services/dotnet_delegates_and_events.html

The type initializer threw an exception

In case this error seems to appear out of thin air in your application, this is usually an indication that a variable declared in one of your classes (likely a static class) is having trouble getting or setting it’s value.

You likely may already be frustrated since the reason for this error is not always apparent, but never fear, it is probably your variables fault. :)

If you drill down further into this error through the exception stack trace, you can actually see the details where it is breaking, but if you’re looking for a fix without having to step through a lot of code, continue reading.

The usual culprit I find for this error is in older code heavily utilizing many static classes which have class variables used instead of properties (<.<). Since it’s not a property, you can’t set breakpoints within the getter/setter, and setting a breakpoint on the variable itself will not work either.

You are basically left with two different approaches you can take to resolve the problem:

1st Approach:
Set your values for class variables in an initializer method.

This will allow you to see where the exception is actually occurring and also give you greater control over each variable’s initial value (such as conditional logic to control the initial value dynamically) which you might need later on or already be implementing in some other method early in the process flow.

2nd Approach (best IMO):
Change all class variables to properties, go object instance instead of static and add try/catch exception handling in the initializer or getter/setter.

This will also allow you to see where the exception is occurring and still give you the same degree of control over initial value without having the mess of a long initialization function if you would prefer to keep everything in the getter/setter.

Brief Note: In the examples below, a “third approach” would technically work also where the logic causing the failure is simply corrected, however, especially in the case of large conditional blocks, point of failures in future iterations is not always predictable at the time of development. If you’re doubting this, and think your logic is always soundproof, read up on Alan Turing. ;)

Example class (this should compile):

static class someappclass1 {
static string appname = "My Cool App";
static string shortappname = shorten(appname);
static string devname = "Ronnie Diaz;"
static string appversion = "1.0.0";
static string lastupdated = "2011/04/28";
static string programfilespath= Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\";
static string apppath = programfilespath + appname; //assuming you installed app first

static void dosomemethod()
{
}

static string shorten(string value) {
int maxlen = 6;
if (value.Length < 6) {maxlen = value.Length;}
value += value.Replace(" ",""); //remove all spaces
return value.SubString(0,maxlen).ToUpper(); //return short DOS compatible name
}
}

Doesn’t look too bad right? Conditional logic checks to make sure substring doesn’t throw an exception if appname is too short. On first run this should compile np.

Now you might be thinking, It is generally never a good idea to initialize any class or static variables using functions, and if you’re thinking this then you are definitely right, but keep in mind just because the function is user defined, it is just as likely you could encounter this issue using a function built in to .Net.

Additionally, in many cases, the “initial state” of a class/obj may be dependent on factors that are not constant and require lookup or calculation (see warehouseproduct class for real world example of such a case).

Can you find the flaw in the code above?

Change appname to a couple different values and in many cases it will work. Lets say your boss takes notice of your app and decides “Cool” is unprofessional and should be removed. NP you say, and with a couple keystrokes, voila! “My Cool App” is now just plain old “My App”. Compile…run.. wait, what happened?

Hint: It’s hiding on line 14.

Since the length of the appname is checked prior to the replacement of the whitespace, the resulting return value is shorter than the upper range of the maxlen variable when substring is calculated. Doh!

But you might be thinking, what kind of bad dev would make this mistake? Well consider this..

In this code example, if it was converted from some ancient VB .Net project which used “Left” instead of “SubString” the issue would not occur, making the problem seem like your conversion skills rather than the previous dev’s poor code structure.

Lesson to learn here: be careful taking shortcuts! If you’re new, it’s OK, this happens.. but if you’re experienced, shame shame!

(If you were using regression testing btw you would catch this problem early, but that is a discussion for another day… ;) )

That was easy…

Wait! Don’t stop reading yet! This is about more than just fixing a bug or exception in .Net that happened out of nowhere, it’s about coding fundamentals :).

So you might be thinking: “That code example was simple, I can fix that NP!.. Move line 14 up one, (between 12 and 13) and voila!”

Well, this would work, but it would form poor programming habits.. Why? Take a look at the alternative example below.

static class warehouseproductname {
static string product_name = "somename";
static string product_internalid = "someguid";

//dimensions as well as other subtypes below could of course be subclassed.. but for purposes of simplicity in this blog kept within same class for user readability in the example
static int product_dimensions_height = "someheight";
static int product_dimensions_width = "somewidth";
static int product_dimensions_squarefootage = product_height*productwidth;
static bool product_dimensions_issquare = (product_height==product_width) ? true:false;
static bool product_dimensions_isrectangular (product_dimensions_issquare==true) ? true:false;

static string vendor_id = lookup_vendor_id(internalid);
static string vendor_name = lookup_vendor_name(vendor_id);

static string warehouse_id = lookup_warehouse_id(internalid,vendorid);
static string warehouse_name = lookup_warehouse_name(warehouse_id);

//etc..
}

A type initializer exception would be much harder to debug in this example… Instead of narrowing it down to 1 of 2 functions, you’re now potentially stepping through to find 1 of 6 functions that could be broken.

See now why this would be a bad habit to make early on? :P

Once you get to the above scenario, you should already be planning how you’re going to convince whoever you need that a major recoding needs to take place..

I would avoid discussing the details of OOP with the higher ups, they tend to interpret it as… O.O, but hopefully if you’re still reading you have realized this is what needs to happen here.

The Solution

(finally)

1st approach using first example class:

static class someappclass2 {
static string appname = ""'
static string shortappname = "";
static string devname = "";
static string appversion = "";
static string lastupdated = "";
static string programfilespath= "";
static string apppath = "";

static void dosomemethod()
{
}

static string shorten(string value) {
int maxlen = 6;
if (value.Length < 6) {maxlen = value.Length;}
value += value.Replace(" ",""); //remove all spaces
return value.SubString(0,maxlen).ToUpper(); //return short DOS compatible name
}

static void Load() {
appname = "My Cool App";
shortappname = shorten(appname);
devname = "Ronnie Diaz;"
appversion = "1.0.0";
lastupdated = "2011/04/28";
programfilespath= Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\";
apppath = programfilespath + appname;
}
}

2nd approach using first example class:

class someappclass3
 {
string appname {get;set;}
string shortappname {get;set;}
string devname {get;set;}
string appversion {get;set;}
string lastupdated {get;set;}
string programfilespath {get;set;}
string apppath {get;set;}

void dosomemethod() {
}

string shorten(string value) {
int maxlen = 6;
if (value.Length < 6) {maxlen = value.Length;}
value += value.Replace(" ",""); //remove all spaces
return value.SubString(0,maxlen).ToUpper(); //return short DOS compatible name
}

//ahh initializer, you can even pass in values to override the initials if you'd like
public someappclass() {
try {
appname = "value";
//etc..
}
catch (Exception ex) {
//yell loudly. alternative you could also wrap each get set and/or put this within the get/set of each individual property. don't forget your redbull
}
}

}

In case you clicked on the fundamentals link earlier and wondering how it’s relevant, notice the above class is not static on the inside… that’s because it’s a fig newton! Our previous examples were like a tough paste, yeah the paste could probably hold itself together, but it works much better when it’s wrapped in something stronger!

Comparison of end results on calling code:

public static void Main(string[] args)
{
//example that throws errors
someappclass1.dosomemethod();

//approach 1
someappclass2.Load();
someappclass2.dosomemethod();

//approach 2
someappclass3 appclassobj = new someappclass3();
appclassobj.dosomemethod();

}

So if you still need a singleton in your project and decide you like approach 2, you could always declare a static var as an object of someappclass3 and access this the same way as if the class of the obj itself was static. Such as:

static class Shared {
static someappclass3 appclassobj; //no need to instantiate, just call dosomemethod from main
}

Conclusion

The end result is roughly the same in either approach 1 or 2, although behind the scenes they are very different.

IMO approach 2 is technically “more correct”, especially if you will be doing any multi-threaded development in the application later. However, keep in mind for your particular scenario which is more practical and realistic for your needs.

There are probably other scenarios out there which throw a similar error. If anyone comes across this article encountering something similar but not resolved by the information above, feel free to post additional info. or send me an email to ronnie [at] ronniediaz [dot] [com] and I will help in any way I can.

References
Wikipedia (Alan Turing), http://en.wikipedia.org/wiki/Alan_Turing
Wikipedia (OOP), http://en.wikipedia.org/wiki/Object-oriented_programming
Wikipedia (Singleton), http://en.wikipedia.org/wiki/Singleton_pattern
MSDN (Blogs), http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/8e4532e6-97e7-435d-bbc3-93fef26ff684/

C# and VB Equivalents

VB:

'shorthand object constructors; assigned initial properties
dim p as New Person() With {.FirstName = "john", .LastName="smith"}

'add handler for events
AddHandler context.BeginRequest, AddressOf Applicaton_BeginRequest

C#:

//shorthand object constructors; assigned initial properties
Person p = new Person() with {FirstName = "john", LastName="smith"}

//add handler for events
context.BeginRequest += Application_BeginRequest;

IIF in C#

I always find myself referencing my other projects for this one when I jump between languages, so decided to toss it on the web.

Both examples are in the context of ASP .Net, but syntax also applies np to Winforms

In VB:

<asp:label id="lblmessage" runat="server" visible='<%# iif(1=1,"true","false") %>' />

C# Equivalent:

<asp:label id="lblmessage" runat="server" visible='<%# 1 == 1 ? "true" : "false" %>' />

Serialize and Deserialize classes and objects in .Net

Serialization is a powerful tool and a major factor in many intermediate development technologies such as webservices.

Simply call “SerializeObject” and pass in the class name of your object for the “T” parameters, and your object will be serialized as an xml string which can then be stored in DB or written to disk!

To mark a public variable so it is not serialized, such as a decrypted key value or password, simply mark it with the attribute [XmlIgnore].

Enjoy. ;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ApplicationName
{

    /// <summary>
    /// Contains generic static/shared methods accessible throughout the site
    /// </summary>
    public static class XMLSerialization
    {
        /// <summary>
        /// Serialize Object of Type T to XML and return value as string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pObject"></param>
        /// <returns></returns>
        public static String SerializeObject<T>(T pObject)
        {
            /*try
            */
            String XmlizedString = null;
            MemoryStream memoryStream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            xs.Serialize(xmlTextWriter, pObject);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return XmlizedString;
            /*}
            catch (Exception e) { System.Console.WriteLine(e); return null; }*/
        }

        public static T DeserializeObject<T>(string URL)
        {
            /*try
            */
            T returnObject;
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextReader xmlTextReader = new XmlTextReader(URL);
            returnObject = (T)xs.Deserialize(xmlTextReader);
            //xs.Serialize(xmlTextWriter, pObject);
            return returnObject;
            /*}
            catch (Exception e) { System.Console.WriteLine(e); return null; }*/
        }

        public static String UTF8ByteArrayToString(Byte[] characters)
        {

            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        public static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }
    }
}


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All server side code examples are in C# .Net.

References
Original reference misplaced.

Quick Silverlight References

Most of the links below are relatively introductory, but they do serve as a quick refresher if it has been awhile since you have worked with Silverlight.

Though not all of the links are specific to SL4, I would recommend a path of RIA services in conjunction with ADO .Net Entity framework for your business apps as these new process flows simplify the project structure and are improvements upon their predecessors.

For quick “agile” development, Linq to SQL is still the way to go IMO, but ADO .Net is also great nonetheless.

- Walkthrough creating a silverlight business application (4.0 or later) and retrieve data using WCF service.
http://www.silverlight.net/learn/tutorials/silverlight-4/aspnet-and-silverlight/

- Using ADO .Net Entity Model / Framework with Silverlight (4.0 or later)
http://msdn.microsoft.com/en-us/library/ee796239%28v=vs.91%29.aspx

- Silverlight custom data forms (3.0 or later)
http://www.silverlightshow.net/items/Creating-Rich-Data-Forms-in-Silverlight-3-Customization.aspx

- Basic Animation in Silverlight
http://www.silverlight.net/learn/videos/silverlight-videos/basic-animation-silverlight-3/

- General Reference (all versions)
http://www.silverlight.net/learn/

- Run Silverlight on Desktop (Out of Browser Application)
http://www.silverlightshow.net/items/Silverlight-3-as-a-Desktop-Application-Out-of-Browser-Applications.aspx

Bind Control to an Object in Windows Forms

Simple solution for basic binding in Windows Forms app. This would NOT be recommended if you are using ASP .Net, Silverlight, WCF, RIA or any other services to retrieve the data as these project types have much better support for binding to controls.

C#:

static class dataaccess {
static mytype object;
}

//on app load
object = new mytype();

//on form load
tbField1.DataBindings.Add("Text", dataaccess.object.property, "Field1")

Programmatically fire an event handler in ASP .NET

I recently came across a situation which any web application developer may face where an assembly reference containing the code-behind for each ASPX page was deprecated and the original source code was no longer available.

Since this code also includes event handlers, any functions that need to be intercepted or their logic modified are now inaccessible.

In many cases these event-handling functions are also declared protected, so simply calling them from the ASPX side is not possible.

To circumvent this, one of my personal favorite .NET libraries can be used to get the method using reflections and call it manually. See examples in VB and C# below.

Enjoy. ;)

VB .NET

    Private Sub btnLogin2_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLogin2.Click
        
'ADD NEW LOGIC HERE
        
        Dim targetObject As Object = btnLogin
        
        Dim methodName As String = "OnClick"
        
        Dim mInfo As System.Reflection.MethodInfo = targetObject.GetType().GetMethod(methodName, System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)
        
        If mInfo Is Nothing Then
            Throw New ArgumentException("Error finding event handler:  " & methodName)
        End If
        
        mInfo.Invoke(targetObject, New Object() {e})
    End Sub

C#

private void btnLogin2_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{

//ADD NEW LOGIC HERE

	object targetObject = btnLogin;

	string methodName = "OnClick";

	System.Reflection.MethodInfo mInfo = targetObject.GetType().GetMethod(methodName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

	if (mInfo == null) {
		throw new ArgumentException("Error finding event handler:  " + methodName);
	}

	mInfo.Invoke(targetObject, new object[] { e });
}

It is generally not good security practice IMO to write code in the ASPX side of a web application. This solution will work however as a quick patch to an application in which the code-behind is not accessible and the site is not accessible by outside parties via (S)FTP.

If security is of concern, another solution which is the better option overall, would be to declare a new class for which this page would inherit from. In this class you could then define a public property which exposes the protected function to be called by other methods, and/or simply write your new functions and logic in here.

If the page is a partial class (as most ASP.NET web applications are structured), this is also possible without inheritance by declaring a new partial class which shares the same type as your page you need to modify. New logic can be added here and/or protected members can be exposed via public properties.

If either inheritance/OO approach is taken, upon deployment or build of the project, your new class will be compiled into a new assembly and now achieve desired functionality while maintaining security of the application as well.

Follow

Get every new post delivered to your Inbox.