Wednesday, February 27, 2013

Threading: 13- Multi-threading

When one programs uses multiple threads to accomplish its tasks, it is called multithreading.

Multithreading doesn’t guaranties the sequence of execution between threads.

Sample Code

Threading: 12- ThreadPool

Managed thread pool, provides efficient use of threads with a pool of background threads managed by system.

 

Example Code

Microsoft Releases Internet Explorer 10 for Windows 7

Microsoft today released Internet Explorer 10 for Windows 7

Find below the download links

 

Internet Explorer 10 for Windows 7 32-bit Edition and Windows Server 2008 R2 32-bit Edition

http://www.microsoft.com/en-us/download/details.aspx?id=36808&WT.mc_id=rss_alldownloads_devresources

 

Internet Explorer 10 for Windows 7 64-bit Edition and Windows Server 2008 R2 64-bit Edition

http://www.microsoft.com/en-us/download/details.aspx?id=36806&WT.mc_id=rss_alldownloads_devresources

Tuesday, February 26, 2013

Threading: 11- Background & Foreground threads

Managed thread can be either background or foreground. Differences are listed below.

If all the foregrounds are completed, background threads will be automatically closed and application will be closed. By default all applications will have a main foreground thread.

 

Background threads can be created by setting Thread’s IsBackground property to true. By default, a thread will be created as foreground thread.

 

var th = new Thread(Greet);
th.Name = "Greeting";
th.IsBackground = true;

Asp.net and web tools 2012.2 released

Asp.net and web tools 2012.2 is released and available on the web.
Download link: http://go.Microsoft.com/fwlink/?linkid=282650

Monday, February 25, 2013

Threading: 10- Assigning a name to a thread

We can assign a meaningful name to the thread after creating the thread and before starting the thread.

var th = new Thread(Greet); // Create new thread
th.Name = "Greeting";

Threading: 09- Getting current thread information

Information about current thread can be obtained using Thread.CurrentThread static property.

Thread.CurrentThread returns the Thread Object related to current thread.

Thread object gives the following information about the thread.

  • Name
  • ManagedThreadId
  • IsBackground
  • IsThreadPoolThread
  • IsAlive
  • Priority
  • ThreadState

Sample Code:

using System;
using System.Threading;

// Current thread info

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
        Console.WriteLine("\tThread Name: " + Thread.CurrentThread.Name);
        Console.WriteLine("\tThread Id: " + Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("\tIs Background: " + Thread.CurrentThread.IsBackground);
        Console.WriteLine("\tIs ThreadPool Thread: " + Thread.CurrentThread.IsThreadPoolThread);
        Console.WriteLine("\tIs Alive: " + Thread.CurrentThread.IsAlive);
        Console.WriteLine("\tPriority: " + Thread.CurrentThread.Priority);
        Console.WriteLine("\tThread State: " + Thread.CurrentThread.ThreadState);
    }
}

Output

Main Started
Hi Bob, Good Morning!
        Thread Name:
        Thread Id: 11
        Is Background: False
        Is ThreadPool Thread: False
        Is Alive: True
        Priority: Normal
        Thread State: Running

Sunday, February 24, 2013

Threading: 08- Aborting a running thread

A running thread can be aborted using Thread.Abort method. When we abort a thread, a thread abort exception will be thrown in that thread.

 

using System;
using System.Threading;

// Thread.Abort

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        Thread.Sleep(500);
        th.Abort();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        try {
            Thread.Sleep(1000);
            Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
            Thread.Sleep(1000);
        }
        catch (ThreadAbortException) {
            Console.WriteLine("Greet Aborted");
        }
    }
}

 

Output:

Main Started
Main Completed
Greet Aborted

Saturday, February 23, 2013

Threading: 07- Waiting for a thread to complete, but just for a while, Thread.Join

We can wait for a thread to complete, but we cannot wait indefinitely sometimes. .Net allows us to wait for a thread to complete just for a while, using Thread.Join method.

Thread.Join method, receives a timeout in milliseconds and waits up to that period. If it is still running, it stops waiting and returns false, else returns true.

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        if (th.Join(800))
            Console.WriteLine("Greeting finished");
        else
            Console.WriteLine("Greeting is still running");
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Thread.Sleep(1000);
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
        Thread.Sleep(1000);
    }
}

 

Output:

Main Started
Greeting is still running
Main Completed
Hi Bob, Good Morning!

Threading: 06- Freezing a thread for a while- Thread.Sleep

We can make a thread sleep for a specific milliseconds. We can use this for testing the thread and asynchronous programming concepts and also we can use this to wait for a resource.

 

Example:

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        th.Join();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
       Thread.Sleep(1000);
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
       Thread.Sleep(1000);
    }
}

 

Above thread will waiting for 1 second (1000 milliseconds) before printing the greetings and after printing the greetings

Threading: 05- Waiting for thread to complete- Thread.Join

We can wait for a thread to complete using the thread’s Join method.

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        th.Join();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
    }
}

 

Join method will block the calling thread until the thread completes.

Threading: 04- Thread with multiple parameters without class or struct

Instead of creating a class to pass multiple parameters to a thread, we can use Object arrays to be passed to the method.

 

Example:

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
    }
}

Threading: 03- Thread with multiple parameters

Thread class supports two types of methods

  • Method without parameter and return values- using ThreadStart delegate
  • Method with one object type parameter and without return values- using ParameterizedThreadStart delegate

To pass multiple values to Thread, we can create a small class to store multiple parameters and send it as the parameter

 

Example:

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new GreetInfo() { Name = "Bob", Message = "Good Morning" });  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private class GreetInfo {
        public string Name { get; set; }
        public string Message { get; set; }
    }

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as GreetInfo).Name, (info as GreetInfo).Message);
    }
}

Threading: 02- Thread with parameter

We can pass one argument to thread during thread start

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start("Good Morning");  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet(object message) {
        Console.WriteLine("Hi, {0}!", message);
    }
}

 

  • Constructor of Thread class here, receives the method to be invoked using a delegate called ParameterizedThreadStart which is defined in BCL.
  • Signature of the parameterized thread start is defined in BCL as

public delegate void ParameterizedThreadStart(object obj);

  • During thread start we can pass value to the Thread

Output

Main Started
Main Completed

Hi, Good Morning!

 

Threading: 01- A Simple Thread

Program in the Sample 00 can be converted to utilize the thread as follows.

 

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start();  // Execute Greet method in the created thread
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }

    private static void Greet() {
        Console.WriteLine("Hi, Good Morning!");
    }
}

 

  • Constructor of Thread class here, received the method to be invoked using a delegate called ThreadStart which is defined in BCL.
  • Console application by default run in Main thread.
  • During th.Start, runtime creates a new thread and starts the execution of Greet method in that thread.
  • So the line after th.Start will continue to execute while Greet method is being executed in a new thread.
  • Result will vary based on system performance.

Output

Main Started
Main Completed

Hi, Good Morning!

 

Threading: 00- Life without Thread

A Simple program without threading.

Project Type: Console Application
class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        Greet();
        Console.WriteLine("Main Completed");
        Console.ReadKey();
    }
    private static void Greet() {
        Console.WriteLine("Hi, Good Morning!");
    }
}
Above programs calls a static method “Greet” from Main method.
Output

Main Started
Hi, Good Morning!
Main Completed

0x80070020- Cannot Start Web Site, The process cannot access the file because it is being used by another process

Error:
Cannot Start Web Site
There was an error while performing this operation.
Details:
The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)

More details:
As we don’t get more information from the above error message, we have to use windows event log to obtain more details
If you open event log and navigate to system log, you can obtain the following two log entries

Event Log 1
Unable to bind to the underlying transport for [::]:80. The IP Listen-Only list may contain a reference to an interface which may not exist on this machine.  The data field contains the error number.
Event Log 2
The World Wide Web Publishing Service (WWW Service) did not register the URL prefix http://*:80/ for site 1. The site has been disabled. The data field contains the error number.

Fix:
Port 80 is already is in use.
We can change the IIS web site configuration to use another port.
We can identify the program which uses port 8 using the following command
> netstat –a –b
After that we can
  • configure that program to use another port
  • configure IIS to use another port
  • stop the program temporarily and start the IIS web site
  • Uninstall the program permanently if not required, and start the IIS web site.


















Friday, February 22, 2013

Unable to create the virtual directory. ASP.NET 2.0 has not been registered on the Web server.

Error:

Unable to create the virtual directory. ASP.NET 2.0 has not been registered on the Web server. You need to manually configure you Web server for ASP.NET 2.0 in order for your site to run correctly.

Fix:

Open Command Prompt in Admin mode

Navigate to C:\Windows\Microsoft.Net\Framework\

To identify the framework versions installed, type dir /ad

 

image

Navigate to the required framework folder

> cd v2.0.50727

Run asp.net registration tool

> aspnet_regiis /i

 

This will install the asp.net of the selected framework into IIS

 

Notes:

.Net framework 2.0, 3.0 and 3.5, uses CLR 2.0

.Net framework 4.0 and 4.5 uses CLR 4.0

Thursday, February 21, 2013

Installing Windows Authentication on IIS

Windows Authentication may not be installed in IIS in some machines, which might be useful debugging and other purposes.
To Install Windows Authentication on IIS, follow the following steps.

Search for “Turn on or off windows features” in Control Panel and Open it
  • Navigate to Internet Information Services/World Wide Web Services/Security
  • Mark Windows Authentication and other authentication modes, if required
  • Click on OK and wait for the installation to complete.
  • If you have already opened the IIS Manager (inetmgr), close and reopen it to see the changes



Verifying the installation
  • 6 IIS (Internet Information Services) Manager
  • Click the root (your machine name) in left side pane
  • In the content window Select IIS/Authentication and Open it
  • There you can see the installed Authentication modes




Following Authentication modifies are available in IIS on Windows 7

  • Basic Authentication
  • Digest Authentication
  • Windows Authentication

Following Authentication modes are installed by default on IIS

  • Anonymous Authentication
  • Forms Authentication
  • ASP.Net Impersonation


Wednesday, February 20, 2013

Unable to create the virtual directory. IIS is not installed on this computer

If you try to create a virtual directory from Visual Studio, you might get the following exception when you don’t have IIS installed.

Unable to create the virtual directory. IIS is not installed on this computer. To access local IIS Web sites, you must install the following IIS components:

      Internet Information Services
      IIS 6 Metabase and IIS 6 Configuration Compatibility
      ASP.NET
      Windows Authentication

In addition, you must run Visual Studio in the context of an administrator account.

To install IIS, Search for “Turn on or off windows features” in Control Panel.
Enable the following items and Click Ok to install the following items

  • Internet Information Services
  • IIS 6 metabase and IIS 6 configuration compatibility


Keywords: IIS, ASP.NET, Virtual Directory

Thursday, February 14, 2013

Console Application: Read File

Console Application: Read File
Following source code, contains a simple console application that gets a file name as a command line argument and prints its content in the console.

Source Code
using System;
using System.IO;

namespace ReadFile {
      class Program {
            static int Main(string[] args) {
                  if (args.Length == 0) {
                        Console.WriteLine("Please specify filename.");
                        return 0;
                  }
                  if (args.Length > 1) {
                        Console.WriteLine("Too many filenames specified.");
                        return 0;
                  }
                  if(! File.Exists((args[0])))
                        Console.WriteLine("Specify file not found.");
                  Console.WriteLine(File.ReadAllText(args[0]));
                  return 1;
            }
      }
}

Sample Output

Keywords:
Console Application, Command Line Arguments, File I/O

Monday, February 11, 2013

Want to learn F#?

Want to learn F#?
Microsoft has recently unvelied an updated vesion of www.tryfsharp.org. You can try learn fsharp interactively.

Attributes

Attributes
Attributes are details/data that can be attached to assemblies, types and members.
These attributes are specific to some programs/libraries and those libraries will use those attributes to do some processing.
For example, if we use XmlAttribute attribute apon a property, that will be writen as attribute in xml while we serialize the containing object using xml serialization.

Saturday, February 02, 2013

Asynchronous Programming

Now a days computers, have multiple cores in its processors, capable of executing multiple programming in parallel. Our code should be written to utilize the available resources to provide high performance processing to our clients. To support this .Net provided many classes written on top of windows low level API.

We can write parallel programming using following concepts

  • Threads
  • Thread Pools
  • Background Worker
  • Timers
  • Delegates with Begin Invoke

we can write asynchronous programming in following modes

  • Start a code execution in a new thread and let it complete its work.
  • Start a code execution in a new thread with a method (using delegate) to thread so that the method will call back our method after completion of the program.
  • Start a code execution in a new thread and do some other work and wait for the signal from the thread about the completion of the thread.

Delegates: Passing methods as Arguments

Methods can be passed to another methods through delegates.
Find below the sample for Passing methods as Arguments

Friday, February 01, 2013

Delegates: Using Delegates

Delegate definition

is almost similar to method declarations.

Syntax
<accessmodifier> delegate <methoddeclaration>
Example
public delegate int Calc(int a, int b);

Delegate variable declaration

is just like variable declaration

Syntax
<delegatetype> <delegatevariable>
Example
Calc c;

Method assignment to delegates

To use a delegate, we have to associate a method to the delegate instance.
Method to be associated to a delegate should match the signature of the delegate, which includes parameter types and return types

Example
public int Add(int x, int y)
{
return x+y;
}

Instantiating delegates

Syntax
new <delegatetype>(<methodname>)
Example
Calc c= new Calc(Add);

Using a delegates

Delegates are basically used to invoke a method which is associated to it.
.Net automatically adds few methods to it which enables us to invoke the method.

Here Invoke(int a, int b) will be added to Calc delegate.
Methods associated with the delegates can be invoked using the following syntax

Syntax
<delegatevariable>.Invoke(<parameters>)
Example
int x = c.invoke(10, 20);

There is another simple shortcut for this.
Syntax
<delegatevariable>(<parameters>)
Example
int x = c(10, 20);

Delegates: Introduction

A delegate is a class that can hold a reference to a method.

A delegate class has a signature, and it can hold references only to methods that match its signature.

Base class for all the delegates is Delegate.

When we declare a delegate, it implicitly defines a class derived from System.Delegate. It automatically adds few methods that supports method invocations.