Found a fantastic reply from Stack Overflow
http://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference
Found a fantastic reply from Stack Overflow
http://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference
Garbage collection works in a separate thread. Want to check this out.
Execute the following code in a Console Project.
using System;
using System.Threading;
namespace Demo {
class Program {
public static void Main(string[] args) {
Log("Calling Test");
Test();
//GC.Collect(0, GCCollectionMode.Forced);
Thread.Sleep(2000);
Log("Called Test");
}public static void Test() {
Person p = new Person();
p = null;}
public static void Log(string s) {
Console.WriteLine("In Thread {0}({1})- {2}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId, s);
Thread.Sleep(2000);
}
}public class Person {
public Person() {
Program.Log("Person");
}
~Person() {
Program.Log("~Person");
}
}
}
You can expect an output showing some logs in a main thread and the destructor log in a separate thread. Garbage collection is done automatically while the program exists as it a small program and does not usually do a collection in between the program.
To check the forced collection, uncomment the following line in main.
//GC.Collect(0, GCCollectionMode.Forced);
One of the important operation in list of values is filtering. in LINQ filtering can be done with where clause or Where extension method.
Where clause receives value of each element and needs an expression that returns a boolean value based on the input element. Result will be the list of elements which results true while evaluating the where clause.
Sample 1
Extension Method
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Where(number => number > 2);
LINQ
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected =from number in numbers where number > 2 select number;
Sample 2
Extension Method
IEnumerable<Employee> managers = employees.Where(employee => employee.Role==”Manager”);
LINQ
IEnumerable<Employee> managers =
from employee in employees
where employee.Role==”Manager”
select employee;
LINQ statements are simple like SQL, with minor changes. One of the important change is the Select clause comes later in LINQ. Examples shown in previous posts can be rewritten as follows.
Query 1
Extension Method
IEnumerable<int> selected = numbers.Select(number => number);
------- ------ ------ ------
Part1 Part2 Part3 Part4
LINQ
IEnumerable<int> selected = from number in numbers select number;
------ ------- ------ ------
Part3 Part1 Part2 Part4
Query 2
Extension Method
IEnumerable<int> selected = numbers.Select(number => number * 2);
------- ------ ------ ----------
Part1 Part2 Part3 Part4
LINQ
IEnumerable<int> selected = from number in numbers select number * 2;
------ ------- ------ ----------
Part3 Part1 Part2 Part4
Query 3
Extension Method
IEnumerable<string> selected =
numbers.Select(number => (number * 2).ToString());
------- ------ ------ -----------------------
Part1 Part2 Part3 Part4
LINQ
IEnumerable<string> selected =
from number in numbers select (number * 2).ToString();
------ ------- ------ -----------------------
Part3 Part1 Part2 Part4
Query 4
Extension Method
IEnumerable<string> selected =
employees.Select(employee => employee.Name);
--------- ------ -------- -------------
Part1 Part2 Part3 Part4
LINQ
IEnumerable<string> selected =
from employee in employees select employee.Name;
-------- --------- ------ -------------
Part3 Part1 Part2 Part4
Here the
Part1 is the source on which the LINQ is to be executed
Part2 is the operation to be executed, here the transformation
Part3 is the alias name to be used for each item in the source
Part4 is the transformation to be applied, it can be any complex expression returning a single value
Linq does few things in background for better performance. One of the important thing is lazy loading. Linq statements or methods are not executed immediately in the very statement. To verify this we can use the following sample class.
public class Employee {
private string name;
public string Name {
get {
Console.WriteLine("Name Get ");
return name;
}
set {
name = value;
}
}
}
In the above code, whenever the Employee name is retrieved it will print the message “Name Get” in the console.
Following code uses the above Employee class for LINQ.
Employee[] employees = new Employee[] {
new Employee { Name = "John" },
new Employee { Name = "Bill" },
new Employee { Name = "Steve" } };
IEnumerable<String> selected = employees.Select(employee => employee.Name);foreach (String item in selected)
Console.WriteLine(item);
Output will be
Name Get
John
Name Get
Bill
Name Get
Steve
Above output clearly shows the Select is not immediately executed.
If we print the Type name of “selected” variable, we can see how this is done.
We can use the following statement to check this.
Console.WriteLine(selected.GetType().FullName);
Output
System.Linq.Enumerable+WhereSelectArrayIterator`2[Employee, String]
So during the execution .Net stores the transformation information in the WhereSelectArrayIterator.
WhereSelectArrayIterator class is an internal class, so cannot see the details using Object Browser, but, we can see the details using reflection. We can see this in further posts.
We can force the execution of LINQ statements to complete using some other LINQ extensions. Some of them are,
Example
Employee[] employees = new Employee[] {
new Employee { Name = "John" },
new Employee { Name = "Bill" },
new Employee { Name = "Steve" } };
List<String> selected = employees.Select(employee => employee.Name).ToList();foreach (String item in selected)
Console.WriteLine(item);
Output
Name Get
Name Get
Name Get
John
Bill
Steve
IEnumerable’s extension method Select, automatically identifies the input and output type. Input and output types are not restricted.
So Select method is powerful enough to transform one object to another. We already have seen one example in “LINQ 10- Projection/Select- 1” which transforms an integer array to string Enumerable.
Following statement extracts the Name from Employee object.
IEnumerable<String> selected = employees.Select(employee => empoyee.Name);
Here Employees is the source IEnumerable witch generic type argument Employee. So TSource is Employee.
Transformation function gets the Name from Employee and returns it. So TResult is String.
Even we can transform a class object to another class object
IEnumerable<Manager> selected = employees.Select(employee => new Manager() {
ID = employee.ID,
Name = employee.Name
});
Above statement transforms a list of Employee objects to List of Manager Objects
Select method provides a way to transform each element to a desirable format.
Following code does nothing but gives a enumerable list of the source.
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number);
Let try a simple transformation like getting the numbers doubled
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number * 2);
foreach (var item in selected) {
Console.WriteLine(item);
}
Console.ReadKey();
Above code returns a Enumerable set of integers with values doubled from the source.
So you will get result 2,4,6,8,10
Select method is declared in System.Linq.Enumerable class as
public static IEnumerable<TResult> Select<TSource, TResult>
(this IEnumerable<TSource> source,
Func<TSource, TResult> selector);
Here TSource is automatically identified from the input enumerable. As we are using Integer Array, TSource is identified as Integer.
TResult is identified from the delegate or lambda expression passed to the method. As we are returning just the doubled number TResult is also identified as Integer.
Consider the following example which returns a String.
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<String> selected = numbers.Select(number => (number * 2).ToString());
foreach (String item in selected) {
Console.WriteLine(item);
}
Console.ReadKey();
As we are returning the string TResult is identified as String, hence the select returns IEnumerable<String>
As we discussed earlier in "LINQ 08- IEnumerable", LINQ works with IEnumerable interface along with many extension methods. These extension methods are available in System.Core assembly in .Net Framework 4.0. You can find several extension methods available in the class System.Linq.Enumerable
So If you are going to use LINQ queries, you have to add System.Core as a reference and add “using Sytsem.Linq” to your imports.
Reference: Enumerable Class
LINQ is designed to work with collections. Common use of collection is iterating through them to read, filter and manipulate them.
Following diagram shows the flow which is commonly used for reading all items with IEnumerable
Foreach loop uses the same logic to iterate through items in collections. Behind the scenes .Net uses IEnumerable for iterating through collections. All the collection classes (from arrays to generic lists) are implemented using IEnumerable. So IEnumerable interface is unavoidable for every .Net programmer.
LINQ extends the concept of IEnumerable with extension methods to provide LINQ queries. Even without LINQ, the extension method provides many collection operations like searching, transforming, grouping and ordering using IEnumerable interface.
Sample Code
var a = new int[] { 1, 2, 3, 4, 5 };
var e = a.GetEnumerator();
while (e.MoveNext()) {
Console.WriteLine(e.Current.ToString());
}
Anonymous types allows users to create objects without creating classes. In many cases, we may need to store compound related data, but that will be referred in within a particular method. In .net framework 2.0, anonymous types, we have to write a simple classes and properties to achieve this.
Anonymous types works with Automatic Type Inferencing, Auto Implemented properties and Object Initializers
Example
var e = new {
ID = 10,
Name = "John",
Designation = "Software Engineer",
Age = 25
};
C# Compiler implicitly creates a type and uses it.
Notes:
Hence
var e = new {
ID = 10,
Name = "John",
Designation = "Software Engineer",
Age = 25
};
and
var f = new {
ID = 11,
Name = "Mike",
Designation = "Software Engineer",
Age = 26
};
are considered as same type.
var e = new[]{ new {
ID = 10,
Name = "John",
Designation = "Software Engineer",
Age = 25
},
new {
ID = 11,
Name = "Mike",
Designation = "Software Engineer",
Age = 26
}};
var e = new {
ID = 10,
FirstName = "John",
LastName ="Carter",
FullName = FirstName + " " + LastName,
Designation = "Software Engineer",
Age = 25
};
Automatic type inferencing allows you to declare variables without specifying the type before the variable name.
You don’t have to specify the exact type when initializing variable with a type specific value
Example:
Instead of
int i = 10;
you can use
var i = 10;
Same can be used for objects to
var e = new Employee();
In case you want a base class type to be used for the variable, you can use casting.
var p = (new Employee()) as Person;
Note:
Object initializer provides a shortcut to initialize an object with property values.
Considering the following class.
public class Employee {
public Employee() {
}
public Employee(int id) {
this.ID = id;
}
public int ID { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
}
With object initializer, we can initialize an Software Engineer John with ID 10, in one statement.
var e = new Employee() {
ID=10,
Name="John",
Designation="Software Engineer"
};
or
var e = new Employee(10) {
Name="John",
Designation="Software Engineer"
};
Second example shows the initialization of a class with parameterized constructor.
While writing properties to classes, mostly we declare a variable and expose it through properties.
public class Employee {
private int id;
public int ID {
get { return id; }
set { id = value; }
}
}
Auto implemented properties help to reduce the code by implicitly doing the field declaration, return and assignment through get and set of the properties.
With auto implemented properties, above code can be optimized as
public class Employee {
public int ID { get; set; }
}
Notes:
Properties type is used for the implicit variable.
Implicit variable will be declared as private.
Automatically implemented properties must define both get and set accessors
We can use separate access modifier for get or set. (public int ID { get; private set; })
Lambda expressions provides a simpler mechanism, to create or pass delegates without creating a separate methods to be referred.
In other words, we can say lambda expressions are inline functions
For example consider the following
we have a delegate CalcDelegate with two integer parameters
delegate void CalcDelegate(int a, int b)
we have a method Calc requires the CalcDelegate to be passed.
int Calc(CalcDelegate, int m, int n)
To create an Add operation with this, we will create a add method
void Add(int a, int b) {return a+b;}
So that we can call the Add using Calc
Calc(Add, 1, 5);
But for using in a single location, we have to create a function for this (without lambda expressions)
With lambda expressions we can simplify this with the inline method
Calc( (a,b) => a+b, 2, 5);
Lambda expressions are simple to create
left side of => is the parameter section
right side of => is the body section
Parameter section
Body section
Extension method is a way to add methods to existing types without inheritance. It is actually a virtual implementation of static methods.
For example, we may frequently want to get the Right n characters from string. We cannot inherit string data type as it is a sealed type. Even if we have a non sealed type, it would be difficult to include the right method to existing objects.
Simplest way would be adding a static method which receives a String and a length parameter, and returns string of right n characters.
public class StringMethods{
public static string Right(string s, int n) {
return s.Substring(s.Length - n);
}}
Calling this method would be easier like,
String s = “Muthukrishnan”;
String t = StringMethods.Right(s, 5); // Will return “shnan”
Extension method makes this easier for better readability.
To convert the right static method to extension method, we have to prefix this keyword to the first parameter which marks it as the calling object.
public class StringMethods{
public static string Right(this string s, int n) {
return s.Substring(s.Length - n);
}}
With this, we can call the Right method with a simple and familiar syntax.
String s = “Muthukrishnan”;
String t = s.Right(5); // Will return “shnan”
Note: To make the Extension methods to a code, the namespace or extension class should be imported.
Language INtegrated Query, is a simplified syntax for processing collection of objects.
We can say most of the new language features in .NET 3.5 and above are innovated to realize, simplify and improve LINQ syntax.
Basically LINQ is built around IEnumerable interface. Almost all of the .Net collection objects from Arrays to Generic List and Dictionary, are implemented with IEnumerable interface.
LINQ syntaxes are realized with Extension methods and Delegates. For eg, LINQ to Objects are built with Extension methods for IEnumerable with delegate parameters.
To simplify the usage of delegate parameters, anonymous methods, lambda methods and lambda expressions are introduced.
var s = new string[] { "Apple", "Orange", "Mango" };
var l = from i in s
select i.Length;
Above is a simple LINQ query, just selects the length of string items from an array. Above can be achieved without LINQ as
var s = new string[] { "Apple", "Orange", "Mango" };
var l = s.Select(i => i.Length);
Following concepts can be used to simply the LINQ statements
We can classify the applications into the following categories
Notes:
Some of the developers may not like returning JsonResult, because it may hide the actual data type we intend to return. They may like to return an object which should be automatically converted to JSON by the controller. The default ASP.NET controller will not do this. We have a work around to fix this.
Action invocation in ASP.NET MVC controller is accomplished by ActionInvoker. IActionInvoker is the base interface used by ASP.NET MVC controller for Action invocation. System.Web.Mvc.Async.AsyncControllerActionInvoker is one of the default action invoker for ASP.NET MVC. We can change the default Action Invoker of a Controller by changing the ActionInvoker property of a controller. Before that we may have to created our own Action invoker for converted object to JsonResult.
public class JsonControllerActionInvoker : AsyncControllerActionInvoker {
protected override ActionResult CreateActionResult(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor,
object actionReturnValue) {
return actionReturnValue == null
? new EmptyResult()
: (actionReturnValue as ActionResult)
?? new JsonResult() { Data = actionReturnValue, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Then we can change the controller’s Action invoker in the controller’s constructor, with the following code.
this.ActionInvoker = new JsonControllerActionInvoker();
Instead of adding this code to all our controller class we can have a base controller for this.
public class JsonController : Controller {
public JsonController() {
this.ActionInvoker = new JsonControllerActionInvoker();
}
}
When we use Mvc controllers as REST API Services, usually we may need to return data as JSON.
If we return data as its in ASP.NET Controllers, the data will be converted to String using ToString()
public string[] MyJsonData()
{ return new String[] { "A", "B", "C" };
}
will return
System.String[]
To avoid this we can use JsonResult method in Controller class
public JsonResult MyJsonData()
{ return Json(new String[] { "A", "B", "C" });
}
If we use the above code when we need to GET the data, it may throw the below error.
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet
To avoid this we can pass a second parameter to the Json method as
public JsonResult MyJsonData()
{ return Json(new String[] { "A", "B", "C" }, JsonRequestBehavior.AllowGet);
}
In case you need to call a javascript code blocks after a Partial Postback using Update Panel, you can use the following code block after window load.
var v= Sys.WebForms.PageRequestManager.getInstance()
v.add_endRequest( function ()
{
// callback code goes here
}
);
The callback code will be called after a Partial PostBack. In case the callback method should also be called during first time page load, you can move the callback code to a method and call it in two places as mentioned below
var v= Sys.WebForms.PageRequestManager.getInstance()
MyCallBackCode();
v.add_endRequest( function ()
{
MyCallBackCode();
}
);
function MyCallBackCode()
{
// callback code goes here
}
To execute this on window load you can use jQuery
$(document).ready(function(){
var v= Sys.WebForms.PageRequestManager.getInstance()
MyCallBackCode();
v.add_endRequest( function ()
{
MyCallBackCode();
}
);
function MyCallBackCode()
{
// callback code goes here
}
});
Factory method pattern provides a way for extensibility. It is a creational pattern. Factory Method pattern, is a method that can be used to create one of the Implemented contracts (Instance of a Concrete class) among choices. Usually creational patterns hides the instantiation from the user.
You want to provide choice to your class users in a specific situation. Those choices fulfils the contract in different ways.
For example you have a part of code that has to add or multiply two values based on a configuration. You will implement this like
void Calc(int n1, int n2)
{
char op= GetOpConfig();
int r;
switch(op)
{
case ‘+’:
r=Add(n1, n2);
case ‘*’:
r=Multiply(n1, n2);
}
Display(r);
}
User has to change the code when you are implementing new methods like Subtract. User has to add another case to implement this.
void Calc(int n1, int n2)
{
char op= GetOpConfig();
int r;
switch(op)
{
case ‘+’:
r=Add(n1, n2);
case ‘*’:
r=Multiply(n1, n2);
case ‘-’:
r=Subtract(n1, n2);
}
Display(r);
}
So you both has to alter the code when the requirement changes.
You can use Factory Method pattern to solve this issue.
Factory method parameters and possible values Factory method is implemented.
Ok. Lets implement a sample for the above requirements.
Understanding the scenario
Creating Common Contract
public abstract class Operation {
public int Num1 { get; set; }
public int Num2 { get; set; }
public int Result { get; set; }
public abstract void Calc();
}
Implementing Contract
public class Add : Operation {
public override void Calc() {
Result= Num1 + Num2;
}
}public class Multiply : Operation {
public override void Calc() {
Result = Num1 * Num2;
}
}
Implementing Factory Method
public class Calculation {
public static Operation GetOperation(char op) {
switch (op) {
case '+': return new Add();
case '*': return new Multiply();
}
return null;
}
}
Using Factory Method
var cal = Calculation.GetOperation(op);
cal.Num1 = n1;
cal.Num2 = n2;
cal.Calc();
var ret = cal.Result;
Extending with Factory Method Pattern
public class Subtract : Operation {
public override void Calc() {
Result = Num1 - Num2;
}
}
case '-': return new Subtract();
We can implement the same using interfaces or delegates as contracts
Following is a stand alone HTML5 code that shows a simple sample for Html5 Geolocation API
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Location Sample</title> <script src="http://maps.google.com/maps/api/js?sensor=true"></script> <script> window.onload = Window_OnLoad; function Window_OnLoad() { var lbl = document.getElementById('lblLocation'); if (navigator.geolocation) { lbl.innerHTML = "Geolocation supported"; navigator.geolocation.getCurrentPosition( function (location) { lbl.innerHTML = location.coords.latitude + "," + location.coords.longitude; ShowGoogleMap(location.coords); AddMarker(location.coords); } ); } else { lbl.innerHTML = "Geolocation not supported"; } } var map; function ShowGoogleMap(Coords) { var mapOptions = { zoom: 15, center: new google.maps.LatLng(Coords.latitude, Coords.longitude), mapTypeId: google.maps.MapTypeId.ROADMAP }; var mapDiv = document.getElementById("divMaps"); map = new google.maps.Map(mapDiv, mapOptions); } function AddMarker(Coords, Title) { var markerOptions = { position: new google.maps.LatLng(Coords.latitude, Coords.longitude), map: map, title: Title, clickable: true }; var myLocationMarker = new google.maps.Marker(markerOptions); } </script>
</head>
<body> <span id="lblLocation"></span> <div id="divMaps" style="width:400px; height:400px"></div>
</body>
</html>
Singleton is a Creational Design Pattern. Often we may need to group a related members into a single class but only one instance of a class is enough for example Helper classes. We can solve this problem with many methods. A simple method would be using a static class with static methods.
// Singleton class
public static class Singleton {private static Data data;
public static void commonMethod1() {
}
public static void commonMethod2() {
}
}
As we marked the Singleton class as static, an instance to the Singleton class cannot be created. To access the singleton methods, we can directly invoke them using the class name as the methods are also static.
Singleton.commonMethod1();
Disadvantage of this implementation is we don’t have the control over the instantiation and destruction of this class as everything is defined as static.
To overcome this, we can implement the singleton pattern as below.
Extensions methods allows you to add methods to an existing classes without modifying or inheriting it.
Previously we were adding static methods outside the class and calling it by passing the object as a parameter.
using System;
class Program {
static void Main(string[] args) {
var emp = new Employee() { Id = 1, Name = "John" };
SampleExtensions.Print(emp);
}
}public class Employee {
public int Id { get; set; }
public string Name { get; set; }
}public static class SampleExtensions {
public static void Print(Employee emp) {
Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
}
}
We can upgrade this code using Extension methods. All we need is to
Note: Extension methods only works with reference types
using System;
class Program {
static void Main(string[] args) {
var emp = new Employee() { Id = 1, Name = "John" };
emp.Print();
}
}public class Employee {
public int Id { get; set; }
public string Name { get; set; }
}public static class SampleExtensions {
public static void Print(this Employee emp) {
Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
}
}
This in fact, improves the readability of the code, so it is easy to understand.
JQuery can be included in your asp.net web application or web site using any one of the following methods.
JQuery is a javascript library which basically designed to work on all the browsers.
JQuery contains many modules to simplify our day to day coding work.
More information can be found in Official JQuery Site.
JQuery can be used in any html based applications. As it is a javascript library, we can use it with .Net, Java, Php etc.. based web applications.
Current version of JQuery is 1.9.1
Microsoft today released Microsoft ASP.NET and Frameworks 2012.2.
Link:
http://www.microsoft.com/en-us/download/details.aspx?id=36829&WT.mc_id=rss_alldownloads_devresources
This release updates ASP.NET and includes updates to Visual Studio 2012 or Visual Studio 2012 Web Express.
For more information see instructions in the release notes at http://go.microsoft.com/fwlink/?LinkID=275132.
ASP.NET Web API
ASP.NET SignalR
ASP.NET MVC
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
Managed thread pool, provides efficient use of threads with a pool of background threads managed by system.
Example Code
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
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 is released and available on the web.
Download link: http://go.Microsoft.com/fwlink/?linkid=282650
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";
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.
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);
}
}
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
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
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!
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
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.
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]);
}
}
Thread class supports two types of methods
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);
}
}
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);
}
}
public delegate void ParameterizedThreadStart(object obj);
Output
Main Started
Main CompletedHi, Good Morning!
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!");
}
}
Output
Main Started
Main CompletedHi, Good Morning!
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
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
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
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
we can write asynchronous programming in following modes
<accessmodifier> delegate <methoddeclaration>Example
public delegate int Calc(int a, int b);
<delegatetype> <delegatevariable>Example
Calc c;
public int Add(int x, int y)
{
return x+y;
}
new <delegatetype>(<methodname>)Example
Calc c= new Calc(Add);
<delegatevariable>.Invoke(<parameters>)Example
int x = c.invoke(10, 20);
<delegatevariable>(<parameters>)Example
int x = c(10, 20);
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.
In .Net 3.5, there are 2 built in classes to support JSON serialization and deserialization.
Exception: When you try to convert a DBNull value to string this error will occur.
Description: DBNull is not equivalent to null. As DBNull is a different type. So it can not be converted to string.
Fix: ADO.NET mostly returns DBNull for database null value.
ToString() on DBNull value will return empty string
Convert.IsDBNull will return true if the given value is null
Example
String s = dr[“column”] ; // will throw error
String s= dr[“column”].ToString()l //will save empty string instead of null
String s= Convert.IsDBNull(dr[“column”])?null:dr[“column”]; // will save null for DBNull value
In VB.Net, there are two useful operators AndAlso & OrElse to Replace And & Or operators.
AndAlso & OrElse, operators are works as follows.
Both takes two operators.
When First one evaluated as false, AndAlso will not evaluate the second, as the result will surely result in false.
When First one evaluated as true, OrAlso will not evaluate the second, as the result will surely result in true.
This operation helps in one important situation, to check null and evaluate.
obj IsNot null AndAlso obj.Value=”value”
When obj is null, second condition will not be evaluated, and so, it will result in NullReferenceException.
Also, AndAlso and OrElse operators perform well than And and Or operators as the second operant will not be executed based on the result of first operand