Creating a ASP .Net Web Service

Introduction

Microsoft .NET marketing has created a huge hype about its Web Services. This is the first of two articles on Web Services. Here we will create a .NET Web Service using C#. We will look closely at the Discovery protocol, UDDI, and the future of the Web Services. In the next article, we will concentrate on consuming existing Web Services on multiple platforms (i.e., Web, WAP-enabled mobile phones, and windows applications).

Why do we need Web Services?

After buying something over the Internet, you may have wondered about the delivery status. Calling the delivery company consumes your time, and it's also not a value-added activity for the delivery company. To eliminate this scenario the delivery company needs to expose the delivery information without compromising its security. Enterprise security architecture can be very sophisticated. What if we can just use port 80 (the Web server port) and expose the information through the Web server? Still, we have to build a whole new Web application to extract data from the core business applications. This will cost the delivery company money. All the company wants is to expose the delivery status and concentrate on its core business. This is where Web Services come in.

What is a Web Service?

Web Services are a very general model for building applications and can be implemented for any operation system that supports communication over the Internet. Web Services use the best of component-based development and the Web. Component-base object models like Distributed Component Object Model (DCOM), Remote Method Invocation (RMI), and Internet Inter-Orb Protocol (IIOP) have been around for some time. Unfortunately all these models depend on an object-model-specific protocol. Web Services extend these models a bit further to communicate with the Simple Object Access Protocol (SOAP) and Extensible Markup Language (XML) to eradicate the object-model-specific protocol barrier (see Figure 1).

Web Services basically uses Hypertext Transfer Protocol (HTTP) and SOAP to make business data available on the Web. It exposes the business objects (COM objects, Java Beans, etc.) to SOAP calls over HTTP and executes remote function calls. The Web Service consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web.


Figure 1. SOAP calls are remote function calls that invoke method executions on Web Service components at Location B. The output is rendered as XML and passed back to the user at Location A.

How is the user at Location A aware of the semantics of the Web Service at Location B? This question is answered by conforming to a common standard. Service Description Language (SDL), SOAP Contract Language (SCL) and Network Accessible Specification Language (NASSL) are some XML-like languages built for this purpose. However, IBM and Microsoft recently agreed on the Web Service Description Language (WSDL) as the Web Service standard.

The structure of the Web Service components is exposed using this Web Service Description Language. WSDL 1.1 is a XML document describing the attributes and interfaces of the Web Service. The new specification is available at msdn.microsoft.com/xml/general/wsdl.asp.

The task ahead

The best way to learn about Web Services is to create one. We all are familiar with stock quote services. The NASDAQ, Dow Jones, and Australian Stock Exchange are famous examples. All of them provide an interface to enter a company code and receive the latest stock price. We will try to replicate the same functionality.

The input parameters for our securities Web service will be a company code. The Web service will extract the price feed by executing middle-tier business logic functions. The business logic functions are kept to a bare minimum to concentrate on the Web service features.

Tools to create a Web Service

The core software component to implement this application will be MS .NET Framework SDK, which is currently in beta. You can download a version from Microsoft. I used Windows 2000 Advance Server on a Pentium III with 300 MB of RAM.

The preferred Integration Development Environment (IDE) to create Web Services is Visual Studio .NET. However, you can easily use any text editor (WordPad, Notepad, Visual Studio 6.0) to create a Web Service file.

I assume you are familiar with the following concepts:

  • Basic knowledge of .NET platform
  • Basic knowledge of C#
  • Basic knowledge of object-oriented concepts

Creating a Web Service

We are going to use C# to create a Web Service called "SecurityWebService." A Web Service file will have an .ASMX file extension. (as opposed to an .ASPX file extension of a ASP.NET file). The first line of the file will look like

<%@ WebService Language="C#" class="SecurityWebService" %>

This line will instruct the compiler to run on Web Service mode and the name of the C# class. We also need to access the Web Service namespace. It is also a good practice to add a reference to the System namespace.
using System;

using System.Web.Services;
The SecurityWebService class should inherit the functionality of the Web Services class. Therefore, we put the following line of code:
public class SecurityWebService : WebService

Now we can use our object-oriented programming skills to build a class. C# classes are very similar to C++ or Java classes. It will be a walk in the park to create a C# class for anyone with either language-coding skills.

Dot-net Web Services are intelligent enough to cast basic data types. Therefore, if we return "int," "float," or "string" data types, it can convert them to standard XML output. Unfortunately, in most cases we need get a collection of data regarding a single entity. Let's take an example.

Our SecurityWebService stock quotes service requires the user to enter a company code, and it will deliver the full company name and the current stock price. Therefore, we have three pieces of information for a single company:

  1. Company code (data type - string)
  2. Company name (data type - string)
  3. Price (data type - Double)
We need to extract all this data when we are referring to a single stock quote. There are several ways of doing this. The best way could be to bundle them in an enumerated data type. We can use "structs" in C# to do this, which is very similar to C++ structs.
public struct SecurityInfo

{
public string Code;
public string CompanyName;
public double Price;
}
Now we have all the building blocks to create our Web Service. Therefore, our code will look like.


<%@ WebService Language="C#" class="SecurityWebService" %>

using System;
using System.Web.Services;

public struct SecurityInfo
{
public string Code;
public string CompanyName;
public double Price;
}

public class SecurityWebService : WebService
{
private SecurityInfo Security;

public SecurityWebService()
{
Security.Code = "";
Security.CompanyName = "";
Security.Price = 0;
}

private void AssignValues(string Code)
{
// This is where you use your business components.
// Method calls on Business components are used to populate the data.
// For demonstration purposes, I will add a string to the Code and
// use a random number generator to create the price feed.

Security.Code = Code;
Security.CompanyName = Code + " Pty Ltd";
Random RandomNumber = new System.Random();
Security.Price = double.Parse(new System.Random(RandomNumber.Next(1,10)).NextDouble().ToString("##.##"));
}


[WebMethod(Description="This method call will get the company name and the price for a given security code.",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)
{
AssignValues(Code);
SecurityInfo SecurityDetails = new SecurityInfo();
SecurityDetails.Code = Security.Code;
SecurityDetails.CompanyName = Security.CompanyName;
SecurityDetails.Price = Security.Price;
return SecurityDetails;
}

}

Remember, this Web Service can be accessed through HTTP for any use. We may be referring to sensitive business data in the code and wouldn't want it to fall into the wrong hands. The solution is to protect the business logic function and only have access to the presentation functions. This is achieved by using the keyword "[Web Method]" in C#. Let's look at the function headers of our code.
[WebMethod(Description="This......",EnableSession=false)]

public SecurityInfo GetSecurityInfo(string Code)
This function is exposed to the public. The "description" tag can be used to describe the Web Service functionality. Since we will not be storing any session data, we will disable the session state.
private void AssignValues(string Code)

This is a business logic function that should not be publicly available. We do not want our sensitive business information publicly available on the Web. (Note:- Even if you change the "private" keyword to "public," it will still not be publicly available. You guessed it, the keyword "[Web Method]" is not used.)

We can use the business logic in this function to get the newest stock price quote. For the purpose of this article I have added some text to the company code to create the company name. The price value is generated using a random number generator.

We may save this file as "SampleService.asmx" under an Internet Information Service (IIS)-controlled directory. I have saved it under a virtual directory called "/work/aspx." I'll bring it up on a Web browser.

This is a Web page rendered by the .NET Framework. We did not create this page. (The page is generated automatically by the system. I did not write any code to render it on the browser. This graphic is a by-product of the previous code.) This ready-to-use functionality is quite adequate for a simple Web Service. The presentation of this page can be changed very easily by using ASP.NET pagelets and config.web files. A very good example can be found at

http://www.ibuyspy.com/store/InstantOrder.asmx.

Notice a link to "SDL Contract." (Even if we are using WSDL, .NET Beta still refers to SDL. Hopefully this will be rectified in the next version). This is the description of the Web Service to create a proxy object. (I will explain this in the next article.) This basically gives an overview of the Web Service and it's public interface. If you look closely, you will only see the "Web-only" methods being illustrated. All the private functions and attributes are not described in the SDL contract.

How do we use a Web Service?

You can also call the Web Service directly using the HTTP GET method. In this case we will not be going through the above Web page and clicking the Invoke button. The syntax for directly calling the Web Service using HTTP GET is

Now we can use this Web Service. Let's enter some values to get a bogus price feed.

By clicking the Invoke button a new window will appear with the following XML document

This is how the Web Service releases information. We need to write clients to extract the information from the XML document. Theses clients could be

  1. A Web page
  2. A console / Windows application
  3. A Wireless Markup Language (WML) / WMLScript to interact with mobile phones
  4. A Palm / Win CE application to use on Personal Digital Assistants (PDAs).

http://server/webServiceName.asmx/functionName?parameter=parameterValue

Therefore, the call for our Web Service will be

http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo?Code=IBM

This will produce the same result as clicking the Invoke button.

Now we know how to create a Web Service and use it. But the work is half done. How will our clients find our Web Service? Is there any way to search for our Web Service on the Internet? Is there a Web crawler or a Yahoo search engine for Web Services? In order to answer these questions we need to create a "discovery" file for our Web Service.

Creating a Discovery file

Web Service discovery is the process of locating and interrogating Web Service descriptions, which is a preliminary step for accessing a Web Service. It is through the discovery process that Web Service clients learn that a Web Service exists, what its capabilities are, and how to properly interact with it. Discovery file is a XML document with a .DISCO extension. It is not compulsory to create a discovery file for each Web Service. Here is a sample discovery file for our securities Web Service.





We can name this file "SampleService.disco" and save it to the same directory as the Web Service. If we are creating any other Web Services under the "/work/aspx" directory, it is wise to enable "dynamic discovery." Dynamic discovery will scan for all the *.DISCO files in all the subdirectories of "/work/aspx" automatically.



An example of an active discovery file can be found at http://services3.xmethods.net/dotnet/default.disco. By analyzing the discovery file we can find where the Web Services reside in the system. Unfortunately both these methods require you to know the exact URL of the discovery file. If we cannot find the discovery file, we will not be able to locate the Web Services. Universal Description, Discovery, and Integration (UDDI) describes mechanisms to advertise existing Web Services. This technology is still at the infant stage. UDDI is an open, Internet-based specification designed to be the building block that will enable businesses to quickly, easily, and dynamically find and transact business with one another using their preferred applications. A reference site for UDDI is http://uddi.microsoft.com.

There have been a lot of Web Services written by developers. www.xmethods.com is one of the sites that has an index of Web Services. Some developers are building WSDL search engines to find Web Services on the Web.

Deploying a Web Service

Deploying the Web Services from development to staging or production is very simple. Similar to ASP.NET applications, just copy the .ASMX file and the .DISCO files to the appropriate directories, and you are in business.

The future of the Web Services

The future looks bright for the Web Service technology. Microsoft is not alone in the race for Web Service technology. Sun and IBM are very interested. There are SOAP toolkits available for Apache and Java Web servers. I believe Web Services needs a bit of work, especially the Web Service discovery process. It is still very primitive.

On a positive note, Web Services have the potential to introduce new concepts to the Web. One I refer to as "pay per view" architecture. Similar to pay-TV, we can build Web sites that can generate revenue for each request a user sends (as opposed to a flat, monthly subscription). In order to get some data, we can sometimes pay a small fee. Commercially this could be handy for a lot of people.

Examples

  • Online newspaper sites can publish a 10-year-old article with a $2 "pay per view" structure.
  • Stock market portals can itemize every user portfolio for every single stock quote and build pricing and discount structures.
And the list goes on ...

On a very optimistic note, Web Services can be described as the "plug and play" building blocks of enterprise Business to Business (B2B) Web solutions.

Appendix A




Tuesday, April 14, 2009

Abstract classes

Abstract classes

Like an interface, you cannot implement an instance of an abstract class, however you can implement methods, fields, and properties in the abstract class that can be used by the child class.

For example, we could create an abstract class for all vehicle to inherit from:

public abstract class Vehicle
{
public void Start()
{
Console.WriteLine("The vehicle has been started");
}

public abstract void Drive();
public abstract void Park();
public abstract void ChangeGear(int gear);

public void SwitchOff()
{
Console.WriteLine("The vehicle has been switched off");
}
}

So each class that inherits from Vehicle will already be able to use the methods Start and SwitchOff, but they must implement Drive, Park and ChangeGear.

So if we were to implement a Car class, it may look something like this.

public class Car : Vehicle
{
public Car()
{
}

public override void Drive()
{
Console.WriteLine("The car is being driven");
}

public override void Park()
{
Console.WriteLine("The car is being parked");
}

public override void ChangeGear(int gear)
{
Console.WriteLine("The car changed gear changed to " + gear.ToString());
}
}

The override keyword tells the compiler that this method was defined in the base class.

Summary for abstract && inheritance

  • An Interface cannot implement methods.
  • An abstract class can implement methods.


  • An Interface can only inherit from another Interface.
  • An abstract class can inherit from a class and one or more interfaces.


  • An Interface cannot contain fields.
  • An abstract class can contain fields.


  • An Interface can contain property definitions.
  • An abstract class can implement a property.


  • An Interface cannot contain constructors or destructors.
  • An abstract class can contain constructors or destructors.


  • An Interface can be inherited from by structures.
  • An abstract class cannot be inherited from by structures.


  • An Interface can support multiple inheritance.
  • An abstract class cannot support multiple inheritance.


Monday, April 13, 2009

Inheritance

Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related classes, and to reuse functionality defined in existing classes.

In the following examples, you will define a base class that contains fields and methods for a generic bank account. You will then define a derived class that represents a particular kind of bank account. The derived class will inherit members from the base class, override selected members, and add new members for the new kind of account.

Requirements

Prior knowledge required:
  • C# syntax
  • Object-oriented concepts

Create a New Console Application

  1. Start Visual Studio and create a new C# console application project named UseInheritance.
  2. Save the project.

Create an Abstract Base Class

  1. In Solution Explorer, switch to the Class View (If you cannot see it, click Class View in the View menu). Right-click the UseInheritance project, point to Add, and then click Class.

    Note In Visual C# .NET 2003, point to Add, and then click Add Class.
  2. In the Add New Item dialog, type in a class name of Account, and then click Add.

    The Account class is displayed. Notice the keyword. Add the public and abstract modifiers to the class so it resembles the following.
    public abstract class Account
    {


    }

Write Code for the Base Class

  1. In the Code View window, add two fields to the Account class to represent the account balance and the name of the account holder:
    private string name;        // Only accessible in base class
    protected double balance; // Accessible in base class and derived class
  2. Modify the constructor as follows to initialize these fields:
    public Account(string nm, double bal)
    {
    this.name = nm;
    this.balance = bal;

    }
  3. Add the following methods to the class. The virtual keyword means these methods can be overridden in derived classes:
    public virtual void Credit(double amount)
    {
    this.balance += amount;
    }

    public virtual void Debit(double amount)
    {
    this.balance -= amount;
    }

    public virtual void Display()
    {
    Console.WriteLine("Name={0}, balance={1}", this.name, this.balance);

    }
  4. Add the following method to the class. Because this method is not marked as virtual, it cannot be overridden in derived classes. This method provides the capability to change the name of the account holder.
    public void ChangeName(string newName)
    {
    this.name = newName;

    }
  5. Add the following method to the class. The abstract keyword means this method must be overridden in derived classes:
    public abstract double CalculateBankCharge();

Create a Derived Class

  1. In the Class View, right-click the UseInheritance project. On the Shortcut menu, choose Add and then click Class.
  2. In the Add New Item dialog box, type SavingsAccount, and then click Add.
  3. View the code for the SavingsAccount class.
  4. Change the SavingsAccount class definition as follows, so that SavingsAccount inherits from Account:
    public class SavingsAccount : Account
    {


    }

Write Code for the Derived Class

  1. Add a field to the SavingsAccount class:
    private double minBalance;   // If the balance drops below minBalance,
    // the bank will charge a fee on the account
  2. Modify the SavingsAccount constructor to initialize the fields in the base class and in this class:
    public SavingsAccount(string nm, double bal, double min)
    : base(nm, bal) // Call base-class constructor first
    {
    minBalance = min; // Then initialize fields in this class

    }
  3. Add the following methods to the SavingsAccount class. These methods override the virtual methods inherited from the base class:
    public override void Debit(double amount)
    {
    if (amount <= balance) // Use balance, inherited from base class
    base.Debit(amount); // Call Debit, inherited from base class
    }
    public override void Display()
    {
    base.Display(); // Call Display, inherited from base class
    Console.WriteLine("$5 charge if balance goes below ${0}", minBalance);

    }
  4. You must override all abstract methods from the base class. Add the following method to the SavingsAccount class:
    public override double CalculateBankCharge()
    {
    if (balance < minBalance)
    return 5.00;
    else
    return 0.00;

    }

Verify It Works

  1. Display the code for Class1.cs in the Code View window.
  2. In the Main method, create a SavingsAccount object and display it as follows:
    SavingsAccount sa = new SavingsAccount("Freda Smith", 100.00, 25);
    sa.Display();
  3. Add the following code to call public methods in SavingsAccount or Account:
    sa.Credit(100);
    sa.Debit(180);
    sa.ChangeName("Freda Jones");
    sa.Display();
    Console.WriteLine("Bank charge: ${0}", sa.CalculateBankCharge());
  4. Build the application.
  5. Set a breakpoint at the start of the Main method, and start the application in the debugger. Step into each statement, and observe which methods are called during the application. The application displays the following information on the console:
    Name=Freda Smith, balance=100
    $5 charge if balance goes below $25
    Name=Freda Jones, balance=20
    $5 charge if balance goes below $25
    Bank charge: $5

dot Net Grid View Control Problems

Some times we are facing problems with grid view control that we can't retrieve value from controls which are placed in grid view template fields in VS .Net 3.5 & for this problem we have to add controls in template fields at runtime. For this we have to code on GridView's RowDataBound event.

For Example :
[VB]

Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
Try
Dim txt as new TextBox
e.Row.Cells(0).Controls.Add(txt)
Catch ex As Exception
End Try
End Sub

[C#]
protected
void gv_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)

    {
    try
    {
    TextBox txt = new TextBox();
    e.Row.Cells(0).Controls.Add(txt);
    }
    catch (Exception ex)
    { }

    }


Note :: this cell(0) is templatefield.


And for retreiving value we can code like this :

first we have to typecast this template field control in its type os control like i m typcasting its textbox in a textbox.

[VB]

Try
Dim txt as new TextBox
txt = gv.Row.Cells(0).Controls(0)

txt.Text 'you can use it anywhere

Catch ex As Exception
End Try

[C#]

    try
    {
    TextBox txt = new TextBox();

    txt = gv.Row.Cells(0).Controls(0);

    txt.Text //you can use it anywhere

    } catch (Exception ex)

    { }

Signature Capture in PocketPC

Introduction

This article shows how to collect and display a signature. The signature is made up of a list of line segments. Each segment contains an array of points (x and y coordinates).

There are two *.cs files MainForm.cs and SignatureControl.cs. These two files are used in C# .NET compact Framework to capture the signature and save that in a *.txt file in PocketPC. You can load the same signature from the *.txt file.

/***********CLIENT CODE****************/

/*****************************************************************/

//SignatureControl.cs File

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.IO;

namespace PocketSignature
{
/****************************************************************************

* Description: Collects and displays a signature. The signature is made
* up of a list of line segments. Each segment contains an array of points
* (x and y coordinates).
* Draws to a memory bitmap to prevent flickering.
* Raises the SignatureUpdate event when a new segment is added to
* the signature.

*

*
*
*/

public class SignatureControl : Control
{

private string background = null;
public string Background
{
get
{
return background;
}
set
{
background = value;

}
}

// GDI objects
Bitmap bmp;
//String bmpFile="\\Program Files\\SignCaptureV2\\sign here.png";

Graphics graphics;
Pen pen = new Pen(Color.Black);
// list of line segments
ArrayList pVector = new ArrayList();

Point lastPoint = new Point(0,0);

// if drawing signature or not
bool drawSign = false;
// notify parent that line segment was updated
public event EventHandler SignatureUpdate;
public SignatureControl(){}
protected override void OnPaint(PaintEventArgs e)
{
// we draw on the memory bitmap on mousemove so there
// is nothing else to draw at this time
CreateGdiObjects();
e.Graphics.DrawImage(bmp, 0, 0);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// don't pass to base since we paint everything, avoid flashing
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
// process if currently drawing signature
if (!drawSign)
{
// start collecting points
drawSign = true;

// use current mouse click as the first point
lastPoint.X = e.X;
lastPoint.Y = e.Y;
}
}
protected override void OnMouseUp(MouseEventArgs e)
{

base.OnMouseUp(e);
// process if drawing signature
if (drawSign)
{
// stop collecting points
drawSign = false;
}
}

protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
// process if drawing signature
if (drawSign)
{
// draw the new segment on the memory bitmap
graphics.DrawLine(pen, lastPoint.X, lastPoint.Y, e.X, e.Y);
pVector.Add(lastPoint.X+" "+lastPoint.Y+" "+e.X+" "+e.Y);
// update the current position
lastPoint.X = e.X;
lastPoint.Y = e.Y;
// display the updated bitmap
Invalidate();
}
}
/// <summary>
/// Clear the signature.
/// </summary>
public void Clear()
{
pVector.Clear();
InitMemoryBitmap();
Invalidate();
}
/// <summary>
/// Create any GDI objects required to draw signature.
/// </summary>
private void CreateGdiObjects()
{
// only create if don't have one or the size changed
if (bmp == null || bmp.Width != this.Width ||
bmp.Height != this.Height)
{
// memory bitmap to draw on
InitMemoryBitmap();
}
}

/// <summary>
/// Create a memory bitmap that is used to draw the signature.
/// </summary>
private void InitMemoryBitmap()
{
// load the background image
if (this.Background==null)
{
bmp = new Bitmap(this.Width,this.Height);
graphics = Graphics.FromImage(bmp);
graphics.Clear(Color.White);
}
else
{
bmp = new Bitmap(this.Background);
// get graphics object now to make drawing during mousemove faster
graphics = Graphics.FromImage(bmp);
}
}

/// <summary>
/// Notify container that a line segment has been added.
/// </summary>
private void RaiseSignatureUpdateEvent()
{
if (this.SignatureUpdate != null)
SignatureUpdate(this, EventArgs.Empty);
}

private void CreateFile(String fileName,String fileContent)
{
if (File.Exists(fileName))
{
Console.WriteLine("{0} already exists.", fileName);
//return;
}
StreamWriter sr = File.CreateText(fileName);
sr.WriteLine (fileContent);
//MessageBox.Show("File creation complete");
sr.Close();
}
public void StoreSigData(String fileName)
{
string sigData = "";
for (int i = 0; ipvector.count// This commented operation is used to convert decimal to hex and store
//sigData = sigData + PadHex(int.Parse(xVector[i].ToString()))+" " +
// PadHex(int.Parse(yVector[i].ToString()))+ "\n";
sigData = sigData + pVector[i].ToString()+ "\n";
}
CreateFile(fileName,sigData);

}
// this method PadHex can be used to convert int to hex format //
// not in use
private string PadHex(int inNum )
{
uint uiDecimal = checked((uint)System.Convert.ToUInt32(inNum));
string s = String.Format("{0:x2}", uiDecimal);
return(s);
}
}
}

/*****************************************************************/

//MainForm.cs File

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
//using Common;
using PocketSignature;

namespace SignCaptureV2
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel areaSignature;
private System.Windows.Forms.Button butNew;
private System.Windows.Forms.Button Save;
private System.Windows.Forms.Button Load;

SignatureControl signature = new SignatureControl();

public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

// add signature control to form
signature.Location = areaSignature.Location;
signature.Size = areaSignature.Size;
signature.Background = "file://program/">\\Program Files\\SignCaptureV2\\sign here.png";
this.Controls.Add(signature);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.areaSignature = new System.Windows.Forms.Panel();
this.butNew = new System.Windows.Forms.Button();
this.Save = new System.Windows.Forms.Button();
this.Load = new System.Windows.Forms.Button();
//
// areaSignature
//
this.areaSignature.BackColor = System.Drawing.Color.Gainsboro;
this.areaSignature.Location = new System.Drawing.Point(8, 8);
this.areaSignature.Size = new System.Drawing.Size(224, 120);
this.areaSignature.Visible = false;
//
// butNew
//
this.butNew.Font = new System.Drawing.Font("Tahoma", 8.25F,
System.Drawing.FontStyle.Regular);
this.butNew.Location = new System.Drawing.Point(0, 232);
this.butNew.Size = new System.Drawing.Size(54, 24);
this.butNew.Text = "Clear";
this.butNew.Click += new System.EventHandler(this.butNew_Click);
//
// Save
//
this.Save.Font = new System.Drawing.Font("Tahoma", 8.25F,
System.Drawing.FontStyle.Regular);
this.Save.Location = new System.Drawing.Point(64, 232);
this.Save.Size = new System.Drawing.Size(72, 24);
this.Save.Text = "Save in File";
this.Save.Click += new System.EventHandler(this.Save_Click);
//
// Load
//
this.Load.Font = new System.Drawing.Font("Tahoma", 8.25F,
System.Drawing.FontStyle.Regular);
this.Load.Location = new System.Drawing.Point(144, 232);
this.Load.Size = new System.Drawing.Size(88, 24);
this.Load.Text = "Load from file";
this.Load.Click += new System.EventHandler(this.Load_Click);
//
// MainForm
//
this.ClientSize = new System.Drawing.Size(258, 270);
this.Controls.Add(this.Load);
this.Controls.Add(this.Save);
this.Controls.Add(this.butNew);
this.Controls.Add(this.areaSignature);
this.Text = "PocketSignature";
}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>

static void Main()
{
Application.Run(new MainForm());
}

private void butNew_Click(object sender, System.EventArgs e)
{
signature.Clear();
this.Refresh();
}

private void Save_Click(object sender, System.EventArgs e)
{
signature.StoreSigData("SignFile.txt");
}

private void Load_Click(object sender, System.EventArgs e)
{
int baseX = 10;
int baseY = 100;
string signatureFile = "SignFile.txt";
load_signature(baseX,baseY,signatureFile);
}
void load_signature(int baseX,int baseY,string signatureFile)
{
System.IO.StreamReader streamReader
= new System.IO.StreamReader("SignFile.txt");
string pointString = null;

while ((pointString = streamReader.ReadLine())!= null)
{
if(pointString.Trim().Length>0)
{
String[] points = new String[4];
points = pointString.Split(new Char[]{' '});
Pen pen = new Pen(Color.Black);
this.CreateGraphics().DrawLine(pen,
(baseX+int.Parse(points[0].ToString())),
(baseY+int.Parse(points[1].ToString())),
(baseX+int.Parse(points[2].ToString())),
(baseY+int.Parse(points[3].ToString())));
}
}
streamReader.Close();
}
}
}

/***********SERVER CODE****************/




pvector.count

Using System.Net for sending mails

Introduction :
Sending Email is a basic task of a web application for many purposes like- Error logging, Reporting, Newsletters, and Performance alerting as well as for many other reasons.If you have taken web space somewhere on a web server then you are provided with the Email accounts and SMTP and POP services for sending and receiving E-mails. Some times you don't have SMTP server accounts and you may want to send email. Or Sometimes, for other reasons also you may want to use third-party SMTP sever for sending E-mails .
Gmail is a good solution for this purpose. Gmail provides SMTP and POP access which can be utilized for sending and receiving E-mails.Here in this tutorial we will be using a Gmail account for sending email by SMTP.

Note :
1. Gmail has a fixed number of quota for sending emails per day, means you may not be able to send unlimited number of e-mails using Gmail due to anti-spamming restrictions.
2. You may not be able to send same e-mail to unlimited number of people, because Gmail's anti-spamming engine restricts for this too.

So, Gmail can be used for sending limited number of e-mails daily to select people only. If you still need to send numerous e-mails to numerous people you can register for a Google Group account and can use that e-mail address to send email to registered members of that group. I will come up with that tutorial in near future.

Requirements:
1. An active Gmail account is required to test this application.
2. Visual Studio 2005

Step 1: Create a new web application in visual studio and add a Web form to it.Next add a Button to the form and double click this button to bring the code for click event of this button in the code window. Copy paste the following code to the click event.

Step 2: Run the web application and click on the Button to send the mail. Check the E-mail whether you get the mail successfully or not.


string from = me@gmail.com; //Replace this with your own correct Gmail Address
string to = you@gmail.com //Replace this with the Email Address to whom you want to send the mail

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, "One Ghost" , System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail" ;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ;
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();

//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "Password");

client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
HttpContext.Current.Response.Write(errorMessage );
} // end try

SQL Server Registration Tool

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows XP
  • Microsoft .NET Framework
  • Microsoft Internet Information Services (IIS)
  • Microsoft SQL Server

Modify the Web.config File of Your Application

To implement ASP.NET SQL Server mode session state management, you must modify the element of your application's Web.config file as follows:
  1. Set the mode attribute of the element to SQLServer to indicate that session state is stored in SQL Server.
  2. Set the sqlConnectionString attribute to specify the connection string for SQL Server. For example:

sqlConnectionString="data source=MySQLServer;user id=;password="

Note The user, , must have permissions to perform this operation on the database.

The modified element should appear as follows:


mode="SQLServer"
sqlConnectionString="data source=127.0.0.1;user id=;password="
cookieless="false"
timeout="20"
/>

Note Ensure that you use the correct case when you specify the element and the associated attribute values. This code is case sensitive.


Troubleshooting


  • If entries in the ASPStateTempSessions table are not removed after the related sessions expire, make sure that the SQL Server agent is running. You can implement this functionality through stored procedures that are scheduled through jobs in SQL Server. The SQL Server agent manages these jobs.
  • When you use the default InstallSqlState.sql and UninstallSqlState.sql script files to configure ASP.NET SQL Server mode session state management, note that these files add the ASPStateTempSessions and the ASPStateTempApplications tables to the tempdb database in SQL Server by default. Furthermore, if you restart SQL Server, you lose the session state data that was stored in the ASPStateTempSessions and the ASPStateTempApplications tables.For additional information about how to run alternative scripts to configure persistent SQL Server session state management so that the session data is not lost when you restart the serve

Adding a SqlDataSource and binding to GridView Control

Adding a SqlDataSource and binding to GridView Control:

In this article I will be using the Northwind database which comes with SQL Server 2000. In the last article I explained how easy it is to bind the Grid View control to the SqlDataSource. You can perform all these actions using the wizard. If you want to code and bind the datasource you can easily perform it using the following code sample:

void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{

// Binds the data

BindData();

}

}

public void BindData()
{

// you can use this line

string connectionString = myDataSource.ConnectionString;

// you can also use this line since by using the SqlDataSource it makes an entry in the
// web.config file if that is what choose to do
//string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
// if you are using Enterprise Library you can also use
//string connectionString = (string)ConfigurationSettings.ConnectionStrings["ConnectionString"];

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "Categories");

myGridView.DataSource = ds;

myGridView.DataBind();

}

You will need to set the Bound column in order to see the text in the cells of the grid view control. This can be easily done by using the Smart tag which appears when you right click on the grid view control.


I have also added a Status column to show you the checkbox column feature. The Status column is a simple bit field whose value can be either 1 or 0. If you are using Access database you can choose Yes/No Column. Once you have set up all your columns and execute the page it will display something like this:

At this moment if you try to select the Checkbox column, meaning if you try to check or uncheck the Status column it won't work. Let's see how we can make it work with our grid view control.

In the above image you see that the Checkboxes are not marked. The reason is because in the database the Checkbox column is NULL. If you make the column value to either 1 or 0 you will see check marks where the value is 1. See the image below and you will have a better idea of what I mean.

Editing in the Grid View Control

You can easily add the editing, updating, selecting, paging and sorting capabilities to your grid view control. Just add a new command column and you will be asked to add whatever functionality you desire.

If you are using the SqlDataSource to bind to the GridView control you will get most of the features by just using the SqlDataSource wizard. Since we are binding the control at runtime we need to add most of the functionality manually.

Edit Mode:

The fields that are marked readonly = false will change into TextBoxes when the Row_Editing event triggers. Like DataGrid control its easy to set the fields in the edit mode.

// Editing mode

void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{

myGridView.EditIndex = e.NewEditIndex;

BindData();

}

Cancel Edit:

If you don't like to edit the row you can press cancel link button which will fire the RowCancelingEdit event. The code to turn the row back to its original form is quite simple and straight forward.

// Cancel Edit Mode

void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{

myGridView.EditIndex = -1;

BindData();

}

Selecting Row:

Selecting row event is fired when you make a click on the select link. If you need any particular item in that row you can easily select it using the cells property:

// Selecting row

void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{

// This will contain the selectedValue of the row

string selectedCategory = myGridView.SelectedRow.Cells[1].Text;

}

The Cells start with index '0' which means Cell[0] is CategoryID , Cell[1] is CategoryName and so on.

Update Row:

For Updating the row we first need to get the value from the row that is entered by the user into the TextBox. For this purpose you can change the bound column into a Template column which will make is easier to locate the item.

After changing the CategoryName column to a tem plated column we can easily use the RowUpdating event to find the Text entered by the user.

void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

GridViewRow row = myGridView.Rows[e.RowIndex];

if (row != null)

{

TextBox t = row.FindControl("TextBox1") as TextBox;

if (t != null)

{

Response.Write("The Text Entered is" + t.Text);

}

}

Paging:

Paging can also be easily enabled in the grid view control. Its just like DataGrid from Asp.net 1.1. First you need to make set the allow paging property to true. And you can also set the page size. Here is a small code sample that will enable paging.

// Grid View Paging

void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

myGridView.PageIndex = e.NewPageIndex;

BindData();

}

Here is a small image shown below of paging. I have limited the page size to 3 so that the distribution of page will take place. In the image below we are in the page number 2.

Using SqlDataSource to execute commands:

You can also use the powerful SqlDataSource control to run and make your query. The SqlDataSource also contains the QUERY builder interface which can enhance the user experience in making SQL Queries. Apart from the SELECT query there are also INSERT, DELETE and UPDATE query builders wizards that you can use in your application.

When you use SqlDataSource you gets the advantage of having the paging, sorting implemented automatically which is pretty cool in some cases.

ASP.NET SQL Server Registration Tool (Aspnet_regsql.exe)

The ASP.NET SQL Server Registration tool is used to create a Microsoft SQL Server database for use by the SQL Server providers in ASP.NET, or to add or remove options from an existing database.

You can run Aspnet_regsql.exe without any command-line arguments to run a wizard that will walk you through specifying connection information for your SQL Server installation, and installing or removing the database elements for the membership, role management, profile, Web Parts personalization, and health monitoring features. (Setting session state and SQL cache dependency are not covered by the wizard.) You can also run Aspnet_regsql.exe as a command-line tool to specify database elements for individual features to add or remove, using the options listed in the table below




Aspnet_regsql.exe 

Session State Options

Option Description
-d Specifies the name of the database to store session state. This option must be used if -sstype is set to c


Specifies the type of session state to us1:

-sstype t|p|c

t - Temporary. Session state data is stored in the SQL Server tempdb database. Stored procedures for managing session state are installed in the SQL Server ASPState database. Data is not persisted if you restart SQL. This is the default.

p - Persisted. Both session state data and stored procedures are stored in the SQL Server ASPState database.

c - Custom. Both session state data and stored procedures are stored in a custom database. The database name must be specified using the -d option.