Tuesday, October 26, 2010

Output Caching in asp.net

Recently one of my friend ask about output cache so I decided to put a post about how output cache works and what is the advantages and disadvantage of using output cache. Output cache is a technique to cache generated response from the asp.net pages or controls. Output Caching increases the performance drastically by reducing server round trips. We can use @OutputCache directive to controls output caching for a page or controls.

The @OutputCache includes following attributes.

  • Duration: This attribute will explain how long output cache will be there for a page or control. It can be set in seconds. If you set 60 then it will not going to generate response from server until 60 second It will generate response from the cache it self. Here is example of duration where it will set 60 second for page.
  • <%@ OutputCache Duration="60" %>  

  • VaryByParam: This attribute will determine cache entries based on get or post parameters. It will vary cache based on get or post parameters suppose you set product Id query string as VaryByParam it will create a different cache based on product Id. Following is a example how you can set the VaryByParam based on Product Id.
  • <%@ OutputCache Duration="Seconds" VaryByParam="ProductId"%>
    

  • Location: This attribute will specify where the Item will be cached. Here are options available for that.
    • Any: The output cache can be located at any browser from where request is generated or Server where request is processed or Proxy server participating in request.
    • Client: The output cache will be located on browser client from where request is generated.
    • Downstream: The output cache can be stored in any HTTP 1.1 cache-capable devices other than the origin server. This includes proxy servers and the client that made the request.
    • Server: The output cache will stored in the server where generated request will be processed.
    • ServerAndClient: The output cache will generated either on Browser where request generated or on server where generated request will be processed. Proxy servers are not allowed for this.
    • None: None specifies that output cache will be disabled for this controls or Page.
Here is example of location.

      <%@ outputcache duration="10"  Location="Server" %>
      

  • VaryByCustom: This attribute is for different browsers where request is generated this means it will generate new instance of cache based on different browser versions.
  • <%@ OutputCache Duration="Seconds" VaryByCustom="Browser" %>
  • VaryByHeader: This attribute allows to determine different instances of cache based on the headers. Here is example for it.
  • <%@ OutputCache VaryByHeader="Accept-Language" %>
    
Note: If you specify the output cache it will not fire server side events like click or selected index changed etc. So make sure the controls that you used in output cache will not have this kind of controls Or you have to handle this in other scenarios.

Hope this will help you.. Happy programming!!

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:

Difference between sliding expiration and absolute expiration

ASP.net cache is great feature through which we can increase the performance of the our web application via reducing server round trips to database. We can cache any serializable data into the cache. There are so many ways to cache data but one of the simplest way to cache data like insert data into cache object. Here we must need to validate cache if any data is changed and there are so many ways from where we can set dependency to validate the cache like files,SQL Cache Dependency etc. We also can validate cache or expire via setting time to duration to its object. Like after the defined time our cache will expire and then it will again put new fresh data into the cache. This is called as time base expiration. We can put this kind of expiration via two way.

  1. Absolute Expiration
  2. Sliding Expiration

Absolute Expiration: Absolute expiration means It will expire cache after some time period set at the time of activating cache. This will be absolute expiration whether cache will be used or not It will expire the cache. This type of expiration used to cache data which are not frequently changing.

Sliding Expiration: Sliding expiration means It will expire cache after time period at the time of activating cache if any request is not made during this time period. This type of expiration is useful when there are so many data to cache. So It will put those items in the cache which are frequently used in the application. So it will not going to use unnecessary memory.

Here is the example how we can set the sliding expiration and absolute expiration.

string cacheData = "The data to be cached";
//Absolute Expiration
Cache.Insert("AbsoluteCacheKey", cacheData, null,
DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
//Sliding Expiration
Cache.Insert("SlidingExpiration", cacheData, null,
System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1));
In above example I have created the a string to be cache that can be any serialized data. In the absolute expiration you can see that it will expires after one minute whether its accessed or not. While in sliding expiration it will expire cache if cache is not accessed within specified time.

Hope this will help you for better understanding of asp.net caching technique. Happy programming!!!

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:
Sunday, August 29, 2010

LinqDatasource A Great Control for declarative programming

I have used data source control many times and its great it provides us great features for declarative binding. LinqDataSource Control is a great control and it allows us to bind linq queries without writing any code declaratively. Let’s create a example in that example I am not going to write a single line of code and we are going to create view,Update and Delete functionality.

So first we need a table which will have data. So, I am going to use the same table which I have used in my old posts. Below is the table structure for this example.

Table Structure of Linq Data Source Example

Let’s insert some data for that table structure. I have already inserted it in previous example. Just like below.

Table data for linq to SQL Linq Data source example

Now, To bind a linqdatasource we need a Linq-To-SQL Data context class Let’s create it via Project->Right Click->Add New Item –>Go to data tab->Linq-To-SQL classes Just like following.

Add new Linq-To-SQL Classes

After that I have just dragged user data to my data context just like following.

Dragging Table to Linq-to-SQL classes

After creating Our Linq-To-SQL Classes Let’s just Add the A grid View control to my default.aspx page and apply some default format like this.

Adding a GridView from ToolBox and applying format

Now Let’s add a LinqDataSource from the toolbox like following.

Creating A Linq Data Source from ToolBox

Now select the data source and click configure data source as we can see as below.

Configuring Linq Data Source

After clicking on the Configure Data source a wizard will appear which will allow us to select Linq-to-SQL Context class just like following.

Select Linq-To-SQL Class for Linq Data Source

After clicking on next it will allow us to select the Linq-To-SQL Table. In our case it is a Users table so select user table just like following and select * for all columns.

Selecting Linq-To-SQL Table

Click finish now our Linq Data Source is Ready Now select the grid view and select Linq Data source we just created like below.

Setting up Grid view data source as linq datasource

Now our grid view is ready We just need to select Enable Sorting and Enable Paging to give default sorting and paging functionality to grid view. Now do to aspx file and you will see that grid view control is created. I have set two more properties AutoGenerateDeleteButton and AutoGenerateEditButton property of grid view to true as we need to create update and delete functionality also. Just like below.

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="LinqDataSource1"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
DataKeyNames="UserId" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId"
SortExpression="UserId" ReadOnly="True" />
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True"
ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
Then go to Linq Data source and set EnableDelete and EnableUpdate property to true as we need this functionality. Just like following.

<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="Blog.MyBlogDataContext"
EntityTypeName="" TableName="Users"
EnableDelete="True" EnableUpdate="True">
</asp:LinqDataSource>
That’s it now everything is ready lets run the example and see how its works here is the update example and its working fine as should.

Ouput Of Linq Data Source Control

So It’s very easy to create this kind of functionality. Hope this help you.. Happy Programming..

Shout it
kick it on DotNetKicks.com
Share:

Calling an asp.net web service from jQuery

As I have post it in earlier post that jQuery is one of most popular JavaScript library in the world amongst web developers Lets take a example calling ASP.NET web service with jQuery . You will see at the end of the example that how easy it is to call a web service from the jQuery.

Let’s create a simple Hello World web service. Go to your project right click->Add –> New Item and select web service and add a web service like following.
Adding  a webservice
Now modify the code of web service like following.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script,
using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class HelloWorld : System.Web.Services.WebService
{
[WebMethod]
public string PrintMessage()
{
return "Hello World..This is from webservice";
}
}

Here please make sure that [System.Web.Script.Services.ScriptService] is un commented because this attribute is responsible for allowing web service to be called by Client side scripts.

Now to call this web service from jquery we have to include jQuery Js like following. I am already having in my project so i don’t need to include in project just need to add script tag like following.

<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js">
</script>

Now let’s add some JavaScript code to call web service methods like following.

<script language="javascript" type="text/javascript">
function CallWebServiceFromJquery() {

$.ajax({
type: "POST",
url: "HelloWorld.asmx/PrintMessage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
});

}

function OnSuccess(data, status)
{
alert(data.d);
}

function OnError(request, status, error)
{
alert(request.statusText);
}
</script>

Here I have written three functions in JavaScript First one is CallWebserviceFromJquery which will call the web service. The another two functions are delegates of webservice if Success is there then onSuccess Method will be called and If Error is there then OnError method will be called.

Inside the CallWebserviceFromJquery I have passed some parameter which will call web service with Ajax capabilities of $ jQuery object. Here are the description for each parameter.

Type: This can be GET or POST for web service we have to take POST as by default web service does not work with GET to prevent Cross site requests.

Url: Here will be url of the webservice. You have insert fully qualified web service name here.

Data:Here it will be Empty as we not calling web service with parameters if you are calling web service with parameter then you have to pass that here.

ContentType: here you have to specify what type of content is going to return by web service.

Datatype:Json it will be result type.

Sucess:Here I have called the OnSuccess when the call is complete successfully. If you check the OnSuccess method you will see that I have set the returned result from the web service to the label. In the OnSuccess method body you see ‘data.d’. The ‘d’ here is the short form of data.

Error: Same as I have done with OnSuccess. If any error occurred while retrieving the data then the OnError method is invoked.

Now let’s add a asp.net button for on client click we will call the javascript function like following.

<asp:Button ID="btnCallWebService" runat="server"
OnClientClick="CallWebServiceFromJquery()"
Text="Call Webservice"/>

Now Let’s run it and here is the output in browser.

Ouput
Hope this will help you!!!.. Happy programming..

Share:
Friday, August 27, 2010

jQuery- JavaScript Library Write less do more

This is introductory post jQuery an open source JavaScript library. I know what you guys thinking and I also know that jQuery does not required introduction. It is so much popular and most of web developers whether they are developing using asp.net,php,Jsp or any language on web they are using jQuery but this post is for who is not aware of it and or they are new to the web based programming.

We all are using JavaScript for client side scripting language almost 95% percentage of web application uses JavaScript as client script. We do lots of things with JavaScript right from the alerts to validation of controls to animation and now days we calling web services from JavaScript and fetching server side data also and rendering them into browser. If you are using JavaScript then you are following some patterns like selecting a element on and then perform some operation on that element on client side like do validation of controls or changing the style sheet of that element or animating them etc. jQuery help you doing this in rather simpler way so you can save lots of time doing other things instead of writing long complex JavaScript.

Why jQuery?

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. jQuery provides lots of functionality like animating elements,Ajax interaction with server sides web service, changing CSS of a Elements etc and you can complete those task in minimum line of the code. For example let’s see the code which are given Homepage of jQuery website.

$("p.neat").addClass("ohmy").show("slow");
Above code kind enough to animate a particular Div in Animating way. If you write this kind of code in normal JavaScript then it will take much time and dozens of line of code. Here you can do simply that in one line of code. So, I would highly recommend every web developers to use jQuery instead of regular JavaScript.

Use Full Links For jQuery

If you want to learn jQuery then following are links which can be useful to you.

http://docs.jquery.com/How_jQuery_Works- For How jQuery Works

http://jquery.org/history- For History of jQuery

http://docs.jquery.com/Main_Page- jQuery documentation

Hope this will help you!!! Happy programming..

Technorati Tags: ,
Shout it
kick it on DotNetKicks.com
Share:
Tuesday, August 24, 2010

Using Let Keyword in Linq

I am using Linq-To-Object in my current project to remove some extra loops and I have found one of the great keyword in Linq called ‘Let’. Let keyword provides facility to declare a temporary variable inside the Linq Query.We can assign the result of manipulation to temporary variable inside query and we can use that temporary variable to another manipulation.

Let’s take a simple example of Linq query I am using an integer array to find square and after finding the square of the integer value I will use let keyword to find square value which are greater then 20. Here is the my query for that.

protected void Page_Load(object sender, EventArgs e)
{

int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8 };
var Result = from i in intArray
let square = i * i
where square>20
select square;
foreach (int i in Result)
{
Response.Write(i.ToString());
Response.Write("\n");
}
}
Here is the result of that query as expected.
LetResult

Let keyword is more useful when you are working with directories and files,xml manipulations so here possibilities are unlimited. Hope this will help you.. Happy Programming!!!

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:
Wednesday, August 18, 2010

Entity Framework 4.0- Bind Stored Procedure with Result Entity class

Microsoft Entity Framework version 4.0 is a brand new ORM(Object Relational Mapper) from Microsoft. It’s provides now some new features which are not there in the earlier version of Entity framework. Let’s walk through a simple example of a new features which will create a new Entity class based on stored procedure result. We will use same table for this example for which they have used earlier for Linq Binding with Custom Entity.

Below is the table which have simple fields like first name,last name etc.

SQL Table for Entity Example.

Let’s insert some data like following.

Sample data for Entity Framework Example

Below is the stored procedure which I am going to use for this example which will simply fetch data from the table.

CREATE PROCEDURE dbo.GetAllUsers

AS
SET NOCOUNT ON
SELECT
UserId,
UserName,
FirstName,
LastName,
FirstName + ' ' + LastName AS [FullName]

FROM dbo.Users
Now let’s create Entity model class just like below via Project->Add New Item->Go to Data tab and then select ADO.NET Entity Data Model.

Adding a New Enity model class for Entity Framework example

Once you click add a dialog box will appear which will ask for Data Model Contents there are two options Generate From Database and another one is Empty Model. Generate from database will create a Entity model from the ready made database while Empty model enable us to create a model first and then it will allow us to create a database from our model. We are going to use Generate From database for this example. Select Generate From Database like following and click Next.

Generating Model from database for Entity Framework 4.0 Example

After click on the next it will ask for database connection string like following where you need to apply connection string for that. I am already having connection string in my web.config so i just selected like below otherwise you need to create one via clicking on new connection. Also you need to specify the connection string name in web.config so it will put a connection string in connection string section with that name.

MyConnection

Once you click next it will fetch the all database objects information like Tables,Views and Stored Procedure like following. Here our purpose is to work with stored procedure so I just selected the stored procedure and selected the GetAllUsers Stored Procedure.

Selecting Stored procedure

After that it will create a Entity Model class in solution explorer.Now we want to bind the stored procedure with result class so first we need to create function which will call ‘GetAllUser’ stored procedure. To create function we just need to select Our Entity Model class and then go to Model Browser and select the Stored Procedure and right click->Add Function Import like following image.

Importing a function from stored procedure example.

It will start a new wizard and will go to next step like following image which will have four options 1. None 2. Scalars 3. Complex 4. Entities and there will be a button Get Column information once you click it. It will gather all the column information of stored procedure result set and then click ‘Create New Complex Type’ It will create a new complex type from the gathered column information.

Gathering a column info and then

You can also rename that class so I have renamed the class as ‘User Info’ like following.

UserInfo

Now click ok and now it will create function which call the stored procedure and will return Object Result set of Type ‘UserInfo’ which we have just created. Now let’s bind that to a simple grid view to see how its works. So Let’s take a simple grid view like below.

<asp:GridView ID="grdUserList" runat="server">
</asp:GridView> 
Now Let’s bind that grid view like following from the code behind file of asp.net like following.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (BlogEntities myEntity = new BlogEntities())
{
grdUserList.DataSource = myEntity.GetAllUsers();
grdUserList.DataBind();
}
}

}
Just run it with Ctrl + F5 and below it the output in browser.

Output of Entity Framework 4.0 Example

That’s it very easy and simple to bind complex type with stored procedure using ADO.NET Entity Framework 4.0. Hope this will help you.. Happy Programming!!!

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews