Monthly Archives: September 2012

Implementing an MVC action filter to throttle requests

The following is from StackOverflow , for my future reference

    /// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
    /// <summary>
    /// A unique name for this Throttle.
    /// </summary>
    /// <remarks>
    /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
    /// </remarks>
    public string Name { get; set; }

    /// <summary>
    /// The number of seconds clients must wait before executing this decorated route again.
    /// </summary>
    public int Seconds { get; set; }

    /// <summary>
    /// A text message that will be sent to the client upon throttling.  You can include the token {n} to
    /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
    /// </summary>
    public string Message { get; set; }

    public override void OnActionExecuting(ActionExecutingContext c)
    {
        var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
        var allowExecute = false;

        if (HttpRuntime.Cache[key] == null)
        {
            HttpRuntime.Cache.Add(key,
                true, // is this the smallest data we can have?
                null, // no dependencies
                DateTime.Now.AddSeconds(Seconds), // absolute expiration
                Cache.NoSlidingExpiration,
                CacheItemPriority.Low,
                null); // no callback

            allowExecute = true;
        }

        if (!allowExecute)
        {
            if (String.IsNullOrEmpty(Message))
                Message = "You may only perform this action every {n} seconds.";

            c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
            // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
        }
    }
}
  

Sample Usage

    [Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
    return Content("TestThrottle executed");
}
  

You can also implement input throttling at the web server. With IIS 7.0 or 7.5, consider
using Dynamic IP restrictions, which are available for download at http://www.iis.net/
download/dynamiciprestrictions.

Binding Client Controls using Ajax

Binding client controls after getting data from Ajax enabled WCF web service. Ajax provides many useful objects to bind data to client controls like DataView, DataContext, ADONetServiceProxy and ADONetDataContext. If you are using ASPX page:
If you are creating an ASP.NET web page, add a ScriptManager with a ScriptReference
to MicrosoftAjaxTemplates.js.

<asp:ScriptManager ID="ScriptManager1" runat="server">
       <Scripts>
              <asp:ScriptReference Name="MicrosoftAjaxTemplates.js" />
      </Scripts>
</asp:ScriptManager>

If you are creating an HTML page or an MVC view, reference the static JavaScript files
directly:

  <script type="text/javascript" src="MicrosoftAjax.js"></script>
   <script type="text/javascript" src="MicrosoftAjaxTemplates.js"></script> 

Bind data from the data fetched from the ajax datacontext like:

   <li>{{FieldName}}: {{FieldName2}} </li>

You need to add the javascript code to the of the ASPX page at the load time, you can use pageLoad function like:

  function pageLoad(){
           $create(Sys.UI.DataView,
                           { 
                              autoFetch: true,
                              dataProvider: 'Service Name.svc',
                              fetchOperation:'MethodName within the service'
                         },
                         {},
                         {}.
                          $get('data object id')             
           );
    }

You can do the Live Binding
for live binding you just need to replace

{{ <Property>}} with <span>{binding <Property>}</span>
      
<ul id="ulidName" style="display:none">
     <li><span>{binding fieldName}</span>: <span>{binding fieldName2}</span></li>
</ul>

Live Binding won’t actually update the controls automatically when there is a change on the server but it’ll update the changes on the client datasource. To update data, you can use DataView.fetchData method.

Two way Data Binding is also available to update the client controls. Two-way data binding provides live binding’s ability to automatically update client controls when the client data source is updated, and it also updates the client data source when the contents of a bound client control are changed.
to use it

      <span>{binding <Property>, mode=twoWay}</span>

You can use live binding with formatted data by specifying JavaScript functions for the convert and convertback properties.
Eg: {binding , convert=toJavascriptFunction, convertBack=fromJavascriptFunction}

Updating Server data from client controls
If you need to allow users to update the data using client controls, use one of the following
three classes with an instance of DataView:
— DataContext
— AdoNetServiceProxy
— AdoNetDataContext

Data Context
The ASP.Net AJAX Sys.Data.DataContext class connects to the WCF data service or Ajax enabled WCF web service and reads, updates, and inserts data from a javascript client. With DataContext, you can develop a CRUD application using nothing but client-side JavaScript code, providing responsiveness similar to a Microsoft Windows application within the browser environment.

Typically, you use a DataView client control to present the DataContext to the user. Set the DataView:DataProvider to the instance of DataContext, and use live-binding markup in the template to allow users to edit the data. When the user has indicated that she is done making changes (such as by clicking a Submit button), call the DataContext.saveChanges JavaScript function.

This example demonstrates using DataContext and DataView together to connect to an ASP.NET web service:

<script type="text/javascript">
var dataContext = new Sys.Data.DataContext();
dataContext.set_serviceUri("../Services/peopleService.svc");
dataContext.set_saveOperation("SavePerson");
dataContext.initialize();
</script>
<button onclick="dataContext.saveChanges()">Submit Changes</button>
<ul sys:attach="dataview" class="sys-template" dataview:autofetch="true"
dataview:dataprovider="{{ dataContext }}"
dataview:fetchoperation="GetPerson"
dataview:fetchparameters="{{ {orderBy: 'Name'} }}"
>
<li>
<input type="text" value="{binding Name}"/><br/>
<input type="text" value="{binding Address}"/>
</li>
</ul>

ADONETSERVICEPROXY
You can use the ASP.NET AJAX Sys.Data.AdoNetServiceProxy class to read, update, add, and delete records exposed by a WCF data service using REST. After you create an instance of AdoNetServiceProxy by specifying the location of the WCF data service, you can call the query and update, insert, remove, and invoke JavaScript functions to perform individual operations, or you can call the createActionSequence JavaScript function to run several operations together.

This example demonstrates using AdoNetServiceProxy and DataView together to connect to a WCF web service:

<head>
<script type="text/javascript" src="../MicrosoftAjax/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../MicrosoftAjax/MicrosoftAjaxTemplates.js">
</script>
<script type="text/javascript" src="../MicrosoftAjax/MicrosoftAjaxAdoNet.js"></script>
<script type="text/javascript">
var peopleService = new Sys.Data.AdoNetServiceProxy('../Services/peopleDataService.svc');
</script>
</head>
<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
<ul class="list sys-template" sys:attach="dataview"
dataview:autofetch="true"
dataview:dataprovider="{{ peopleService }}"
dataview:fetchoperation="People"
dataview:fetchparameters="{{ {$orderby: 'Name'} }}"
>
<li>
<span class="name">{{ Name }}</span>
<span class="value">{{ Address }}</span>
</li>
</ul>
</body>

Ado Net DataContext
Although you should be familiar with AdoNetServiceProxy, ASP.NET AJAX provides a second class for accessing WCF data services: AdoNetDataContext. AdoNetDataContext is derived from DataContext, and it uses the AdoNetServiceProxy class for communicating with WCF data services. However, it adds support for identity management, associating entity sets from different fetch operations, hierarchical data, and optimistic concurrency. You can use AdoNetDataContext exactly like you use AdoNetServiceProxy.

Planning Role Management in ASP.Net

When planning role management, follow these best practices:
1> Use Windows authentication for intranet applications when users have Active Directory domain accounts. This provides single sign-on for users and centralizes account management. If you use Windows authentication, ASP.Net uses roles to represent group memberships.
2> If you must create accounts for users separate from their Active Directory domain accounts, work with systems administrators to include the application’s role management in their account management process. For example, when a user leaves the organization, systems administrators will need to remove both the user’s Active Directory domain account and the application account.
3> Never assign privileges to an individual user. Instead, add users to roles, and assign privileges to those roles. If an employee leaves the organization, you only need to remove the user from the role rather than modifying how privileges are assigned.
4> Create separate roles for different management tasks. For example, instead of creating roles for just users and administrators of a blog application, create separate roles for readers, writers, editors, content approvers, and website managers. Even though it might require you to add users to multiple roles, having more granular roles simplifies delegating tasks if more flexibility is required in the future.
5> Always derive new security classes from existing .NET classes. Microsoft has carefully reviewed and tested the security components of the .NET framework. This does not mean the .NET framework does not contain security weaknesses; all code does. However, the .NET framework’s extensive review and testing helps to make them more secure than classes written by individual developers.

ASP.Net web services (ASMX) vs WCF web services

The following are the few things which distinguish ASMX services to WCF webservices:
–WCF web services provide many bindings
–WCF web services are written to implement contracts defined by interfaces.
–For ASMX web services, you add attributes to the methods. For WCF web services, you add attributes to the interfaces.
–ASMX web services must be hosted in IIS, but WCF web services can ei

.Net Data Design Stratagies

While designing an application to design a data layer or connecting to database there are multiple options:
1. ADO.Net: This the old way of connecting to the data base, creating a connection and binding the data to dataset or datatable and updating or reading the data from database.
2. Entity Framework: Entity Framework is inbuit of .net framework now and it’s a abstract way of connecting to the database and better way for the developers who are not entirely familiar with the database programming. Database is not entirely object oriented like the way the objects are in .net like inheritance so orm tools like Entity Framework maps the relational objects to object oriented entities for the developers to directly interact with the data as objects. Similarly, Entity Framework can map the objects or entities creates in .net and map to relational objects like Code first methodology.

3. WCF Services: .Net Framework version 3.0 introduced WCF as to combine and update several communication technologies like enterprise services, Active Server Methods (ASMX) webservices, Web Service Extensions (WSE), Microsoft Message Queuing (MSMQ) and .Net remoting. WCF web services is the most powerful, flexible, and secure way to provide Application Logic layer services to a Presentation Layer, whether the presentation Layer is part of the same application or different one.

4. WCF Data Services: It was formerly known as ADO.Net Data Services. It allows you to quickly build an OData or REST service. OData or REST are HTTP based open standards for exposing data across the web, where they can be consumed by clients built on a wide variety of platforms, including .Net, Microsoft Silverlight, JQuery, PHP and Javascript.

You can get into a dilemma to choose the correct methodology or framework for data design, below are the few scenarios where we can categorize each with:

Choose Entity Framework when you
–implementing the Data Layer
–connect to the database without network protocol restriction
–require rapid application development
–require strongly typed objects.
Choose WCF Data Services when you are
–implementing the Data Layer
–Connect to the database server by using HTTP
–require access from javascript
–require application level control over access to the data.
Choose WCF web services when you are
–implementing the Application Logic layer
–require specific network protocols, such as WS-Security, SOAP or REST
–require multiple binding types for different clients
–require access from Javascript
Choose ASMX web services when you are
–implementing either Application Logic or Data Layer for a remote application
–need to add web services to an existing ASP.Net application
–will host the application only on IIS
–require only basic HTTP communication.

Design Patterns

There are different classifications/categoris of design pattern when we group together
Classifications:
.Creational
.Structural
.Behavioral
.Security
.Concurrency
.Sql
.User Interface
.Relational
.Social
.Distributed

The classification of design patterns keep growing, this is only exhaustive list.
Design Patterns:
Different types of design patterns:
Creational Patterns
1. Abstract factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
2. Builder: Separate the construction of a complex object from its representation allowing the same construction process to create various representations.
3. Factory method: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
4. Lazy initialization: Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
5. Multiton: Ensure a class has only named instances, and provide global point of access to them.
6. Object pool: Avoid expensive acquistion and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and thread pool patterns.
7. Prototype: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
8. Resource acquisition is initialization: Ensure that resources are properly released by tying them to the lifespan of suitable objects.
9. Singleton: Ensure a class has only one instance, and provide a global point of access to it.

Structural Patterns:
1. Adapter or Wrapper or Translator: Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator.
2. Bride: Decouple an abstraction from its implementation allowing the two to vary independently.
3. Composite: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
4. Decorator: Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.
5. Facade: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a high-level interface that makes the subsystem easier to use.
6. Flyweight: Use sharing to support large numbers of similar objects efficiently.
7. Front Controller: The pattern relates to the design of Web applications. It provides a centralized entry point for handling requests.
8. Module: Group several related elements, such as classes, singletons, methods, globally used, into a single conceptual entity.
9. Proxy: Provide a surrogate or placeholder for another object to control access to it.

Behavioral Patterns:
1. Blackboard: Generalized observer, which allows multiple readers and writers. Communicates information system-wide.
2. Chain of responsibility: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
3. Command: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log request, and support undoable operations.
4. Interpreter: Given a language, define a representation for its grammar alond with an interpreter that uses the representation to interpret sentences in the language.
5. Iterator: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
6. Mediator: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicityly, and it lets you vary their interaction independently.
7. Memento: Without violating encapsulation, capture and externalize an objects’s internal state allowing the object to be restored to this state later.
8. Null object: Avoid null references by providing a default object.
9. Observer or Publish/subscribe: Define a one-tomany dependency between objects where a state change in one object results in all its dependents being notified and updated automatically.
10.Servant: Define common functionality for a group of classes.
11.Specification: Recombinable business logic in a Boolean fashion.
12.State: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
13.Strategy: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
14.Template method: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
15.Visitor: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Concurrency Patterns:
1. Active Object: Decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.
2. Balking: Only execute an action on an object when the object is in a particular state.
3. Binding Properties: Combining multiple observers to force properties in different objects to be synchronized or coordinated in some way.
4. Double-checked locking: Reduce the overhead of acquiring a lock by first testing the locking criterion (the ‘lock hint’) in an unsafe manner; only if that succeeds does the actual lock proceed. Can be unsafe when implemented in some language/hardware combinations. It can therefore sometimes be considered an anti-pattern.
5. Event-based asynchronous: Addresses problems with the asynchronous pattern that occur in multithreaded programs.
6. Guarded Suspension: Manages operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed.
7. Lock: One thread puts a “lock” on a resource, preventing other threads from accessing or modifying it.
8. Messaging design pattern (MDP): Allows the interchange of information (i.e. messages) between components and applications.
9. Monitor object: An object whose methods are subject to mutual exclusion, thus preventing multiple objects from erroneously trying to use it at the same time.
10.Reactor: A reactor object provides an asynchronous interface to resources that must be handled synchronously.
11.Read-write lock: Allows concurrent read access to an object, but requires exclusive access for write operations.
12.Scheduler: Explicitly control when threads may execute single-threaded code.
13.Thread pool: A number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. Can be considered a special case of the object pool pattern.
14:Thread-specific storage: Static or global memory local to a thread.

Creational Patterns
->Abstract Factory
-> Builder
-> Factory Method
-> Prototyp
-> Singleton
-> Lazy instatiation
-> Utility Pattern
Creational pattern talks about how we instatiate an object. Different patterns for different ways of instantiation.

Lets check some of the commonly used patterns:
Adapter Pattern
Bridge Pattern
Builder Pattern
Chain of Responsibility
Command Pattern
Composite Pattern
Decorator Design Pattern
Event Aggregator
Facade Pattern
Factory Pattern
Flyweight
Interpreter
Iterator Pattern
Lazy Load Pattern
Mediator Pattern
Memento
Model View Presenter (MVP) Pattern
Model View ViewModel (MVVM) Pattern
Null Object Pattern
Observer Pattern
The Prototype Pattern
Proxy Pattern
Repository Pattern
Singleton
Service Locator Pattern
State Pattern
Strategy Pattern
Template Method
Unit of Work
Visitor Pattern

Lets get the brief introduction of the above mentioned patterns
Adapter Pattern: Adapters are commonly known as wrappers. It’s basically like to when you want to use some methods in a library but the objects or parameters are not the same as in your application then you’ll create a wrapper/adapter which takes the parent/host library methods and convert them to the way that your application can utilize it. It’s called adapter pattern.
Like AC – to – DC adapter we use in our day to day life or voltage adapter when we travel to different countries for your electronic appliances.

Bridge Pattern: “Decouple an abstraction from its implementation so the two can vary independently” as per Gangs of Four. In simple terms, when you are using an object in combination with some other objects rather than providing all the possible combinations you can create an abstraction for each object and then let the user decide on the combination so that at any point of time in the future if you want to add any new items to any of the objects it should not affect the combination. Since the combination is still possible. (Ex: different Burgers and fries & drink or different Burgers and Vegetables & milk.. if you create an abstraction for burgers and fries & drink or vegetables & milk then you can create any number of combinations even if you add another kind of burger or another combination of drink like vegetables & drink).

Builder Pattern: “Separates the construction of a complex object from its representation so that the same construction process can create different representations.” as per Gangs of Four. In simple software terms, separate the data from logic and reuse that logic. Instead of giving the entire steps of a process which is to be repeated, create a logic for that and reuse it. (Ex: going to subway and giving the same instruction again and again whenever you go there create a pattern and just mentioning the pattern that you like to have each time you go there.) simplify the process.

Chain of Responsibility: “Ordered list of message handlers which knows how to do things”. The process goes in this way: Sender gets a message which need to be deciphered and send the response, sender is aware of receiver 1 in the chain as there are multiple receivers in the chain and Sender sends the message to receiver 1 to decipher, as Receiver 1 is not able to decipher that it will send to the next level of receiver Receiver 2 and receiver 2 is capable of deciphering it and sends the response to the sender. Sender is not aware about the receiver 2 and the higher levels of receiver 2 are not aware of the message. It’s like every level has its responsibility and if it’s not capable of resolving the problem it will send to the next higher level and next higher level. Whichever level is able to resolve the problem, will send the response directly to the initial layer raising the problem. Best like Linked list.

The Command Pattern: Also known as Action/Transaction Pattern. Represent an action/logic/operation as an object. Decouple clients that execute the command from the details and dependencies of the command logic. It enables delayed execution.

Factory Patterns: Consider factories when we are unsure of the implementation of an interface I want to return for a given class or creation should be separated from representation of an object or lots of if/else statements when deciding which concrete class to create or switch statements when deciding which concrete class to create:
3 different types of factories available
1. Simple Factory Pattern: Encapsulate object creation. Allows for late-bound decisions regarding instationation (configuration based, other persistent storage, input or other dynamic data). Caller class knows what concrete factory it needs.