Sending Email from C#

Pure code is here. You can just copy and use it, and you can understand easily from the comments.

string to = "someone@hotmail.com"; // here the username can be any address // this is the address that the reciever will reply to when he/she hits the Reply button // this doesn't have to be the same as the credential address below. string from = "username@gmail.com"; string subject = "My mail from C#"; string body = "<a href=\"http://www.microsoft.com\"> Click here </a><br/><img src=\"http://t0.gstatic.com/images?q=tbn:2LUYVF-U1KxK2M:http://img.bollywoodsargam.com/albumsbolly/Priyanka_Chopra/Priyanka_Chopra_In_Barsaat_Movie_Stills_002_18_08_2005.jpg\"/>"; System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(from, to, subject, body); msg.IsBodyHtml = true; // adding attachement System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(@"C:\Users\Thurupathan\Desktop\myfile.zip"); msg.Attachments.Add(at); // sending from the gmail account // for the hotmail / live / outlook => smtp.live.com port => 587 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); // provide credentials System.Net.NetworkCredential gmailAuthentication = new System.Net.NetworkCredential("username@gmail.com", "password"); smtp.Credentials = gmailAuthentication; // SSL enable based on the smtp.EnableSsl = true; try { smtp.Send(msg); } catch (Exception ex) { Console.WriteLine(ex.Message); }

Developing a simple Data bound Windows Phone Application

I was asked to develop a Windows Phone Application development tutorial for beginners. This is not an advance coding stuff, but a simple basic tutorial.

Setting the Dev Environment

Windows Phone (WP) SDK latest version is 7.1 (very recent one is 7.1.1 targeted for 512 Mb mobile devices for multimedia rich apps. but SDK 7.1 is more than enough if you are developing generic WP apps)

Download the WP SDK free from

http://go.microsoft.com/fwlink/?LinkID=226694

The above link has the ISO which includes Visual Studio (VS) Express for WP development, Emulator and all the features needed for the development in a raw machine. If you already have VS this will install the missing module only.

Optional: If you want to have 7.1.1 update apply the update from this link after installing the 7.1 SDK http://www.microsoft.com/en-us/download/details.aspx?id=29233

Developing a simple List Data Bound Application

· Open VS

· New -> Project -> Silverlight for Windows Phone -> Windows Phone Application

clip_image002

Select the version as 7.1 to target Mango (latest version) [ Mango phone version is 7.5 and the SDK version is 7.1]

clip_image003

· Initial Development Interface

clip_image006

· Find the following Grid where we place our user elements

clip_image008

· Create a List box by XAML or drag and drop from Toolbox inside the Grid

· Write the ListBox template.

<!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox x:Name="ListCourses"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="0,15,0,0"> <TextBlock Text="{Binding CourseName}" FontSize="36"/> <TextBlock Text="{Binding Description}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>

· Go to the code behind C# file of the MainPage.xaml

· Double click and open to write the code.

clip_image011 

· Create a class Course. And populate some data in a List.

public partial class MainPage : PhoneApplicationPage { private List<Course> _courses = new List<Course>() { new Course() { CourseName = "Mobile Computing", Description = "Good course ! 🙂 " }, new Course() { CourseName = "Wireless Communication", Description = "Good course ! 🙂 " }, new Course() { CourseName = "Artificial Intelligent", Description = "Good course ! 🙂 " }, new Course() { CourseName = "Database Design", Description = "Good course ! 🙂 " }, new Course() { CourseName = "Marketing", Description = "Good course ! 🙂 " }, new Course() { CourseName = "Communication Skills", Description = "Good course ! 🙂 " }, new Course() { CourseName = "Presentation Skills", Description = "Good course ! 🙂 " }, new Course() { CourseName = "Windows Phone Development", Description = "Good course ! 🙂 " }, }; // Constructor public MainPage() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); } void MainPage_Loaded(object sender, RoutedEventArgs e) { ListCourses.DataContext = typeof(Course); ListCourses.ItemsSource = _courses; } } public class Course { public string CourseName { get; set; } public string Description { get; set; } }

· In the Loaded event we set the DataContext and ItemSource of the ListBox.

· Run the App

clip_image014

Dinning Philosopher – C#

 

This post demonstrates another threading problem. There are many solutions for dinning philosopher problem. The famous one is to introduce a waiter for the table. Where the waiter acts as the monitor and the philosophers have to ask the waiter to take a fork. Another solution is that let the philosophers talk with themselves.

But this solution has a another simple mechanism, which avoids the dead lock by it’s own by randomizing the time a philosopher can hold a single fork. Having both the forks is not randomized, since having the both forks is a ready state for eating. So even the dead lock is about to occur it never lasts. And another threshold value is used as starvation count, which represents the maximum number of continuous thinking a philosopher can bare without considered being starved.

When running this algorithm you can notice that the philosophers may get starved (mainly if the starvation count is low) but it is almost impossible for a philosopher to starve forever.

Pure object orientation and C# techniques are used in developing this code. It is true that this code is not the best one when it comes to efficiency. This code can be improved in other ways. But still it provides a self time slicing feature for the dinning philosophers problem.

using System;
using System.Threading;

namespace DinningPhilosophers
{
    class Program
    {   
        static void Main(string[] args)
        { 
            Philosopher aristotle = new Philosopher(Table.Plastic,Table.Platinum,"Aristotle",4); 
            Philosopher palto = new Philosopher(Table.Platinum, Table.Gold,"Plato",5);
            Philosopher john = new Philosopher(Table.Gold, Table.Silver,"John Dewey",6);
            Philosopher augustine = new Philosopher(Table.Silver, Table.Wood, "Augustine",4);
            Philosopher thomas = new Philosopher(Table.Wood, Table.Plastic,"Thomas Aquinas",7);

            new Thread(aristotle.Think).Start();
            new Thread(palto.Think).Start();
            new Thread(john.Think).Start();
            new Thread(augustine.Think).Start();
            new Thread(thomas.Think).Start();

            Console.ReadKey();
        }

    }



    enum PhilosopherState { Eating, Thinking }


    class Philosopher
    {
        public string Name { get; set; }

        public PhilosopherState State { get; set; }

        // determines number of continuose thinkings, without being considered starving
        readonly int StarvationThreshold;

        // defines the right and the left side fork of a philosopher
        public readonly Fork RightFork;
        public readonly Fork LeftFork;

        Random rand = new Random();

        int contThinkCount = 0;

        public Philosopher(Fork rightFork, Fork leftFork, string name, int starvThreshold)
        {
            RightFork = rightFork;
            LeftFork = leftFork;
            Name = name;
            State = PhilosopherState.Thinking;
            StarvationThreshold = starvThreshold;
        }

        public void Eat()
        {
            // take the fork in the right hand
            if (TakeForkInRightHand())
            {
                // if got the fork in the right hand immediatley try to take the fork in the left hand
                if (TakeForkInLeftHand())
                {
                    // if got both forks then eat
                    this.State = PhilosopherState.Eating;
                    Console.WriteLine("(:::) {0} is eating..with {1} and {2}", Name, RightFork.ForkID, LeftFork.ForkID);
                    Thread.Sleep(rand.Next(5000, 10000));

                    contThinkCount = 0;

                    // place the forks back
                    RightFork.Put();
                    LeftFork.Put();
                }
                // got the right fork but not the left one
                else
                {
                    // wait for a small random period and try agian to get left fork
                    Thread.Sleep(rand.Next(100, 400));
                    if (TakeForkInLeftHand())
                    {
                        // if got the left fork then eat
                        this.State = PhilosopherState.Eating;
                        Console.WriteLine("(:::) {0} is eating..with {1} and {2}", Name, RightFork.ForkID, LeftFork.ForkID);
                        Thread.Sleep(rand.Next(5000, 10000));

                        contThinkCount = 0;

                        RightFork.Put();
                        LeftFork.Put();
                    }
                    // if couldn't get the fork even after the wait, out the right fork on the table
                    else
                    {
                        RightFork.Put();
                    }
                }
            }
            // if couldn't get fork on the right hand
            else
            {
                // get a fork the left hand
                if (TakeForkInLeftHand())
                {
                    // wait for a small random time period and then try acquire the right one
                    Thread.Sleep(rand.Next(100, 400));
                    if (TakeForkInRightHand())
                    {
                        // if got the right one then eat
                        this.State = PhilosopherState.Eating;
                        Console.WriteLine("(:::) {0} is eating..with {1} and {2}", Name, RightFork.ForkID, LeftFork.ForkID);
                        Thread.Sleep(rand.Next(5000, 10000));

                        contThinkCount = 0;

                        RightFork.Put();
                        LeftFork.Put();
                    }
                    else
                    {
                        // else put the left fork back on the table
                        LeftFork.Put();
                    }
                }
            }

            Think();
        }

        public void Think()
        {
            this.State = PhilosopherState.Thinking;
            Console.WriteLine("^^*^^ {0} is thinking...on {1}", Name, Thread.CurrentThread.Priority.ToString());
            Thread.Sleep(rand.Next(2500,20000));
            contThinkCount++;

            if (contThinkCount > StarvationThreshold)
            {
                Console.WriteLine(":ooooooooooooooooooooooooooooooooooooooooooooooo: {0} is starving", Name);
            }

            Eat();
        }

        private bool TakeForkInLeftHand()
        {
            return LeftFork.Take(Name);
        }

        private bool TakeForkInRightHand()
        {
            return RightFork.Take(Name);
        }

    }




    enum ForkState { Taken, OnTheTable }
    

    class Fork
    {
        public string ForkID { get; set; }
        public ForkState State { get; set; }
        public string TakenBy { get; set; }

        public bool Take(string takenBy)
        {
            lock (this)
            {
                if (this.State == ForkState.OnTheTable)
                {
                    State = ForkState.Taken;
                    TakenBy = takenBy;
                    Console.WriteLine("||| {0} is taken by {1}", ForkID, TakenBy);
                    return true;
                }

                else
                {
                    State = ForkState.Taken;
                    return false;
                }
            }
        }

        public void Put()
        {
            State = ForkState.OnTheTable;
            Console.WriteLine("||| {0} is place on the table by {1}", ForkID, TakenBy);
            TakenBy = String.Empty;   
        }
    }



    class Table
    {
        internal static Fork Platinum = new Fork () { ForkID = "Platinum Fork", State = ForkState.OnTheTable};
        internal static Fork Gold = new Fork() { ForkID = "Gold Fork", State = ForkState.OnTheTable };
        internal static Fork Silver = new Fork() { ForkID = "Silver Fork", State = ForkState.OnTheTable };
        internal static Fork Wood = new Fork() { ForkID = "Wood Fork", State = ForkState.OnTheTable };
        internal static Fork Plastic = new Fork() { ForkID = "Plastic Fork", State = ForkState.OnTheTable };
    }
}

Sleeping Barber – C#

The sleeping barber is one of the problems which is used to demonstrate the correct thread notification mechanism. Here’s the a sample code for the sleeping barber problem in C# for .NET 4.0. Keep in mind that this code is optimized for the .NET 4.0 not for prior versions. You have concurrent collections in .NET 4.0.

 

using System;
using System.Threading;
using System.Collections.Concurrent;
using Microsoft.ConcurrencyVisualizer.Instrumentation;

namespace SleepingBarber
{
    class Program
    {
        internal static AutoResetEvent customerEvent = new AutoResetEvent(false);

        // no explict locks needed as it is a ConcurrentQueue > feature in .NET 4.0
        internal static ConcurrentQueue<Customer> queue = new ConcurrentQueue<Customer>();

        static void Main(string[] args)
        {
            Random rand = new Random();

            // make the barber background so the program can exit once the main thread is finished.
            // this does not impact the thread priority.
            new Thread(Barber.CutHair) { IsBackground = true, Name = "Barber" }.Start();

            Thread.Sleep(100);

            Thread.CurrentThread.Name = "Main";
            // creating 25 customers in random order
            for (int i = 0; i <25; i++)
            {
                // temp is used to avoid the captured variable problem
                int temp = i;
                Thread.Sleep(rand.Next(600, 2000));
                Customer c = new Customer() {Name = "Customer " + temp };
                queue.Enqueue(c);

                if (queue.Count == 1)
                {
                    Customer.WakeUpBarber();
                }
            }

            Console.ReadKey();
        }
    }

    class Customer
    {
        public string Name { get; set; }

        internal static void WakeUpBarber()
        {
            Program.customerEvent.Set();
        }
    }

    class Barber
    {
        internal static void CutHair()
        {
            while (!Program.queue.IsEmpty)
            {
                Customer c;

                // time to cut the hair is 1 sec
                Thread.Sleep(1000);

                // after cutting hair barber removes him from the queue
                if (Program.queue.TryDequeue(out c))
                {
                    Console.WriteLine("Done hair cutting to {0}", c.Name);
                }
                else
                {
                    // this will never happen in this scenario as only one barber is here
                    Console.WriteLine(" 😦 customer is not going out ...");
                }
            }

            Console.WriteLine("Going to sleep.... grr...err....");
            GoToSleep();
        }

        private static void GoToSleep()
        {
            using (Markers.EnterSpan("wait start"))
            {
                Program.customerEvent.WaitOne();
                Console.WriteLine("Waking up..Oh ! Customer arrived..");
            }
            CutHair();
        }
    }
}

Simple Client–Server in C#

 

This is a very simplest client server model which is only to demonstrate the client server working model. And a simple program to learn threads in C#.

Client connects to the server and then server delivers a unique number to each client by simply incrementing a static variable. The increment is locked for thread safety.

Code for the server.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;

namespace ConsoleServer
{
    class Program
    {
        static TcpListener server;
        static int count = 0;
        static readonly object o = new object();

        static void Main(string[] args)
        {
            IPHostEntry host = Dns.GetHostEntry("localhost");
            IPAddress ip = new IPAddress(host.AddressList.First().GetAddressBytes());

            server = new TcpListener(ip, 2000);
            server.Start();

            bool exit = false;

            Console.WriteLine("Server started on port 2000");

            while (!exit)
            {
                // here pending requests are in a queue.
                if (server.Pending())
                {
                    new Thread(Program.ServerService).Start();
                }
            }

            Console.ReadKey();
            server.Stop();

        }

        public static void ServerService()
        {
            Socket socket = server.AcceptSocket();

            Console.WriteLine("Connected " + socket.RemoteEndPoint);

            Stream stream = new NetworkStream(socket);
            StreamWriter writer = new StreamWriter(stream);
            StreamReader reader = new StreamReader(stream);

            writer.AutoFlush = true;
        
            writer.Write("Initial Number {0}",GetNumber());

            bool client = false;

            new Thread(() =>
            {
                while (!client)
                {
                    string s = "";
                    s = reader.ReadLine();

                    if (s == "req")
                    {
                        writer.Write(GetNumber());
                        writer.Flush();
                    }
                }
            }).Start();
        }

        private static int GetNumber()
        {
            // here sleep time gets activated after one client leaves the lock block.
            // so if a first client gets short long sleep time and second one gets short, still the second one has to wait till the first one finishes.

            Random r = new Random();
            int time = r.Next(200, 2000);
            Console.WriteLine("Sleeping time : {0}", time);

            lock(o)
            {
                Thread.Sleep(time);
                return ++count;
            }
        }
    }
}


Code for the client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("localhost", 2000);

            Stream stream = client.GetStream();
            StreamReader reader = new StreamReader(stream);

            Console.WriteLine(reader.ReadLine());

            stream.Flush();
            
            new Thread(() =>
             {
                 Console.WriteLine("New Request {0} ", reader.ReadLine());

                 Console.WriteLine("Waiting for exit");
                 Console.ReadKey();
             }).Start();

 

            while (true)
            {
                string req = Console.ReadLine();

                if (req == "new")
                {
                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write(req);
                    writer.Flush();
                }
            }
            client.Close();

        }
    }
}

Come on let’s talk .. ..

I was reading a book last night and noticed plenty of codes in that book were using ‘ref’ in the methods. Mmm.. plenty in the sense almost all of them except where the example methods have some value type parameters.

Here’s a simple example, (a screen shot of the page)

image

Then I thought we all know that reference types are passed to methods as reference (though the pointer is passed as a copy), there is no any specific need to have the ‘ref’ keyword. (Please correct me if I’m wrong)

Unless you can save few bytes of memory for the new pointer in the stack. 🙂 which will be kicked out immediately after the code/methods returns.

I have already made a post on ‘ref’ and ‘out’ keywords. (See here) These two keywords are really very interesting bits of C#.

Windows Phone All in One Kick Start => Meet Jack Sparrow

Hi this is a quick and simple WP7 application, which demonstrates some of the advanced features within very few steps.

If you are already familiar wit h WCF and Silverlight then WP7 development is very easy for you.

This application explains the following features.

  • Accessing the WCF service from the WP7 application.
  • Handling Cross reference threads in Wp7 and create responsive UI.

Application

The application asks you simple question, and if you answer correct then you will be taken to meet Jack Sparrow. If you do not answer correctly, then the application asks another question and this process repeats.

WCF service is responsible for generating the questions and evaluating the answer. Thread is used to load the web browser.  Browser object is in the Collapsed Visibility mode, and the thread used to navigate the page, and bind the delegate of Navigated event.

Since the web browser is created in the main thread and accessed in another thread, this creates the cross thread reference problem. It is solved using the traditional way of the BeginInvoke() call. But the BeginInvoke() call is made from the Dispatcher object of the current thread.

Code Implementation

In my WCF service I have 2 operational contracts. One is to generate the question and the other one is for evaluate the answer. (Read the comments within the code blocks)

Code for my IService1.cs

image

Code implementation of those methods are mentioned here, You can download the complete solution here

As like Silverlight we have to call the WCF service through asynchronous method calls and binding a delegate to that. But we do not have to worry much since VS generates the Async methods for us.

Build the service, and the reference of the Service to the WP7 application.

The below image shows my WP7 application interface in the design mode.

image

 

In the MainPage.xaml.cs file we have code logic of the application.

Here is the code for calling a service in WP7. It is 100% similar to Silverlight applications. (Read the comments ..)

image

Once the Method call is returned from the service, the following method will be fired. (Note that GetQuestion() is the method we created. GetQuestionAsync() is generated by VS. We have to simply call that. (If you are familiar with Silverlight then this is not a big deal for you)).

image

The following method handles the cross thread reference problem, and provides a responsive UI. (Note that I didn’t code any explicit Threads. In .NET you can do this with simple delegates, .NET handles the thread for you).

image

Notice that in the BeginInvoke() I’m again making a call to my main thread for the Navigated event.

After the application completes it happily displays Jack Sparrow Winking smile

 

image

Dynamic Controls and Static Events with Different output

The title sounds little awkward.. Well. This code explains an easy and a good coding practice in handling dynamic controls and writing events for them.

Let me explain the scenario, one of my friend needs a code for a garment fault detection system; the machine checks the cloths and detects the faults. Each fault has to appear as button and when the user clicks the button it has to do some other thing corresponding to that fault.

The problem is, we are not aware of the number of faults each piece of cloth has. So we have to generated the controls dynamically and the events.

Only one thing we know that, the hardware is capable of detecting 10 different types of faults. So maximum we can get 10 and that’s it.

He was so confused whether to write 10 different event handlers and assign them, to dynamic controls by writing some conditional branching statements.

The code below is simple but powerful, it makes life easier with just 2 methods. Let’s get into the action.

Some how you can get a parameter which says how many controls you have to generate dynamically. I store them in a List (for demonstration)

image

Another method to create the controls and load them to the Windows Form.  (here I’m using a Windows Form application)

image

As you see here I’m not keeping the references of the Button controls, but I’m assigning a single event to all of them.

This event is the only thing I have to refer the controls. But let’s see how I use the single event to distinguish the different buttons and ask them to do different tasks.

As I mentioned earlier it so simple…

I’m loading the strings to the List from a method (which I haven’t metioned here, because getting the parameter which decides the number of dynamic controls depends on the scenario you are working on).

image

This is cool, I identify the Buttons with their Text field, you can use any of the fields which is comfortable and suits your need.

The power of this method is; it’s very simple, I’m not keeping any references to the Buttons. The same piece of code can be used to generate the any number of controls without any modifications.

And you have to write only one event handler for all the controls like the above method.

Just imagine 10 controls and 10 references and 10 different even handlers, and dynamically comparing them and calling every time. 😦 It’s too much of a work. But this is really cool.

You can design your actions in a separate library (.dll) and call them in the case : of the switch statements, that gives a good design also. So whenever you want the actions to be modified, you just have to change a seperated .dll file rather changing the main assembly.