Thursday, December 20, 2012

How to retrieve an image that is an embedded resource of the assembly?


The image can be embedded resource of the assembly. This is useful in case you are developing any custom library or windows application etc. You need to first add the image in the project under any subfolder. Once it is added to the project, go to its properties by pressing F4 on image. Change the Build Action property to Embedded Resource.

In order to use the image m you need to use the following code:

try
           {
                      Assembly myAssembly = Assembly.GetExecutingAssembly();
            using (Stream imgStream = myAssembly.GetManifestResourceStream   
                        ("Namespace.Subfolder.Image.jpg"))
                {
                    Image img = Image.FromStream(imgStream);
                    picBoxLogo.Image = img;
                }
                         } catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

Calling WCF service methods asynchronously in C# Application


The WCF service methods can be called asynchronously. The main benefit of calling the wcf methods asynchronously is to avoid unnecessarily waiting by the application for the response from the service. This will also help to avoid the application from hanging state. This is also good from usability prospective. All you need is while consuming the service; client has an option whether to generate classes for handling calls asynchronously or not. So follow the following steps if you want to call the methods asynchronously

1.       Open the Solution Explorer
2.       Right Click on serve reference and Click Add Service Reference..
 

3.       Add Service Reference window will be opened
4.       Click on Advanced Button and Service Reference Settings window will open
5.       Check the option  Generate asynchronous operations and Press Ok

 

6.       Add the wcf url in address and press Ok to generate the proxy calls with auto generated  asynchronous methods
7.       Now Open a Class where you want to call wcf methods
8.       Add the Namespace for the service
9.       Create the proxy object of the service as

TestServiceClient  client = new TestServiceClient(); 

10.   Define the delegates only once in the constructor of the Class as 

client.CreateEntityCompleted += new EventHandler<CreateEntityCompletedEventArgs>(client_CreateEntityCompleted);

Note: CreateEntity is an remote method exposed by the service. This delegate will call automatically once the service returns the response.

11.   Definition of the delegate will be created automatically once you declare the above statement as below
           void client_CreateEntityCompleted(object sender, CreateEntityCompletedEventArgs e)
       {
            } 

12.   Call the asynchronous method of the service as below

client.CreateEntityAsync(Obj, 1);

CreateEntity is the actual method created in the wcf code but CreateEntityAsync is created while consuming the service to call the wcf methods asynchronously. The service will call this method asynchronously and once the service returns response the above delegate method client_CreateEntityCompleted is called. You application will not hang till the service returns the response.

13.   Now in order to handle any kind of error or result use the following code in completion delegate method code
 
        void client_CreateEntityCompleted(object sender, CreateEntityCompletedEventArgs e)
       {
//check of there is any error happened
                       if (e.Error != null)
              {
                if (e.Error is FaultException)
                {
                    FaultException ex = (FaultException)e.Error;
                    MessageBox.Show("Error : " + ex.Code.Name + "\nReason : " + ex.Reason);
                }
                else
                {
                    MessageBox.Show("Error: " + e.Error.ToString());
                }
            }
            else if (e.Result)
            {
                MessageBox.Show(e.Result);
            }
            else
            {
                MessageBox.Show("Request is failed !!!!!!");
            }
            }

 

Wednesday, June 27, 2012

How to disable unit test and removed from the test run?

The unit test can be disabled by simply adding the following Ignore attribute at the top of the test method and will automatically removed from test run.

[Ignore]
[TestMethod]
public void TestMethod()
-----

Monday, March 12, 2012

Deleting duplicate rows on table with/without primary key in Sql Server


Table with primary key
Id    name
1                     Harpreet
2                     Harpreet
3                     Harpreet
4                     John
5                     Smit
select min(id) from #tablewithprimary group name
=1,4,5
Delete from .. where id not in (1,4,5)
Result : 1,4,5
delete from #tablewithprimary where id not in   
  (select min(id) from #tablewithprimary group by course,subject) 

C# Lock


lock ensures that one thread does not enter a critical section while another thread is in the critical section of code. If another thread attempts to enter a locked code, it will wait (block) until the object is released.
The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. This statement takes the following form:
 
Object thisLock = new Object();
lock (thisLock)
{
    // Critical code section
}

class Program
    {
        static void Main(string[] args)
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
            Console.ReadKey();
        }
    }

    class Account
    {
        int balance;

        Random r = new Random();

        public Account(int initial)
        {
            balance = initial;
        }

        int Withdraw(int amount)
        {

            // This condition will never be true unless the lock statement
            // is commented out:
            if (balance < 0)
            {
                throw new Exception("Negative Balance");
            }

            // Comment out the next line to see the effect of leaving out
            // the lock keyword:
            lock (this)
            {
                if (balance >= amount)
                {
                    Console.WriteLine("Balance before Withdrawal :  " + balance);
                    Console.WriteLine("Amount to Withdraw        : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Balance after Withdrawal  :  " + balance);
                    return amount;
                }
                else
                {
                    return 0; // transaction rejected
                }
            }
        }

        public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
            {
                Withdraw(r.Next(1, 100));
            }
        }
    }

How to get the current assembly path?


*** Program is the name of the class 
string assemblyPath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
Console.WriteLine(assemblyPath);
Console.ReadKey();