Archive for March 11th, 2008

Data Caching in ASP.NET

Tuesday, March 11th, 2008

Caching enables you to store the expensive data into Cache object and later retrieve it without doing expensive operations. Data Caching can tremendously increase performance since each time the data is requested you can turn to the Cache object rather than going to the database and fetching the result.

You all must be familiar with datagrid paging where you can display certain number of records in the datagrid control and use the numeric or next-previous buttons to view the other records. All the records are fetched for each and every page in the datagrid. Meaning that if you have 40000 records in the database and you are using paging. Each time you click to go to the next page you retrieve 40000 records. This is way too much performance kill. That’s why for this task we can use Data Caching, let’s see how we can use data caching to make our application more efficient.

Example:

Example:
private void Button3_Click(object sender, System.EventArgs e)
{
if(Cache[”MyArticles”] == null)
{

Posted by Mahesh ( Tryangled )

Calling a Stored Procedure from ASP.NET 2.0

Tuesday, March 11th, 2008

added a parameter to the SQL command object providing the name of the parameter and also the data type and size. After the parameter is added, the value needs to be specified.
open the connection, execute the stored procedure (automatically passing the parameters defined), and close the connection.

Protected Sub Btn1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Btn1.Click
Dim sConnStr As String = {MyConnectionString}
Dim cnBKTest As New SqlConnection(sConnStr)
Dim cmdTest As New SqlCommand(”Insert_Test”, cnBKTest)
cmdTest.CommandType = Data.CommandType.StoredProcedure
cmdTest.Parameters.Add(New SqlParameter(”@TestParam”, Data.SqlDbType.VarChar, 10))
cmdTest.Parameters(”@TestParam”).Value = “Testing”
cnBKTest.Open()
cmdTest.ExecuteNonQuery()
cnBKTest.Close()
End Sub

Posted by Mahesh ( Tryangled )

What is HTTP Handler?

Tuesday, March 11th, 2008

HttpHandlers are the earliest possible point where we have access to the requests made to the web server (IIS). When a request is made to the web server for an ASP.NET resource (.aspx, .asmx, etc.), the worker process of the ASP.NET creates the right HttpHandler for the request which responds to the request. The default handlers for each request type that ASP.NET handles are set in the machine.config file.

Creating an HttpHandler
To create an HttpHandler, we need to implement the IHttpHandler interface. The IHttpHandler contains one property and one method.

IHttpHandler interface
public interface IHttpHandler
{
bool IsReusable { get; }
void ProcessRequest(HttpContext context);
}

The property IsReusable specifies whether the ASP.NET should reuse the same instance of the HttpHandler for multiple requests.
The ProcessRequest () method is where you actually implement the logic to handle the request.
After you create the HttpHandler, you have to map a path to the handler in the web.config
web.config setting for httpHandler

<configuration>
<system.web>

<httpHandlers>
<add verb=”*” path=”gettryimage.img” type=”Sample.ImageHandler, Sample” />
</httpHandlers>
</configuration>

Posted by Mahesh ( Tryangled )

Searching Index Server With ASP

Tuesday, March 11th, 2008

using Index Server from within ASP. It assumes you have access to a web server running Internet Information Server 4.0 on Windows NT Server.
1.Creating a search form
The first thing to do is to create a page containing a form in which the user can enter their search word or phrase. You can of course have a combined search form page and search results page, but I prefer to keep them separate.
2.Creating a search results page
The following code can be used for a basic search results page. It should be saved as SearchResults.asp.

The first part of the search results page initialises variables and constants:
<%
Dim sSearchString
Dim oQuery

sSearchString = Request.Form(”query”)

Const SEARCH_CATALOG = “catalog_name”
%>
The search string was posted from the SearchForm.asp search form page, and the word or phrase to be searched for are extracted from the query item in the Request.Form collection.
The SEARCH_CATALOG constant is also defined.This name will vary so you will have to change it. If your site is hosted with a hosting company then they will usually set up a catalog on the Index Server for you, then let you know the name of your search catalog. If you are using your own web server, then you should be able to determine the catalog name from the Index Server Management Console

The next part of the search results page initialises the Index Server Query COM component which enables the search to be performed:

<%
Set oQuery = Server.CreateObject(”IXSSO.Query”)

oQuery.Catalog = SEARCH_CATALOG
oQuery.Query = “@all ” & sSearchString & _
” AND NOT #path *_* AND NOT #path *downloads* ” & _
” AND NOT #path *images* AND NOT #filename *.class ” & _
“AND NOT #filename *.asa AND NOT #filename *.css AND NOT #filename *postinfo.html”
oQuery.MaxRecords = 200
oQuery.SortBy = “rank[d]”
oQuery.Columns = “DocAuthor, vpath, doctitle, FileName, Path, ” & _
“Write, Size, Rank, Create, Characterization, DocCategory”
Set oRS = oQuery.CreateRecordSet(”nonsequential”)
%>
Catalog: The name of the search catalog to be searched.
Query:   The query to be made. Note that the query in this example is comprised of the search string, plus a list of file and folder exclusions.
MaxRecords: This property specifies the maximum number of search results that should be returned.
SortBy: This specifies which column name the search results should sorted by. The usual setting for this is rank[d], i.e. sort results in descending order according to their          similarilty to the search string.
Columns: A list of column properties that should be returned in the search results.

Finally, an ADO RecordSet is created from the records found for this search.

<%
If oRS.EOF Then
Response.Write “No pages were found for the query ” & sSearchString & “”
Else
Do While Not oRS.EOF
Response.write “FileName: ” & oRS(”FileName”) & ”

Response.write “doctitle: ” & oRS(”doctitle”) & ”

Response.write “Size: ” & oRS(”Size”) & ”

Response.write “Create: ” & oRS(”Create”) & ”

Response.write “Write: ” & oRS(”Write”) & ”

Response.write “Characterization: ” & oRS(”Characterization”) & “”
oRS.MoveNext
Loop
End If
%>

Posted by Mahesh ( Tryangled )

Differences between Web Service and Remoting?

Tuesday, March 11th, 2008

ASP.NET Web Services and .NET Remoting are two separate paradigms for building distributed applications using Internet-friendly protocols and the .NET framework.

1. Web Services typically use SOAP for the message format.  This makes Web Services good for communication over the Internet and for communication between non-Windows systems.Remoting can be configured to use either SOAP or Microsoft’s proprietary binary protocol for communication.

2. In .NET’s Remoting technology we require the Server and the Client both to be of the same technology; in other words, they should both be .NET applications and require the .NET framework to be running in both of these environments.

Posted by Mahesh ( Tryangled )

How to Build a Web Service in ASP.NET?

Tuesday, March 11th, 2008

Building a Web Service with Visual Studio.Net involves creating a new Web Services project and adding methods and properties to a Web Services class form (i.e. an .asmx file).  This section builds a Web Service with Visual Studio.Net.  Followings are the steps in short to create an .asmx file.

1.      Start Visual Studio .NET
2.      Select New Project
3.      Select Visual C# Project as Project Type and Asp.Net Web Service as Template

A solution will be generated.  In solution explorer there will be an asmx file.
The following code we should write in .asmx file as specified in Listing 4.
Listing 4

[WebMethod]
public string Add(int a, int b)
{
return Convert.ToString(a + b);
}

[WebMethod]
public DataSet Populate(string con, string sql)
{
DataSet DS=new DataSet();
SqlConnection conn=new SqlConnection(con);
SqlDataAdapter DA=new SqlDataAdapter(sql, conn);
DA.Fill(DS);
return DS;
}

In the above code there are two methods in Web Service.  These methods are known as the WebMethods.  The Add WebMethod returns the sum of two integer value as string.  Populate web method takes two string type arguments, one for connection string and the other for sql query, and returns a DataSet object.

Posted by Mahesh ( Tryangled )

Web Service Attribute

Tuesday, March 11th, 2008

The Web Service Attribute is a member of the System.Web.Services namespace.  This we can use to let the clients know where to find information about a Web Service.  There are three properties of the Web Service attribute.  They are as follows:
1.      Description
2.      Namespace
3.      Name

Description
The Description property is used to provide a brief description of the functionality of the class.  We can write the same as specified in Listing 2.
Listing 2

[WebService(Description=”This class contains methods for working with Addition of numbers and Population of DataSet”)]

Namespace

The Namespace property sets the XML namespace for the service.  Generally we use an URL.  It does not have to be an actual URL; it can be any string value.  The idea is that it should be unique.  It is common practice to use URL because a URL is always unique.

Name
When the WSDL is generated for an ASP.NET Web Service, the name of the class is used for the service name within the WSDL.  When a proxy uses the WSDL and builds a proxy class, the name of the class generated corresponds to the name value of service.  This property allows overriding the default value.

Posted by Mahesh ( Tryangled )

How to loop through a DataTable?

Tuesday, March 11th, 2008

The following example tells you how to loop through a DataTable. We can relate the DataTable to the RecordSet in Classic ASP (Active Server Pages).
Dim adapter As SqlDataAdapter
Dim ds As DataSet
Dim ctr As Integer
Try
adapter = New SqlDataAdapter(”YourSQLStatement”, “YourConnectionString”)
ds = New DataSet()
adapter.Fill(ds, “myTable”)
If ds.Tables(0).Rows.Count > 0 Then
For ctr = 0 To ds.Tables(”entries”).Rows.Count - 1
Response.Write(ds.Tables(0).Rows(ctr).Item(”ColumnName”))
Next
End If
Catch exc As SqlException
Response.Write(”SQL Error Occured: ” & exc.ToString)
Catch exc As Exception
Response.Write(”Error Occured: ” & exc.ToString)
Finally
adapter = Nothing
ds = Nothing
End Try

Posted by Mahesh ( Tryangled )