A day with .Net

My day to day experince in .net

Archive for August, 2012

C# Async HelloWorld

Posted by vivekcek on August 26, 2012

You need Visual Studio 2012 to run this code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    /// <summary>
    /// Program Class.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// Entry Point
        /// </summary>
        /// <param name="args">Command Line Parameters.</param>
        public static void Main()
        {
             Calculate();
             Console.WriteLine("Asynchronous Execution Started");
             Console.ReadLine();
        }

        /// <summary>
        /// Async Method.The method marked as async.
        /// </summary>
        public static async void Calculate()
        {
            Task<int> t = Task<int>.Factory.StartNew(() =>
                {
                    int i = 0;
                    for (; i < 100; i++)
                    {
                        System.Threading.Thread.Sleep(10);
                    }

                    return i;
                });

            await t;//At this point Calculate Method started asynchronous waiting
            Console.WriteLine(t.Result);
        }
    }
}

Advertisements

Posted in c#.net | Tagged: | Leave a Comment »

Create a Word Document From a Template using c# (Mail Merge)

Posted by vivekcek on August 25, 2012

I want to create a word document from a word template.The advantage of using template is, we can define a structure for the document and decorate the it with dynamic text.

Software’s Used
——————————–

1. Word 2007.

2. Visual Studio 2010

Library used
—————————–

1. Microsoft Word 12.0 Object Library

Steps
———————-

1. Create a Word Template.

2. Create a console application using VS 2010.

3. Add reference to Microsoft Word 12.0 Object Library.

4. Enjoy 🙂

1. Create a Word Template.
——————————————-

Word templates are created using MergeField’s in word.

a. Open a new Word 2007

b. Type “Name:”, Where ‘Name:’ is just a label.

c. Now we need to insert a MergeField right to our label ‘Name:’

d. Place cursor on the right of our label.

e. Select insert tab in word.

f. Select Quick Parts. Then Field.

g. Select field category as MergeField. Give the MergeField name as ‘Name’.

h. Save the document as WordTemplate.

Now our Template contains.

Name: «Name»

The field inside <> is our merge Field. We will replace that field through code to create a new word document.

* Note the extension of out template will be .dotx(MyTemplate.dotx)

2. Create a console application using VS 2010.
—————————————————————
a. Create a console application.

b. Add refrence to Microsoft Word 12.0 Object Library.

c. Add NameSpace “using Microsoft.Office.Interop.Word;”.

d. The Final document will be save in MyDocuments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
namespace WordAuto
{
    class Program
    {
        static void Main(string[] args)
        {
            //OBJECT OF MISSING "NULL VALUE"

            Object oMissing = System.Reflection.Missing.Value;

            Object oTemplatePath = "D:\\MyTemplate.dotx";

            
            Application wordApp = new Application();
            Document wordDoc = new Document();

            wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

            foreach (Field myMergeField in wordDoc.Fields)
            {

                
                Range rngFieldCode = myMergeField.Code;

                String fieldText = rngFieldCode.Text;



                // ONLY GETTING THE MAILMERGE FIELDS

                if (fieldText.StartsWith(" MERGEFIELD"))
                {

                    // THE TEXT COMES IN THE FORMAT OF

                    // MERGEFIELD  MyFieldName  \\* MERGEFORMAT

                    // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"

                    Int32 endMerge = fieldText.IndexOf("\\");

                    Int32 fieldNameLength = fieldText.Length - endMerge;

                    String fieldName = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                    fieldName = fieldName.Trim();

                    // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//

                    // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE

                    if (fieldName == "Name")
                    {

                        myMergeField.Select();

                        wordApp.Selection.TypeText("Vivek");

                    }

                }

            }
            wordDoc.SaveAs("myfile.doc");
            wordApp.Documents.Open("myFile.doc");
            wordApp.Application.Quit();
        }
    }
}

DOWNLOAD SOURCE

http://sdrv.ms/NQmKeD

Posted in c#.net | Tagged: , , | 26 Comments »

Monitor Task Cancellation With Delegate

Posted by vivekcek on August 21, 2012

After we cancel a task. The delegate registered with the token will be executed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskCancelDelegate
{
    class Program
    {
        static CancellationTokenSource tokenSource = new CancellationTokenSource();
        static CancellationToken token = tokenSource.Token;
        static void Main(string[] args)
        {
            Task t1 = new Task(() => Iterate(), token);
            //Delegate reistartion with token
            token.Register(() => { Console.WriteLine("Task Cancellation called Message from delegate"); });
            Console.WriteLine("Task Started");
            t1.Start();
            System.Threading.Thread.Sleep(2000);
            Console.WriteLine("Task Cancelling call");
            tokenSource.Cancel();
            try
            {
                t1.Wait();
            }
            catch (AggregateException ag)
            {
                Console.WriteLine(ag.InnerException.Message.ToString());
            }

            Console.ReadLine();
        }
        static void Iterate()
        {
            for (int i = 0; i < int.MaxValue; i++)
            {
                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException("Task Cancelled Exception");
                }
                else
                {
                    Console.WriteLine(i.ToString());
                }
            }
        }
    }
}

Posted in Parallel Programming | Leave a Comment »

Cancelling Tasks

Posted by vivekcek on August 19, 2012

I hope you have some experience with Thread Pool in .net. We can queue work items to thread pool and wait for all to complete. But it was very hard to control the queued work items. So here comes TPL. We can cancel a task when it is working. Try out this code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskCancel
{
    class Program
    {
        static CancellationTokenSource tokenSource ;
        static CancellationToken token;
        static void Main(string[] args)
        {

            tokenSource = new CancellationTokenSource();
            token = tokenSource.Token;
            Task t1 = new Task(() => iterate(),token);
            t1.Start();
            System.Threading.Thread.Sleep(100);
            tokenSource.Cancel();
            Console.ReadLine();
        }

        static void iterate()
        {
           
                for (int i = 0; i < int.MaxValue; i++)
                {
                    if (token.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }
                    else
                    {
                        Console.WriteLine(i);
                    }
                }
            
        }
        
    }
}

Posted in Parallel Programming | Leave a Comment »

Exception Handling with the Task Parallel Library

Posted by vivekcek on August 19, 2012

We use the AggregateException class to handle exception in task’s

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExceptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<int> t1 = new Task<int>(() => Add());
            try
            {
                t1.Start();
                t1.Wait();
            }
            catch (AggregateException ag)
            {
                Console.WriteLine(ag.InnerExceptions[0].Message);
            }
            Console.ReadLine();
        }
        static int Add()
        {
            
                
            throw new ArgumentException("Exception");
            
           
        }
    }
}

Posted in Parallel Programming | Leave a Comment »

Passing arguments to a task

Posted by vivekcek on August 19, 2012

Look at the example below. Hope it is simple to understand.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetResult1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<int> t1 = new Task<int>(() => Add(1,2));
            t1.Start();
            Console.WriteLine("Result: {0}", t1.Result);
            Console.ReadLine();
        }
        static int Add(int a,int b)
        {
            return a + b;
        }
    }
}

Posted in Parallel Programming | Leave a Comment »

Getting result from A task

Posted by vivekcek on August 19, 2012

Some times your task may return some value. In this post i will show how to get an integer result from a task you created.

For that you have to use the generic version of task Task.

The Result property of Task will give result of type T.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetResult1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<int> t1 = new Task<int>(() => Add());
            t1.Start();
            Console.WriteLine("Result: {0}", t1.Result);
            Console.ReadLine();
        }
        static int Add()
        {
            return 1 + 2;
        }
    }
}


Posted in Parallel Programming | Leave a Comment »

Creating and starting task

Posted by vivekcek on August 19, 2012


In this post i mentioned the various method to create and start a task
.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartTask
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Action
            Task t1 = new Task(new Action(SayHello));
            t1.Start();

            //Using delegate
            Task t2 = new Task(delegate { SayHello(); });
            t2.Start();

            //Lambda Expression
            Task t3 = new Task(() => SayHello());
            t3.Start();

            //Anonymous Metod
            Task t4 = new Task(() => { Console.WriteLine("Hello"); });
            t4.Start();


            ////////Task.Factory/////////////

            //No need to call any start method
            Task.Factory.StartNew(() => SayHello());

            Console.ReadLine();
        }
        static void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

Posted in Parallel Programming | Leave a Comment »