Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘C# 2.0’ Category

Capture web page as image using ASP.NET

Posted by Ramani Sandeep on December 5, 2009

Introduction

This article describes how you can take a screenshot of a special webpage programmatically with ASP.NET. The goal of this sample is to find a way to capture a webpage’s image. The parameter is just a special url. Only by knowing this url we want to be able to take a screenshot of this webpage – a bitmap of what the user would see if he/she types this url in the browser.

How to take a screenshot of browser-content?

Here I have used one utility program to take screen shot of browser content name is IECapt.exe. IECapt is a small command-line utility to capture Internet Explorer’s rendering of a web page into a BMP, JPEG or PNG image file. We have to put IECapt.exe on the server and define that we have the right to execute it.

Download IECapt.exe

Here is the sample application for the same.

Step 1: Create the web application with two web page & in first page create screen like this

1

Here is the html for that:

 <table cellpadding="10" cellspacing="0" width="700" style="border-style:solid; background-color:green;">
            <tr>
                <td align="center" colspan="2">
                    <h1>
            Take a Snap of Web page</h1> <hr />
                </td>
            </tr>
            <tr>
                <td align="right">
                    Url:
                </td>
                <td align="left">
                    <asp:TextBox ID="txtUrl" runat="server" Width="300">http://www.ramanisandeep.wordpress.com</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Width:
                </td>
                <td align="left">
                    <asp:TextBox ID="txtWidth" runat="server">500</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Height:
                </td>
                <td align="left">
                    <asp:TextBox ID="txtHeight" runat="server">500</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Save image with this name :
                </td>
                <td align="left">
                    <asp:TextBox ID="txtDestImage" runat="server">MyImage3</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                </td>
                <td align="left">
                    <asp:Button ID="btnCapture" runat="server" OnClick="btnCapture_Click" Text="Capture"
                         />
                </td>
            </tr>
        </table>

Step 2: On Button click event call the class method & redirect to new page to show the image

Code behind would be like this:

 protected void btnCapture_Click(object sender, EventArgs e)
    {
        int Width, Height;
        Width = Convert.ToInt32(txtWidth.Text);
        Height = Convert.ToInt32(txtHeight.Text);
        CaptureWebPage cwp = new CaptureWebPage();
        string imagePath = cwp.GetImage(txtUrl.Text, txtDestImage.Text, Server.MapPath("~"), Width, Height);
        Response.Redirect("~/Default2.aspx?Path=" + imagePath);
    }

Step 3: Create class CaptureWebPage.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

public class CaptureWebPage
{
    private const string EXTRACTIMAGE_EXE = "IECapt.exe";
    private const int TIMEOUT = 60000;
    private const string TMP_NAME = "InBetween.png";

    public CaptureWebPage()
    {
    }

    private void Shot(string url, string rootDir)
    {
        Process p = new Process();
        p.StartInfo.FileName = rootDir + "\\" + EXTRACTIMAGE_EXE;
        p.StartInfo.Arguments = String.Format("\"{0}\" \"{1}\"", url, rootDir + "\\" + TMP_NAME);
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = false;
        p.Start();
        p.WaitForExit();
        p.Dispose();
    }

    private System.Drawing.Image Scale(System.Drawing.Image imgPhoto,int Width, int Height)
    {
        int srcWidth = imgPhoto.Width;
        int srcHeight = imgPhoto.Height;
        int srcX = 0; int srcY = 0;
        int destX = 0; int destY = 0;

        float percent = 0; float percentWidth = 0; float percentHeight = 0;

        percentWidth = ((float)Width / (float)srcWidth);
        percentHeight = ((float)Height / (float)srcHeight);

        if (percentHeight < percentWidth)
        {
            percent = percentWidth;
            destY = 0;
        }
        else
        {
            percent = percentHeight;
            destX = 0;
        }

        int destWidth = (int)(srcWidth * percent);
        int destHeight = (int)(srcHeight * percent);

        System.Drawing.Bitmap bmPhoto = new System.Drawing.Bitmap(Width,
                Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode =
                InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(srcX, srcY, srcWidth, srcHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

    public string GetImage(string url, string name, string rootDir,	int width, int height)
    {
        string fileName = rootDir + "\\" + TMP_NAME;
        Shot(url, rootDir);
        System.Drawing.Image thumbImage = System.Drawing.Image.FromFile(fileName);
        Scale(thumbImage, width, height);
        System.Drawing.Image scaledImg = Scale(thumbImage, width, height);
        fileName = rootDir + "\\" + name + ".png";
        if (File.Exists(fileName))
            File.Delete(fileName);
        scaledImg.Save(fileName, ImageFormat.Png);
        return name + ".png";
    }
}

Step 4: Create new page Default2.aspx to display the shot taken

Here is the html for that:

 <asp:Image ID="theImage" runat="server" />
  <asp:Button ID="Button1" runat="server" Text="Go Back" OnClick="Button1_Click" />

Code behind would be:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Path"] != null)
        {
            theImage.ImageUrl = "~//" + Request.QueryString["Path"].ToString();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }

Step 5: Most important thing is Download IECapt.exe from the above link & put at the rool level.

Run the Application

2

Great !!!

Now enjoy taking the snap of the web page in your web application when ever required or application demands.

Jay Ganesh

Posted in ASP.NET, C# 2.0 | Tagged: , , , , , , , , , , | Leave a Comment »

CodeRun Web Toolkit: C# to JavaScript web framework

Posted by Ramani Sandeep on December 3, 2009

What is CodeRun Web Toolkit?

CodeRun Web Toolkit (CWT) is a complete framework for creating Rich Internet Applications with C#. CWT provides the following components:

  • C# to JavaScript converter
  • C# to JavaScript remoting handler
  • Rich UI library, loosely modeled after WPF (Windows Presentation Foundation)

You can use CodeRun Web Toolkit to:

  • Implement client side scripts for existing ASP.NET applications with C#
  • Work with external JavaScript libraries (such as YUI) in C#.
  • Develop compelling and optimized AJAX Applications in C#

CodeRun Web Toolkit Added Features

Language Features

  • Namespaces
  • Classes
  • Interfaces
  • Properties
  • Events
  • Method Overloads
  • Polymorphism
  • Extension Methods
  • Delegates
  • Indexers
  • Generics
  • LINQ
  • Reflection and Attributes
  • Object Initializers

Productivity Features (in Visual Studio)

  • Compilation Error Reporting
  • Code Coloring
  • Code Refactoring
  • Performance Profiling

Toolkit Features

  • Ajax as method calls
  • Rich UI Library

Simple code example

The following example demonstrates how to write a simple C# method and use CodeRun Web Toolkit to convert it to JavaScript:

//Demonstrates how to execute a C# class at the browser
namespace CWT_Samples
{
  public partial class SimpleExample : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
     {
       this.RegisterRunAtClientScripts(SimpleExample_Client.Main, head, body);
     }
   }

  //The following class will be converted to JavaScript
  [RunAtClient]
  public class SimpleExample_Client
  {
     public static void Main()
     {
        var window = HtmlDom.Window;
        window.alert("Hello from C#!");
     }
  }
}

for more information – click here

Posted in C# 2.0, JavaScript | Tagged: , , | Leave a Comment »

.NET Challenge – for or foreach?

Posted by Ramani Sandeep on November 2, 2009

Question:

for should be used instead of foreach to iterate over collections in performance-critical loops.

Answer: True

foreach uses an enumerator which can sometimes be slower than the simple iteration of a variable in a for loop. Enumerators, such as those contained in the .NET Framework, have both managed heap and virtual function overhead. The amount of overhead depends on the collection used and the version of the .NET Framework. As always, the best way to determine the overhead between techniques is to run a performance test and compare.

To illustrate the performance impact, 10 strings were concatenated 100 times using the techniques outlined below. 

Running against .NET Framework 3.5 using an ArrayList, a generic List and a LinkedList with 5,000 strings, the following results were obtained using Ants Performance Profiler 5:

Wall Clock Time (ms) Loop Structure (5,000 strings)
25.003 for LinkedList<string>
0.037 foreach LinkedList<string>
0.039 for ArrayList
0.053 foreach ArrayList
0.019 for List<string>
0.034 foreach List<string>

 

Except for the LinkedList, the for loop is faster.

The for loop is thought by many developers to be less readable and maintainable than foreach. Using foreach also makes it possible to iterate across anything that’s IEnumerable, allowing for the creation of more general algorithms and the use of "yield" to build custom collections.

It is normally good practice to code for clarity rather than micro-optimization.

Reference : Rad-gate

Posted in ASP.NET, ASP.NET 3.5, C# 2.0, C# 3.0 | Tagged: , , , , | Leave a Comment »

What is httpHandler & httpModule?

Posted by Ramani Sandeep on September 24, 2009

httpHandler – Extenstion Based Preprocessor :

ASP.NET HTTP handler is the process that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

httpModule – Event based Preprocessor :

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

When to use HTTP handlers:

  • RSS feeds: To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
  • Image server:   If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler’s response.

When to use HTTP modules:

  • Security:   Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
  • Statistics and logging:   Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
  • Custom headers or footers:   Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.

Main Features:

  • The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.
    The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.
  • Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.
  • Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change.
  • Modules can subscribe to a variety of request-pipeline notifications. Modules can receive notification of events of the HttpApplication object.

Built-in HTTP Handlers in ASP.NET

  • ASP.NET page handler (*.aspx): The default HTTP handler for all ASP.NET pages.
  • Web service handler (*.asmx): The default HTTP handler for Web service pages created as .asmx files in ASP.NET.
  • Generic Web handler (*.ashx): The default HTTP handler for all Web handlers that do not have a UI and that include the @ WebHandler directive.
  • Trace handler (trace.axd): A handler that displays current page trace information.

Reference:

I have taken the content & compiled from here.

Other Useful Articles are:

  1. The Two Interceptors: HttpModule and HttpHandlers – Click here
  2. Displaying images in ASP.NET using HttpHandlers – Click here

Posted in ASP.NET, C# 2.0 | Tagged: , , , , | Leave a Comment »

Calling Web Service Methods Using ASP.NET AJAX

Posted by Ramani Sandeep on September 22, 2009

The Microsoft ASP.NET AJAX asynchronous communication layer enables a browser to call Web service methods on the server by using ECMAScript (JavaScript). It exposes APIs that JavaScript functions can use in any browser to call Web service methods on the server.

The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the Web server.

This following code example shows how to expose a Web service method in an ASP.NET Web page.

Step 1: Create ASP.NET Ajax Enabled Web site

Step 2: Now Add New Item – Select Web Service from the List of Items and Name it WebService.asmx.

Step 3: Replace the WebService.cs with the following code:

Listing – 1

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
     return "This is Message From Server - Hello World - " + DateTime.Now.ToString();
    }
}

Note: We have added [ScriptService] tag and Replaced HelloWorld().

Step 4: Now come back on default.aspx page and and Update the ScriptManager with the following:

Listing – 2

    <asp:ScriptManager runat="server" ID="scriptManager">
         <Services>
            <asp:ServiceReference Path="WebService.asmx" />
         </Services>
    </asp:ScriptManager>

Here given the ServiceReference to WebService that we have just created.

Step 5: Add button control on page which will be used to call the webservice.

Listing – 3

    <div>
      <p>Calling a service that returns the current server time.</p>
       <input id="Button1" type="button" value="Call Web Service" onclick="HelloWorld()"/>
    </div>

Step 6: Add Javascript on the page with HelloWorld() function with will call the WebService & Return the Result.

Listing – 4

    <script type="text/javascript">
            function HelloWorld()
            {
                WebService.HelloWorld(OnSucceeded);
            }
            function OnSucceeded(result)
            {
                var myResult = document.getElementById("rst");
                myResult.innerHTML = result;
            }
        </script>

Step 7: finally put <spam> tag on page on which we will display our result.

Listing – 5

    <hr />
       <div>
           <span id="rst"></span>
       </div>

Reference:

http://www.asp.net/AJAX/Documentation/Live/overview/AsynchronousLayerOverview.aspx

Related Post:

http://ramanisandeep.wordpress.com/2009/09/03/using-jquery-to-directly-call-asp-net-ajax-page-methods/

Hope this will Help you !!!

Jay Ganesh

Posted in ASP.NET Ajax, C# 2.0 | Tagged: , , | 2 Comments »

DataReader vs DataSet

Posted by Ramani Sandeep on September 21, 2009

This article contain difference between Dataset and DataReader and also Detailed explaination of Functionality & Features provided by DataReader/DataSet.

I have found lots of article who talk about Dataset and DataReader but the article written by John Papa in MSDN Magazine contains very useful explaination on this topic. So I have used that information to write this article & tried to give you the best.

Here Points to ponder contain the difference between Dataset and DataReader.

Points to ponder:

  • DataSet Object works under Disconnected mode, While DataReader Object has Connected mode.
  • DataSet Object has Read/Write access, While DataReader Object has Read-only access.
  • DataSet Object Supports multiple tables from different databases, While DataReader Object Supports a single table based on a single SQL query of one database.
  • DataSet Object has Greater overhead to enable additional features, While DataReader Object being Lightweight object with very little overhead.
  • DataSet Object is Bind to multiple controls, While DataReader Object is Bind to a single control.
  • DataSet Object supports Forward and backward scanning of data, While DataReader Object supports Forward-only scanning of data.
  • DataSet Object has Slower access to data, While DataReader Object has Faster access to data.
  • DataSet Object is Supported by Visual Studio .NET tools, While DataReader Object Must be manually coded.

Connected Mode:

A DataReader is a stream of data that is returned from a database query. When the query is executed, the first row is returned to the DataReader via the stream. The stream then remains connected to the database, poised to retrieve the next record. The DataReader reads one row at a time from the database and can only move forward, one record at a time.

As the DataReader reads the rows from the database, the values of the columns in each row can be read and evaluated, but they cannot be edited.

Unlike the DataSet, the DataReader is not implemented directly in the System.Data namespace.

Rather, the DataReader is implemented through a specific managed provider’s namespace such as System.Data.SqlClient.SqlDataReader.

Because all DataReaders, including the OleDbDataReader, the SqlDataReader, and other managed provider’s DataReaders implement the same IDataReader interface, they should all provide the same base set of functionality.

Each DataReader is optimized for a specific data provider. If the database you are developing against has a managed provider for ADO.NET, then you should take advantage of it. Otherwise, you can use the System.Data.OleDb or the System.Data.Odbc namespaces, which expose more generic managed providers that can access a variety of data sources.

If you are developing against SQL Server™ or Oracle, it would be more efficient to use the provider that was made specifically for these databases. In this column, I will query the SQL Server Northwind database using the System.Data.SqlClient namespace.

The SqlDataReader can only retrieve one row at a time from the data source and in order for it to get the next record, it has to maintain its connection to the data source.

The DataSet, however, doesn’t need to know about where it gets its data.

The DataReader can only get its data from a data source through a managed provider.

The DataSet can also get its data from a data source via a managed provider, but the data source can also be loaded manually, even from an XML file on a hard drive.

In ASP.NET, DataReader objects can be used for more robust situations such as binding themselves to an ASP.NET DataGrid or a DropDownList server control.

The following code demonstrates how to retrieve a list of products from the Northwind database using a SqlDataReader object:

   1: string sSQL = "SELECT * FROM Products";

   2: string sConnString =

   3:     "Server=(local);Database=Northwind;Integrated Security=SSPI;";

   4: using (SqlConnection oCn = new SqlConnection(sConnString))

   5: {

   6:     SqlCommand oSelCmd = new SqlCommand(sSQL, oCn);

   7:     oSelCmd.CommandType = CommandType.Text;

   8:     oCn.Open();

   9:     SqlDataReader oDr = oSelCmd.ExecuteReader();

  10:     DataGrid1.DataSource = oDr;

  11:     DataGrid1.DataBind();

  12: }

Now Read the Data using

   1: SqlDataReader oDr = oCmd.ExecuteReader();

   2: while(oDr.Read()) {

   3:     Console.WriteLine(oDr[0]);

   4: }

Supporting Multiple Resultsets

The DataReader supports access to multiple resultsets, one at a time, in the order they are retrieved. This code is easily modified to handle multiple resultsets. The following code retrieves a SqlDataReader and loops through its rows, again writing the first column’s value for each row to the console:

   1: SqlDataReader oDr = oCmd.ExecuteReader();

   2:     do {

   3:         while(oDr.Read())

   4:         {

   5:             Console.WriteLine(oDr[0]);

   6:         }

   7:         Console.WriteLine(oDr[0]);

   8:     }

   9:     while(oDr.NextResult());

Once all of the rows from the first resultset are traversed, the rowset from the second query is retrieved and its rows are traversed and written. This process can continue for several resultsets using a single SqlDataReader.

The Read method of the SqlDataReader loads the next record so that it can be accessed and moves the position of the cursor ahead. It returns a Boolean value indicating the existence of more records. This feature can help circumvent a common problem in classic ADO development: the endless loop.

The DataReader in the previous code sample shows how to get the value for a column from the DataReader using its ordinal index position.

Disconnected Mode:

The DataSet is the main data storage tool in the ADO.NET disconnected architecture. Unlike the DataReader, the DataSet is not connected directly to a database through a Connection object when you populate it.

Instead, to fill a DataSet from a database you first create a DataAdapter object for the provider and associate it with a SqlConnection object. Then the SqlDataAdapter can broker the data retrieval for the DataSet by issuing a SqlCommand against the database through the SqlConnection, retrieving the data, and filling the DataSet.

You can think of the SqlDataAdapter as a bridge between the connected and disconnected objects.

One of its purposes is to serve as the route for a rowset to get from the database to the DataSet.

For example, when the SqlDataAdapter’s Fill method is executed it opens its associated SqlConnection object (if not already open) and issues its associated SqlCommand object against the SqlConnection. Behind the scenes, a SqlDataReader is created implicitly and the rowset is retrieved one row at a time in succession and sent to the DataSet.

Once all of the data is in the DataSet, the implicit SqlDataReader is destroyed and the SqlConnection is closed.

The following code shows how a DataSet can be filled from the Products table of the Northwind database:

   1: string sSQL = "SELECT * FROM Products";

   2: string sConnString = 

   3:     "Server=(local);Database=Northwind;Integrated Security=SSPI;";

   4: SqlDataAdapter oDa = new SqlDataAdapter();

   5: DataSet oDs = new DataSet();

   6: using(SqlConnection oCn = new SqlConnection(sConnString))

   7: {

   8:     SqlCommand oSelCmd = new SqlCommand(sSQL, oCn);

   9:     oSelCmd.CommandType = CommandType.Text;

  10:     oDa.SelectCommand = oSelCmd;

  11:     oDa.Fill(oDs, "Products");

  12: }

The DataSet can read and load itself from an XML document as well as export its rowset to an XML document. Because the DataSet can be represented in XML, it can be easily transported across processes, a network, or even the Internet via HTTP.

Unlike the DataReader, the DataSet is not read-only.

A DataSet can be modified, and rows can be added or deleted. Changes to a DataSet can be sent to the database via a managed provider’s objects.

Another key difference between the DataSet and the DataReader is that the DataSet is fully navigable. Its rows can be traversed forward or backward. The DataReader can be traversed forward only.

In addition, a DataSet is highly flexible in that its DataTable objects can be filtered vertically or horizontally and they can be sorted or even searched.

The DataSet is independent of any one data provider as it relies on a DataAdapter specific to each provider to broker the data between the DataSet and the database.

Not only can the DataSet be loaded from XML, it can also be loaded manually.

   1: //-- Create the table

   2: DataTable oDt = new DataTable("Employees");

   3: DataRow oRow;

   4: oDt.Columns.Add("EmployeeID", System.Type.GetType("System.Int32"));

   5: oDt.Columns.Add("FirstName", System.Type.GetType("System.String"));

   6: oDt.Columns.Add("LastName", System.Type.GetType("System.String"));

   7: oDt.Constraints.Add("PK_Employees", oDt.Columns["EmployeeID"], true);

   8: oDt.Columns["EmployeeID"].AutoIncrement = true;

   9: oDt.Columns["EmployeeID"].AutoIncrementSeed = -1000;

  10: oDt.Columns["EmployeeID"].AutoIncrementStep = -1;

  11: oDs.Tables.Add(oDt);

  12:  

  13: //-- Add the rows

  14: oRow = oDs.Tables["Employees"].NewRow();

  15: oRow["FirstName"] = "Haley";

  16: oRow["LastName"] = "Smith";

  17: oDs.Tables["Employees"].Rows.Add(oRow);

  18: oRow = oDs.Tables["Employees"].NewRow();

  19: oRow["FirstName"] = "Madelyn";

  20: oRow["LastName"] = "Jones";

  21: oDs.Tables["Employees"].Rows.Add(oRow);

  22:  

  23: //-- Bind it to a DataGrid

  24: grdEmployees.DataSource = oDs.Tables["Employees"];

Because the DataSet is disconnected, its use can reduce the demand on database servers. It does, however, increase the memory footprint in the tier where it is stored, so be sure to account for that when designing around a DataSet as your data store.

Scaling up on the middle tier using parallel servers and load balancing is a common way to handle the increased load so that session-based information can be stored in objects such as the DataSet.

When to Use the DataSet

The DataSet’s disconnected nature allows it to be transformed into XML and sent over the wire via HTTP if appropriate. This makes it ideal as the return vehicle from business-tier objects and Web services.

DataSet objects are a good choice when the data must be edited or rows added or deleted from the database.

Since the DataSet can be traversed in any direction, all of these features are available. This flexibility also makes the DataSet an easy choice when the situation calls for multiple iterations of the rowset.

If a rowset is intended to be bound to more than one read-only ASP.NET server control, you should consider using a DataSet instead.

The DataSet also works well when a rowset must be persisted between page calls to the Session or Cache objects.

When to Use the DataReader

Binding a DataReader to a DropDownList or even a read-only DataGrid in ASP.NET works well as the data can be retrieved and displayed in the list but does not need to be persisted for editing.

When populating a list or retrieving 10,000 records for a business rule.

When a huge amount of data must be retrieved to a business process, even on a middle tier, it can take a while to load a DataSet, pass the data to it on the business tier from the database, and then store it in memory. The footprint could be quite large and with numerous instances of it running (such as in a Web application where hundreds of users may be connected), scalability would become a problem. If this data is intended to be retrieved and then traversed for business rule processing, the DataReader could speed up the process as it retrieves one row at a time and does not require the memory resources that the DataSet requires.

When output or return parameters need to be retrieved, a DataReader will not allow you to get them until the DataReader and its connection are closed. If data must be bound to a read-only list in a Web Form, a DataReader is a very good choice.

 

Reference:

http://msdn.microsoft.com/en-us/magazine/cc188717.aspx

Posted in ADO.NET, C# 2.0 | Tagged: , , , , | Leave a Comment »

If At First You Don’t Succeed – Retrying Mail Operations in .NET

Posted by Ramani Sandeep on September 21, 2009

Mail sent from your application didn’t go through? Don’t give up so easily! The majority of mail server interruptions are very temporary in nature, lasting only a few seconds. Instead of failing right away, why not give your SMTP client another shot?

As I’m sure you’re very aware, sending email from applications is an extremely common task. For example, just about every web site has a “Contact Us’ page of some sort. Yours are probably much prettier that the screenshot below, but the idea is the same.

my1

If you only need to send mail from this one place, you might stick the required code directly in the code-behind of your contact page. However, most applications need to send mail for all kinds of reasons – to confirm new member signups, subscription requests, password changes and resets, and various other notifications based on your business rules. Therefore, it’s much more convenient to encapsulate the mail-sending logic and just call it from wherever you need to, as below.

Read more…

Posted in ASP.NET, ASP.NET Ajax, ASP.NET MVC, C# 2.0 | Tagged: , , | Leave a Comment »

How to hide Gridview column programmatically?

Posted by Ramani Sandeep on April 7, 2009

Question :  How to hide Gridview column programmatically?

Solution :

The Columns collection only stores the explicitly declared columns, so if you’re using autogenerated columns, the count will be zero.
If you’re using autogenerated column, after databind you could loop through the rows collection and make the appropriate cells invisible, like:

        GridView1.DataBind();
        if (GridView1.Columns.Count > 0)
            GridView1.Columns[0].Visible = false;
        else
        {
            GridView1.HeaderRow.Cells[0].Visible = false;
            foreach (GridViewRow gvr in GridView1.Rows)
            {
                gvr.Cells[0].Visible = false;
            }
        }

Hope this will help you !!!

Happy Programming

Posted in ASP.NET, C# 2.0 | Tagged: , , , | 7 Comments »

Programming the web.config File Using C#

Posted by Ramani Sandeep on April 7, 2009

What Is web.config?

The web.config file is the application’s configuration file. It is typically used to configure an ASP.NET Web application and define the configuration settings for the Web application. It typically contains the application-wide settings, such as database connection string, culture settings, authentication, and authorization information, etc. In ASP.NET 1.x, much effort was required to manipulate the web.config file programmatically. With ASP.NET 2.0 however, this can be done quite easily and efficiently. The following section discusses how this can be achieved.

The Configuration API in ASP.NET 2.0

The configuration API of ASP.NET 2.0 adds a great level of flexibility in that it allows us to add or edit a configuration file seamlessly in ASP.NET. The WebConfigurationManager class in the System.Web.Configuration namespace has the OpenWebConfiguration method that can be used to open the configuration file of the application as a Configuration object for reading from or writing to the configuration file. The virtual path to the configuration file is specified to this method as a parameter.

The following code snippet displays all the keys of the appSettings section of the web.config file:

Listing – 1

        Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");

        AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
        if (appSettingsSection != null)
        {
            foreach (string key in appSettingsSection.Settings.AllKeys)
            {
                Response.Write(key);
            }
        }


The following method can be used to modify a specific key — value pair of the web.config file — programmatically using C#:

Listing – 2

        public void Modify(string key, string value)
        {
            Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
            if (appSettingsSection != null)
            {
                appSettingsSection.Settings[key].Value = value;
                config.Save();
            }
        }

The following method can be used to delete a specific key in the web.config file programmatically using C#:

Listing – 3

        public void Remove(string key)
        {
            Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
            if (appSettingsSection != null)
            {
                appSettingsSection.Settings.Remove(key);
                config.Save();
            }
        }

Conclusion

Even if modifying a web.config file programmatically can be a handy solution in some situations, it is not recommended to do so frequently in a Web application, as any change in the web.config file will restart the Web server and refresh the cache entries.

Posted in ASP.NET, C# 2.0 | Tagged: , , , , | 5 Comments »

Capcha Image Code in C#

Posted by Ramani Sandeep on January 29, 2009

Introduction

CAPTCHA stands for “completely automated public Turing test to tell computers and humans apart.” What it means is, a program that can tell humans from machines using some type of generated test. A test most people can easily pass but a computer program cannot.

You’ve probably encountered such tests when signing up for an online email or forum account. The form might include an image of distorted text, like that seen above, which you are required to type into a text field.

The idea is to prevent spammers from using web bots to automatically post form data in order to create email accounts (for sending spam) or to submit feedback comments or guestbook entries containing spam messages. The text in the image is usually distorted to prevent the use of OCR (optical character reader) software to defeat the process. Hotmail, PayPal, Yahoo and a number of blog sites have employed this technique.

This article demonstrates how to create such an image and employ it within an ASP.NET web form.

Using the code

The code file contains the source for one class and two web forms. To use it, just create a new web project and add those items.

* CaptchaImage.cs – defines the CapchaImage object which actually creates the image.
* Default.aspx, Default.aspx.cs – a sample web form.
* JpegImage.aspx, JpegImage.aspx.cs - a web form designed to output a JPEG image rather than HTML.

Let’s look at each component and it’s purpose.

CaptchaImage.cs

The CaptchaImage object creates an image given parameters for the text to be displayed, the image dimensions and, optionally, the font to use.The heart of the code is the GenerateImage() method, shown below, which creates a bitmap image of the specified width and height. This method is called from the CaptchaImage constructor, so the image is ready as soon as you create a new instance of the object.To create the image, we first fill in the background using a hatched brush (the “dirtier” the image appears, the harder it is for an OCR program to read it).

To make the text fit within the image, we start with an initial font size based on the image height and use the Graphics.MeasureString() method to find the resulting dimensions of the drawn text. If the text exceeds the image dimensions, we reduce the font size and test again and again until a suitable font size is found.

// ===========================================

// Creates the bitmap image.

// ===========================================

private void GenerateImage()
{
// Create a new 32-bit bitmap image.

Bitmap bitmap = new Bitmap(
this.width,
this.height,
PixelFormat.Format32bppArgb);

// Create a graphics object for drawing.

Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);

// Fill in the background.

HatchBrush hatchBrush = new HatchBrush(
HatchStyle.SmallConfetti,
Color.LightGray,
Color.White);
g.FillRectangle(hatchBrush, rect);

// Set up the text font.

SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.

do
{
fontSize–;
font = new Font(
this.familyName,
fontSize,
FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width > rect.Width);

// Set up the text format.

StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

// Create a path using the text and warp it randomly.

GraphicsPath path = new GraphicsPath();
path.AddString(
this.text,
font.FontFamily,
(int) font.Style,
font.Size, rect,
format);
float v = 4F;
PointF[] points =
{
new PointF(
this.random.Next(rect.Width) / v,
this.random.Next(rect.Height) / v),
new PointF(
rect.Width – this.random.Next(rect.Width) / v,
this.random.Next(rect.Height) / v),
new PointF(
this.random.Next(rect.Width) / v,
rect.Height – this.random.Next(rect.Height) / v),
new PointF(
rect.Width – this.random.Next(rect.Width) / v,
rect.Height – this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

// Draw the text.

hatchBrush = new HatchBrush(
HatchStyle.LargeConfetti,
Color.LightGray,
Color.DarkGray);
g.FillPath(hatchBrush, path);

// Add some random noise.

int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}

// Clean up.

font.Dispose();
hatchBrush.Dispose();
g.Dispose();

// Set the image.

this.image = bitmap;
}

Once the font is set, we define a GraphicsPath() which essentially converts the text to a set of lines and curves. This can then be distorted using the GraphicsPath.Warp() method with some randomly generated values. The effect is similar to holding a cardboard sign up by opposite corners and giving it a bit of a twist. The resulting path is drawn onto the image, again using a hatch brush to give it a “dirty” appearance.

To complete the distortion, small blots are randomly painted over the image. You could experiment with other effect to thwart OCRs, but keep in mind that it should still be legible to humans, some of whom may have visual impairments

Default.aspx

This is a very simple sample web form that contains only a few basic elements, namely an <IMG> tag for the image, a text box and a “Submit” button.

<form id=”Default” method=”post” runat=”server”>
<img src=”JpegImage.aspx”><br>
<p>
<strong>Enter the code shown above:</strong><br>
<asp:TextBox id=”CodeNumberTextBox” runat=”server”></asp:TextBox>
<asp:Button id=”SubmitButton” runat=”server” Text=”Submit”>
</asp:Button><br>
</p>
<p>
<em class=”notice”>
(Note: If you cannot read the numbers in the above<br>
image, reload the page to generate a new one.)</em>
</p>
<p><asp:Label id=”MessageLabel” runat=”server”></asp:Label></p>
</form>

Note that the SRC attribute of the <IMG> tag points to the web form JpegImage.aspx.

The code-behind for Default.aspx simply generates a random text string for the image and validates that this text was entered by the user when the form is submitted.

The key is to store the text string in the Session object.

private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)

// Create a random code and store it in the Session object.

this.Session["CaptchaImageText"] = GenerateRandomCode();

else
{
// On a postback, check the user input.

if (this.CodeNumberTextBox.Text ==
this.Session["CaptchaImageText"].ToString())
{
// Display an informational message.

this.MessageLabel.CssClass = “info”;
this.MessageLabel.Text = “Correct!”;
}
else
{
// Display an error message.

this.MessageLabel.CssClass = “error”;
this.MessageLabel.Text = “ERROR: Incorrect, try again.”;

// Clear the input and create a new random code.

this.CodeNumberTextBox.Text = “”;
this.Session["CaptchaImageText"] = GenerateRandomCode();
}
}
}

The reason for storing the text string in the Session object is so that it can be accessed by JpegImage.aspx.

JpegImage.aspx

For this web form, no HTML is needed (what’s there is just the default code generated by Visual Studio when the file was created). Instead of HTML, the code will produce a JPEG image.In the code-behind, we first create a CaptchaImage object, using the text retrieved from the Session object. This creates a bitmap image for us.

private void Page_Load(object sender, System.EventArgs e)
{
// Create a CAPTCHA image using the text stored in the Session object.

CaptchaImage ci = new CaptchaImage(
this.Session["CaptchaImageText"].ToString(),
200, 50, “Century Schoolbook”);

// Change the response headers to output a JPEG image.

this.Response.Clear();
this.Response.ContentType = “image/jpeg”;

// Write the image to the response stream in JPEG format.

ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

// Dispose of the CAPTCHA image object.

ci.Dispose();
}

We then modify the HTTP response headers to set the Content-type to “image/jpeg” so the client browser will know we are sending an image.The last step is to retrieve the bitmap image from CaptchaImage.Image and write it to the HTTP response output stream in JPEG format. Fortunately, the Save() method of the Bitmap object makes this simple. Any other supported image format could be used as well so long as the Content-type header is set accordingly.

Posted in ASP.NET, C# 2.0 | Tagged: , , , | 5 Comments »