Thursday, May 24, 2012

How will implement Page Fragment Caching?

How will implement Page Fragment Caching?

Page fragment caching involves the caching of a fragment of the page, rather than the entire page. When portions of the page are need to be dynamically created for each user request this is best method as compared to page caching. You can wrap Web Forms user control and cache the control so that these portions of the page don’t need to be recreated each time.

How can you cache different version of same page using ASP.NET cache object ?

How can you cache different version of same page using ASP.NET cache object ?

Output cache functionality is achieved by using "OutputCache" attribute on ASP.NET page header. Below is the syntax
  1. VaryByParam :- Caches different version depending on input parameters send through HTTP POST/GET. 
  2. VaryByHeader:- Caches different version depending on the contents of the page header. 
  3. VaryByCustom:-Lets you customize the way the cache handles page variations by declaring the attribute and overriding the GetVaryByCustomString handler. 
  4. VaryByControl:-Caches different versions of a user control based on the value of properties of ASP objects in the control.

What are different types of caching using cache object of ASP.NET?

What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be transmitted to and displayed in a Web browser:
  1. Page Output Caching - Page output caching adds the response of page to cache object. Later when page is requested page is displayed from cache rather than creating the page object and displaying it. Page output caching is good if the site is fairly static. 
  2. Page Fragment Caching - If parts of the page are changing, you can wrap the static sections as user controls and cache the user controls using page fragment caching.

What is Cache Callback and Scavenging in Cache?

What is Cache Callback in Cache?

Cache object is dependent on its dependencies example file based, time based etc...Cache items remove the object when cache dependencies change.ASP.NET provides capability to execute a callback method when that item is removed from cache.

What is scavenging?

When server running your ASP.NET application runs low on memory resources, items are removed from cache depending on cache item priority. Cache item priority is set when you add item to cache. By setting the cache item priority controls the items scavenging are removed first

What are dependencies in cache and types of dependencies?

What are dependencies in cache and types of dependencies?

When you add an item to the cache, you can define dependency relationships that can force that item to be removed from the cache under specific activities of dependencies.Example if the cache object is dependent on file and when the file data changes you want the cache object to be update.

 Following are the supported dependency :-
1. File dependency :- Allows you to invalidate a specific cache item when a disk based file or files change.

2. Time-based expiration :- Allows you to invalidate a specific cache item depending on predefined time.

3. Key dependency :-Allows you to invalidate a specific cache item depending when another cached item changes.

Application State vs Session State

Application state variables:
The data stored in these variables is available to all the users i.e. all the active sessions.

Session state variables:
These are available to the single session who has created the variables.


Are Application state variables available throughout the current process?

Yes, Application state variables are available throughout the current process, but not across processes. If an application is scaled to run on multiple servers or on multiple processors within a server, each process has its own Application state.

ASP.NET, C# "DateTime" format and "DateTime.ToString()" Patterns

1 MM/dd/yyyy  08/22/06
2 dddd, dd MMMM yyyy  Tuesday, 22 August 2006
3 dddd, dd MMMM yyyy HH:mm  Tuesday, 22 August 2006 06:30
4 dddd, dd MMMM yyyy hh:mm tt  Tuesday, 22 August 2006 06:30 AM
5 dddd, dd MMMM yyyy H:mm  Tuesday, 22 August 2006 6:30
6 dddd, dd MMMM yyyy h:mm tt  Tuesday, 22 August 2006 6:30 AM
7 dddd, dd MMMM yyyy HH:mm:ss  Tuesday, 22 August 2006 06:30:07
8 MM/dd/yyyy HH:mm  08/22/2006 06:30
9 MM/dd/yyyy hh:mm tt  08/22/2006 06:30 AM
10 MM/dd/yyyy H:mm  08/22/2006 6:30
11 MM/dd/yyyy h:mm tt  08/22/2006 6:30 AM
12 MM/dd/yyyy h:mm tt  08/22/2006 6:30 AM
13 MM/dd/yyyy h:mm tt  08/22/2006 6:30 AM
14 MM/dd/yyyy HH:mm:ss  08/22/2006 06:30:07
15 MMMM dd  August 22
16 MMMM dd  August 22
17 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK  2006-08-22T06:30:07.7199222-04:00
18 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK  2006-08-22T06:30:07.7199222-04:00
19 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'  Tue, 22 Aug 2006 06:30:07 GMT
20 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'  Tue, 22 Aug 2006 06:30:07 GMT
21 yyyy'-'MM'-'dd'T'HH':'mm':'ss  2006-08-22T06:30:07
22 HH:mm  06:30
23 hh:mm tt  06:30 AM
24 H:mm  6:30
25 h:mm tt  6:30 AM
26 HH:mm:ss  06:30:07
27 yyyy'-'MM'-'dd HH':'mm':'ss'Z'  2006-08-22 06:30:07Z
28 dddd, dd MMMM yyyy HH:mm:ss  Tuesday, 22 August 2006 06:30:07
29 yyyy MMMM  2006 August
30 yyyy MMMM  2006 August

What is the Unchecked Keyword in C#?

The unchecked keyword is used to control the overflow-checking context for integral-type arithmetic operations and conversions. It can be used as an operator or a statement according to the following forms.
The unchecked statement:
unchecked block
The unchecked operator:
unchecked (expression)
where:
block
The statement block that contains the expressions to be evaluated in an unchecked context.
expression
The expression to be evaluated in an unchecked context. Notice that the expression must be in parentheses ( ).

What is the checked keyword in C#?

The checked keyword is used to control the overflow-checking context for integral-type arithmetic operations and conversions. It can be used as an operator or a statement according to the following forms.
The checked statement:
checked block
The checked operator:
checked (expression)
where:
block
The statement block that contains the expressions to be evaluated in a checked context.
expression
The expression to be evaluated in a checked context. Notice that the expression must be in parentheses ( ).

What is "USING and how to use the "USING" statement.

The following example shows how to use the using statement.

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}


File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}


Multiple instances of a type can be declared in a using statement, as shown in the following example.

using (Font font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}


You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.
            Font font2 = new Font("Arial", 10.0f);
            using (font2) // not recommended
            {
                // use font2
            }
            // font2 is still in scope
            // but the method call throws an exception
            float f = font2.GetHeight(); 


Reference:http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Monday, May 14, 2012

Using jQuery and JSON Action methods in MVC

  1. jQuery + JSON Action Methods = Cool
    It is easy to return a JSON object instead of a view.
    public JsonResult Create(string CategoryName)
    {
        var category = new Models.Category();
        category.Name = CategoryName;
        category.URLName = CategoryName.ToLower().Replace(" ", "-");
        categoryRepository.Add(category);
        categoryRepository.Save();
    
        return Json(category);
    }
    <script class="str" type="<span">
    "text/javascript" language="javascript">
        $("#CreateNewCategory").click(function() {
            $.getJSON("/category/create/",
                      { "CategoryName": $("#NewCategoryName").val() },
                      CategoryAdded);
                  });
    
                  function CategoryAdded(category) {
                      $("#CategoryList").append("
    
  2. + category.URLName + "/cat\">" + category.Name + "
  3. "
    ); } </script>

Sunday, May 13, 2012

What is Repository Pattern in ASP.NET MVC?

What is Repository Pattern in ASP.NET MVC?
Repository pattern is usefult for decoupling entity operations form presentation, which allows easy mocking and unit testing.
“The Repository will delegate to the appropriate infrastructure services to get the job done. Encapsulating in the mechanisms of storage, retrieval and query is the most basic feature of a Repository implementation”
“Most common queries should also be hard coded to the Repositories as methods.”
Which MVC.NET to implement repository pattern Controller would have 2 constructors on parameterless for framework to call, and the second one which takes repository as an input:
class myController: Controller
{
    private IMyRepository repository;
 
    // overloaded constructor
    public myController(IMyRepository repository)
    {
        this.repository = repository;
    }
 
    // default constructor for framework to call
    public myController()
    {
        //concreate implementation
        myController(new someRepository());
    }
...
 
    public ActionResult Load()
    {
        // loading data from repository
        var myData = repository.Load();
    }
}

What is difference between Viewbag and Viewdata in ASP.NET MVC?

What is difference between Viewbag and Viewdata in ASP.NET MVC?

The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

How to access Viewstate values of this page in the next page?

How to access Viewstate values of this page in the next page?

PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page.
Page poster = this.PreviousPage;
Once that is done, a control can be found from the previous page and its state can be read.
Label posterLabel = poster.findControl("myLabel");
 string lbl = posterLabel.Text;

How to call javascript function on the change of Dropdown List in ASP.NET MVC?

How to call javascript function on the change of Dropdown List in ASP.NET MVC?
Create a java-script function:
Call the function:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Products, "Value", "Text"),
"Please Select a product", new { id = "dropDown1",
onchange="selectedIndexChanged()" })%>

What is the ‘page lifecycle’ of an ASP.NET MVC?

What is the ‘page lifecycle’ of an ASP.NET MVC?
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

Friday, May 11, 2012

Remove MVC Action from Cache

For removing the Cache from the action so it get refresh each time, use the below stuff
 
public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted ( ActionExecutedContext context )
    {
        context.HttpContext.Response.Cache.SetCacheability( HttpCacheability.NoCache );
    }
}

[HttpGet]
[NoCache]
public JsonResult GetSomeStuff ()
{
    ...
}