Feeds:
Posts
Comments

Posts Tagged ‘C#’

Introduction

When an assembly has been loaded in an Application Domain, the embeded code can be executed.

This code can be executed in the current Application Domain or in another one, we will see how to proceed by differents way.

For all the following examples we will use a namespace MyNameSpace containing 2 classes :  ObjectRemote & Program.

 // This namespace contains code to be called.
 namespace MyNameSpace
 {
   public class ObjectRemote : System.MarshalByRefObject
   {
     public ObjectRemote ()
     {
       System.Console.WriteLine("Hello, World! (ObjectRemote Constructor)");
     }
   }
   class Program
   {
     static void Main()
     {
       System.Console.WriteLine("Hello, World! (Main method)");
     }
   }
}

I) Loading assembly in the current AppDomain

To reach some code from another application you can load your assembly in the current AppDomain or create a new AppDomain and load your assembly inside.

The following example shows how to load an assembly in the current AppDomain :

static void main()
{
  //Load the assembly into the current AppDomain
 System.Reflection.Assembly newAssembly = System.Reflection.Assembly.LoadFrom(@"c:\MyNameSpace.exe")

 //Instanciate ObjectRemote:
 newAssembly.CreateInstance("MyNameSpace.ObjectRemote");
}

II)Loading assembly in another AppDomain

When using this approach, you have to use ExecuteAssembly method of AppDomain class to reach the default entry point or CreateInstanceFrom method to create an instance of the ObjectRemote.

static void main()
{
//Load the assembly into another AppDomain and call the default entry point
System.AppDomain newAppDomain = new System.AppDomain.CreateDomain("");
NewAppDomain .ExecuteAssembly(@"c:\MyNameSpace.exe")

//Create an instance of ObjectRemote
NewAppDomain.CreateInstanceFrom(@" :\MyNameSpace.exe"," MyNameSpace.ObjectRemote");
}

Enjoy ūüėČ

Advertisements

Read Full Post »

Introduction:

In the .Net 4.0 we can find a new class Parallel containing many static methods to help us in parallel programing. System.Threading.Parallel provides one For static method which will be the main point of this article.
As a matter of fact at the end of this article you’ll find a link redirecting you in one where we explain you how to implement this static method in C# .Net 2.0!!

Loop For in a C# 2.0 bloc code

public static void MethodWithoutParallel()
{
      List<string>lstInForLoop = new List<string>();
      for(int i =0;<20;i++)
      {
            lstInForLoop.Add(i.ToString());
            //simulate a heavy instruction
            Thread.SpinWait(10);
       }
}

Loop Parallel.For in a C#4.0 bloc code

public static void MethodWithParallel()
{
      List<string>lstInParallelLoop = new List<string>();
      Parallel.For(0, 20, (int i) =>
      {
             lstInParallelLoop.Add(i.ToString());
             //simulate a heavy instruction
             Thread.SpinWait(10);
      });
}

Now let’s compare the timing of these two methods

class Program
{
   public static void Main(string[] args)
   {
      DateTime startTime;
      TimeSpan duration;

      startTime = DateTime.Now;
      MethodWithParallel();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithParallel done in {0}", duration.TotalMilliseconds + " ms");

      startTime = DateTime.Now;
      MethodWithoutParallel ();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithoutParallel  done in {0}", duration.TotalMilliseconds + " ms");

      Console.Read();
    }
}

Output

with Thread.SpinWait method

Running in parallel performs processing time by half !!!
There are endeed dependencies on your hardware (according to the number of cores etc…)

However, let’s remove the Thread.SpinWait static method and run our loops again.

Output

without Thread.SpinWait method

The loop for inside MethodWithoutParallel performs better than the Parallel.For loop inside MethodWithParallel. It makes evidence that it must not be systematically used.
First of all, always find out where are the expensive instructions and if they can be perform thanks to a little step (or chunk) in your loop.

Now let’s have a look on how to provide a Parallel.For loop in C#2.0

Enjoy :)!!

Read Full Post »

Yesterday, i was facing a curious problem on my form. I have a DateTimePicker control , and when i choose manually the date and i press Enter or Escape, i have an annoying sound. You know, this sound that is heard when Windows displays an error message box.

I have bypassed the problem by creating a UserControl which inherit from DateTimePicker and overriding the OnKeyPress method to handle the event when the Escape or Enter key is pressed.

public partial class MyDateTimePicker : DateTimePicker
{
    public MyDateTimePicker()
    {
        InitializeComponent();
    }

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if ((e.KeyChar != 13) || (e.KeyChar != 27))
        {
            e.Handled = true;
        }

        base.OnKeyPress(e);
    }
}

Read Full Post »

Shallow Copy VS Deep Copy in .Net

Introduction :

In the .Net Framework there is 2 distincts memory space to store our objects: STACK and HEAP.

  • On the stack is stored value types of .net framework as struct, enum, primitives types…and all what inherit from System.Value.
  • On the heap is stored reference types of .net framework as all object which doesn’t inherit from System.Value. On the stack is only stored a pointer to the object on the heap.

Reference type :

Let’s start quickly with an example where we have a reference type object “PersonTypeRef” which has a constructor having 3 value type parameters(Firstname, Lastname, Birthday).

The instance of “PersonTypeRef” will be copied in another one being in the same type, and one member of this instance will be modified. After that let’s see the results.

PersonTypeRef personTypeRef1 =
   new PersonTypeRef("Zinedine", "Zidane", new DateTime(1972, 06, 23));
PersonTypeRef personValueRef2 = personTypeRef1;

//Before changing firstname member of instance personTypeRef1
Console.WriteLine("Here personTypeRef2 is identical to personTypeRef1 :\n");
Console.WriteLine(personValueRef2.ToString() + "\n");
//OK personTypeRef2 is identical to personTypeRef1

personTypeRef1.FirstName = "Yazid";
Console.WriteLine("After changing firstname member of personTypeRef1 : \n");
Console.Write("personTypeRef1 -->" + personTypeRef1.ToString() + "\n");
//OK personTypeRef1 firstname member has changed as "Yazid"

Console.WriteLine("\npersonTypeRef2 -->" + personValueRef2.ToString());
//KO personTypeRef2 firstname member has changed too!

Result :Copy04

By creating a copy of personTypeRef1 we only copy the pointer(in the stack) to the object stored in the heap.So there is a dependency between the 2 objects and a modification on one object will be passed to the other object.

Solution : Shallow copy or deep copy Shallow copy: Each members of the instance will be copied according to their type(value type or reference type). If  one member of the instance is a value type, the shallow copy will copy the value in a new variable.BUT if the instance member is a reference type, we will have a copy of the reference and not a copy of the value of this member.

To illustrate this, in the PersonTypeRef we have to implement ICloneable interface and use its Clone() method like this:

PersonTypeRef personTypeRef1 =
  new PersonTypeRef("Zinedine", "Zidane", new DateTime(1972, 06, 23));
PersonTypeRef personValueRef2                          =(PersonTypeRef)personTypeRef1.Clone();

//Before changing firstname member of instance personTypeRef1
Console.WriteLine("personTypeRef2 is identical to personTypeRef1 :\n");
Console.WriteLine(personValueRef2.ToString() + "\n");
//OK personTypeRef2 is identical to personTypeRef1

personTypeRef1.FirstName = "Yazid";
Console.WriteLine("changing firstname of personTypeRef1 : \n");
Console.Write("personTypeRef1 -->" + personTypeRef1.ToString());
//OK personTypeRef1 firstname member has changed as "Yazid"
Console.WriteLine("personTypeRef2 -->" +personValueRef2.ToString());
//OK personTypeRef2 firstname member hasn't changed too!

Clone() method use MemberwiseClone() method as what is following :

public object Clone()
{
     return this.MemberwizeClone();
}
 Result :Copy03

We have seen how to simply copy an object, but what about composed objects?

Copying an object composed by references types

Here we will see that sometimes shallow copy isn’t sufficient.

For example we will see the case of composed objects and the better example are collections. We will create 3 instance of PersonTypeRef and add them in a strong typed list of PersonTypeRef.

internal class Person
{
      public static void DisplayPersons(List<PersonTypeRef> param)
      {
          foreach (PersonTypeRef item in param)
          {
             Console.WriteLine(item);
          }
      }
}

public static void Main()
{
List<PersonTypeRef> listPersons = new List<PersonTypeRef>()
{
new PersonTypeRef
{
   FirstName = "Zinedine",
   LastName = "Zidane",
   BirthDate = new DateTime(1972, 06, 23)
  },
  new PersonTypeRef
  {
   FirstName = "Solar",
   LastName = "Robick",
   BirthDate = new DateTime(1981, 08, 04)
  },
  new PersonTypeRef
  {
   FirstName = "Hamid",
   LastName = "Senni",
  BirthDate = new DateTime(1982, 09, 14)
  }
 };
Console.WriteLine("Initial list of listPersons :");
Person.DisplayPersons(listPersons);
}

Let’s see the result :

Copy06

Now let’s modify our list of persons by adding one more person in this list.

Console.WriteLine("Initial list of listPersons :");
Person.DisplayPersons(listPersons);
Console.WriteLine("Modified list of listPersons :");
listPersons.Add(new PersonTypeRef("Bill", "Gates", new DateTime(1900, 01, 01)));
Person.DisplayPersons(listPersons);//OK listPersons has been modified

Result :

Copy08

Question: How can we do to get back our initial list (listPerson)?

List<PersonTypeRef> listPersonsCopy = new List<PersonTypeRef>(listPersons);

Console.WriteLine("Initial list of listPersons :");
Person.DisplayPersons(listPersons);

Console.WriteLine("\n\nModified list of listPersons :");
listPersons.Add(new PersonTypeRef("Bill", "Gates", new DateTime(1900, 01, 01)));
Person.DisplayPersons(listPersons);//OK listPersons has been modified

Console.WriteLine("\n\nContent of listPersonsCopy :");
//KO listPersonsCopy has been  modified too!!
Person.DisplayPersons(listPersonsCopy);

If we copy another list from this one, we wouldn’t have the waited result because¬†we would copy only the reference of our list and not the list itself.

Result :

Copy10 One solution is to create a new instance of our ¬†“listPersonsCopy” having for parameter “listPersons” :

List<PersonTypeRef> listPersonsCopy = new List<PersonTypeRef>(listPersons);

Console.WriteLine("Initial list of listPersons :");
Person.DisplayPersons(listPersons);

Console.WriteLine("\n\nModified list of listPersons :");
listPersons.Add(new PersonTypeRef("Bill", "Gates", new DateTime(1900, 01, 01)));
Person.DisplayPersons(listPersons);//OK listPersons has been modified

Console.WriteLine("\n\nContent of listPersonsCopy :");
//OK listPersonsCopy hasn't been modified!!
Person.DisplayPersons(listPersonsCopy);

Result : Copy12

Very good, we find our initial “listPersons”, but what’s happen if we modify one of the items in the collection “listPersons” (or “listPersonsCopy”) ?

List<PersonTypeRef> listPersonsCopy = new List<PersonTypeRef>(listPersons);

Console.WriteLine("Initial list of listPersons :");
Person.DisplayPersons(listPersons);

Console.WriteLine("\n\nModified list of listPersons :");
listPersons.Add(new PersonTypeRef("Bill", "Gates", new DateTime(1900, 01, 01)));
Person.DisplayPersons(listPersons);//OK listPersons has been modified

personTypeRef1.FirstName = "John";

Console.WriteLine("\n\nContent of listPersonsCopy :");
//KO listPersonsCopy has one of its member modified!!
Person.DisplayPersons(listPersonsCopy);

Result :

Copy17

As you can see, because of the references, if we modify one of the items in the collection, this modification will be done everywhere! We haven’t got our initial listPersons as waited.

Solution: Deep copy will allow us by creating copies of values of these reference(references “PersonTypeRef” inside the items of collection “listPersons”). To illustrate this, in the PersonTypeRef we have to implement ICloneable interface, use its Clone() method and use [Serializable] attribute for our class PersonTypeRef. As a matter of fact, actually serialization is the solution. Serialization allow us to store (in memory or in a file) and convert an object in a byte sequence. Deserialization is the reverse process.

#region ICloneable Membres
public object Clone()
{
    BinaryFormatter objectBF = new BinaryFormatter();
    object personCopy = null;
    using (MemoryStream ms = new MemoryStream())
    {
        objectBF.Serialize(ms, this);
        ms.Position = 0;
        personCopy = objectBF.Deserialize(ms);
    }
    return personCopy;
}
#endregion

Now we can proceed with a collection of PersonTypeRef (implementing IEnumerable to have have collection behavior, we will see how to proceed in another chapter about IEnumerable and IEnumerator in C#2.0 Exam 70-536 category).

PersonTypeRef[] tabPersonTypeRef = new PersonTypeRef[3]
{
  new PersonTypeRef("Zinedine", "Zidane", new DateTime(1972, 06, 23)),
  new PersonTypeRef("Solar", "Robick", new DateTime(1981, 08, 04)),
  new PersonTypeRef("Hamid", "Senni", new DateTime(1982, 09, 14))
};

//Here PersonTypeRef implement IEnumerable interface and the method GetEnumerator
CollectionPerson collectionPerson =
                       new CollectionPerson (tabPersonTypeRef);
Console.WriteLine("Initial collectionPerson before changing firstname");
Console.WriteLine(collectionPerson);
//Deep copy
CollectionPerson collectionPersonCopy
                         =(CollectionPerson)collectionPerson.Clone();

tabPersonTypeRef[0].FirstName = "Jean";

//OK collectionPerson has been modified
Console.WriteLine("collectionPerson after changing firstname");

//OK collectionPersonCopy hasn't been modified
Console.WriteLine(collectionPersonCopy);

Result :

Copy15

First of all, the advantage in serializing is that it is a simple way to practise because the framework does serialization and deserialization. Then BinaryFormatter accepts as parameter an object, so we can serialize whatever the type!

Copying an object composed by values types

(to be continued…)

Read Full Post »

AMP: Asynchronous Model Programing

Introduction

Developping a multithread application can be realised in several ways.¬†Let’s see about one of these ways : using Asynchronous delegates calls.

In this article we will see step by step the interrest of using  asynchronous delegates calls, by 4 examples.

őôrst Example : ¬†Synchronous delegate call

AsynchCall1

Output :

//Waiting for 5 seconds before having the following output:

Text_1 : Simulated instruction by this text …

Result :  5

End of application

In this case before displaying the output we are obliged to wait for 5 seconds  until the end of the Invoke method of myOriginalDelegate.Invoke(5) has finished.

őôőônd Example : ¬†Asynchronous delegate call whitout callback

AsynchCall2

Output :

Text_1 : Simulated instruction by this text …

//Waiting for 5 seconds (that MyTragetMethod provide the result )before having the following output ONLY when the EndInvoke() method is called:

Result :  5

End of application

To make an asynchronous call we use the BeginInvoke() method which ¬†is going to start MyTragetMethod¬†on another thread. BeginInvoke() doesn’t return the return value of MyTragetMethod.

So what is the returned value ?

It returns an IAsyncResult object that we can use to determine when the asynchronous operation is complete.

The EndInvoke() method of the delegate will use an IAsyncResult object as parameter, ¬†to¬†wait for the end of the operation if it hasn’t already finished and to provide the returned value.

őôőôőôrd Example : The second parameter of BeginIvoke() method : AsyncCallback

AsynchCall3

AsyncCallback is a delegate provided by using namespace “System.Runtime.InteropServices”. This delegate targets a method having only one parameter of type IAsyncResult and returning nothing (void).

In our example an instance of AsyncCallback delegate invoke CallBackMethod() when the MyTragetMethod has completed . In this case EndInvole() method is call in  CallBackMethod() to return the value just when having it! Look how to proceed and the casts required to use the static AsyncDelegate property which returns a reference to the original asynchronous delegate MyOriginalDelegate.

Output :

Text_1 : Simulated instruction by this text …

//The result is displayed AS SOON AS it is available

Operation finished !! Result is : 5

End of application


őôVth Example : The third parameter of BeginInvoke() method : Object

The last parameter of BeginInvoke() allow us to pass an additionnal information in your CallBackMethod. This additionnal information is know as “AsyncState” which provide us the possibility to pass an Object to the original Thread where myOriginalDelegate is processing. We can handle anything because it inherite from Object.

Here our object will be a class called NumberByLetters.

Asynchronous4

Output :

Text_1 : Simulated instruction by this text …

//The result is displayed AS SOON AS it is available

Operation finished !! Result is : 5 and we write it like this : five

End of application

Hope this post enought understandable and helped you to assimilate the AMP with delegate!


Read Full Post »