ASP.NET

You are currently browsing the archive for the ASP.NET category.

This is a getting started tutorial to Windows Communication Foundation (WCF) Services. I have discussed a simple service to calculate the area of a rectangle; yup, very simple ;)

1. First you need to download and install Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation).

Oops, looks like it needs a windows validation (bit of a problem if you have a pirate copy :P )

2. Once the installation is complete, start Visual Studio to create the project.

Goto File->New->Web Site, and you’ll see a new template called WFC Service.

Click OK to create an empty WCF Service.

3. Time to get started with the coding

Service.svc

<% @ServiceHost Language=C# Debug="true" Service="GeometryService" CodeBehind="~/App_Code/Service.cs" %>

Only a small change here – the name of the service

Web.config

<?xml version="1.0"?>
 
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <system.serviceModel>
    <services>
      <!-- Before deployment, you should remove the returnFaults behavior configuration to avoid disclosing information in exception messages -->
      <service name="GeometryService" behaviorConfiguration="GeometryServiceBehavior">
        <endpoint contract="IGeometryService" binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="GeometryServiceBehavior" >
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 
  <system.web>
    <compilation debug="true"/>
  </system.web>
 
 </configuration>

Enable metadata publishing and change the name of the service.

Service.cs

using System;
using System.ServiceModel;
using System.Runtime.Serialization;
 
// A WCF service consists of a contract (defined below as IMyService, DataContract1), 
// a class which implements that interface (see MyService), 
// and configuration entries that specify behaviors associated with 
// that implementation (see <system.serviceModel> in web.config)
 
[ServiceContract()]
public interface IGeometryService
{
 [OperationContract]
 int GetArea(Rectangle rect);
 [OperationContract]
 int GetPerimeter(int width, int height);
}
 
public class GeometryService : IGeometryService
{
 public int GetArea(Rectangle rect)
 {
  return rect.Area();
 }
 
 public int GetPerimeter(int width, int height)
 {
  Rectangle rect = new Rectangle(width, height);
  return rect.Perimeter();
 }
}
 
[DataContract]
public class Rectangle
{
 int width;
 int height;
 
 public Rectangle(int width, int height)
 {
  Width = width;
  Height = height;
 }
 
 [DataMember]
 public int Width
 {
  get { return width; }
  set { width = value < 0 ? 0 : value; }
 }
 
 [DataMember]
 public int Height
 {
  get { return height; }
  set { height = value < 0 ? 0 : value; }
 }
 
 public int Area()
 {
  return Height * Width;
 }
 
 public int Perimeter()
 {
  return 2 * (Height + Width);
 }
}

This is the code for the service.

4. Run the service – click F5 :)

This is what you get on the browser. So, lets do what they want.

5. Run the following on you command on Visual Studio Command Prompt

svcutil.exe http://localhost:1479/GeoWFCService/Service.svc?wsdl

Watch out, the path might be different ;) . And if you don’t know what Visual Studio command prompt is

6. Let’s create the client

Create (or rather add) a new project; this could even be a website

7. Then run the service – Ctrl + F5

8. Add a web reference to the service

8. Copy the GeometryService.cs created by svcutil in step 5 to the clients working (main) folder and add them to the project

You should also copy the configurations of output.config created by svcutil to app.config

9. Again time for coding

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace GeoWFCClient
{
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
  }
 
  private void calculateButton_Click(object sender, EventArgs e)
  {
   GeometryServiceClient gsclient = new GeometryServiceClient();
 
   /* The overloaded constructor of Rectangle is not present here */
   Rectangle rect = new Rectangle();
 
   rect.Width = Int32.Parse(widthTextBox.Text);
   rect.Height = Int32.Parse(heightTextBox.Text);
 
   areaTextBox.Text = gsclient.GetArea(rect).ToString();
   perimeterTextBox.Text = gsclient.GetPerimeter(rect.Width, rect.Height).ToString();
  }
 }
}

Set the textboxes and labels with appropriate names.

10. When you compile you’ll get a set of error because some assemblies are not referenced. Add references to them

11. Now see how it works

Start the service if haven’t done so already, and run the client

Wow! It works :D

Ok, hope you learned something with this and I got to go study for exam :P

Tags: , , , , ,

There are many free packages for graphing and charting among expensive charting components.

ZedGraph is a charting tool for .NET. It’s very easy to use and you can customize the look of the charts easily; furthermore, they provide lot of example codes and help files which makes it very easy to understand.

There’s another charting tool I’ve used for Java, JFreeChart, which is also a very powerful tool for charting, but they provide only a few sample codes and help documents, which makes it little hard for a beginner to use all those powerful features it has.

Tags: , , , ,

Bulk Insert

Have you ever wanted to insert a large set of records to a MySQL database? One way to do is to insert row by row, but this will take a looong time. I was also faced with this problem last week since I had to insert a large set of data to a table from ASP.NET.

First of all I used a transaction.

OdbcConnection con = new OdbcConnection("...");
con.Open();
OdbcTransaction trans = con.BeginTransaction();
for(int i = 0; i < 10000; i++)
{
 OdbcCommand cmd = new OdbcCommand("INSERT ... ");
 cmd.ExecuteNonQuery();
}
trans.Commit();
con.Close();

This increase the speed by about three times and it worked in a reasonable time for small data sets, but not for very large ones. Another advantage with this is that if the insertion fails at middle of the transaction none of the data will be inserted.

Then, as a friend of mine suggested me I used the SQL command LOAD DATA INFILE. I wrote all the records to a comma separated text file and the used LOAD DATA INFILE to insert the data to the database; this ran very fast since al the data is added at once as a batch, communications with the database are less and table indexes are updated once for all the data.

LOAD DATA INFILE 'sample.txt' INTO TABLE table_name
 FIELDS TERMINATED BY ',' ENCLOSED BY '"'
 (field_list);

The text file should not contain any spaces between ,’s (commas). Although this works fine, you won’t be able to use it if you don’t have proper rights set for the MySQL user id; this might happen if you’re using a commercial server, where you’re unable to alter the permissions.

At last you can use large packets of SQL statements; that is, break the large data set into small (not so small – about 1 megabytes) sets or records, and insert each of these small data sets one by one (or using a transaction).

INSERT INTO table_name (field_list) VALUES
 ('data', 'data', ... )
 ('data', 'data', ... )
 ...
 ('data', 'data', ... )

You cannot use very large packets since there is a limit to the packet size.

 

Tags: , , ,