Thursday, April 24, 2008

Referencing Namespace from Web.Config

Instead of making the code in .cs file complex you can also add all your name space in web.config. Harry Potter The name space referenced from web.config file will be available to all cs or vb files in the project. Every time writing the same name space again and again increases the LOC.


<configuration>
<system.web>
<pages>
<namespaces>
<add namespace=”System.Net.Mail”/>
</namespaces>
</pages>
</system.web>
</configuration>

Monday, April 14, 2008

Writing CLS comliant code

Hi Guys,

I know some of us guys think that the code we are writing is CLS compliant by default but actually it is not. For writing CLS compliant code we have to explicitly declare CLSAttribute="true"

Wednesday, April 9, 2008

Where Vs Having / Difference between having and Where clause

We always get confused between WHERE and Having clause and make mistakes. Here in this article, I will try to highlight all the major differences between WHERE and HAVING, and things you should be aware of, when using either WHERE or HAVING.

------------------------------------------------------------------------------

Most of the time you will get the same result with Where or Having . The below given two SQL command produces the same result set That is, both count the number of records found for the states of California and Los Angles.

SELECT state, COUNT(*)
FROM Test
WHERE state IN ('CA', 'LA')
GROUP BY state
ORDER BY state

SELECT state, COUNT(*)
FROM Test
GROUP BY state
HAVING state IN ('CA', 'LA')
ORDER BY state


So, where is the difference ,Which is better? I'll let you answer those questions in a minute.

The main reason for using WHERE clause is to select rows that are to be included in the query. For example, assume table Test.Suppose I want the names, account numbers, and balance due of all customers from California and Los Angles. Since STATE is one of the fields in the record format, I can use WHERE to select those customers.


SELECT cusnum, lstnam, init
FROM Test
WHERE state IN ('CA', 'LA')

CUSNUM LSTNAM INIT BALDUE
====== ============ ==== ========
938472 John G K 37.00
938485 Mark J A 3987.50
593029 Lily E D 25.00


Suppose I want the total amount due from customers by state. In that case, I would need to use the GROUP BY clause to build an aggregate query.

SELECT state,SUM(baldue)
FROM Test
GROUP by state
ORDER BY state

State Sum(Baldue)
===== ===========
CA 250.00
CO 58.75
GA 3987.50
MN 510.00
NY 589.50
TX 62.00
VT 439.00
WY .00



Suppose I want the same information, but I don't care about states where nobody owes me any money. Since the total owed by state is an aggregate figure, i.e., the figure is generated from a group of records, you must use HAVING to select the proper data.

SELECT state,SUM(baldue)
FROM Test
GROUP by state
HAVING SUM(baldue) > 0
ORDER BY state

State Sum(Baldue)
===== ===========
CA 250.00
CO 58.75
GA 3987.50
MN 510.00
NY 589.50
TX 62.00
VT 439.00



Here's the rule. If a condition refers to an aggregate function, put that condition in the HAVING clause. Otherwise, use the WHERE clause.

Here's another rule: You can't use HAVING unless you also use GROUP BY.

Now, go back to the first example, where WHERE and HAVING produce the same result set. What's the difference? The first query uses the WHERE clause to restrict the number of rows that the computer has to sum up. But the second query sums up all the rows in the table, then uses HAVING to discard the sums it calculated for all states except Texas and Georgia. The first query is obviously the better one, because there is no need to make the computer calculate sums and then throw them away.

I mentioned a tip that some of the more experienced readers may not have seen. Some queries combine aggregate processing with non-aggregate processing. In a classic example, one table contains individual sales, while another contains a quota for a sales rep. The first table contains more than one record per rep, and those records must be summarized in order to get an aggregate total, which is then compared to the sole quota record for a rep. How do we find the reps who have not met their quotas?

Like this:

SELECT rep, SUM(amount)
FROM sales AS a
GROUP by rep
HAVING SUM(a.amount) >=
(SELECT quota
FROM Test AS b
WHERE b.rep = a.rep)
ORDER BY rep

The first SELECT sums the individual sales by rep. Each rep's sum is compared to one record from the Test table, in order to determine if the aggregate sum is at least as much as the quota. As before, it's necessary to put the aggregate function (SUM) in the HAVING clause.

If these are the sales:

Rep Amount
=== ======
1 20
1 30
2 40
3 30
3 20

And these are the quotas:

Rep Quota
=== =====
1 70
2 30
3 40

This is the result:

Rep SUM(Sales)
=== ==========
2 40
3 50

Your comments are always welcome


kick it on DotNetKicks.com

Tuesday, April 8, 2008

Limit postbacks with ASP.NET client callbacks

Disconnected

Over the years, there have been various solutions that circumvent the stateless limitation of Web applications, with the focus on reducing the number of page calls or reloads to avoid hampering the user experience. For example, many developers used hidden frames to serve as data sources so data could easily be sent to or retrieved from the hidden frame page. Also, some developers chose to load everything with the initial load, so subsequent page loads are reduced.

The problem arises when it is absolutely necessary to make a server call. This is where the AJAX group of technologies enters the picture. AJAX utilizes the XMLHTTP object, along with XML and client side scripting (aka JavaScript) to handle asynchronous server calls.


ASP.NET model

The default behavior of an ASP.NET page begins when the page is requested by a user and loaded in the requesting client. The user interacts with the page via various actions like clicking a button. These actions may trigger a call to the server called a postback (i.e., the page is posted back to the host with a new version of the page reloaded as a result of the action).

Page postbacks come with a price. For example, client state may be lost, and communicating with the server interrupts the user experience as they wait during communication and page reload. AJAX methodologies address these issues by facilitating asynchronous communication with a server while the user experience is not interrupted. A similar approach may be implemented in ASP.NET 2.0 through the use of the ICallbackEventHandler interface.

Implementing a callback


A callback is a function associated with a specific user interface component. The callback performs a certain action in response to a component event. The event can be any one of the many available mouse clicks or any other event.

Implementing callbacks in an ASP.NET 2.0 page has a few differences from standard Web pages. The following list outlines the necessary changes to the page code:

The page must implement the ICallbackEventHandler interface.
The RaiseCallbackEvent method of the ICallbackEventHandler interface must be implemented by the page. This method is invoked to perform the callback on the server.
The page must implement the GetCallbackResult method of the ICallbackEventHandler interface. This method will return the callback result to the client.
With these code changes in place, the callback may be utilized on the client side of the page (HTML source). The Web page must include client-side functions to perform the actual server request along with receiving the results from the server request.

The C# page in the following code listing provides a demonstration of implementing a callback.

<%@ Page Language="C#" %>
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

ASP.NET Callback







Test

A few notes on the code:

The page’s Page_Load event sets a reference to the callback function (GetData) via the GetCallbackEventReference method available in the page’s ClientScript property. The method accepts these parameters: a reference to the page; the name of the argument by which the data are passed; the name of the client script function that receives the callback data; and an argument that passes any context you want. In this example, the context isn’t used.

The function that will be used to call the server is created (callbackScript variable in the example) with the function reference included. Also, the arguments that are accepted by the generated function must match the names passed to the GetCallbackEventReference method. Finally, the callback script is registered on the page via the RegisterClientScriptBlock method of the Page object’s ClientScript property.

The GetCallbackResult method provides the output (string) returned by the callback. In this example, the current date and time (on the server) is returned.

The client function that receives callbacks is loaded in the header portion of the page (GetData in the example). The function must be named to match the name passed in the call to the GetCallbackEventReference method. The function accepts two string values for the return value and an optional second value for the context value that is passed back from the server.
The button on the page is tied to the callback function. In this example, the HTML span object receives the callback result.

A smooth user experience

Avoiding page reloads simplifies the user experience and can reduce the amount of data sent back and forth between the client and server. You can use the AJAX approach to provide this functionality; you can also use ASP.NET 2.0’s callback support. The applications for these techniques are endless, and anything that improves the user experience is good for business.

I hope you liked this article..if yes please drop some comments

kick it on DotNetKicks.com

Monday, April 7, 2008

Top 10 new features in SQL Server 2005

1. T-SQL (Transaction SQL) enhancements

T-SQL is the native set-based RDBMS programming language offering high-performance data access. It now incorporates many new features including error handling via the TRY and CATCH paradigm, Common Table Expressions (CTEs), which return a record set in a statement, and the ability to shift columns to rows and vice versa with the PIVOT and UNPIVOT commands.

More information from Microsoft.



2. CLR (Common Language Runtime)
The next major enhancement in SQL Server 2005 is the integration of a .NET compliant language such as C#, ASP.NET or VB.NET to build objects (stored procedures, triggers, functions, etc.). This enables you to execute .NET code in the DBMS to take advantage of the .NET functionality. It is expected to replace extended stored procedures in the SQL Server 2000 environment as well as expand the traditional relational engine capabilities.


More information from Microsoft.



3. Service Broker
The Service Broker handles messaging between a sender and receiver in a loosely coupled manner. A message is sent, processed and responded to, completing the transaction. This greatly expands the capabilities of data-driven applications to meet workflow or custom business needs.


More information from Microsoft.



4. Data encryption
SQL Server 2000 had no documented or publicly supported functions to encrypt data in a table natively. Organizations had to rely on third-party products to address this need. SQL Server 2005 has native capabilities to support encryption of data stored in user-defined databases.


More information from Microsoft.


5. SMTP mail
Sending mail directly from SQL Server 2000 is possible, but challenging. With SQL Server 2005, Microsoft incorporates SMTP mail to improve the native mail capabilities. Say "see-ya" to Outlook on SQL Server!


More information from Microsoft.


6. HTTP endpoints
You can easily create HTTP endpoints via a simple T-SQL statement exposing an object that can be accessed over the Internet. This allows a simple object to be called across the Internet for the needed data.



More information from Microsoft.


7. Multiple Active Result Sets (MARS)
MARS allow a persistent database connection from a single client to have more than one active request per connection. This should be a major performance improvement, allowing developers to give users new capabilities when working with SQL Server. For example, it allows multiple searches, or a search and data entry. The bottom line is that one client connection can have multiple active processes simultaneously.


More information from Microsoft.
.


8. Dedicated administrator connection
If all else fails, stop the SQL Server service or push the power button. That mentality is finished with the dedicated administrator connection. This functionality will allow a DBA to make a single diagnostic connection to SQL Server even if the server is having an issue.



More information from Microsoft.


9. SQL Server Integration Services (SSIS)
SSIS has replaced DTS (Data Transformation Services) as the primary ETL (Extraction, Transformation and Loading) tool and ships with SQL Server free of charge. This tool, completely rewritten since SQL Server 2000, now has a great deal of flexibility to address complex data movement.



More information from Microsoft.


10. Database mirroring
It's not expected to be released with SQL Server 2005 at the RTM in November, but I think this feature has great potential. Database mirroring is an extension of the native high-availability capabilities. So, stay tuned for more details…. For now, here's



More information from Microsoft.






I hope you liked this article..if yes please drop some comments

kick it on DotNetKicks.com

Friday, April 4, 2008

Ajax Update Panel

In this article, I am going to explain how we can auto refresh data on an ASP.NET page after a certain interval using AJAX UpdatePanel and other controls (assuming you have some basic knowledge of AJAX Toolkit). I am using some Ajax controls and using SQL server database and Data Grid control. Lets for the time, use database north wind and set our interval time for refreshing data as 30 seconds.




Code behind page :

public void BindData()
{
con = new SqlConnection("Initial Catalog=Northwind; Data Source=localhost; Uid=sa; pwd=;");
cmd.CommandText = "select * from Employees ";
cmd.Connection = con;
con.Open();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
cmd.ExecuteNonQuery();
GridData.DataSource = ds;
GridData.DataBind();
}


protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = "Grid Refreshed at: " + DateTime.Now.ToLongTimeString();
}



Here is HTML desing code:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="30000">
</asp:Timer>
</div>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Grid not refreshed yet."></asp:Label><br />
<asp:Label ID="Label4" runat="server" Text="(Grid Will Referesh after Every 30 Sec)" Font-Bold="true"></asp:Label> 
<br /><br />
<asp:DataGrid ID=GridData runat="server" Width="100%" GridLines="Both" HeaderStyle-BackColor="#999999" AutoGenerateColumns="false">
<Columns>
<asp:BoundColumn DataField="EmployeeID" HeaderText="Employee ID"></asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="First Name"></asp:BoundColumn>
<asp:BoundColumn DataField="LastName" HeaderText="Last Name"></asp:BoundColumn>
<asp:BoundColumn DataField="City" HeaderText="City"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
</ContentTemplate>
</asp:UpdatePanel>
</form>


I hope you liked this article..if yes please drop some comments

kick it on DotNetKicks.com