How to create a Simple Windows Service in C#
Posted On Saturday, September 12, 2009 at at 12:37 PM by test
We all know what a Windows Service is - a long running executable that's designed to work without user interaction. They can be configured to start when the system boots and they can be run without any users logged into the system. This tutorial is going to provide step-by-step instructions on how to build a Windows Service using C# and .NET.
The first thing you're going to want to do is create a new Console Application in Visual Studio. I like to start building services as console applications so they can easily be tested and debugged before converting them to services.
In order to build services, we depend on some .NET objects location in the System.ServiceProcess
and System.Configuration.Install
assemblies. Go ahead and add those references to your project.
When you created the project, Visual Studio should have created a file called Program.cs
, which looks something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
class Program
{
static void Main(string[] args)
{
}
}
}
The only thing we need to do in order to make this class into a service is make Program
extend System.ServiceProcess.ServiceBase
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
namespace MyWindowsService
{
class Program : ServiceBase
{
static void Main(string[] args)
{
}
}
}
By extending ServiceBase
, we're given a bunch of service related functions we can override. At a minimum, every service should override OnStart
and OnStop
. These are where, as the names imply, your custom logic should go when the service is started and stopped.
class Program : ServiceBase
{
static void Main(string[] args)
{
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
There are several other functions beyond start and stop like pause, continue, and shutdown, but they're not needed for a basic service. For all available functions, check out the ServiceBase member list on MSDN.
Now we need to add some information about our service - like a name. Let's add a constructor to Program
and put it there.
class Program : ServiceBase
{
static void Main(string[] args)
{
}
public Program()
{
this.ServiceName = "My Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
The constructor is where you'd also set lots of other information about your service (if the default settings wouldn't work). These can include things like which events it can handle, what operation it can do (pause, stop, etc.), and what event log it should log information to (application, system, etc.). For us, however, the default settings will work just fine.
We're very close to having a finished service. All that left is to tell Windows what service to run when your application it executed. Just like normal applications, execution begins in the Main
function. This is where we'll create an instance of our service and tell it to run.
class Program : ServiceBase
{
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "My Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
That's it! The service implementation is complete. We can't install it yet though, because we haven't implemented an installer. To do that we need to add another class to our project called MyWindowsServiceInstaller
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
class MyWindowsServiceInstaller
{
}
}
When Visual Studio creates a class for you, it doesn't automatically make it public. It's very important that this class be made public. When you install a service, the installer will look through your assembly for public classes with a specific attribute. If it's not public, it won't find it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
public class MyWindowsServiceInstaller
{
}
}
This class needs to extend System.Configuration.Install.Installer
and be given a RunInstaller attribute. This is the attribute that the service installer looks for when installing your service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.ComponentModel;
namespace MyWindowsService
{
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
}
}
Now we need to configure how we want our service installed. We'll do this in the constructor for the class we just created.
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "My Service";
serviceInstaller.StartType = ServiceStartMode.Manual;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = "My Service";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}
This is pretty much the bare minimum when it comes to service options. We have to create a ServiceProcessInstaller
and a ServiceInstaller
. These two classes are responsible for installing the service. The ServiceProcessInstaller
installs information common to all services, and the ServiceInstaller
installs information for this specific service.
The Account
property sets which privileges you'd like the service to run under. The default is User
, but then we'd have to specify a username and a password to determine the account. I chose LocalSystem
, which gives the service a lot (probably too much) access to the local computer.
Services are identified by name, so you have to ensure serviceInstaller.ServiceName
is exactly the same as what you set in the constructor of Program
. The rest of the options are pretty obvious. All that's left is to add our two installers to the Installers
collection.
We're done! All that's left to do now is install the service.
Installing The Service
Services are installed using a tool from Microsoft called installutil.exe. This tool is free and is probably already on your computer. I doubt it's in your system path, so you might want to do a quick search for it and add it to your environment variables before continuing.
All you have to do to install your service is open a command prompt, cd to your Release directory, and type:
installutil MyWindowsService.exe
Your service is now installed and ready to go. If you bring up your services manager, you should see one labeled "My Service". Of course, if you start it, nothing will happen since we didn't actually put any code in the OnStart function.
If you want to uninstall the service, you can do so with the same utility but with the "-u" flag.
installutil -u MyWindowsService.exe
There's a lot of power that we haven't even touched in Windows Services, but this tutorial should hopefully give you a starting point on which you can expand and build some much more complex solutions. All of the example code has been attached as a Visual Studio 2008 solution.
How To Configure And Use Visual Studio Macros
Posted On Friday, September 11, 2009 at at 12:33 PM by test
Microsoft Visual Studio has pretty much every operation you'd ever need right at your fingertips through the built in keystrokes. However, there are times when you'd like the text editor to do something that isn't built in. This is where macros come in. Macros can be wired up to keystrokes and can do pretty much unlimited modifications to your text - as long as you're willing to program it. In this tutorial, I'm going to demonstrate how to import an existing macro and configure a keystroke for it.
I'm not going to show you how to write macros in this tutorial. For almost anything you need, someone has already probably written it anyway. It's just a Google search away. At some point in the future, however, I'll go into the details on how to write a custom macro.
The macro I'm going to use in this tutorial is one I found especially useful a while ago that reverses the statements on either side of an assignment operator. So this:
myVariable = myOtherVariable;
Turns into this:
myOtherVariable = myVariable;
This macro is hosted on CodeProject and was written by someone named John C.
All of Visual Studio's macros can be found using the Macro Explorer, which can be accessed through the Tools menu.
If you've never added a macro to Visual Studio, the explorer should look something like this:
Macros are placed into projects and grouped together in modules. Visual Studio has already created and added the MyMacros project with one module called Module1. As you can see, however, there are no macros in that module. This is where we're going to add the macro I linked to above. The first thing you'll want to do is right-mouse click on Module1 and add a new macro.
As soon as you hit that menu item, the Macro IDE will display. This is where you'd program your macro, but in our case, this is where we past John C's macro.
Visual Studio went ahead and put a blank macro in the module for you, but all we have to do is simply replace all of the text with John's macro.
It's not quite ready to use yet. John named his module JohnUtils, but ours is named Module1. Before this macro can be used, we need to change the name of the module in John's code to Module1.
Public Module JohnUtils
Needs to change to:
Public Module Module1
That's it. Now when you save and close the Macro IDE, the new macro will be visible in the macro explorer.
Theoretically, this macro is ready to run. If you select some lines of code, right-mouse click on the macro and select "run", it will execute on the lines you've selected. However, I don't want to have to use the mouse to run my macros. I want to hook them up to keystrokes. Fortunately, Visual Studio has a nice little keyboard editor where you can do just that. The first thing we need to do is bring up the keyboard editor, which is located under the Tools/Options menu.
That list of commands contains every command available to Visual Studio - which is a lot. It also contains all of your macros. You'll want to filter the list by simply typing "macro" in the text box above the commands.
As soon as you find the macro you want to hook up to a keystroke, simply click the shortcut keys text box and enter your keystroke. It can sometimes be difficult to find a keystroke not already used by Visual Studio, but from what I've learned, control+0 is not used anywhere. There's nothing wrong with using an existing keystroke, but it will replace whatever the original command was, so choose wisely. Once your keystroke is entered, just click the "Assign" button and everything is done. Now whenever you hit that keystroke, the selected macro will run.
There's still a lot to cover when it comes to macros, but this tutorial should give you a good introduction on how to import and use an existing macro. Look forward to more in-depth tutorials in the future on how to write your own Visual Studio macros. As always, questions and comments are always welcome.
How to make custom code snippet in Visual Studio
Posted On Sunday, September 6, 2009 at at 9:19 PM by test
A cool feature that Visual Studio has is the concept of a "code snippet." You know those chunks of code that you need to type over and over again throughout your code? Perhaps your logging calls, or even more mundane than that, the generic code for try-catch blocks. Well, the folks behind Visual Studio came up with an idea to help keep that concept to a minimum - code snippets. Essentially, it is like having that repetitive code always on your clipboard, ready to "paste" into your code - except it is way more powerful than just copying and pasting code.
If you have used Visual Studio for a while, you have probably run across some of the standard code snippets - you may even be using them intentionally all the time. Today we are going to look at first how to use snippets in your code (really easy to do), and then we are going to take a look at how you can write your own code snippets. It is in writing your own code snippets that you really start to see the power of the code snippet system, and hopefully after today's tutorial you can go off and streamline your own work flow by writing a couple snippets for yourself.
So first, lets take a look at adding existing snippets to code. There are a number of ways to do this in Visual Studio, the most common of which is to use regular intellisense. For instance, below we are about to add a for
loop snippet:
You can also get to a menu of just snippets by using the right click menu and choosing the option "Insert Snippet". And, of course, if the mouse is too much work for you, there is a keyboard shortcut that will bring up this menu directly - ctrl-k + ctrl-x. Below, you can see the menu in action as we choose again to insert the for
loop snippet.
You might be wondering "why would I want to use a for loop snippet?" - cause after all, a for loop it really isn't that complex to write. Well, what it does is give you the full for loop framework with only a couple keystrokes. This is what inserting the for loop snippet will give you:
If your not convinced that saved you that many keystrokes, theres another handy feature. See how the first "i" is highlighted and the second two are surrounded by dotted lines? That means that those variables are supposed to be the same - which mean that if you edit the first "i" right after you insert the code snippet, the other "i"s change to the new name automatically. That 'linkage' isn't kept around forever, as soon as you go and edit something other than the snippet, those dotted lines go away and any changes that you make later on don't automatically get propagated. But pretty cool, eh?
Another handy feature of snippets, is that for many of them you not only have the ability to "insert" them, you also have the ability to surround other code with them. For instance, if you had highlighted some code, done a right click, you can pick "Surround With.." from that right click menu (it is right below "Insert Snippet" in the right click menu pictured above). Then, only the code snippets that can do a "surround" operation will appear, and you can pick one and add it. And surround does exactly what you might expect - for instance, in the case of the for loop, it will surround the code you had highlighted with the for loop structure pictured above. The keyboard shortcut for this "Surround With" action is ctrl-k + ctrl-s.
Ok, enough on using code snippets - lets try and write one! For this tutorial, we are going to create a really simple snippet for performance timing. It will work as both an "insert" and "surround" code snippet, and this will be the code that it produces:
All it does is surround a block of code with a line at the start that captures the start time, and a line at the end that prints out the difference between the start time and the current time. There are two blocks that are set as editable - first, the name of the startTime
variable (which will also change the startTime
reference at the end of the snippet), and the "My function" part of the string, so that you can put a more descriptive name of exactly what you are timing.
So how do we do this? Well, all a code snippet is is an xml file - and a relatively simple one at that. Here is the basic outline of a code snippet xml file:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
</Header>
<Snippet>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Pretty standard initial xml declaration stuff. There is a CodeSnippets
block that can contain one or more CodeSnippet
blocks. Each CodeSnippet
block has a Header
block (for stuff like title and author) and a Snippet
block (for the actual snippet code). Below is an example Header
block:
<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
Code snippet for surrounding a section of code with
some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
Nothing crazy here - we give the snippet a title, a shortcut (which is what shows up in all the intellisense menus), a description and an author. With the SnippetTypes
block, you declare what type(s) this snippet supports - in this case, it can do both "SurroundsWith" and "Expansion" (i.e., insertion). So onto the actual definition of the snippet:
<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
long $startTime$ = Environment.TickCount;
$selected$ $end$
$DiagnosticsDebug$.WriteLine(String.Format(
"$message$ took {0} ticks.", Environment.TickCount - $startTime$));
]]>
</Code>
</Snippet>
There are two main sections here, Declarations
and Code
. It is in the declarations that we can declare the special variables that appear in multiple places in the code (like startTime
), or variables that just need to be edited when the snippet appears (like the "My function" string). As you can see, the first literal that we declare is startTime
- we give it a name to refer to it as in the snippet (in this case "startTime"), a tool tip that will appear for the user describing what the variable is, and a default value. We can then use this literal down inside the code snippet itself - refering to it as $startTime$
.
The next literal is just as simple - it is the placeholder for the "My function" string, and we call it message
. You can see it down in the code in the output string refered to as $message$
. The third literal is kind of weird. It is not editable by the user (declared by the Editable="false"
attribute), and it has a Function
tag. What this allows us to do is have the snippet figure out automatically if it should output the code using the full reference System.Diagnostics.Debug
or just the shorthand Debug
. If already have a using System.Diagnostics;
statement in your code, then there is no need for the full declaration, and the snippet realizes this. The work is actually done in that SimpleTypeName
function in the Function
tag. You can read more about this and the other available functions for use in snippets in the MSDN docs.
And that brings us down to the actual code inside the Code
tag. Most of this is the actual code that will appear after insertion, and we already explained what $startTime$
and $message$
. There are two other oddities here - $selected$
and $end$
. They are both reserved identifiers in code snippets - $selected
represents whatever the user had highlighted when they decided to do a "Surround With" snippet, and $end$
signifies where the caret should go after the user finishes inserting the snippet.
And that is about it for defining a code snippet. There are, of course, a number of other optional attributes/tags that we did not hit on with this simple snippet, but the MSDN docs do a pretty good job of explaining them. Below is the entire timing code snippet as a single block:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
Code snippet for surrounding a section of code
with some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
<Type>long</Type>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
long $startTime$ = Environment.TickCount;
$selected$ $end$
$DiagnosticsDebug$.WriteLine(String.Format(
"$message$ took {0} ticks.", Environment.TickCount - $startTime$));
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
But wait! You might be wondering how you actually add a code snippet for Visual Studio to use after you have created it. You will want to go up to the Tools menu and choose Code Snippets Manager:
Once you click on that, you get the Code Snippets Manager dialog:
And from here it is pretty self explanatory - you can import snippet files (using the aptly named "Import" button), or you can add a folder's worth (in which case, as you add and remove snippets from that folder, they will appear/disappear from the available snippets).
I hope you've enjoyed this introduction to Visual Studio snippets. There are a number of resources out there for finding code snippets that other people have written, such as Got Code Snippets. If you have any questions about writing your own snippets, or cool uses for them, please leave a comment.
ASP.NET, HTML, JavaScript Snippet Support (VS 2010 and .NET 4.0 Series)
Posted On at at 9:04 PM by test
ASP.NET, HTML, JavaScript Snippet Support (VS 2010 and .NET 4.0 Series)
This is the sixth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release.
Today’s post covers another useful improvement in VS 2010 – HTML/ASP.NET/JavaScript snippet support. Snippets allow you to be more productive within source view by allowing you to create chunks of code and markup that you can quickly apply and use in your application with a minimum of character typing.
Visual Studio has supported the concept of “snippets” for VB and C# in previous releases – but not for HTML, ASP.NET markup and JavaScript. With VS 2010 we now support snippets for these content types as well.
Using ASP.NET Snippets
Let’s walkthrough how we can use snippets to quickly implement a common security scenario. Specifically, we’ll implement the functionality necessary to display either a “[ Login ]” link or a “[ Welcome UserName ]” message at the the top right of a site depending on whether or not the user is logged in:
The above functionality is automatically added for you when you create a project using the new ASP.NET Project Starter Template in VS 2010. For the purpose of this walkthrough, though, we’ll assume we are starting with a blank master page and will build it entirely from scratch.
We’ll start by adding a standard
We are going to use the built-in
Typing in “ We’ll select the built-in “loginview” code snippet from the above list and hit the “tab” key to complete it: Want to read full article, Go to Scott Blog Happy Reading
C# Sharp Programming Basics Adding Sound - Part One
Posted On at at 7:40 PM by testMaking a simple Calculator in C#(C sharp)
Posted On Saturday, September 5, 2009 at at 7:34 PM by testC# Tutorial: Writing If Statements and Boolean Tests
Posted On Friday, September 4, 2009 at at 7:33 PM by testAn Introduction to Test Driven Development in C#
Posted On Thursday, September 3, 2009 at at 7:30 PM by testInheriting from Forms in Visual Studio using C#
Posted On Wednesday, September 2, 2009 at at 7:29 PM by testWhat is new .NET RIA CTP2009 July?
Posted On Tuesday, September 1, 2009 at at 9:31 PM by test
Here is a list of what is new in the July 2009 Preview:
1. A new and improved model for handling operations on the client – you can more easily specify callback/event for an operation, track its status and cancel it.
2. Improved class library support
3. Extensibility points in generated code
4. Cleaner user model and better extensibility support for Application services
5. Better DomainDatasource capability for handling paging and updates.
6. Cleaner shared code support
7. First wave of ADO.NET Data Services alignment (add a DomainService to DataService for writing app logic / expose DomainService as DataService).
8. Bug fixes and initial performance improvement on the server
How to use C# Events
Posted On at at 7:25 PM by testHow to use Visual Inheritance in VS2010 .
Posted On at at 2:29 PM by test
First of all i would like to explain a bit about the inheritance, Inheritance is one of the most important property of Object Oriented Programming language ,by which we reuse the code and extend the existing functionality where there is a relation of "IS A" exists in two classes . For example
Lets take an example in C#
public class base
{
public base(){
System.out.println("base class Constructor");
}
public void print ()
{
System.out.println("Base Class");
}
}
public class derived :base
{
public derived()
{
base.base();
System.out.println("derived class");
}
public void printEx(){
System.out.println("Printinng extended functionality");
}
}
This is how we use inheritance in C# but we are lacking this feature in Windows Forms applications where we want to reuse the existing windows forms to extend the functionality.This feature is available now in VS2010 where we can use our existing Win Form as base form to inherit from , thats called
visual inheritance.
Steps to use Visual inheritance in VS2010
1: Create a Windows Form project in VS2010
2: By default one Win Form will be added with name Form1.cs or vb. whatever language you use for creating Win Apps
3: Design this form
4: Build the project so that DLL is build for this project
5: Now add one more Win Form to project and select Inherited Form as given below in figure.
Note : if you dont compile your Form1.cs than you will not be able to add Form1.cs as base form to inherit from.
6: Now you will see that your Form2.cs will have all the controls of your base Form1.cs on your Form2.cs
Now question arises, how to access the controls of base class ie Form1.cs.
1: Best practices say that you should provide public getter and setter on the base class.
or
2: You can change the access modifier of base class(Form1.cs) control to Public or Protected as per your design .
Now build the application and run it .
Happy Coding.
Null Object Design Pattern in C#
Posted On Sunday, August 30, 2009 at at 7:11 PM by testHow to use System Windows Forms in C#
Posted On Saturday, August 29, 2009 at at 4:51 PM by testWhat are Stacks & Queues
Posted On Friday, August 28, 2009 at at 4:50 PM by testHow to use Windows Media in C#
Posted On Thursday, August 27, 2009 at at 4:49 PM by testHow to use Flash Objects in C#
Posted On Wednesday, August 26, 2009 at at 4:48 PM by testWhat Silverlight Class Libraries developer should know ?
Posted On Tuesday, August 25, 2009 at at 9:45 PM by test
In order to write practical code, you need to know quite a bit about the classes you have to
work with. That means acquiring a thorough knowledge of the core class libraries that ship
with Silverlight.
Silverlight includes a subset of the classes from the full .NET Framework. Although it
would be impossible to cram the entire .NET Framework into Silverlight—after all, it’s a 4MB
download that needs to support a variety of browsers and operating systems—Silverlight
includes a remarkable amount of functionality.
The Silverlight version of the .NET Framework is simplified in two ways. First, it doesn’t
provide the sheer number of types you’ll find in the full .NET Framework. Second, the classes
that it does include often don’t provide the full complement of constructors, methods, properties,
and events. Instead, Silverlight keeps only the most practical members of the most
important classes, which leaves it with enough functionality to create surprisingly compelling
code.
• mscorlib.dll. This assembly is the Silverlight equivalent of the mscorlib.dll assembly
that includes the most fundamental parts of the .NET Framework. The Silverlight version
includes core data types, exceptions, and interfaces in the System namespace;
ordinary and generic collections; file management classes; and support for globalization,
reflection, resources, debugging, and multithreading.
• System.dll. This assembly contains additional generic collections, classes for dealing
with URIs, and classes for dealing with regular expressions.
• System.Core.dll. This assembly contains support for LINQ. The name of the assembly
matches the full .NET Framework, which implements new .NET 3.5 features in an
assembly named System.Core.dll.
• System.Net.dll. This assembly contains classes that support networking, allowing you
to download web pages and create socket-based connections.
• System.Windows.dll. This assembly includes many of the classes for building Silverlight
user interfaces, including basic elements, shapes and brushes, classes that
support animation and data binding, and a version of the OpenFileDialog that works
with isolated storage.
• System.Windows.Browser.dll. This assembly contains classes for interacting with
HTML elements.
• System.Xml.dll. This assembly includes the bare minimum classes you need for XML
processing: XmlReader and XmlWriter.
Thats all you need to know to write a Silver Light apps.
Happy Coding.
What Silverlight Class Libraries developer should know ?
Posted On at at 9:45 PM by test
In order to write practical code, you need to know quite a bit about the classes you have to
work with. That means acquiring a thorough knowledge of the core class libraries that ship
with Silverlight.
Silverlight includes a subset of the classes from the full .NET Framework. Although it
would be impossible to cram the entire .NET Framework into Silverlight—after all, it’s a 4MB
download that needs to support a variety of browsers and operating systems—Silverlight
includes a remarkable amount of functionality.
The Silverlight version of the .NET Framework is simplified in two ways. First, it doesn’t
provide the sheer number of types you’ll find in the full .NET Framework. Second, the classes
that it does include often don’t provide the full complement of constructors, methods, properties,
and events. Instead, Silverlight keeps only the most practical members of the most
important classes, which leaves it with enough functionality to create surprisingly compelling
code.
• mscorlib.dll. This assembly is the Silverlight equivalent of the mscorlib.dll assembly
that includes the most fundamental parts of the .NET Framework. The Silverlight version
includes core data types, exceptions, and interfaces in the System namespace;
ordinary and generic collections; file management classes; and support for globalization,
reflection, resources, debugging, and multithreading.
• System.dll. This assembly contains additional generic collections, classes for dealing
with URIs, and classes for dealing with regular expressions.
• System.Core.dll. This assembly contains support for LINQ. The name of the assembly
matches the full .NET Framework, which implements new .NET 3.5 features in an
assembly named System.Core.dll.
• System.Net.dll. This assembly contains classes that support networking, allowing you
to download web pages and create socket-based connections.
• System.Windows.dll. This assembly includes many of the classes for building Silverlight
user interfaces, including basic elements, shapes and brushes, classes that
support animation and data binding, and a version of the OpenFileDialog that works
with isolated storage.
• System.Windows.Browser.dll. This assembly contains classes for interacting with
HTML elements.
• System.Xml.dll. This assembly includes the bare minimum classes you need for XML
processing: XmlReader and XmlWriter.
Thats all you need to know to write a Silver Light apps.
Happy Coding.
What is Inheritance
Posted On at at 4:47 PM by testHow to create Stand-Alone Silverlight Project
Posted On Monday, August 24, 2009 at at 9:40 PM by test
The easiest way to start using Silverlight is to create an ordinary website with HTML pages and
no server-side code. Here’s how:
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 a
full-fledged ASP.NET website that can run server-side code or an ordinary website with
HTML pages .For now, choose the second option (“Automatically generates
a test page”) to create an ordinary website and click OK.
Every Silverlight project starts with a small set of essential files, as shown in above 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 created in project:
• 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 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—custom classes that derive from UserControl. 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 the 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, which contains information about your project (such as its name,
version, and publisher) that’s 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, make sure you’ve
compiled your application at least once. Then, click the Show All Files button at the top of the
Solution Explorer, and expand the Bin\Debug folder (which is where your application is compiled)
Creating a Simple Silverlight Page
As you’ve already learned, every Silverlight page includes a markup portion that defines the
visual appearance (the XAML file) and a source code file that contains event handlers. To customize
your first Silverlight application, you simply need to open the Page.xaml file and begin
adding markup.
Visual Studio gives you two ways to look at every XAML file—as a visual preview (known
as the design surface) or the underlying markup (known as the source view). By default, Visual
Studio shows both parts, stacked one on the other. Figure shows this view and points out
the buttons you can use to change your vantage point.
As you’ve no doubt guessed, you can start designing your XAML page by dragging controls
from the Toolbox and dropping them onto the design surface. However, this convenience
won’t save you from learning the full intricacies of XAML. In order to organize your elements
into the right layout containers, change their properties, wire up event handlers, and use Silverlight
features like animation, styles, templates, and data binding, you’ll need to edit the
XAML markup by hand.
To get started, you can try creating the page shown here, which defines a block of text and
a button. The portions in bold have been added to the basic page template that Visual Studio
generated when you created the project.
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="100">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel>
<TextBlock x:Name="lblMessage" Text="Hello world."
Margin="5"></TextBlock>
<Button x:Name="cmdClickMe" Content="Click Me!" Margin="5"></Button>
</StackPanel>
</Grid>
</UserControl>
This creates a page that has a stacked arrangement of two elements. On the top is a block
of text with a simple message. Underneath it is a button.
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:
<Button x:Name="cmdClickMe" Click="cmdClickMe_Click" Content="Click Me!"
Margin="5"></Button>
This example assumes that you’ve created an event handling method named cmd-
ClickMe_Click. 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 double-clicking 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.
You can also connect an event with code. The place to do it is the constructor for your
page, after the call to InitializeComponent(), which initializes all your controls. Here’s the code
equivalent of the XAML markup shown previously:
public Page()
{
InitializeComponent();
cmdClickMe.Click += cmdClickMe_Click;
}
event handler at some point during the lifetime of your window. By comparison, the events
you hook up in XAML are always attached when the window object is first instantiated. The
code approach also allows you to keep your XAML simpler and more streamlined, which is
perfect if you plan to share it with non-programmers, such as a design artist. The drawback is
a significant amount of boilerplate code that will clutter up your code files.
If you want to detach an event handler, code is your only option. You can use the -= operator,
as shown here:
cmdClickMe.Click -= cmdClickMe_Click;
It is technically possible to connect the same event handler to the same event more than
once. This is almost always the result of a coding mistake. (In this case, the event handler will
be triggered multiple times.) If you attempt to remove an event handler that’s been connected
twice, the event will still trigger the event handler, but just once.
Testing a Silverlight Application
You now have enough to test your Silverlight project. When you run a Silverlight application,
Visual Studio launches your default web browser and navigates to the hidden browser test
page, named TestPage.html. The test page creates a new Silverlight control and initializes it
using the markup in Page.xaml.
Above Figure shows the previous example at work. When you click the button, the event handling
code runs and the text changes. This process happens entirely on the client—there is no
need to contact the server or post back the page, as there is in a server-side programming
framework like ASP.NET. All the Silverlight code is executed on the client side by the scaleddown
version of .NET that’s embedded in the Silverlight plug-in.
Insight into LINQ and its different components in .NET C# 3.5
Posted On at at 5:36 PM by test
LINQ Components
Because LINQ is so powerful, you should expect to see a lot of systems and products become LINQ
compatible. Virtually any data store would make a good candidate for supporting LINQ queries. This
includes databases, Microsoft’s Active Directory, the registry, the file system, an Excel file, and so on.
Following are the components for usage.
LINQ to Objects
LINQ to Objects is the name given to the IEnumerable<T> API for the Standard Query Operators. It is
LINQ to Objects that allows you to perform queries against arrays and in-memory data collections.
Standard Query Operators are the static methods of the static System.Linq.Enumerable class that you
use to create LINQ to Objects queries.
LINQ to XML
LINQ to XML is the name given to the LINQ API dedicated to working with XML. This interface was
previously known as XLinq in older prereleases of LINQ. Not only has Microsoft added the necessary
XML libraries to work with LINQ, it has addressed other deficiencies in the standard XML DOM, thereby
making it easier than ever to work with XML. Gone are the days of having to create an XmlDocument
just to work with a small piece of XML. To take advantage of LINQ to XML, you must have a reference to
the System.Xml.Linq.dll assembly in your project and have a using directive such as the following:
using System.Xml.Linq;
LINQ to DataSet
LINQ to DataSet is the name given to the LINQ API for DataSets. Many developers have a lot of existing
code relying on DataSets. Those who do will not be left behind, nor will they need to rewrite their
code to take advantage of the power of LINQ.
LINQ to SQL
LINQ to SQL is the name given to the IQueryable<T> API that allows LINQ queries to work with
Microsoft’s SQL Server database. This interface was previously known as DLinq in older prereleases
of LINQ. To take advantage of LINQ to SQL, you must have a reference to the System.Data.Linq.dll
assembly in your project and have a using directive such as the following:
using System.Data.Linq;
LINQ to Entities
LINQ to Entities is an alternative LINQ API that is used to interface with a database. It decouples the
entity object model from the physical database by injecting a logical mapping between the two. With
this decoupling comes increased power and flexibility, as well as complexity. Because LINQ to Entities
appears to be outside the core LINQ framework, it is not covered in this book. However, if you find
that you need more flexibility than LINQ to SQL permits, it would be worth considering as an alternative.
Specifically, if you need looser coupling between your entity object model and database,
entity objects comprised of data coming from multiple tables, or more flexibility in modeling your
entity objects, LINQ to Entities may be your answer.
Happy Reading for more in-depth knowledge of LINQ in future blogs.
What is relation between Silverlight and WPF
Posted On Sunday, August 23, 2009 at at 9:22 PM by test
Silverlight and WPF
One of the most interesting aspects of Silverlight is the fact that it borrows the model WPF uses
for rich, client-side user interfaces.
WPF is a next-generation technology for creating Windows applications. It was introduced
in .NET 3.0 as the successor to Windows Forms. WPF is notable because it not only
simplifies development with a powerful set of high-level features, it also increases performance
by rendering everything through the DirectX pipeline. To learn about WPF, you can refer
to Pro WPF in C# 2008 (Apress, 2008).
Silverlight obviously can’t duplicate the features of WPF, because many of them rely deeply
on the capabilities of the operating system, including Windows-specific display drivers and
DirectX technology. However, rather than invent an entirely new set of controls and classes for
client-side development, Silverlight uses a subset of the WPF model. If you’ve had any experience
with WPF, you’ll be surprised to see how closely Silverlight resembles its big brother. Here
are a few common details:
• To define a Silverlight user interface (the collection of elements that makes up a Silverlight
content region), you use XAML markup, just as you do with WPF. You can even
map data to your display using the same data-binding syntax.
• Silverlight borrows many of the same basic controls from WPF, along with the same
styling system (for standardizing and reusing formatting), and a similar templating
mechanism (for changing the appearance of standard controls).
• To draw 2-D graphics in Silverlight, you use shapes, paths, transforms, geometries, and
brushes, all of which closely match their WPF equivalents.
• Silverlight provides a declarative animation model that’s based on storyboards, and
works in the same way as WPF’s animation system.
• To show video or play audio files, you use the MediaElement class, as you do in WPF.
Microsoft has made no secret about its intention to continue to expand the capabilities of
Silverlight by drawing from the full WPF model. In future Silverlight releases, you’re likely to
find that Silverlight borrows more and more features from WPF. This trend is already on display
with the shift from Silverlight 1 to Silverlight 2.
What is Encapsulation
Posted On at at 4:46 PM by testHow to query a SQL Server Database using LINQ
Posted On at at 3:38 PM by test
This example queries standard Microsoft Northwind sample database
using System;
using System.Linq;
using System.Data.Linq;
using northwindEntity;
Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind");
var custs =from c in db.Customers
where c.City == "Rio de Janeiro"
select c;
foreach (var cust in custs)
Console.WriteLine("{0}", cust.CompanyName);
You may need to change the connection string that is passed to the Northwind constructor in above code for the connection to be properly made.
In the above given example, we are using System.linq and System.Data.Linq name spaces and our own NorthwindEntity namespace which contains the classes for northwind database.you u can see that I added a using directive for the northwindEntity namespace. For this example to work,you must use the entity framework class, or the Object Relational Designer, to generate entity classes for the targeted database, which in this example is the Microsoft Northwind sample database. . The generated entity classes are created in the northwindEntity namespace, which I specify when generating them. I then add the entity generated source module to my project and add the using directive for the northwindEntity namespace. Rest of example is self explanatory.
Happy Coding.
Comparision between Silverlight vs. Flash
Posted On Saturday, August 22, 2009 at at 9:18 PM by test
The most successful browser plug-in is Adobe Flash, which is installed on over 90 percent of
the world’s web browsers. Flash has a long history that spans more than ten years, beginning
as a straightforward tool for adding animated graphics and gradually evolving into a platform
for developing interactive content.
It’s perfectly reasonable for .NET developers to create websites that use Flash content.
However, doing so requires a separate design tool, and a completely different programming
language (ActionScript) and programming environment (Flex). Furthermore, there’s no
straightforward way to integrate Flash content with server-side .NET code. For example, creating
Flash applications that call .NET components is awkward at best. Using server-side .NET
code to render Flash content (for example, a custom ASP.NET control that spits out a Flash
content region) is far more difficult.
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).
The Silverlight plug-in has an impressive list of features, some of which are shared in
common with Flash, and a few of which are entirely new and even revolutionary. Here are
some highlights:
• 2-D drawing.
Silverlight provides a rich model for 2-D 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.
• 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.
• 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.
• Media.
Silverlight provides playback of Windows Media Audio (WMA), Windows Media
Video (WMV7–9), 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.
Microsoft also provides a free companion hosting service (at http://silverlight.live.
com) that gives you space to store media files. Currently, it offers a generous 10 GB.
• The common language runtime.
Most impressively, Silverlight includes a scaled-down
version of the CLR, complete with an essential set of core classes, a garbage collector, a
JIT (just-in-time) 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.
• Networking.
Silverlight applications can call old-style ASP.NET web services (.asmx) or
WCF (Windows Communication Foundation) web services. They can also send manually
created XML requests over HTTP and even open direct socket connections for fast
two-way communication. This gives developers a great way to combine rich client-side
code with secure server-side routines.
• Data binding.
Although it’s not as capable as its big brother, 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 web page—often with
just a couple of lines of code.
Of course, it’s just as important to note what Silverlight doesn’t include. Silverlight is a new
technology that’s evolving rapidly, and it’s full of stumbling blocks for developers who are used
to relying on .NET’s rich libraries of prebuilt functionality. Prominent gaps include a lack of
database support (there’s no ADO.NET), no support for 3-D drawing, no printing, no command
model, and few rich controls like trees and menus (although many developers and
component companies are building their own). All of these features are available in Windowscentric
WPF applications, and they may someday migrate to the Silverlight universe—or not.
What is Polymorphism?
Posted On at at 4:46 PM by testQuery XML using LINQ
Posted On at at 3:21 PM by test
Query XML
Example below given shows that how easy it is to displays the ease with which one
can interact with and query Extensible Markup Language (XML) data utilizing the LINQ to XML API.
You should pay particular attention to how I construct the XML data into an object named books that
I can programmatically interact with.
A Simple XML Query Using LINQ to XML
using System;
using System.Linq;
using System.Xml.Linq;
XElement books = XElement.Parse(
@"<books>
<book>
<title>Learn Integrated Query in C# 2008</title>
<author>Kulveer Singh</author>
</book>
<book>
<title>Pro WF: Windows Workflow in .NET 3.0</title>
<author>Bill Gates</author>
</book>
<book>
<title>Learn how to make Money </title>
<author>MoneyMaker</author>
</book>
</books>");
var titles = from book in books.Elements("book")
where (string) book.Element("author") == "Joe Rattz"
select book.Element("title");
foreach(var title in titles)
Console.WriteLine(title.Value);
Namespace system.linq and system.xml.linq are included to run this example. which is required by linq to run.Did you notice how I parsed the XML data into an object of type XElement? Nowhere did I create an XmlDocument. Among the benefits of LINQ to XML are the extensions made to the XML API. Now instead of being XmlDocument-centric as the W3C Document Object Model (DOM) XML API requires,LINQ to XML allows the developer to interact at the element level using the XElement class.
HashTable in C#
Posted On Friday, August 21, 2009 at at 4:45 PM by testBase Classes & Base Keyword in C#
Posted On Thursday, August 20, 2009 at at 4:43 PM by testInterface in C# Part2
Posted On Wednesday, August 19, 2009 at at 4:42 PM by testInterfaces in C#
Posted On at at 4:41 PM by testHow to use Collections in C#
Posted On Tuesday, August 11, 2009 at at 1:14 PM by testnHibernate ( Part 3)
Posted On Monday, August 10, 2009 at at 8:20 AM by test
Introduction:
In the last article we saw that how we can insert the data into the database using only few lines and without stored procedures. In this article we will look at some of the other cool features of NHibernate.
Retrieving a single record from the database:
You can easily retrieve a single record for a particular person based on the primary key. Just send in the primary key and you will be returned the object of the record.
private void Button1_Click(object sender, System.EventArgs e) { Configuration cfg = new Configuration(); cfg.AddAssembly("WebApplication1"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); Person person = (Person) session.Load(typeof(Person),1); Response.Write(person.Name); }
|
I have made the important line in bold. We are using session.Load method and sending the object type and the id of the object to pick up. In our database the id '1' belongs to 'Azam' and hence the object returned will contain information about Azam.
It is important to note that we are sending the 'PersonID' to the session.Load method and hence retrieving the live object. PersonID is also primary key in our database and an identity column. Since its an identity column we do not provide the set accessor in the PersonID property. But session.Load method requires that PersonID must have a set accessor in order to retrieve the record. In real application scenario you should have some other primary key like email or username so that you don't have to assign the identity column. |
Retrieving collection of objects:
You can also easily retrieve collection of objects. In the code below we are retrieving all the data from the table 'Person' and binding it to the datagrid.
private void Button2_Click(object sender, System.EventArgs e) { Configuration cfg = new Configuration(); cfg.AddAssembly("WebApplication1"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); IList personList = session.CreateCriteria(typeof(Person)).List(); DataGrid1.DataSource = personList; DataGrid1.DataBind(); } |
Retrieving objects based on Expression:
We can also retrieve objects based on Expressions. If we want to retrieve record of a Person whose name is 'Azam' we will just write something like:
IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.Eq("Name","Azam")).List(); |
In the above line we are simply adding an Expression just like the where clause in T-SQL. 'Eq' means Equal hence we are retrieving all the records where the property 'Name' is 'Azam'. It will return us with one record since there is only one record in the database with the name Azam.
You can also change the order of the rows retrieved. The order can be Ascending or Descending. In the code below I am retrieving the whole list and ordering them on the basis of the "Name" property in ascending order:
IList personList = session.CreateCriteria(typeof(Person)).AddOrder(NHibernate.Expression.Order.Asc("Name")).List(); |
If you have been working with T-SQL you should know that the 'IN' operator is one of the most important operators. Luckily we can use the 'IN' operator using NHibernate. The following code will return you the data of all the Person whose name is in the ArrayList. You can use any collection which implements the ICollection interface. I used Arraylist since it inherits the ICollection interface.
ArrayList myList = new ArrayList(); myList.Add("Azam"); myList.Add("Ali"); IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.In("Name",myList)).List(); |
You can also retrieve the results based on a certain range. Suppose you want all the people who work between two dates than you can use the following line.
IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.Between("DateStarted", new DateTime(2005,01,01),new DateTime(2005,12,01))).List(); |
As you can see that now we are using the "Between" operator. There are lots of other operators that you can use depending on your need.
Please note that I have included two new properties "DateCreated" and "DateEnded" in Person.cs file which maps to the two new fields "StartDate" and "EndDate" in the database. |
Searching using NHibernate:
Searching is also very easy using NHibernate. Basically you just need to search in the collection and if the record with a particular search key is found you can take the appropriate action. In the code below we are searching for a Person name "Azam". If the person is found than a message is printed on the screen saying that "Person is found".
IList personList = session.CreateCriteria(typeof(Person)).List(); foreach(Person person in personList) { if(person.Name.Equals("Azam")) { Response.Write("Azam is in the list"); break; } else { Response.Write("Azam is not in the list"); } } |
You can also change the object properties and update it easily. Suppose that you want to change the date of the Person name "Azam" which is contained in the collection. Let's see how we can do this:
IList personList = session.CreateCriteria(typeof(Person)).List(); foreach(Person person in personList) { if(person.Name.Equals("Azam")) { person.DateStarted = DateTime.Now; person.DateEnded = DateTime.Now; session.Flush(); break; } else { Response.Write("Azam is not in the list"); } } |
As you can see above that we are simply finding the right person using the name property of the object. And than assigning the new Dates to the object and finally to make the changes we flush the session so that the changes appear in the database.
95% of all the operations that you can perform using T-SQL can be performed by using NHibernate classes.
Happy coding !
nHibernate (Part2)
Posted On Sunday, August 9, 2009 at at 8:19 AM by test
Introduction:
I know you all must be really anxious to find out that how NHibernate works and how it can make your life easier. In this article we will look at the add feature of the NHibernate. I will go step by step so you understand what is going on.
Making a Class Library:
The first task is to create a class library which will be mapped using the NHibernate. So, lets make a simple class User.
public class User { private int personID; private string email; private string password; private bool status; private DateTime dateCreated;
// Defining properties public int PersonID { get { return personID; } set { personID = value; } } public string Email { get { return email; } set { email = value; } } public string Password { get { return password; } set { password = value; } }
public bool Status { get { return status; } set { status = value; } } public DateTime DateCreated { get { return dateCreated; } set { dateCreated = value; } }
|
As you can see that there is nothing special about the class. It has some private variables which you can access using the properties. All of this has been explained in my articles before.
NOTE:
All these properties will map to the database fields. That's why I have created the database script file for you. Just run the script file using query analyzer and it will create table for you. If it does not work than you can easily create a table based on the properties above. |
Creating Mapping File:
Now let's take a look at the mapping file for the User.cs class. This mapping file is called (User.hbm.xml). It's a good idea to name the mapping file based on the class name.
xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"> <class name="Glasses.Test.User, Glasses" table="Person"> <id name="PersonID" column="PersonID" type="Int32" length="4" unsaved-value="0"> <generator class="identity" /> id> <property name="Email" column= "Email" type="String" length="50"/> <property name="Password" type="String" length="50"/> <property name="Status" type="Boolean" length="1"/> <property name="DateCreated" type="DateTime"/> class> hibernate-mapping> |
Let's take a look at the mapping file now.
- Glasses.Test.User is the name of the class that I am using. Glasses is the name of the assembly, Test is the name of the folder and finally user is the class.
- Person is the name of the table
- identity means that PersonID is the identity (Automatically generated) column in the database and we don't have to supply it.
- The
tags contain name which is the name of the property in the User.cs class. - column is the "database" column.
Note:
Make sure that the mapping file is configured as the "Embedded Resource". Right click on the "User.hbm.xml" file and select properties and set build option to "Embedded Resource". |
Add Method Code:
Now let's see the Add method that adds the user object into the database. In future articles we will implement an interface and inherit from that interface to get the common functionality. But for now let's look at the easy way to add the object.
public static void Add(User user) {// make the configuration file Configuration cfg = new Configuration(); cfg.AddAssembly("Glasses"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); ITransaction transaction = session.BeginTransaction(); session.Save(user); transaction.Commit(); session.Close();
} |
- First we are making a Configuration object cfg
- We load the assembly using the AddAssembly method
- ISessionFactory interface creates a session factory which can be used to create sessions.
- ISession interface is used to create independent session which is opened by using the factory.OpenSession() method
- Once the session has been open than it means that you can communicate with the database.
- ITransaction interface which begines the session transactions.
- session.Save(user) is used to save the session.
- transaction.Commit() is used to save the data to the database.
- session.Close() finally closes the session.
The Client Code:
The Client code is pretty simple and self explanatory.
private void Button1_Click(object sender, System.EventArgs e) { User user = new User(); user.Email = "codersource@source.net"; user.Password = "mypassword"; user.Status = true; user.DateCreated = DateTime.Now; Test.User.Add(user);
} |
Don't wait now and check your database. A new entry should be added if you have done everything right. Isn't this the coolest thing ever. In the upcoming articles we will see more features of NHibernate.
I hope you enjoyed the article. Happy programming !