Wednesday, February 6, 2013

ASP.NET Caching Complete Reference

One of the core concepts in web development is caching. Understanding why we need caching is important before digging into them.

Caching helps you to reduce traffic to web server by storing some of the 'data' website requires by storing it in some form of memory, than web server serving consequent requests for the same website from that client. This will reduce the web server from redoing everything for each and every request thereby improving the performance.

Caching can be roughly divided into
  • Output caching
  • Application state
  • Cache class
  • Static member variables

Output caching


Output caching has been available since first version of ASP.NET and is also available in ASP.NET MVC as an attribute. 

In ASP.NET you can add a outputcache directive for aspx page. (see example) then for the specified duration of the output cache duration setting the page will be cached.

In MVC you can decorate a action or a whole controller with outputCache attribute. (asp.net). 

Above what we have done is application output caching. There's another concept called proxy output caching. (Article includes good practical example of the usage)

Output Caching is extensible. You can use custom output cache providers. Usually these Custom providers derives from OutputCacheProvider type. You can do the required configurations in Web.config.

Application state 

You can store application level variables Application property of HttpContext. (link)

Cache class

Use cache class to to cache data in a ASP.NET Web application (for other types of applications you can use Memory Cache) sources: Object cache, Object caching 

Static Member variables

Use Static members to store application level attributes which do not change

Saturday, January 26, 2013

Execution Sequence of Entity Framework

When talking about Entity Framework its important to understand the operations happening,

Loading metadata
Happens only once in each application domain. Model and mapping metadata used by EF is loaded into MetadataWorkspace.

Opening the database connection
EF opens and closes database connection as needed. 

Generating views
This is usually a costly operation

Preparing the query

Executing the query

Loading and validating types

Tracking



Materializing the objects

Monday, January 14, 2013

Tuesday, January 1, 2013

Functional and Non Functional Requirements



Basically functional requirement is something specific the system should do. Functional requirement of a system could be,
  • Business rules
  • Administrative functions
  • Authentication and Authorization
  • Reporting
On the other hand non functional requirement describes how system works or how the system should behave. These can be,
  • Performance
  • Scalability
  • Capacity
  • Availability
  • Maintainability
  • Security 
  • Usability etc. 
Non functional requirements can be identified as quality attributes of a system. Non functional requirements are defined in terms of metrics (something that can be measured about the system).

Resources
http://reqtest.com/requirements-blog/functional-vs-non-functional-requirements/#conversion-0
http://stackoverflow.com/questions/16475979/what-is-functional-and-non-functional-requirement

image credit : http://www.steffen-zschaler.de/bibliographies/nfp/sommerville.png

Monday, December 31, 2012

Saturday, December 29, 2012

What you need to know about performance in Entity Framework


http://msdn.microsoft.com/en-us/data/hh949853.aspx 

Mapping Views
Mapping views are set of SQL statements that represents the database in an abstract way, which are also part of the metadata.
link1, link2

Query execution
Deferred vs. Immediate execution
Client side execution of LINQ queries
Query and mapping complexity
Mapping complexity
Query complexity
Relationships
Query paths
Saving changes
Distributed Transactions


Strategies for Performance improvement

Pre-generate views
Consider using NoTracking merge option for queries
Return the correct amount of data
Limit the scope of ObjectContext
Consider opening db connection manually.

Extra

  • In EF its best to understand how query execution happens 
  • Data Source is the one which provides connection pooling facility. Not the Entity Framework. The .NET provider for SQL Server provides support for Connection Pooling
  • In previous versions of EF (before 6) there was a performance problem when using Contains. This has been fixed now.

https://msdn.microsoft.com/en-us/data/hh949853.aspx
http://www.asp.net/web-forms/overview/older-versions-getting-started/continuing-with-ef/maximizing-performance-with-the-entity-framework-in-an-asp-net-web-application


http://www.asp.net/whitepapers/aspnet-data-access-content-map#gettingstarted


Saturday, December 8, 2012

Stuff you need to know about JavaScript

JavaScript has lot of concepts around it. There are things that you might miss out. Lets see some of them.

  • In JavaScript there are some variables starting as __ (__defineGetter, __defineSetter, __proto__). These are variables defined by the browser and are not defined by ECMAScript #convention (link2)
  •  Best practice to define libraries is to define one global variable (google, jquery) and define all your methods/variables within the scope of that object
  • JavaScript curry
  • Adding custom headers to JQuery AJAX request
  • Browser closing events
    • http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch
    • http://stackoverflow.com/questions/2076299/how-to-close-current-tab-in-a-browser-window
  • http://stackoverflow.com/questions/4869613/solutions-for-distributing-html5-applications-as-desktop-applications

Scope and Context in JavaScript

Wednesday, November 28, 2012

Compilation basics in .NET

Compiler is a computer program that transforms the source code into a target language which can be executed directly. 

Following are few concepts behind compilation
  • JIT - Just In Time compiler
  • Ahead of time compilation
Compilation in ASP.NET #

Intermediate language (IL)
Also known as MSIL (Microsoft Intermediate Language). All .NET source code is compiled to IL which is then converted to machine code. 

Resources


Thursday, November 22, 2012

C# Tips and Tricks

For a seasoned software developer, knowing just the basics and theories of programming is going to do any good. They must also be aware of little tricks which makes development easy and fun. In this article I'll share few tips which we can use to improve our coding. (I'll be focusing on C# here.)

Null-Coalescing operator

Rather than explaining its better to show it using an example.

You can also chain these
Stackoverflow :What do ?? means in C#

yield method

using yield you can return each element one at a time for a list. (Lazy) (MSDN, SO, CodeProject easy to understand)


IEnumerable<int> Integers()

        {
            List<int> list = new List<int> { 1, 2, 3 };

            foreach (var item in list)
            {
                yield return item;
            }
        }

Extension methods

Allows you to add methods to existing types without creating new derived type. These are special kind of static method. The most common extension methods are LINQ standard query operators that add query functionality to existing System.Collections.IEnumberable and System.Collections.Generic.IEnumerable<T> types. 

You can use extension methods to extend a class or interface, but not to override them. An extension method with same name and signature as an interface or class method will never be called. At compile time extension methods always have low priority than instance methods. 

Defining extension method on Object will make the method available to all objects. This won't have any performance cost. Basically it won't get attached to each object. Rather you can call the extension method from any object. (See SO article)

I'll update this list continually. Hope this list will be useful for you. 

P.S: Find out more Hidden features of C# (SO)

image credit : blastmobilefitness

Saturday, November 10, 2012

JavaScript prototyping

In JavaScript, every object has a prototype property. Prototype property is also an object. All JavaScript objects inherit there properties and methods from there prototypes.

Using prototypes makes object creation faster.



When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

Object.create :  Create a new object with specified prototype object and properties

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain

hasOwnProperty is an own property of Object.prototype. When we create an object, it inherits hasOwnProperty from Object.prototype.

Arrays inherits from Array.prototype (it has methods like forEach, call)
// f ---> Function.prototype ---> Object.prototype ---> null
 
 
The lookup time for properties that are high up on the prototype chain can have a negative impact on performance, and this may be significant in code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.

Also, when iterating over the properties of an object, every property that is on the prototype chain will be enumerated.



Saturday, November 3, 2012

Introduction to IIS

IIS is a web server software developed by Microsoft. IIS provides a request processing architecture. IIS includes,
  • A customizable web server engine by adding or removing modules
  • Windows Process Activation Service (WAS) which enables sites to use protocols other than HTTP and HTTPS
  • Integrated request processing pipelines from IIS and ASP.NET

Components in IIS

Performs important functions in IIS. Some components of IIS are protocol listeners (HTTP.sys) and services such as World Wide Web publishing service (WWW Service) Windows Process Activation Service (WAS).

Protocol listeners
These receive protocol specific requests, send them to IIS for processing and returns responses. One example is HTTP.sys HTTP listener which listens to both HTTP and HTTPS. You can also use protocol listeners for WCF etc.

Windows Process Activation Service (WAS)

By default IIS only supports HTTP protocol. You can use WAS component to enable other protocols. Also see http://www.iis.net/learn/manage/provisioning-and-managing-iis/features-of-the-windows-process-activation-service-was

Following video will show you how to host WCF services in IIS.

Pipelines

In IIS 7 there are 2 request processing pipelines. Classic and Integrated pipeline. Classic was the only existed in IIS 6 and below. With Integrated pipeline it is tightly integrated as ASP.NET request pipeline. (SO)

Managed code modules that implements IHttpModule has access to all events in request pipeline. In IIS6 and IIS7 classic mode, ASP.NET request pipeline was separate from Web server pipeline. But in IIS 7, it is a unified pipeline which handles the requests. 

In ASP.NET application life cycle, firstly 

  • The ApplicationManager and HostingEnvironment objects gets created
  • Application objects such as HttpContext, HttpRequest gets created
  • HttpApplication object is created (if one doesn't exist to use) and assigned to the request


Automatic Deployment using Microsoft Web Deploy
http://weblogs.asp.net/scottgu/automating-deployment-with-microsoft-web-deploy

Resources


Wednesday, October 17, 2012

ASP.NET MVC Controller class

Controller is the base class from which we create Controllers in ASP.NET MVC (article). The base class Controller has many useful properties and methods. If you look in to the MSDN documentation of the Controller class you can see a comprehensive list of that.

Controller actions


HttpContext (type = HttpContextBase)

Gets HTTP specific information about an individual HTTP request. You should note that the type of HttpContext is HttpContextBase. See difference between HttpContext and HttpContextBase.

HttpContextBase class is an abstract class that contains same members as the HttpContext class. But this class enables you to create derived classes that are like HttpContext class, but you can customize and that work outside ASP.NET pipeline. 

HttpContext.Current: static property which returns current HttpContext for the thread. You can also use Page.Context property to access HttpContext for the current HTTP request.

Request (type = HttpRequestBase)

Gets the HttpRequestBase object for the current HTTP request. Enables you to read HTTP values sent by a client during a web request. This is an abstract class which contains same members as the HttpRequest class. Same as in HttpContext, HttpRequestBase class allows you to create derived classes that are like HttpRequest class.

HttpRequestWrapper class derives from the HttpRequestBase class. The HttpRequestWrapper class serves as a wrapper for HttpRequest class. At run time, you typically use and instance of the HttpRequestWrapper class to invoke members of the HttpRequest.

Response (type = HttpResponseBase)

Same as in Request

RouteData (type = RouteData)

Gets the route data for the current request

Server (type = HttpServerUtilityBase)

Gets the HttpServerUtility object that provides methods that are used during Web request processing

Session (type = HttpSessionStateBase)

The implementation of HttpSessionStateBase class, HttpSessionState provides access to session-state values as well as session-level settings and lifetime management methods. You can access session and functionality through the Session property of the current HttpContext, or Session property of the Page.

You might wonder why there's a Session property in Controller as well as in HttpContext.Current. They are almost the same. The Session property in Page class actually calls the HttpContext.Current.Session itself. But there are places where you can't directly call Session property, such as from static context like WebMethod. 

 See the difference between HttpContext.Current.Session and Session. also look at these stackoverflow references (link2, link3, link4 also the google search)

User (type = IPrincipal)

Gets the user security information for the current HTTP request



Additional note: GenericIdentity objects

You can use GenericIdentity class in conjunction with the GenericPrincipal class to create an authorization scheme that exists independent of a Windows domain. 

Steps

  1. Create a new instance of the identity class and initialize it with the username. 
  2. Create a new instance of GenericPrincipal class and initialize it with previously created GenericIdentity and array of string of user roles you want to attach
  3. Attach the principal to the current thread. 
In case you want to store additional data in generic principal then create a class out of GenericIdentity class.

Can I Overload controller methods?
You can do something like below (Sources - SO)

[ActionName("MyOverloadedName")]




Monday, October 8, 2012

Sunday, September 30, 2012

Lambda Expressions in C#

Lambda expression is a anonymous function that you can use to create delegates or expression tree types. These are useful for writing LINQ query expressions.

Expression Lambdas

A lambda expression with a statement on right side of => operator. These are used to construct expression trees. 


Statement Lambdas

Resembles an expression lambda except that statements are enclosed in braces. 


Async Lambdas


Incorporate asynchronous processing by using async and await keywords.



Generic Delegates ##

a delegate can define its own type parameters. A code that uses generic delegate can specify type argument to create a closed constructed type, just like when instantiating or creating a generic. 


What is a method group in C# (SO)


Lambdas with Standard Query Operators

Many standard query operators have an input parameter whose type is one of Func<T,TResult> family of generic delegates. 


Type inference in Lambdas

Usually you don't have to specify the type of input parameters because compiler can infer the type based on lambda body,  the parameters delegate type etc. 


Resources

Friday, September 14, 2012

Session State Modes in ASP.NET

ASP.NET session state supports several different storage options for session data. Each option is identified by value in the SessionStateMode enum. ASP.NET Session has the type HttpSessionStateBase type. Session has 2 methods, Session.Clear() and Session.Abandon(). See the difference.

InProc (default)

Store session state in web server memory.

StateServer 

  • Store session state in a separate process called ASP.NET state service. 
  • This ensures session state is preserved if the web app is restarted. 
  • Makes session state available to multiple web servers in a server farm. 
  • If using stateServer the objects stored in the session should be serializable. 
  • If using in a server farm you must have same machine key in all machines. 

SQL Server

  • Store in SQL Server DB. Same as state server, ensures preservation of data when web app restarted and on web farms. 
  • Objects should be serializable
  • You must first install ASP.NET session state database in SQL Server
  • You can use fail over cluster 

Custom

Enables you to specify custom storage provider. See how to implement session state store provider. There's one for Redis.

Off

Disable session state
__________________________________________________________________

HttpSessionState 

  • Provides access to session-state values as well as session-level settings and lifetime management methods.
  • Enables you to store information associated with a unique browser session across multiple requests
  • Can access these through Session property of the current HttpContext, or Session property of the Page
  • Session data is associated with a specific browser using a unique identifier. By default, this identifier is stored in non-expiring cookie in the browser.
  • You can also use Timeout property set a timeout
  • When a new session begins session Start event is raised
  • When session times out, the Abandon method is called.
  • When ASP.NET application shut down the session End event is raised. (The End event is raised only when the session state mode is set to InProc)
  • Session state does not persist across application boundaries
  • Session values are stored in the memory of the web server.

Session object in ASP.NET

http://stackoverflow.com/questions/2874078/asp-net-session-sessionid-changes-between-requests
http://stackoverflow.com/questions/tagged/sessionid
http://stackoverflow.com/questions/940742/difference-between-session-and-httpcontext-current-session

In ASP.NET For session state management we have,
  • View State
  • Control state
  • Hidden fields
  • Cookies
  • Query Strings

Monday, September 10, 2012

Delegates in C#

In simple words delegate is a type that references to a method with a particular parameter list and a return type. You can invoke(call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are methods invoked through delegates. Delegate is a similar concept as function pointers in C and C++.

The ability to pass methods as parameters makes delegates ideal for defining callbacks. (When to use delegates, link2). Delegates are ideal to encapsulate codes. For example when you attach an event handler to a button, the handler becomes a delegate. The button doesn't need to know what it does. (Difference between Delegate and an Event).

Delegate types are derived from Delegate class. Delegate types are sealed and cannot be derived from. The ability to pass delegate as a parameter to a method and to call the delegate at a later time is known as asynchronous callback. 

When to use Delegates and Interfaces
Interfaces and delegates allows developer to separate type declaration and implementation. Use the following guidelines to decide.

Use delegates when,
  • Event based design pattern is used
  • Easy composition is desired
Use interfaces when,
  • There are group of related methods that might be called
  • Class only needs one implementation of the method
Source : MSDN, StackExchange

Delegates with Named Methods




Delegate with Anonymous Method

C# 2.0 introduced anonymous methods. Anonymous methods enables you to omit parameter list. This means anonymous method can be converted to delegates with variety of signatures. (This is not possible with Lambda expressions). Anonymous methods provide a way to pass a code block as a delegate parameter. They are basically methods without a name.


Lambda Expressions

Lambda expression is a anonymous function that you can use to create delegates or expression tree types. These are useful for writing LINQ query expressions. 

To create lambda expressions you specify any input parameters on the left side of => lambda operator and the expression or statement block on the other side. You can assign this expression to a delegate type. 



There are different types of lambda expressions,
  • Expression lambdas
  • Statement lambdas
  • Async lambdas
Lambda Expressions (MSDN)

Resources

Saturday, September 1, 2012

HTML Elements

Upto HTML 4.01. block level elements and inline elements. 

inline elements: 
  • respect l to r margins and padding. not top and bottom
  • cannot have width and height set
  • allow other elements to sit to their l and r
  • can display things before and after it, on the same line.
  • span, a, strong, em, img, input, abbr, acronym
block
  • respect all of those
  • force a line break after the block element
  • demands its own line with whitespace around it. 
  • <p>, <div>, h1 to h6, ul, ol, dl, li, dt, dl, table, pre, form

From HTML5 onwards
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories

Talking about attributes, you can use data-* attributes to store extra information on standard semantic HTML elements. (link)

HTML5 WAI-ARIA is a spec defining support for accessible web apps. (link, link)


s
Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook