Windows Phone SDK in Windows Server 2008 R2

I have been using WS2K R2 in main primary laptop for last 5 months. I wanted to install the Windows Phone SDK on my server. Then I got the error that WP SDK is not compatible with the Server OS. I googled and finally found this useful link.

http://blogs.msdn.com/b/astebner/archive/2010/05/02/10005980.aspx

If you have an offine WP 7 installer like an ISO file extract them using any file compressing tool and follow the steps mentioned in the above link.

But another pain point is Zune does not support on the server OS. Don’t worry .. I did the search again found this following link.

http://robmensching.com/blog/posts/2009/9/12/How-to-install-Zune-software-on-Windows-2008-R2

Personally I didn’t check the Zune install on Windows Server 2008. So if it is not working don’t blame me, I just believe the Google 🙂

 

C# Delegates

Delegates offer a great deal of power to the C# and they fundamentally alter the way C# works compared to Java. I came across an article about delegates in C# from one of the MSDN blogs.

Here is the link

The link has the code where you can simply understand just by reading scanning the code.

The funny part is the author has mentioned that if you still want to execute a delegate in a asynchronous way and still need more control on that, then try executing the delegate from a thread. It’s true. But I can’t imagine a situation why we call delegate as a new thread, rather we can simply use the new thread for the work.

But if you think a little more you can really understand that, author has a good point in that, which really explains and clears the confusion most of the people have on delegates, which is whether the delegates are synchronous or asynchronous.

Delegates can be called either synchronously or asynchronously.

Rajini Style App

 

Hi, I never thought of writing a post today. But this website made me to do so. http://www.desimartini.com/​allaboutrajni.htm

A tribute for the creativity of those guys, it’s simply cool. So what is it to have a Silverlight version of the Rajini style app.

No big worries here’s the code. I named it as Rajini Style app. The code is not a matter here, but I salute the creativity of those guys who really made us think.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.NetworkInformation;

namespace RajiniStyleApp
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
        }

        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                textBlock1.Text = "You need to switch off the Internet \n in order to view the content";
            }
            else
            {
                textBlock1.Text = "Disconnected ... Runs on Rajini power >> \n visit :: http://www.desimartini.com/​allaboutrajni.htm ";
            }
        }
    }

 

You have to add the System.Net.NetworkInformation namespace.

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();

        }
    }
}

Concurrent Collections and TPL–.NET 4.0

TPL in .NET 4.0 is a cool thing when programming modern PCs which have CPUs with more than one core. CPUs with many cores are popular these days because hardware vendors make CPUs with many cores to cater the Moore’s Law. 🙂 Or they might have tired of shrinking the transistor size up to 32nm. There are smaller versions than that..

Task Parallel Library’s (TPL’s) Task.Factory.StatNew( () => {..} is the .NET 4.0’s replacement for the Thread.QueueUserWorkItem() and asynchronous delegates. In this case TPL is more close to the asynchronous delegates and also it is documented that; TPL can leverage the underlying CPU cores more effectively than asynchronous delegates.

But in the documentation TPL considered as a library for the parallel programming.

And we also have Concurrent Collections in System.Collections.Concurrent namespace which contains the thread safe versions of the normal collections. So this makes easy that we do not need to handle explicit locks while handling the collections from different threads.

Concurrent Collections are slower compared to normal collections and little different, but thread safe. Even in the documentation and MSDN samples concurrent collections are mentioned in the parallel programming paradigm, not in a multi threaded application’s view.

I had some doubt on this, whether is it OK to use them in multi threaded environment; and raised a question in the MSDN, The thread seems to be useful and interesting.

I didn’t repost the question , answers and the code in my blog, as you can see them here

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#.