You are on page 1of 17

Introduction to .

NET Framework
You can make use .Net Framework (Click here for more information on Microsoft
.NET Framework) as a development environment or a platform for developing user
friendly web-based applications that can allow seamless access by users from any
where in the world and from any type of client machines. You can apply the open
standards such as XML (eXtensible Markup Language), SOAP (Simple Object Access
Protocol) and HTTP (HyperText Transfer Protocol) for developing your web-
applications and web applications created with such open standards can interact well
with other applications of other platforms.

You can use different programming languages such as C#, VBScript, VB.NET,
Managed C++ for developing your applications in .NET Framework, as the .NET
Framework is not dependent on one particular language or platform and can support
many kinds of platforms and programming languages that are in use today. Further,
you can use .NET Framework for running your applications in almost all platforms
such as Linux, Macintosh and Unix without any hitches.

The presence of many off-the-shelf libraries in .NET Framework can assist you in
developing your applications in a faster, cheaper and easier manner. The most
recent .Net Framework version is capable of supporting over 20 different
programming languages today.

The functionality of .Net Framework supporting many programming languages is due


to the use of the powerful CLR, the Common Language Runtime engine. The
application programming codes are first compiled by CLR into a Microsoft
Intermediate Language (MSIL) code instead of native codes and the MSIL, which is
nothing but an instruction set, in turn creates the native code for running the
application.

The main advantage of language and platform independent feature of .NET


Framework can be attributed to CLR and the same CLR also takes care of run-time
services such as memory processes, security enforcement, integration of language,
and thread management. Hence, you can make use of the various infrastructures
that have been provided in .NET Framework for creating your web-applications.

As per the classification by the Microsoft, there are two categories of .NET
Framework and they are CLR and .Net Framework class library.

Common Language Runtime: The CLR is responsible for providing a common runtime
environment or services with which all .NET applications can run. Further, the
various capabilities of CLR can enable any developer to write even big applications
with ease using the features such as strong type naming, life-cycle management,
dynamic binding that is capable of making any business logic into re-usable
component and finally the cross-language exception handling.

.Net Framework class library: This class library constitutes various predefined
functional sets that are very useful while developing the applications by developers.
There are three main components in this class library and they are:
· ASP.NET.
· Windows Forms.
· ADO.NET.

With the .Net Framework you can make your codes written in fewer lines and other
favourable features such as easy web settings, easy deployment of applications, easy
compilation procedures, easy Web configuration makes the .NET Framework a great
platform to work with. In an overall scenario, the developers will be able to
concentrate more on Web controls and spend an efficient time in application design
and implementation and to have an effective control over the flow of the application
sequence.

Another great feature that any developer can take note of is the feature of .NET
Framework taking into cognisance all the Web controls, server-side blocks of codes
and Web forms and getting them compiled whenever a call for the page compilation
is completed.

Once the components of .NET framework are compiled in your machine, the compiled
version can easily be uploaded with all the relevant pages in the /bin directory of the
system. The process of uploading is very easy when compared to the complicated
process of web-application in ASP, where in you have to first upload the application
pages with the relevant components and you also need to register them with the
operating system.

In .NET Framework the simple uploading in /bin directory of the operating system is
enough and you need not carry out the complicated process of registering the
components of web-application with the operating system.

With the help of an XML based web.config file you can carry out the web settings
which is nothing but configuring the .NET applications for successful running. The
XML based web.config file can be modified through a program and when any such
modification is done, the system recognises the change and registers it immediately
that makes configuration of .NET applications easy and quick.

Caching is a process or a method with which the most commonly and frequently
used resources and data will get loaded onto the memory for easy and fast access.
There are three types of caching in .Net Framework and they are output caching,
data caching, and fragment caching.

Latest developments in the .NET

MVC Extensions for ASP.NET -- Deliver Lightweight and High Performance User
Interfaces
DevExpress, the Award-Winning ASP.NET Vendor Is Set to Release Over 30 MVC
Extensions as Part of Its Upcoming Release of DXperience

Microsoft pushes out ASP.Net model view controller 3 release candidate


Web development framework upgrade goes to release candidate stage Microsoft
made available this week a release candidate for its ASP.Net MVC (Model View
Controller) 3 framework.

Microsoft moves ahead with ASP.Net MVC 3


Microsoft made available this week a release candidate for its ASP.Net MVC (Model
View Controller) 3 framework. Downloadable at Microsoft's website, the software
enables development of Web applications via a Model View Controller pattern and
represents the third version of the platform. An MVC framework is provided atop
the .Net 4 runtime. Release candidates generally are the final stage before ...

About CLR and its functionalities


Common Language Runtime (CLR) is the engine available in .Net Framework to
compile and run the program. CLR engine does not compile the code in machine
code but converts the code in a set of instructions called Microsoft Intermediate
Language (MSIL). This MSIL is one of the section of Portable Executable (PE) file, the
other being Metadata. PE file automatically get generated when you compile the
program code.

The conversion of the program


code to MSIL by CLR engine,
makes .Net platform and
language independent. Although
at present, Microsoft does not have CLR engines for other platforms, in future you
can find .Net application being compiled in UNIX or Linux operating system. After the
conversion of the program code to MSIL, the code is then translated to native or
machine code. Instead of compiling the program code at development time, the MSIL
code gets translated ‘just in time’ (JIT) by JIT compilers.

There are currently over 15 compilers being built by Microsoft and other companies
that produce code that will execute in the CLR. CLR engine is divided into modules
that contain code, metadata, and resources. The code is stored in common
intermediate language (CIL) format. The module's metadata includes the types such
as names, inheritance relationships, method signatures, and dependency
information. The module's resources consist of static read-only data such as strings,
bitmaps, and other aspects of the program that are not stored as executable code.

The CLR supports component-based programming. Component development has


numerous attractive benefits such as code reuse, proper maintenance of all
components by allowing independent bug fixes to each. In addition, the CLR helps
developers in managing both allocation and deallocation of memory. This removes
two of the largest sources of programmer error: leaks and memory corruption.

CLR is also helpful for security purposes. CLR provide permissions to a component
based on what process it runs in, validates the code based on evidence such as
information about code at load time and the website from which component was
obtained to assign permissions on a component-by-component basis. Moreover, CLR
checks the code to see if it has been manipulated. The metadata in a CLR component
can contain a digital signature that can be used to verify that the component was
written by genuine person and that it has not been modified. You can verily identify
if anyone has tried to modify with the code. For example, if someone tries to change
the code of transferring money from the intended recipient to himself the CLR will
prevent the altered code from running.

Understanding ASP.NET HTML Server


Controls
ASP.NET HTML Server Controls
are the HTML controls that run
at the server-side i.e. they have
runat=”server” attribute. You
can also have normal HTML controls in your ASP.NET page, but these controls will
run only at the client-side. Therefore, using ASP.NET HTML Server Controls you can
make full use of the .Net Framework utilities such as ViewState management and
validation. ASP.NET HTML Server Controls must have the <form> tags enclosing
them with runat=”server” attribute.

The ASP.NET HTML Server Controls that you can apply in ASP.NET page are as
follows:

• HTMLAnchor: Creates a server-side control that links to the <a> HTML element.
The <a> element is used to create a link to another page. You can place an
HTMLAnchor control within the HTMLForm control.

• HTMLButton: Creates a server-side control button that maps to the <button> HTML
element. This ASP.NET HTML Server Control has various methods to modify the
appearance of an HtmlButton control. You can assign style attributes to the button,
include formatting elements or assign property value. You can also include images
within the button elements themselves, or even include other Web Forms controls.

• HTMLImage: Creates a server-side control that allows you to view an image. In


addition, you can set and retrieve the image's source, width, height, border width,
alternate text, and alignment by using the Src, Width, Height, Border, Alt, and Align
properties of this ASP.NET HTML Server Control. The HTMLImage control does not
require a closing tag.

• HTMLForm: Creates a server-side control that allows you to place multiple controls
in it. The HTMLForm control must have an opening and closing tags. If both the tags
are not available, either the elements in it will not be viewed or run in the browser
window or the compilation error message will occur.

• HTMLGeneric: Creates a server-side control for the HTML elements such as


<body>, <div>, <span>, and <font>. This control links the tags of the particular
element to be used as an HTML control to ASP.NET through the TagName property.
This ASP.NET HTML Server Control has functionality of the HtmlContainerControl
class, which allows you to dynamically change inner content of HTML control tags.
Understanding ASP.NET Web Server
Controls
ASP.NET Web Server Controls are controls that run at the web server. All ASP.NET
Web Server Controls can be identified by their attribute ‘runat=”server”’. ASP.NET
Web Server Controls are similar to HTML controls. The only difference is that HTML
controls run at the client-side and the developers have to write the code for each
type of browsers. The ASP.NET Web Server Controls run at the server-side and
automatically adapt to the type of browser that request it.

ASP.NET Web Server Controls


also encapsulates and generates
large amount of HTML tags,
thereby allowing the developers
time to concentrate on coding. ASP.NET Web Server Controls makes exhaustive use
of ViewState management. This makes data and values to be consistent across
ASP.NET pages.

All web controls are obtained from a common base class. This ensures that the
object model remains consistent across various controls. For example, in order to
move the cursor consistently across a form you can specify the Web control
TabIndex property. This is very difficult while using normal HTML. You can also
disable a particular web control by exposing the Enabled property. This process is
also difficult in HTML and ASP.

ASP.NET ASP.NET Web Server Controls consists of Web form controls, List controls,
and Rich controls. All the web form controls are defined within the namespace
System.Web.UI.WebControls. This namespace is a collection of classes that enables
you to create new ASP.NET Web Server Controls. The controls that you can use web
form controls category are button control, checkbox control, radiobutton control,
table control, image control, label control, and panel control. These web form
controls have a common set of properties that can be used across multiple controls.

The controls listed in the List controls category are dropdown list control, repeater
control, datalist control, and datagrid control. These controls use the concept of data
binding. The controls listed in the Rich controls category include calendar control and
adrotator control. These controls are specifically being employed for complex tasks.

Understanding WSDL and UDDI


Web Services Description Language (WSDL) is one of the prime specifications in web
services, the other two being SOAP and UDDI. WSDL is the description language for
web services that describes a set of SOAP messages and how these messages are
exchanged across network. WSDL will be in XML format; therefore it can be easily
understood and edited by humans and machines.

Another advantage of WSDL


being in XML format is that it is
programming language independent and also platform independent. In addition,
WSDL defines where the web service is available from and what communications
protocol has been used to talk to the web service. As a result the WSDL file describes
everything that is required to write a program for an XML Web service. There are
tools available in Microsoft Visual Studio .NET to read a WSDL file and generate the
code required to communicate with an XML Web service.

Universal Discovery Description Language (UDDI) is a directory where you can


expose your web services for other users to easily access it. You can also consume
the web service that is already posted in UDDI. However, you can also post a web
service without registering it in UDDI. DISCO is another directory where you can post
your web service. But if you want to reach to maximum of customers, you can place
it in UDDI. The UDDI directory offers three parts for you to register:

• White Pages
• Yellow Pages
• Green Pages

The white pages consist of the description such as name and address of the company
offering the service. The yellow pages consist of industrial categories based on
standard taxonomies such as North American Industry Classification System and
Standard Industrial Classification. The green pages describe the interface to the web
service in detail so that anyone can write an application after using the web service.
Web services are described in UDDI directory through a document called Type Model
or tmodel. Normally, this tModel contains a WSDL file that describes a SOAP
interface to an XML Web service, but the tModel is flexible enough to describe almost
any kind of web service.

Apart from using the web services from UDDI, you can also search a particular web
service in UDDI. In addition, you can search for companies’ information that posted
web services. In certain times, you might know the names of the companies that
offer web services but you may not be aware of the web services that they offer. The
WS Inspection is a specification in UDDI that allows you to search for a collection of
web services that are located in a particular company name. You can evaluate these
web services according to your requirements.

Understanding Custom Server Controls in


ASP.NET
ASP.NET offers many server controls for the developers to create web applications.
However, at some point of development time when the developer does not get the
control they want, they can create a new server control. This new server control can
be called ASP.NET Custom Server Controls or user control. The basic difference
between a ASP.NET Custom Server Controls and a user control is that unlike a user
control that does not appear in the Toolbox, you can view a ASP.NET Custom Server
Controls in the Toolbox. ASP.NET Custom Server Controls have their own events
such as Enter, Onclick, and Onmouseover.
ASP.NET Custom Server
Controls are very handy tool to
use in your web forms. User
controls prove inefficient in
advanced scenarios. ASP.NET Custom Server Controls are the compiled code that
makes them user friendly. You should write the ASP.NET Custom Server Controls in
code, thereby view it in the visual designer with full properties and design-time
features. You can create a ASP.NET Custom Server Controls by inheriting one of the
base control classes. These classes have all the functionality that is needed for a
server control. Therefore, you just have to modify some of the programming aspects
to suit your requirements.

Just as you have created a ASP.NET Custom Server Controls you can customize it too
to create a unique identity. You can even consume a single ASP.NET Custom Server
Controls for multiple web forms. For ASP.NET Custom Server Controls only one copy
of the control is needed in the Global Assembly Cache (GAC). Moreover, ASP.NET
Custom Server Controls are very helpful if you want a dynamic layout for your web
application.

Understanding Repeater Controls in


ASP.NET
ASP.NET Repeater Control is one of the control in List control, the other two being
DataList control and DataGrid control. List control is extensively used in web
applications to show a list of data such as strings or data items from the database.
The list of data may not be displayed in the web application because this will take
more space. If you place a list control such as drop down list in a web application,
you can contain all the data in one control.

ASP.NET Repeater Control is the


easiest one of the list controls to
create. It is simply adding a
numbers of items underneath
each other. This type of control will be ideally suited for displaying a list of hyperlinks
in a web application. You can use the ASP.NET Repeater Control by creating
templates that defines the layout of the control's content. A template can contain
any grouping of HTML text and controls that are applicable on a Web Forms page.
While running the application you cannot view the ASP.NET Repeater Control if not
even a single template is defined, or if none of the templates contain elements.

The ASP.NET Repeater Control supports four types of templates: ItemTemplate,


AlternatingItemTemplate, HeaderTemplate and FooterTemplate, and
SeparatorTemplate. A ASP.NET Repeater Control does not have any default look. You
have to define the way how the information should look like. Therefore, it is possible
for you to display items in a ASP.NET Repeater Control in a table layout, in a
comma-delimited list, in a bulleted list or in a numbered list.

The ASP.NET Repeater Control will not render the result unless you bound it to a
data source through its DataSource property. The ASP.NET Repeater Control
supports several events such as ItemCreated, ItemCommand, ItemDataBound, Load,
and Unload. These events help developer to create an event when the user clicks the
button.

Creating a Simple Chat application in


.Net
Chat applications are found in almost all the sites that are interactive with the users.
Chat rooms in the websites provide a means of communicating with the customer
service cell of any company so that the customer gets the first hand information on
any products and services that is on display in the site.

Chat applications with many features are even sold for a sum but some sites may
require a very simple feature to interact with the customer service personnel who is
online. Such simple chat applications can be built on your own. Let us see some
algorithm and the code snippets that go in the way of creating a simple chat
application.

To store the messages that are typed during a chat you can either use static arrays
or use a database for that purpose. Using a database is a good way of storing
messages. However you can also use static arrays for that purpose. The chat
application that we are going to see will work on any browser that supports
<iFrame>, since we are using <iFrame> to display the chat window of the
application. We will be refreshing the page in the <iFrame> to refresh the chat
window alone without refreshing the whole page in which the <iFrame> is present.

To enter the chat you need an .aspx page where the user enters the name of the
room and the user id. Then the user presses a Join chat button. You can pass these
parameters to the ChatPage.aspx where you will be having an iFrame for displaying
the messages and a text box control to type the messages and a button to send the
typed messages. To pass the parameters collected from the user to the
ChatPage.aspx you can use the following code which looks like,

private void Join_Click(object sender, System.EventArgs e)


{
Response.Redirect("ChatPage.aspx?Room=" + Room.Text + "&User=" +
UserID.Text);
}
For the purpose of creating the chat application you may need to create a class that
is used for performing various functions in the chat like adding messages that are
typed into a static array. You can create any class for this purpose. To add messages
you can have methods within the class for this purpose. Methods for retrieving the
entire message typed, and methods for displaying the messages in the chat window
are also needed.

A code snippet for adding messages can be something like given below.
static protected ArrayList stArray = new ArrayList();
static public void AddMesg(string sRoom, string sUser, string sMsg)
{
string sAddTxt = sRoom + ":" + sUser + ":" + sMsg;
pArray.Add(sAddTxt);

if ( stArray.Count > 100 )


{
stArray.RemoveRange(0,20);
}
}

Within the ChatPage.aspx, once you type the message that is to be sent and when
you click the Send button, you need to add the message that is typed. You check the
text box for that purpose and if it contains any text you just add the message to the
static array.

private void Send_Click(object sender, System.EventArgs e)


{
string sRoom = "";
string sUser = "";

if ( Request.Params["Room"] != null )
sRoom = Request.Params["Room"].ToString();
else
sRoom = "1";

if ( Request.Params["User"] != null )
sUser = Request.Params["User"].ToString();
else
{
sUser = "Anonymous User";
}

if ( TB_ToSend.Text.Length > 0)
{
PageModule.Chat.AddMessage(sRoom,
sUser,
ToSend.Text);

ToSend.Text = "";
}
}

You can use the following code to refresh the page in the <iFrame> to display all the
messages that are typed.

Response.Write( "<meta http-equiv=\"Refresh\"content=\"4\">" );


Call the method that is created to display all the messages in the <iFrame> after
refreshing the page.

You can thus create a simple chat application which can be used in all the sites that
need interaction with the user.

Saving an Image in a SQL Server


Database
Most of the web applications have a lot of images used in it. These images are
usually stored in a web server folder and they are accessed by giving the relative
path to the file with respect to the root folder of the website.

.Net being the platform for distributed application now, ASP.Net can be used to store
images that are small to be stored in a database like SQL Server 2000 and later
versions. For this purpose the SQL Server database provides a data type called
“image” which is used to store images in the database.

To access these images stored in the database we will be using the ADO.Net classes.
To find out how to insert and retrieve an image in to the SQL Server database, you
can create a .aspx page which can have a HTMLInputFile control which is used to
select the image file that is to be saved in the database.

You can also create a textbox control in which you can add the image name or some
comment or an image id for the image saved. Use a button control to upload the
image to the database. Namespaces like System.Data.SqlClient, System.Drawing,
System.Data, System.IO, and System.Drawing.Imaging are used in this task.

In the OnClick property of the button you can write the following code to upload an
image to the database.

// create a byte[] for the image file that is uploaded


int imagelen = Upload.PostedFile.ContentLength;
byte[] picbyte = new byte[imagelen];
Upload.PostedFile.InputStream.Read (picbyte, 0, imagelen);
// Insert the image and image id into the database
SqlConnection conn = new SqlConnection (@"give the connection string here...");
try
{
conn.Open ();
SqlCommand cmd = new SqlCommand ("insert into ImageTable "
+ "(ImageField, ImageID) values (@pic, @imageid)", conn);
cmd.Parameters.Add ("@pic", picbyte);
cmd.Parameters.Add ("@imageid", lblImageID.Text);
cmd.ExecuteNonQuery ();
}
finally
{
conn.Close ();
}

You can also write the above code in a function and call that function in the OnClick
event of the upload button. The code given above performs the following steps in the
process of inserting an image into the database.

1. Get the content length of the image that is to be uploaded


2. Create a byte[] to store the image
3. Read the input stream of the posted file
4. Create a connection object
5. Open the connection object
6. Create a command object
7. Add parameters to the command object
8. Execute the sql command using the ExecuteNonQuery method of the command
object
9. Close the connection object

To retrieve the image from the SQL Database you can perform the following steps.

1. Create a MemoryStream object. The code can be something like,


MemoryStream mstream = new MemoryStream ();
2. Create a Connection object
3. Open the connection to the database
4. Create a command object to execute the command to retrieve the image
5. Use the command object’s ExecuteScalar method to retrieve the image
6. Cast the output of the ExecuteScalar method to that of byte[]
byte[] image = (byte[]) command.ExecuteScalar ();
7. Write the stream
mstream.Write (image, 0, image.Length);
8. Create a bitmap object to hold the stream
Bitmap bitmap = new Bitmap (stream);
9. Set the content type to “image/gif”
Response.ContentType = "image/gif";
10. Use the Save method of the bitmap object to output the image to the
OutputStream.
bitmap.Save (Response.OutputStream, ImageFormat.Gif);
11. Close the connection
12. Close the stream
mstream.Close();

Using the above steps you can retrieve and display the image from the database to
the web page.

You can use these algorithms and take advantage of the “image” data type available
in the SQLServer 2000 database to store small images that correspond to a
particular record in the table of the database. This method of storing avoids the
tedious task of tracking the path of the web folder if the images are stored in a web
folder.
Tracking Emails - Know Whether the
Recipient Opens it
It is very easy to track whether the user has read the email. The concept is very
simple. You insert a link to a small transparent image in the mail sent, the mail being
sent in HTML format, and when the user opens the email the image is loaded sending
you a querystring to the web page that tracks the email. The web page requests the
querystring or the parameter that is passed. This ensures that the email is read by
the user.

When the page that is tracking is requested by the email sent you can get the value
of the date and time when the request comes and you can store them in a database
or send you an alert indicating the time and date at which the email was read by the
user. This is the simple way that is used to track whether the emails sent are read or
not.

To send emails you may be importing the namespace System.Web.Mail. You would
be creating a MailMessage object as given below.

Imports System.Web.Mail

string sBody;

MailMessage mailMsg = new MailMessage();

mailMsg.BodyFormat = MailFormat.Html;
SmtpMail.SmtpServer = “your Server name”;
mailMsg.From = "your email address";
mailMsg.To = “to email address”;
mailMsg.Subject = “subject line of the mesg”;
mailMsg.Body = sBody;
SmtpMail.Send(mailMsg);

The above code sends an email to an email address as given in the mailMsg.To
property. For tracking an email, all you have to do is to add an image tag to the
body of the message i.e. sBody. This can be done by

sBody = sBody + "<IMG height=1 src=\"http://www." + sYourDomain +


"/trackemail.aspx?sentto=" + sParam + "\" width=1>";

In the above line sParam is the parameter that is passed to the url and sYourDomain
is your domain name where you create this page to track the email. If you send an
email with the body of the message as given above, when the user reads the email,
the image tag will try to load the url given in the tag. This will send the parameter
“sentto” that is given by you to the page requested. In the trackemail.aspx page you
can write code to retrieve the value of the parameter “sentto”. Once you receive the
parameter you can do anything on that page to indicate that the user has read the
email.

The code given below can be used in the trackemail.aspx page to retrieve the
parameter.

private void Page_Load(object sender, System.EventArgs e)


{
if ( Page.IsPostBack == false )
{
if ( Request.Params["sentto"] != null )

//here you can send a mail to yourself


...
mailMsg.Body = Request.Params["sentto"].ToString()
+ “ has read your email”;
...

Response.Redirect("transparent.gif");
}

Once you have retrieved the parameter that is passed to the page you can redirect
the request to a transparent image so that this transparent image, “transparent.gif”
loads in the email message of the user who is reading the mail. Make this
“transparent.gif” as small as possible, usually of 1 pixel by 1 pixel height and width,
so that it does not take time to load. Since it is transparent the user who reads your
mail may not know that an image has been loaded in the email message and the
email that he reads is being tracked.

This way of tracking the email is so easy. Once you get the parameter in your
trackemail.aspx page you can add a time stamp to the body of the email message
that is sent to you in the Page_Load event of that page. This enables you to know
the time and date at which the email was read by the user.

Using Cryptography Classes to Encrypt


and Decrypt Data
Cryptography is a way to encrypt and decrypt data. By encrypting data you are
protecting your data from other curious users who would like to know the data that
is present. Once you encrypt the data it is in a unreadable form for humans. You
need to decrypt the data to read it again.
Thus a person who intercepts the encrypted data will find it difficult to decrypt it.
.Net provides a namespace for the classes that are used to encrypt and decrypt data.
The namespace Cryptography is used for accessing the classes to encrypt and
decrypt data. Classes like AysmmetricAlgorithm, SymmetricAlgorithm, and
HashAlgorithm are used for this purpose. These are abstract classes.

The following are the different types of cryptographic primitives that are used in .Net
to encrypt and decrypt data.

· Private-key encryption or Symmetric Cryptography


· Public-key encryption or Asymmetric Cryptography
· Cryptographic Signing
· Cryptographic hashes

The Private-key encryption uses a single shared key to encrypt and decrypt data
whereas the Asymmetric cryptography uses public/private key pair for that purpose.
Cryptographic signing uses digital signatures to ensure that the data originates from
the intended user. The digital signatures are unique to a particular party.
Cryptographic hashes are another method of cryptography where data is mapped
from any length to fixed-length byte sequence.

The following are the classes that are provided to implement the private-key
algorithms. DESCryptoServiceProvider, RC2CryptoServiceProvider, RijndaelManaged,
and TripleDESCryptoServiceProvider. For implementing the public-key encryption
algorithms DSACryptoServiceProvider and RSACryptoServiceProvider classes are
provided. These classes in public-key algorithms can also be used for Cryptographic
signing. Classes like HMACSHA1, MACTripleDES, MD5CryptoServiceProvider,
SHA1Managed, SHA256Managed, SHA384Managed, and SHA512Managed are used
in Cryptographic hashes algorithms / digital signature algorithms.

We will see some code for symmetric cryptography. Symmetric cryptography uses a
private key and an initialization vector for processing the encryption of data. You
know that encryption is done using key (or password) that is provided by you. The
intended party also should know that key to decrypt the data. Initialization vector is
used when the mode of encryption used is CipherMode.CBC (Cipher Block Chaining).
Using this mode the data is encrypted in blocks. The third block of data is encrypted
using the output of second block and the second block is encrypted using the output
of first block. If this chaining process happens, what data is used for encrypting the
first block? Hence we give an initialization vector which is used to encrypt the first
block of data.

Dim crypProvider as SymmetricAlgorithm


Dim mStream as MemoryStream
crypProvider = SymmetricAlgorithm.Create("RC2")
mStream = New MemoryStream()
Dim crypTrans As ICryptoTransform = crypProvider.CreateEncryptor()
Dim CS As New CryptoStream(mStream, crypTrans, CryptoStreamMode.Write)
Dim SW As New StreamWriter(CS)
SW.Write(txtData.Text)
SW.Flush()
CS.FlushFinalBlock()
Dim dbytes(mStream.Length - 1) As Byte
mStream.Position = 0
mStream.Read(mBytes, 0, mStream.Length)
Dim ENC As New Text.UTF8Encoding()
Dim encD As String = ENC.GetString(dbytes)
MsgBox("Encrypted Data: " & vbCrLf & encD)

The above code can be used to encrypt some value entered in a textbox. The above
code uses the RC2 algorithm. You can also use any other algorithm like DES or
Rijndael. The data that is entered in a text box is encrypted upon clicking a button in
the form. All the above code is written under the click even of the button. The
encrypted data is displayed in a message box. You can also display it in another
textbox in the form and then use an decryption code to decrypt the data in the other
textbox.

mStream.Position = 0
crypTrans = crypProvider.CreateDecryptor()
Dim nCS As New CryptoStream(mStream, crypTrans, CryptoStreamMode.Read)
Dim nSR As New StreamReader(nCS)
Dim dData As String = nSR.ReadToEnd()
MsgBox("Decrypted Data: " & vbCrLf & dData)

The code above is used to decrypt the data that is encrypted. In the above
algorithms we have not specified any key or initialization vector. This is because that
.Net uses the default key for encryption.

You can use other types of cryptographic encryption and decryption to protect your
data. The type of algorithm used for that purpose depends on the scenario of the
application that is created.

How to create a guest book in ASP.Net?


A guest book for a website is a very important feature to know the feedback of the
users who are using the website. This feedback from the users helps in refining the
content or the services the website is intended for. Hence many of the websites
which provide distinct services go for guest book features in their websites.

When you open up a guest book you should be aware that you will not only get
accolades for the services but also curses when you do not provide proper services.
There are usually many so called bad guys who scold you and also write some filthy
stuff in your guest book. You should know how to handle such messages. You can
simply delete such messages from the guest book. Hence a guest book should have
a feature for you to delete unwanted messages or messages that spoil your
reputation.

Creating a guest book is easy if you use ASP.Net since you can avoid a lot of coding
that is done if you are using other technologies. You can use a simple Access
database to hold the messages that are written by the users of the guest book. All
you have to do is to read the message from the database and display it in your
webform. To display them it is better to have a datagrid in the webform so that you
can incorporate paging to display limited number of messages in a particular page.
When you are using a database you are certain to use the ADO.Net for inserting,
reading, updating, and deleting the records in the database. For the sake of
simplicity we will see some code that is involved in inserting the records using
ADO.Net and some code to read the records and bind them to the datagrid so that
the guest book can be viewed.

You need to create an aspx page for the user to enter information about him and his
comments about the site. For this purpose you need to have text box controls and
label controls in your aspx page. For writing the comments you can have multi-line
text box control. To have multiple lines in the textbox you can set the ‘TextMode’
property of the textbox to ‘MultiLine’. RequiredField validators can be used if do not
want the user to leave any field blank. Once you create this page for entering data,
you have to write the code to insert this data in to the database. Assuming that you
have created the required fields in the database, the following code gives you an
idea of how to insert the data in to the Guest Book database.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

If IsPostBack Then
Dim Name As String = TextBox1.Text
Dim Country As String = TextBox2.Text
Dim Comment As String = TextBox3.Text
Dim conn As OleDbConnection = New OleDbConnection("----your connectionstring
here----")
Dim qry As String
Dim cmd As OleDbCommand

qry = "Insert into Guest_Book (name,country,comment) VALUES ('" & Name & "',''"
& Country & "','" & Comment & "'" & ")"
cmd = New OleDbCommand(qry, conn)

Try
conn.Open()
cmd.ExecuteNonQuery()
Catch e As Exception
Throw e
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End If

Response.Redirect("viewGB.aspx")

End Sub
When the user is redirected to the view page to view the guest book the data from
the MSAccess database is retrieved and bound to a datagrid in the view page. A
sample code for this process in the view page is given below:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
BindDG()
End Sub
Public Sub BindDG()
Dim ds As DataSet
Dim cnn As OleDbConnection
Dim cmd As OleDbDataAdapter
Dim qry As String
qry = "select * from Guest_Book"
conn = New OleDbConnection("-your connectionstring here-")
cmd = New OleDbDataAdapter(qry, conn)

ds = New DataSet()
cmd.Fill(ds, "Guest_Book")
DataGrid1.DataSource = ds.Tables("Guest_Book").DefaultView
DataGrid1.DataBind()
End Sub
Private Sub DataGrid1_PageIndexChanged(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles
DataGrid1.PageIndexChanged
DataGrid1.CurrentPageIndex = e.NewPageIndex
BindDG()
End Sub

By changing the “qry” string you can achieve task like deleting records from the
database and this can be done by the owner of the website. If you work around the
DataGrid during the design time you can set properties so that you can sort the
records displayed in the grid of the view page. Thus a simple guest book can be
created using the concepts of ADO.Net very easily in ASP.Net.

You might also like