Tuesday, December 23, 2008

Silverlight - Micorosoft's magic for RIA (Part 3)

For previous part of this post, please visit Silverlight (Part 2).

Creating an ASP.NET Web Site with Silverlight Content:

Although Silverlight does perfectly well on its own, you can also develop, test, and deploy it as part of an ASP.NET web site. Here’s how to create a Silverlight project and an ASP.NET web site that uses it in the same solution:

1. Select File -> New -> Project in Visual Studio, choose the Visual C# group of project types, and select the Silverlight Application template. It’s a good idea to use the Create directory for solution option, so you can group together the two projects that Visual Studio will create—one for the Silverlight assembly and one for ASP.NET web site.


2. Once you’ve picked the solution name and project name, click OK to create it.


3. When asked whether you want to create a test web, choose the first option, Add a new Web. You’ll also need to supply a project name for the ASP.NET web site. By default, it’s your project name with the added text _Web. Finally, click OK to create the solution.

There are two ways to integrate Silverlight content into an ASP.NET application:

(1) Create HTML files with Silverlight content: You place these files in your ASP.NET web site folder, just as you would with any other ordinary HTML file. The only limitation of this approach is that your HTML file obviously can’t include ASP.NET controls, because it won’t be processed on the server.

(2) Place Silverlight content inside an ASP.NET web form: To pull this trick off, you need the help of the Xaml web control. You can also add other ASP.NET controls to different regions of the page. The only disadvantage to this approach is that the page is always processed on the server. If you aren’t actually using any server-side ASP.NET content, this creates an extra bit of overhead that you don’t need when the page is first requested.

Of course, you’re also free to mingle both of these approaches, and use Silverlight content in dedicated HTML pages and inside ASP.NET web pages in the same site. When you create a Silverlight project with an ASP.NET web site, you’ll start with both. For example, if your Silverlight project is named SilverlightApplication1, you can use SilverlightApplication1TestPage.html or SilverlightApplication1TestPage.aspx. The HTML file is identical to the test page in the ordinary Silverlight-only solution you saw earlier. The .aspx file is an ASP.NET web form that uses ASP.NET’s Xaml web control to show your Silverlight application. The end result is the same, but the Silverlight control creates the test page markup dynamically, when it’s processed on the server. (This extra step gives you a chance to use your own server-side code to perform other tasks when the page is initially requested, before the Silverlight application is downloaded and launched.) Below figure shows how a Silverlight and ASP.NET solution starts out.

Along with the two test pages, the ASP.NET web site also includes a Default.aspx page (which can be used as the entry point to your ASP.NET web site) and web.config (which allows you to configure various web site settings).





Silverlight and ASP.NET provide essentially the same debugging experience as a Silverlight-only solution. When you run the solution, Visual Studio compiles both projects and copies the Silverlight assembly to the ClientBin folder in the ASP.NET web site. (This is similar to assembly references—if an ASP.NET web site references a private DLL, Visual Studio automatically copies this DLL to the Bin folder.) Once both projects are compiled, Visual Studio looks to the startup project (which is the ASP.NET web site) and looks for the start page (which is SilverlightApplication1TestPage.aspx). It then launches the default browser and navigates to the start page.

Silverlight Compilation and Deployment:
Now that you’ve seen how to create a basic Silverlight project, add a page with elements and code, and run your application, it’s time to dig a bit deeper. In this section, you’ll see how your Silverlight is transformed from a collection of XAML files and source code into a rich browser-based application.

Compiling a Silverlight Assembly:
When you compile a Silverlight project, Visual Studio uses the same csc.exe compiler that you use for full-fledged .NET applications. However, it references a different set of assemblies and it passes in the command-line argument nostdlib, which prevents the C# compiler from using the standard library (the core parts of the .NET Framework that are defined in mscorlib.dll). In other words, Silverlight applications can be compiled like normal .NET applications written in standard C#, just with a more limited set of class libraries to draw on. The Silverlight compilation model has a number of advantages, including easy deployment and vastly improved performance when compared to ordinary JavaScript. Your compiled Silverlight assembly includes the compiled code and the XAML documents for every page in your application, which are embedded in the assembly as resources. This ensures that there’s no way for your event handling code to become separated from the user interface markup it needs. Incidentally, the XAML is not compiled in any way (unlike WPF, which converts it into a more optimized format called BAML).
Your Silverlight project is compiled into a DLL file named after your project. For example, if you have a project named SilverlightApplication1, the csc.exe compiler will create the file SilverlightApplication1.dll. The project assembly is dumped into a ClientBin folder in your project directory, along with a few other important files:

(1) A PDB file: This file contains information required for Visual Studio debugging. It’s named after your project assembly (for example, SilverlightApplication1.pdb).
(2) AppManifest.xaml: This file lists assembly dependencies.
(3) Dependent assemblies: The ClientBin folder contains the assemblies that your Silverlight project uses, provided these assemblies have the Copy Local property set to true. Assemblies that are a core part of Silverlight have Copy Local set to False, because they don’t need to deployed with your application. (You can change the Copy Local setting by expanding the References node in Solution Explorer, selecting the assembly, and using the Properties window.).
(4) TestPage.html: This is the entry page that the user requests to start your Silverlight application.
(5) A XAP file: This is a Silverlight package that contains everything you need to deploy your Silverlight application, including the application manifest, the project assembly, and any other assemblies that your application uses.

Deploying a Silverlight Assembly:
Once you understand the Silverlight compilation model, it’s a short step to understanding the deployment model. The XAP file is the key piece. It wraps the units of your application (the application manifest and the assemblies) into one neat container. Technically, the XAP file is a ZIP archive. To verify this, rename a XAP file like SilverlightApplication1.xap to SilverlightApplication1.xap.zip. You can then open the archive and view the files inside.

The XAP file system has two obvious benefits:
(1) It compresses your content: Because this content isn’t decompressed until it reaches the client, it reduces the time required to download your application. This is particularly important if your application contains large static resources , like images or blocks of text.

(2) It simplifies deployment: When you’re ready to take your Silverlight application live, you simply need to copy the XAP file to the web server, along with TestPage.html or a similar HTML file that includes a Silverlight content region. You don’t need to worry about keeping track of the
assemblies and resources.


Thanks to the XAP model, there’s not much to think about when deploying a simple Silverlight application. Hosting a Silverlight application simply involves making the appropriate XAP file available, so the clients can download it through the browser and run it on their local machines. However, there’s one potential stumbling block. When hosting a Silverlight application, your web server must be configured to allow requests for the XAP file type. This file type is included by default in IIS 7, provided you’re using Windows Server 2008 or Windows Vista with Service Pack 1. If you have Windows Vista without Service Pack 1, you have an earlier version of IIS, or you have another type of web server, you’ll need to add a file type that maps the .xap extension to the MIME type application/xsilverlight-app. For IIS instructions, see http://learn.iis.net/page.aspx/262/silverlight.

Now, you get enough basic knowledge of Silverlight. For more articles, videos, blogs please visit
http://silverlight.net/

Silverlight - Micorosoft's magic for RIA (Part 2)

For first part of this post, please visit Silverlight (Part 1).

Silverlight and Visual Studio 2008:


VS2008 does not support built in template for Silverlight application. You need to download Silverlight tools from following link:
http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=en.

VS2010 will includes built in template for Silverlight application so be patient till release of VS2010 :).

There are two types of Silverlight web sites that you can create in Visual Studio:
(1) Ordinary HTML web site: In this case, the entry point to your Silverlight application is a basic HTML file that includes a Silverlight content region.

(2) ASP.NET web site: In this case, Visual Studio creates two projects—one to contain the Silverlight application files, and one to hold the server-side ASP.NET web site that will be deployed alongside your Silverlight files. The entry point to your Silverlight application can be an ordinary HTML file or an ASP.NET web form that also includes server-generated content.

ASP.NET is a better approach in the following cases:
- You want to create a web application that combines ASP.NET web pages with Silverlight- enhanced pages.
- You want to generate Silverlight content indirectly, using ASP.NET web controls.
- You want to create a Silverlight application that calls a web service, and you want to design the web service at the same time (and deploy it to the same web server).

Creating a Silverlight Project:
Now that you understand the two types of Silverlight web sites, you’re ready to create a new Silverlight application by following these steps:

1. Select File ->New ->Project in Visual Studio, choose the Visual C# group of project types, and select the Silverlight Application template. As usual, you need to pick a project name and a location on your hard drive before clicking OK to create the project.

2. At this point, Visual Studio will prompt you to choose whether you want to create an ordinary HTML web site or a full-fledged ASP.NET web site that can run server-side code. For now, choose the second option to create an ordinary web site and click OK.

The Anatomy of a Silverlight Application:
Every Silverlight project starts with a small set of essential files, as shown in Figure.



All the files that end with the extension .xaml use a flexible markup standard called XAML. All the files that end with the extension .cs hold the C# source code that powers your application.

Here’s a rundown of the files shown in above Figure:
- App.xaml and App.xaml.cs: These files allow you to configure your Silverlight application. They allow you to define resources that will be made available to all the pages in your application, and they allow you to react to application events such as startup, shutdown, and error conditions. In a newly generated project, the startup code in the App.xaml.cs file specifies that your application should begin by showing Page.xaml.

- Page.xaml: This file defines the user interface (the collection of controls,
images, and text) that will be shown for your first page. Technically, Silverlight pages are user controls. A Silverlight application can contain as many pages as you need—to add more, simply choose Project à Add New Item, pick the Silverlight User Control template, choose a file name, and click Add.

- Page.xaml.cs: This file includes the code that underpins your first page, including the event handlers that react to user actions.

Along with these four essential files, there are a few more ingredients that you’ll only find if you dig around. Under the Properties node in Solution Explorer, you’ll find a file named AppManifest.xml, which lists the assemblies that your application uses. You’ll also find a file named AssemblyInfo.cs that contains information about your project (such as its name, version, and publisher), which is embedded into your Silverlight assembly when it’s compiled. Neither of these files should be edited by hand—instead, they’re modified by Visual Studio when you add references or set projects properties. Lastly, the gateway to your Silverlight application is an automatically generated but hidden HTML file named TestPage.html. To see this file, click the Show All Files icon at the top of the Solution Explorer window, and expand the ClientBin folder (which is where your application is compiled).
Let’s add one textblock named “lblMessage” and one button named “cmdClickMe” on page.xaml.

Adding Event Handling Code:
You attach event handlers to the elements in your page using attributes, which is the same approach that developers take in WPF, ASP.NET, and JavaScript. For example, the Button element exposes an event named Click that fires when the button is triggered with the mouse or keyboard. To react to this event, you add the Click attribute to the Button element, and set it to the name of a method in your code.


This example assumes that you’ve created an event handling method named cmd_ClickMe. Here’s what it looks like in the Page.xaml.cs file:

private void cmdClickMe_Click(object sender, RoutedEventArgs e)
{
lblMessage.Text = "Goodbye, cruel world.";
}

You can’t coax Visual Studio into creating an event handler by doubleclicking
an element or using the Properties window (as you can in other types of projects). However, once you’ve added the event handler, you can use IntelliSense to quickly assign it to the right event. Begin by typing in the attribute name, followed by the equal sign. At this point, Visual Studio will pop up a menu that lists all the methods that have the right syntax to handle this event and currently exist in your code-behind class. Simply choose the right event handling method.


For next part of this post, please visit Silverlight (Part 3).

Monday, December 22, 2008

Silverlight - Micorosoft's magic for RIA (Part 1)

Hi Friends, sorry for delay in new post. Actually, I was busy with some personal stuff. Today, I got time and going to discuss Silverlight.

Microsoft has released two versions of Silverlight: Silverlight 1.0 and Silverlight 2.0. Personally I don’t like Silverlight 1.0. The actual magic begins with Silverlight 2.0. So let’s start our journey with Silverlight 2.0.

Silverlight is a framework for building rich, browser-hosted applications that run on a variety of operating systems. Silverlight works its magic through a browser plug-in. When you surf to a web page that includes some Silverlight content, this browser plug-in runs, executes the code, and renders that content in a specifically designated region of the page. The important part is that the Silverlight plug-in provides a far richer environment than the traditional blend of HTML and JavaScript that powers ordinary web pages.


Silverlight Vs. Flash
The most successful browser plug-in is Adobe Flash, which is installed on over 90 percent of the world’s web browsers. It’s perfectly reasonable for .NET developers to create web sites that use Flash content. However, doing so requires a separate design tool and a completely different programming language (ActionScript) and programming environment (Flex).

Silverlight aims to give .NET developers a better option for creating rich web content. Silverlight provides a browser plug-in with many similar features to Flash, but one that’s designed from the ground up for .NET. Silverlight natively supports the C# language and embraces a range of .NET concepts. As a result, developers can write client-side code for Silverlight in the same language they use for server-side code (such as C# and VB) and use many of the same abstractions (including streams, controls, collections, generics, and LINQ).


Features Silverlight 2.0:

(1) Lightweight download: In order to encourage adoption, Silverlight is installed with a small-size setup (about 4MB) that’s easy to download.

(2) 2D Drawing: Silverlight provides a rich model for 2D drawing. Best of all, the content you draw is defined as shapes and paths, so you can manipulate this content on the client side. You can even respond to events (like a mouse click on a portion of a graphic), which makes it easy to add interactivity to anything you draw.

(3) Controls: Developers don’t want to reinvent the wheel, so Silverlight is stocked with a few essentials, including buttons, text boxes, lists, and a grid. Best of all, these basic building blocks can be restyled with custom visuals if you want all of the functionality but none of the stock look.

(4) Animation: Silverlight has a time-based animation model that lets you define what should happen and how long it should take. The Silverlight plug-in handles the sticky details, like interpolating intermediary values and calculating the frame rate.

(5) Media: Silverlight provides playback of Windows Media Audio (WMA), Windows Media Video (WMV7 through WMV9), MP3 audio, and VC-1 (which supports high definition). You aren’t tied to the Windows Media Player ActiveX control or browser plug-in—instead, you can create any front end you want, and you can even show video in full-screen mode.

(6) The CLR: Most impressively, Silverlight includes a scaled-down version of the CLR, complete with an essential set of core classes, a garbage collector, a just-in-time (JIT) compiler, support for generics, threading, and so on. In many cases, developers can take code written for the full .NET CLR and use it in a Silverlight application with only moderate changes.

(7) Networking: Silverlight applications can call old-style ASP.NET web services (ASMX) or Windows Communication Foundation (WCF) web services. They can also send manually created XML requests over HTTP. This gives developers a great way to combine rich client-side code with secure server-side routines.

(8) Data binding: Although it’s not as capable as in its big brother, Windows Presentation Foundation (WPF), Silverlight data binding provides a convenient way to display large amounts of data with minimal code. You can pull your data from XML or in-memory objects, giving you the ability to call a web service, receive a collection of objects, and display their data in a webpage—often with just a couple of lines of code.


Limitations Silverlight 2.0:
- Lack of database support (there’s no ADO.NET)
- No support for 3D drawing
- No printing
- No command model and few rich controls like trees and menus


For next part of this post, please visit Silverlight (Part 2).

Thursday, October 23, 2008

Processes, Threads, AppDomains and Object Contexts

When I was new in .NET, one question always confuses me and that question is: What is the difference between Processes, Threads, Application Domains and Object Context and how they work internally?

I read good articles on these topic one or two weeks back. Today I got time to write so let’s begin…



Process:
Process term used to describe the set of resources and the necessary memory allocations used by a running application. In Windows OS, for each *.exe loaded into memory, the OS create a separate and isolated process.

Using this application isolation approach, OS can manage application more robustly. The result is a much more robust and stable environment, given that the failure of one process does not affect the other process. You can see list of running process using Windows Task Manager in Windows OS.

.NET provides number of classes to interact with processes. The System.Diagnostics namespace defines a number of types that allow you to programmatically interact with processes.


Threads:
Thread is a path of execution within a process.

Every Win32 process has exactly one main “thread” that functions as the entry point for the application and this thread known as Primary Thread.

Processes that contain a single primary thread of execution are intrinsically thread safe, given the fact that there is only one thread that can access the data in the application at a given time. However, a single-threaded process will often appear a bit unresponsive to the user if this single thread is performing a complex operation (such as printing out a lengthy text file, performing a mathematically intensive calculation, or attempting to connect to a remote server located thousands of miles away).

.NET provides facility to spawn additional secondary threads also termed Worker Threads. If worker thread is busy with other operation, the main thread is still responsive to user input, which gives the entire process the potential of delivering greater performance. The System.Threading namespace contains various types that allow you to create multithreaded applications.


Application Domains:
The traditional Win32 application directly hosted within a process, while .NET executables are not hosted directly within a process. Rather, a .NET executable is hosted by a logical partition within a process termed as application domain.

This additional subdivision of process offers sever benefits, some of them are:

• AppDomains are far less expensive in terms of processing power and memory than a fullblown process. Thus, the CLR is able to load and unload application domains much quicker than a formal process.
• AppDomains provide a deeper level of isolation for hosting a loaded application. If one
AppDomain within a process fails, the remaining AppDomains remain functional.

As suggested in previous list, a single process can host any number of AppDomains. Given this fact, be very aware that an application running in one AppDomain is unable to obtain data of any kind (global variables or static fields) within another AppDomain unless they make use of a distributed programming protocol (such as Windows Communication Foundation).

Every process contains at least one application domain which termed as default application domain. This specific application domain is automatically created by the CLR at the time the process launches. After this point, the CLR creates additional application domains on an as-needed basis.

We can also create Application Domain programmatically using System.AppDomain class.


Object Context:
Application domain further subdivided into numerous context boundaries. Using context, the CLR is able to ensure that objects that have special runtime requirements are handled in an appropriate and consistent manner by intercepting method invocations into and out of a given context. For example, if you define a C# class type that requires automatic thread safety (using the [Synchronization] attribute), the CLR will create a “synchronized context” during allocation.

Just as a process defines a default AppDomain, every application domain has a default context. This default context (sometimes referred to as context 0) is used to group together .NET objects that have no specific or unique contextual needs. As you may expect, a vast majority of .NET objects are loaded into context 0. If the CLR determines a newly created object has special needs, a new context boundary is created within the hosting application domain.

Context-agile objects: .NET types that do not demand any special context are termed context-agile objects.

Context-bound objects: .NET types that demand special context allocation are termed context-agile objects.

Wednesday, October 8, 2008

New Features of C#.NET 2008 Language (Part 2)

This is a second part of my post "New Features of C#.NET 2008 Language (Part 1)".


(4) Extension Methods:

As we know, once a type is defined and compiled into a .NET assembly, its definition is, more or less, final. The only way to add new members, update members or remove members is to recode and recompile the code base into an updated assembly.

In C# 2008, using extension methods we can add new functionality to existing complied class without directly updating that class.

This technique can be quite helpful when you need to inject new functionality into classes for which you do not have an existing code base. Using extension methods, you can add functionality to precompiled classes while providing the illusion these methods were there all along.

Restrictions:

(a) Extension methods must be defined within a static class and therefore each extension method must also be declared with the static keyword.
(b) All extension methods are marked as such by using the this keyword as a modifier on the first (and only the first) parameter of the method.
(c) Every extension method can be called either from the correct instance in memory
or statically via the defining static class!

Example:

static class MyExtensions
{
// This method allows any object to display the assembly
// it is defined in.
public static void DisplayDefiningAssembly(this object obj)
{
Console.WriteLine("{0} lives here:\n\t->{1}\n", obj.GetType().Name,
Assembly.GetAssembly(obj.GetType()));
}

// This method allows any integer to reverse its digits.
// For example, 56 would return 65.
public static int ReverseDigits(this int i)
{
// Translate int into a string, and then
// get all the characters.
char[] digits = i.ToString().ToCharArray();
// Now reverse items in the array.
Array.Reverse(digits);
// Put back into string.
string newDigits = new string(digits);
// Finally, return the modified string back as an int.
return int.Parse(newDigits);
}
}

Now that we have these extension methods, so all objects have a new method named DisplayDefiningAssembly(), while System.Int32 class have method named ReverseDigits().

// The int has assumed a new identity!
int myInt = 1234;
myInt.ReverseDigits();

// So has the DataSet!
System.Data.DataSet ds = new System.Data.DataSet();
ds.DisplayDefiningAssembly();


(5) Object Initializer Syntax:
Using this technique, it is possible to create a new type variable and assign a slew of properties and/or public fields in a few lines of code. Syntactically, an object initializer consists of a comma-delimited list of specified values, enclosed by the { and } tokens. Each member in the initialization list maps to the name of a public field or public property of the object being initialized.

Example:
Class A
{
private int customerId;
private string customerName;
public CustomerId
{
Get { return customerId; }
Set { customerId = value; }
}
public CustomerName
{
Get { return customerName; }
Set { customerName = value; }
}
}

Now, you can declare object of class A as follow:
A objA = new A{CustomerId = 1, CustomerName = “XYZ};

Collection Initialization:

This syntax makes it possible to populate a container (such as ArrayList or List) with items using a syntax that models that of a simple array. Consider the following examples:


// Init a standard array.
int[] myArrayOfInts = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Init a generic List<> of ints.
List myGenericList = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Init an ArrayList with numerical data.
ArrayList myList = new ArrayList { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };


(6) Anonymous Types:

There are other times in programming when you would like to define a class simply to model a set of encapsulated (and somehow related) data points without any associated methods, events, or other custom functionality. Furthermore, what if this type is only used internally to your current application and it’s not intended to be reused? If you need such a “temporary” type, earlier versions of C# would require you to nevertheless build a new class definition by hand:

internal class MyClass
{
// Define a set of private member variables...
// Make a property for each member variable...
}

As of C# 2008, we are now provided with a massive shortcut for this very situation termed anonymous types, When you define an anonymous type, you do so by making use of the new var keyword in conjunction with the object initialization syntax. E.g.

var myCust = new {customerId = 1, customerName = “XYZ”};

At compile time, the C# compiler will autogenerate a uniquely named class on our behalf. Given the fact that this class name is not visible from C#, the use of implicit typing using the var keyword is mandatory.

Limitations of anonymous type:

• You don’t control the name of the anonymous type.
• Anonymous types always extend System.Object.
• The fields and properties of an anonymous type are always read-only.
• Anonymous types cannot support events, custom methods, custom operators, or custom overrides.
• Anonymous types are always implicitly sealed.
• Anonymous types are always created using the default constructor.

Tuesday, October 7, 2008

New Features of C#.NET 2008 Language (Part 1)

Everbody wondering Microsoft releasing new version of .NET very frequently so it is some what difficult to learn new features. I was thinking to write artical on new features of C#.NET 2008 language. Today I got some time to write so lets starts with summary of new features.

Followings are the new features of C#.NET 2008:



  1. Implicitly Typed Local Variables
  2. Automatic Properties
  3. Partial Methods
  4. Extension Methods
  5. Object Initializer Syntax
  6. Anonymous Types

(1) Implicitly Typed Local Variables:
C# 2008 provides a new keyword var, which can use in place of specifying a formal data type (such as int, string, double). So now you can declare variable as follow:

var myCounter = 15;
var myBool = true;

When you declare variables as above, the compiler will automatically infer the underlying data types based on the initail value used to initialize the variables.
You can use this implicit typing for any type including arrays, generic types and your own custom types.

Limitations of Implicitly Typed Variables:
(1) Implicity typing applies only to local varibles in a method or property scope.
(2)We can not use var keyword to define return values, parameters or field data of a type.

// Error! var cannot be used as field data!
private var myInt = 10;
// Error! var cannot be used as a return value or parameter type
public var MethodName(var a, var b){}

(3)Local variable declared with var keyword must be assigned an initial value at the time of declaration and cannot be assigned the initial value of null.

//Error! Must assign a value
var myVar
// Error! Must assign value at exact time of declaration!
var myVar;
myVar = 0;
// Error! Can't assign null as initial value!
var myObject = null;

(4) It is illegal to define a nullable implicitly typed local variable using the C#? token.

You have seen syntax and limitations of implicitly typed local variables, I am sure you are wondering when to make use of this construct as var keyword is more confusing then int keyword for declaring integer variable. So the real use of implicitly typed local variable is in LINQ.

(2) Automatic Properties:
As a developer, we must know the use of properties. Generally we creates properties to give access of our class or interface to outside world.
C# property syntax is not too problematic but just imagine if you are modeling a class that requires 20 properties then you have to declare 20 private variables (backing fields) for 20 properties which requires lots of typing.
C# 2008 provides solution of this problem by providing feature of Automatic Properties. As the name implies, this feature will offload the work of defining a private backing field and the related C# property member to the compiler using a new bit of syntax.


e.g.
class Customer
{
// Automatic Property Syntax
public string CutomerName {get; set;}
}


When defining automatic properties, you simply specify the access modifier, underlying data type, property name and empty get/set scopes. At compile time, your class will be provided with an autogenerated private backing fields.

One more thing about automatic property, it is not possible to build read-only or write-only automatic properties.


// Read-only property? Error!
public int ReadOnlyProperty { get; }
// Write only property? Error!
public int WriteOnlyProperty { set; }


(3) Partial Methods:
As we know, .NET 2.0 provides facility of partial class which allows us to partition the full implementation of a class across multiple code files.
C# 2008 widens the scope of the partial keyword in that it can now be applied on the method level. This allows you to prototype a method in one file and implementation in another file. However C# partial methods have a number of following restrictions:

• Partial methods must return void.
• Partial methods can not have arguments with the out modifier.
• Partial methods are always implicitly private.
• Partial methods can be static or instance level.
• Partial methods can only be defined within a partial class.

Example:
Partial class A
{
public int sum(int a, int b)
{
varifynumbers(int a, int b);
}
//Partial method
partial void verifynumbers(int a, int b);
}

Implementation of verifynumers method in another file:
partial class A
{
partial void verifynumbers(int a, int b)
{
//some logic here
}
}

Uses of Partial Methods:
From above limitations, it is hard to see many useful applications of this new langauge feature. The truth is partial methods will more likely used feature!!!
Consider verifynumber() method of our example perform some very intensive calculations. By marking this method with the partial modifier, other class builders have the option of providing implementation details if they so choose. In this case, partial methods provide a cleaner solution than using preprocessor directives, supplying “dummy” implementations to virtual methods or throwing NotImplementedException objects.



In some ways, C# partial methods are a strongly typed version of conditional code compilation (via the #if, #elif, #else, and #endif preprocessor directives).

You can find second part of this post at New Features of C#.NET 2008 Language (Part 2).

BOOKS OF VB.NET 2008, C#.NET 2008, SQL SERVER 2008

Interested in 2008 series of .NET and SQL Server??? To download books of VB.NET, C#.NET and SQL Server click below icon:

Monday, October 6, 2008

Get HardDrive serial number in .NET

This is my first post in this blog which is related to getting HardDrive serial number in .NET. Getting serial number of HardDrive in .NET application is very hot topic in developer community. Mostly developer needs HardDrive serial number to avoid piracy of windows based software as I have used this idea 3 yrs. back in my windows application.


In .NET, we can not get hardware information in depth as we were in C/C++. Because of this limitation we need to use C/C++ exe or dll in our .NET application.There are many ways to use non .NET dll in .NET applications. One of famous way is to create COM component in VC++ and use that COM in our .NET application but I have not used this way becuase I don't know how to create COM component in VC++. For sake of simplity of VC++ dll I had created simple API dll in VC++ and make API call through VB.NET application


To call API dll from VB.NET, we need to follow some specific steps. I have written those steps below:

  1. Put API dll in same folder where your application's exe reside.
  2. Add reference of System.Runtime.InteropServices in the class from where you wants call API function.
  3. Add <DllImport("API Dll Name")> attribute before function name which calls the API function. This function must be Shared.
  4. e.g.
  5. <DllImport("API Dll Name")> _
    Public Shared Function getHardDriveComputerID() As String
    End Function
    'Leave function empty - DLLImport attribute forces calls to function of API dll.
    Call getHardDriveComputerID() function from any class of your application as per your requirement.

In our case, I have used API dll named "Win32.dll" (I found this dll from googling) in my VB.NET application. This dll is works for following versions of Windows:

  • Windows 98
  • Windows 2000
  • Windows NT
  • Windows XP

Below compressed file contains sample application.