28 February 2011

ASP.NET 2.0 - Post Cache Substitution

Fragment Caching - where you cache a user control, so the entire page isn't cached, but the small portion of the page you wanted to be cached, is cached.
Well, Post-Cache Substitution is the exact opposite of that - the entire page is cached, except that little teenie weenie that you want to keep dynamic. It is implemented as the HttpResponse.WriteSubstitution method.
public void WriteSubstitution (HttpResponseSubstitutionCallback callback)
Per MSDN - "HttpResponse.WriteSubstitution allows insertion of response substitution blocks into the response, which allows dynamic generation of specified response regions for output cached responses",
... which in english means, when the ASP.NET page renders, your method which you passed in as the HttpResponseSubstitutionCallback delegate is called (callback?) to get the dynamic content, which is then inserted into the cached content and voilla - you got Post-Cache substitution. Cool eh? :)
Now here's the catch - the method that will sit inside HttpResponseSubstitutionCallback delegate instance, has to be either static or global or basically "instantiated and ready to eat". Why? Because ASP.NET will need to be able to call it without actually instantiating the page (i.e. when fetching from cache). The signature of HttpResponseSubstitutionCallback is quite straightforward -
public delegate string HttpResponseSubstitutionCallback (HttpContext context)
So a sample function could be -
public static string GetMyContent(HttpContext context)
{
   return " This blog rocks " ;
}
And how you'd hook it up inside your page is like this -
protected voide Page_Load(object sender, EventArgs e)
{
   Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetMyContent)) ;
}
But wait a minute - we're talking with the "Response" object - whatever happened to the fancy ASP.NET object model that we should have been using? Yeah I know it sucks, but for Post-Cache substitution, you hafta work with the Response object and not the object model. One explanation of this implementation could be - You don't really have the object model without instantiation the page (i.e. when fetching it out of the cache) - heh :) that makes sense.
But you could always wrap the substitutable content inside your own control, or heck ASP.NET 2.0 even comes with a generic substitution control that looks like this -
WOOHOO !! :) - now that's more elegant and now you don't need that programmatic Page_Load hookup either. 

27 February 2011

@@ERROR

It Returns the error number for the last Transact-SQL statement executed.

When Microsoft® SQL Server™ completes the execution of a Transact-SQL statement,

  • @@ERROR is set to 0 if the statement executed successfully.
  • If an error occurs, an error message is returned. @@ERROR returns the number of the error message until another Transact-SQL statement is executed.

You can view the text associated with an @@ERROR error number in the sysmessages system table.

As this variable is cleared and rest after each statement execution we are supposed to check it immediately following the statement being validated or just save it to a local variable that can be checked later.

 

Error Code

Description

0-10

It is Informational messages not actual error, actually 0 means No Error, No Information, before invoke the Programs, DB Engine converts to 0 then start performing operations

11-16

Error can be corrected by user, this may be syntax error

11

Object Doesn't Exists

12

Don't allow to do lock on Any Object

13

Transaction Dead Lock Errors

14

Security related Error, access denied

15

Syntax Error

16

General Error like invalid arguments, string value not quoted properly etc.,

17-19

Software Error, not corrected by User

17

Out of memory exception, disk usage, lock, write protected, no access to resource etc.,

18

DB Engine related error

19

Non-Configurable limit exceeded with DB Engine

19-25

Note: 19-25 error will be updated in SQL Error Log

20-25

Fatal Error occurred based on single or batch process running currently

20

Problem with current Task only

21

problem affects all other process

22

Table or Index Damaged by software or hardware. It occurs rarely. Run DBCC CHECKDB to determine error

23

Problem with integrity of Database, corrupted

24

Need to restore database, database may be corrupted, may be hardware issue

25

System Error


Truncate Within A Transaction

In the previous post, we have seen, what is the difference between in “Truncate vs. Delete”?

Actually if we use truncate then we can’t rollback the data, but the question is … What will happen if we use truncate within a transaction, Whether we can rollback or not?.

The following example reveals the answer for our question.

I created a table and inserted a rows, as shown below

Then I executed the below Query:

It Returns:

Conclusion:
Truncated Data can be roll backed if it is executed within a transaction

23 February 2011

How To Process JSON With C# and JQuery

JavaScript Object Notation affectionately known as JSON is a wonderful way to deliver content to the browser in a lightweight method that can both save on bandwidth and reduce page weight.

Following example contain 3 sections
1.Call a Asp.net server method using using jQuery
2.Return the Employees as a JSON data.
3.Display the Data in a standard HTML table.

Steps

1.Make a Class Employee

   1: public class ClsEmployee
   2: {    
   3:     public string PropPubStrFirstName
   4:     {    get;    set;    }
   5:  
   6:     public string PropPubStrLastName
   7:     {    get;    set;    }
   8:  
   9:     public string PropPubStrMiddleName
  10:     {    get;    set;    }
  11:  
  12:     public Employee(string StrPriFirstName, string StrPriMiddleName, string StrPriLastName)
  13:     {
  14:         PropPubStrFirstName= StrPriFirstName
  15:         PropPubStrMiddleName= StrPriMiddleName
  16:         PropPubStrLastName= StrPriLastName
  17:     }
  18: }    

2.Now create a web method in your code behind file as



   1:  
   2: [WebMethod]
   3: public static List GetEmployees()
   4: {
   5:     const string query = "SELECT [FirstName], [MiddleName], [LastName] FROM TblEmployee";
   6:     DataTable dt = BuildDataTable(query);
   7:     List empList = null;
   8:  
   9:     if (dt != null)
  10:     {
  11:         empList = new List();
  12:  
  13:         for (int i = 0; i < dt.Rows.Count; i++)
  14:         {
  15:         empList.Add(new Employee(dt.Rows[i]["FirstName"].ToString(),
  16:         dt.Rows[i]["MiddleName"].ToString(),
  17:         dt.Rows[i]["LastName"].ToString()));
  18:         }
  19:     }
  20:  
  21:     return empList;
  22: }
  23:  
  24:  
  25: public static DataTable BuildDataTable(string query)
  26: {
  27:     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionstring"].ConnectionString);
  28:     SqlDataAdapter ada = new SqlDataAdapter(query, con);
  29:     DataTable dt = new DataTable();
  30:     ada.Fill(dt);
  31:     return dt;
  32: }

3.Write a jQuery Function to get and show the data in a table.



   1: <script type="text/javascript">// <![CDATA[
   2: $(document).ready
   3: (
   4:     function() 
   5:     {
   6:         $.ajax
   7:         (
   8:             {
   9:                 type: "POST",
  10:                 url: "Default.aspx/GetTopTenEmployees",
  11:                 contentType: "application/json; charset=utf-8",
  12:                 dataType: "json",
  13:                 success: function(msg) 
  14:                 {
  15:                     BuildTable(msg.d);
  16:                 }
  17:             }
  18:         );
  19:     }
  20: );
  21:  
  22: function BuildTable(msg) 
  23: {
  24:     var table = '
  25:     <table>
  26:     <thead>
  27:     <tr>
  28:     <th>First Name</th>
  29:     <th>Middle Name</th>
  30:     <th>Last Name</th>
  31:     </thead>
  32:     <tbody>';
  33:     for (var i = 0, l = msg.length; i < l; i++)
  34:     {
  35:         var person = msg[i];
  36:         var row = '
  37:         <tr>';
  38:         row += '
  39:         <td>' + person.FirstName + '</td>';
  40:         row += '
  41:         <td>' + person.MiddleName + '</td>';
  42:         row += '<td>' + person.LastName + '</td>';
  43:         row += '</tr>';
  44:         table += row;
  45:     }
  46:     table += '</tbody></table>';
  47:     $('#Container').html(table);
  48: }
  49: </script>
  50: <div id="Container">

You can use HTTP Snipper to see the contents being returned..It will be as follows


{"d":[{"__type":"Employee","FirstName":"Gustavo","LastName":"Achong","MiddleName":""},{"__type":"Employee","FirstName":"Catherine","LastName":"Abel","MiddleName":"R."},{"__type":"Employee","FirstName":"Kim","LastName":"Abercrombie","MiddleName":""},{"__type":"Employee","FirstName":"Humberto","LastName":"Acevedo","MiddleName":""},{"__type":"Employee","FirstName":"Pilar","LastName":"Ackerman","MiddleName":""},{"__type":"Employee","FirstName":"Frances","LastName":"Adams","MiddleName":"B."},{"__type":"Employee","FirstName":"Margaret","LastName":"Smith","MiddleName":"J."},{"__type":"Employee","FirstName":"Carla","LastName":"Adams","MiddleName":"J."},{"__type":"Employee","FirstName":"Jay","LastName":"Adams","MiddleName":""},{"__type":"Employee","FirstName":"Ronald","LastName":"Adina","MiddleName":"L."}]}


As you can see we have the type of the Employee object along with the properties and values


Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...