Null Object Design Pattern in C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

How to use System Windows Forms in C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

What are Stacks & Queues

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

How to use Windows Media in C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

How to use Flash Objects in C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 1 comments

What Silverlight Class Libraries developer should know ?

Your Ad Here

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.

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

What Silverlight Class Libraries developer should know ?

Your Ad Here

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.

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

What is Inheritance

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

How to create Stand-Alone Silverlight Project

Your Ad Here

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.

SolutionExplorer

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.

HTMLPage

 

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.

Output

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.

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

Insight into LINQ and its different components in .NET C# 3.5

Your Ad Here

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.

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 28 comments

What is relation between Silverlight and WPF

Your Ad Here

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.

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

What is Encapsulation

Your Ad Here

Subscribe
Posted in | 0 comments

How to query a SQL Server Database using LINQ

Your Ad Here

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.

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

Comparision between Silverlight vs. Flash

Your Ad Here

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.

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 60 comments

What is Polymorphism?

Your Ad Here

Subscribe
Posted in | 0 comments

Query XML using LINQ

Your Ad Here

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.

Subscribe
Posted in | 1 comments

HashTable in C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

Base Classes & Base Keyword in C#

Your Ad Here

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

Interface in C# Part2

Your Ad Here

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

Interfaces in C#

Your Ad Here

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

How to use Collections in C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

nHibernate ( Part 3)

Your Ad Here

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 !

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 8 comments

nHibernate (Part2)

Your Ad Here

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 !

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

Introduction to Object Relational Mapping with nHibernate (Part1)

Your Ad Here

This is an article series in which I will talk about using O/R Mapping. O/R Mapping can ease your life since you don't have to write those hefty stored procedures to access database. O/R Mapping will also put an end to using datasets in your applications. In the first part of the article I will just discuss that why we need O/R Mapping and what it is all about. The fun part (coding) and seeing mapping in action will start from the next article. This is Edited !

Introduction:

We all are familiar with datasets which is a carrier used to carry data from one layer to another. In my previous article I described some of the pitfalls of using datasets. Datasets are most commonly used when we are accessing database. The common pattern of accessing data from the database is given in the following steps:

1) Make connection to the database

2) Make DataAdapter

3) Execute commands using dataadapter or command objects using stored procedures or Ad-hoc queries.

4) Fill the dataset using dataadapter

5) Bind dataset to the control on the webform.

The above procedure does not look that long but consider doing this over and over and over again. What will happen when some database field you misspelled and now its occurring in 200 stored procedures. You need to tell your Boss that you need a week or even more to fix this simple spelling problem. Not only that but migration can also be a big problem. If you have a stored procedure that takes 5 seconds to execute (Although 5 seconds is too long) and some one tweaked the procedure so now it runs in <>

What if I told you that you can insert, delete, update, edit in other words perform all type of database operations without executing any SQL at all. This seems impossible and kind of a crazy thought but this is what O/R Mapping is all about. O/R Mapping also known as Object Relationship Mapping which allows us to map our data in file(s) and use those mapping files to retrieve or add data to the database. The main idea behind the O/R Mappings is relationships. Consider the following query:

SELECT Person.Name, Person.Email FROM Person,Customer

WHERE Person.PersonID = Customer.CustomerID

As you can see that Person table and the Customer table has relationship between them which let's them perform different actions. Just in the same way O/R mapping is also relationships and these relationships can be created in files.

There are many O/R Mappers available to download. Some are free and some are pretty expensive. In this article and for the rest of the series we will be looking at the NHibernate O/R Mapper which is a free and open source. You can download the NHibernate O/R Mapper from http://nhibernate.sourceforge.net/ .

Here is a list of different O/R Mappers (List of O/R Mappers)

When not to use O/R Mapping:

You should not use O/R Mapping when your business logic is dependent on complex stored procedures. Having said so if you have business logic implemented in stored procedures than you have another thing coming :). Almost 95% of all the stored procedures that you write can be represented by O/R Mapping.

Installing NHibernate:

Installation is pretty simple. I assume you downloaded the Zip file from http://sourceforge.net/project/showfiles.php?group_id=73818. Once you done downloading simply extract it on your hard drive. It will have different folders inside the main directory, some of those folders contains the code and some have different type of files. Your concern will be the .dll files in the bin directory.

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 2 comments

Loading User Control Dynamically in C#

Your Ad Here

Abstract:
User Controls are great in ASP.NET. They let us divide the page into small sections. You can easily use User Controls on a ASP.NET page by simply dragging and dropping the control from the solution explorer. Sometimes we need to load the User Control dynamically. In this small article we will learn how to load the User Control dynamically.

Introduction:

User Controls are great in ASP.NET. They let us divide the page into small sections. You can easily use User Controls on a ASP.NET page by simply dragging and dropping the control from the solution explorer. Sometimes we need to load the User Control dynamically. In this small article we will learn how to load the User Control dynamically.

Loading User Control Dynamically:

There are no tricks involve in loading User Control dynamically and its simple as anything else. All you have to do is to make an instance of the User Control and add it to the Page Controls collection. Let's look at a small example.

private void LoadMyUserControl()

{

// Load the User Controls Dynamically

MyUserControl myControl = (MyUserControl) Page.LoadControl("MyUserControl.ascx");

Page.Controls.Add(myControl);

}

All we are doing is we make an instance of the User Control and simply add the control to the Page Controls collection. Just one thing to note that since you are making it dynamically you need to load it each time the Page_Loads. You can simply put a call to the LoadMyUserControl method inside the InitializeComponent() method.

You can also load the User Control in the the panel control.

private void LoadMyUserControl()

{

// Load the User Controls Dynamically

MyUserControl myControl = (MyUserControl) Page.LoadControl("MyUserControl.ascx");

Panel1.Controls.Add(myControl);

Panel1.DataBind();

}

I hope you liked the article, happy coding!

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 5 comments

CAPTCHA Functionality using C#

Your Ad Here

According to wikipedia, CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") is a challenge response test which is used to check that if the user is human or not. CAPTCHA is used exclusively in applications where the user input is required. These applications include Blogs, Forums and Portals. In this article I will demonstrate how to create a simple webpage that uses CAPTCHA functionality.

Introduction:

According to wikipedia, CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") is a challenge response test which is used to check that if the user is human or not. CAPTCHA is used exclusively in applications where the user input is required. These applications include Blogs, Forums and Portals. In this article I will demonstrate how to create a simple webpage that uses CAPTCHA functionality.

The CreateImage Method:

The first task is to create an image and put it on the screen. For that I have created an ASP.NET page named CaptchaControl.aspx. The CaptchaControl.aspx page will be responsible for displaying the image to the user. Let’s take a look at the following code which generates the image.

private void CreateImage()

{

string code = GetRandomText();

Bitmap bitmap = new Bitmap(200,150,System.Drawing.Imaging.PixelFormat.Format32bppArgb);

Graphics g = Graphics.FromImage(bitmap);

Pen pen = new Pen(Color.Yellow);

Rectangle rect = new Rectangle(0,0,200,150);

SolidBrush b = new SolidBrush(Color.DarkKhaki);

SolidBrush blue = new SolidBrush(Color.Blue);

int counter = 0;

g.DrawRectangle(pen, rect);

g.FillRectangle(b, rect);

for (int i = 0; i <>

{

g.DrawString(code[i].ToString(), new Font("Verdena", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));

counter += 20;

}

DrawRandomLines(g);

Response.ContentType = "image/gif";

bitmap.Save(Response.OutputStream,ImageFormat.Gif);

g.Dispose();

bitmap.Dispose();

}

There is a bunch of stuff going on inside the CreateImage method. The GetRandomText method generates the random text and returns to the caller. If you are unfamiliar with creating random strings then I would suggest that you check out my article Creating Random Password. After I created the Rectangle where the text would appear I resized the text to give it a strange look. Finally, I called the DrawRandomLines method which protects the image from OCR softwares.

The GetRandomText Method:

The purpose of the GetRandomText method is to generate a random text every time a user gets the old text wrong. Take a look at the simple method which returns the random text.

private string GetRandomText()

{

StringBuilder randomText = new StringBuilder();

if (Session["Code"] == null)

{

string alphabets = "abcdefghijklmnopqrstuvwxyz0123456789";

Random r = new Random();

for (int j = 0; j <= 5; j++)

{

randomText.Append(alphabets[r.Next(alphabets.Length)]);

}

Session["Code"] = randomText.ToString();

}

return Session["Code"] as String;

}

The DrawRandomLines Method:

The DrawRandomLines method puts the lines on the text which, are displayed on an image. The purpose of these lines is to make it difficult for the bots to read the text. This way the text can only be read by humans.

private void DrawRandomLines(Graphics g)

{

SolidBrush green = new SolidBrush(Color.Green);

for (int i = 0; i <>

{

g.DrawLines(new Pen(green, 2), GetRandomPoints());

}

}

private Point[] GetRandomPoints()

{

Point[] points = { new Point(rand.Next(10, 150), rand.Next(10, 150)), new Point(rand.Next(10, 100), rand.Next(10, 100)) };

return points;

}

Using the CAPTCHA Page:

We have created the CAPTCHA feature but the question is how do we use it. In order to use the CAPTCHA feature you will need to create a page which consumes the CaptchaControl.aspx page. I have created the Default.aspx page which uses the CaptchaControl.aspx as the ImageUrl to the ASP.NET image control. Check out the complete HTML code of the Default.aspx page.

<form id="form1" runat="server">

<div>

<asp:Image ID="myImage" runat="server" ImageUrl="~/CaptchaControl.aspx" />

<br />

<br />

Enter code: <asp:TextBox ID="TextBox1" runat="server">asp:TextBox>

<asp:Button ID="Button1" runat="server" Text="Validate" OnClick="Button1_Click" />

<br />

<br />

<asp:Label ID="lblError" runat="server" Font-Bold="True" Font-Size="X-Large" ForeColor="Red">asp:Label>div>

form>

The important thing to note is the ASP.NET image control which, requests the CaptchaControl.aspx page and generates the image. The code for the validation of the user text against the CAPTCHA text is pretty simple and you can view it in the downloaded files.

Below is an image of how the application looks like:

Conclusion:

In this article I demonstrated how easy it is to create a CAPTCHA feature. This feature can play a very important role in the security of the application.

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments