Friday, July 13, 2012

Tuesday, July 10, 2012

Filters in ASP.NET MVC

Filters are .NET attributes used to inject extra logic into MVC framework request processing. You can apply filters before and after calling an action method (pre-action and post-action). 

Filters can be used for,
- Custom Authentication
- Custom Authorization (User or Role base)
- Error handling and logging
- User Activity logging
- Data caching and compression

.NET attribute
Attribute are special .NET classes derived from System.Attribute namespace. Used to embed additonal information into compiled code to read at runtime. 

What are global filters?
You can add global filters inside Global.asax file. By using these you don't have to specify filter attributes in each controller and action. You can also add these conditionally. (resource).

There are 5 basic types of filters,

Authorization filters
  • Runs first, before any other filter or action method. 
  • Implements IAuthorizationFilter.
  • Makes security decisions about whether to execute an action method such as performing authentication or validating properties of the request. 
  • AuthroizeAttribute class and RequireHttpsAttribute class are examples of an authorization filter. 
Action filters
  • Runs before and after the action method. 
  • Implements IActionFilter
  • IActionFitler declares two methods
    • OnActionExecuting : runs before the action method
    • OnActionExecuted: runs after the action method
Result filters
  • Runs before and after the action result is executed
  • Implements IResultFilter 
  • IResultFilter declares two methods
    • OnResultExecuting : runs before the ActionResult object is executed
    • OnResultExecuted: runs after the result and perform additional processing of the result such as modifying the HTTP response
  • The OutputCacheAttribute class is an example of a result filter (implementation,  web farm limitations)
  • Extending ASP.NET MVC OutputCache
Exception filters
  • Runs only if another filter, the action method or the action result throws an exception
  • Implements IExceptionFilter
  • Execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. 
  • Can be used for tasks such as logging or displaying error page
  • HandleErrorAttribute class is an example of an exception filter (article). Usually HandleError is added to global filters in MVC projects.
Authentication filters (New in ASP.NET MVC 5, article)
  • Implements IAuthenticationFilter
  • Applied prior to any Authorization filter
  • You have two methods to implement
    • OnAuthentication(AuthenticationContext filterContext)
    • OnAuthenticationChallenge : runs after OnAuthentication. You can perform additional things here



Controller class implements each of the filter interfaces (IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IResultFilter). All above Attributes implements abstract FilterAttribute base class, which then again implements Attribute class. AuthorizeAttribute and HandleErrorAttribute contain useful features you can use without creating derived class.

AuthorizeAttribute Class
  • When you mark an action method with this, access to the action method is restricted to users who are authenticated and authorized.
  • Use AllowAnonymousAttribute attribute to specify that a particular action method is not restricted to only authroized users.
  • Use Roles and Users properties to specify which roles or users are permitted
  • If unauthorized user tries to access MVC framework returns a 401 HTTP status code
  • If you derive from the AuthorizeAttribute class, the derived type should be thread safe. Therefore do not store state in an instance of the type itself. Instead, store state per request in the Items property which is accessible through context objects passed to AuthorizeAttribute.
  • See examples here

Tuesday, July 3, 2012

Generics in C#

Introduced in .NET 2.0, Generics introduced type parameters to the framework. Generics makes it possible to design classes or methods to defer the specification of types until the class or method is declared and instantiated by the client code. 



Generic types combines reusability, type safety and efficiency when compared to non-generic counterparts. Generics are frequently used with collections.

You can check if a type is of generic type using Type.IsGenericType property.


Benefits

Before generics, generalization in C# was achieved by casting types to and from Object type. But using generics you can assure type safety at compile time. 

With generics, you don't have to box unbox types as we used to do with ArrayList in .NET 1.0



Benefits of Generics

Generic type parameters ##

It is a placeholder for a specific type the client specifies when instantiating a generic type. 

Generic Classes
Encapsulate operations that are not specific to a single data type. Are commonly used with collection classes. 

Difference between Generic type and Generic type definition
  • Generic type definition : List<T>
    • T is called Generic Type Parameter
  •  Generic type : List<string> 
Constraints on generic type
https://msdn.microsoft.com/en-us/library/d5x73970.aspx

System.Collections.Generic namespace

Contains useful generic collections. 
  • Dictionary
  • LinkedList
  • List




Saturday, June 16, 2012

Tuesday, June 12, 2012

All about C Sharp

Basics
Structs and classes
Modifiers
Enums
Abstract
Interfaces
Constructors

Generics

Delegates and Events


Lambda expressions
Nullable types
Dynamic binding
Attributes

Globalization
String and text hanlding
Dates and times

Collections
LINQ
 XML
Disposal and Garbage collection
Threading
Streams and I/O
Networking
Dynamic programming
Security
Advanced threading
Parallel programming
COM
Regular expressions


Reflection
Serialization
Tips and tricks
Interesting things

http://www.amazon.com/C-5-0-Nutshell-Definitive-Reference/dp/1449320104/ref=sr_1_1?ie=UTF8&qid=1418552522&sr=8-1&keywords=c+sharp#reader_1449320104

Sunday, May 20, 2012

Federated Identity

Single Sign On (SSO) allows users to access multiple services with a single login. 

Federated Identity refers to where the user stores their credentials. Also Federated Identity can be viewed as a way to connect identity management systems together. 

Claim based Authentication
Claim based authentication for dummies (SO)
Claim based architectures
Claim based identity model 







Resources
http://security.stackexchange.com/questions/13803/what-is-single-sign-on-versus-federated-login
http://en.wikipedia.org/wiki/Federated_identity
http://en.wikipedia.org/wiki/Claims-based_identity

Saturday, April 14, 2012

HTTP Modules

HTTP module is an assembly which gets called for every request made to the application. You can use these to customize and extend ASP.NET request pipeline. HTTP Modules are similar to ISAPI filters in that they run for all requests.

ISAPI filter : Internet Server API (Read more here)

You can work on this example to see how HttpModule works.

Typical usage

  • Security : because you can examine each request, your HTTP module can perform custom authentication or other security checks before the requested page, XML Web service or handler is called
  • Statistics and logging: gather information in central place rather than on each page
  • Custom headers or footers : Because you can modify the response you can inject content 
HTTP Modules differ from HTTP handlers. While module get called for all requests and responses, Handlers run only in response to specific requests.(MSDN)

HTTP handlers
This is the process which runs in response to a request made to an ASP.NET web application. More info.

Using IHttpHandler interface, you  can write custom HTTP handlers to process specific types of HTTP requests. It provides functionality much like ISAPI filters but in a more simpler way. 

The most common HTTP handler is ASP.NET page handler which processes your request for .aspx pages. 

Also see ihttphandler vs ihttpmodule

Resources


Saturday, April 7, 2012

Introduction to RequireJS


To do modular programming you can use RequireJS. It is a JavaScript file and module loader. 
  • Loads all codes relative to a baseUrl
  • With paths config you can setup locations of a group of scripts
  • You can define modules in RequireJS in few different ways
    • Simple name/value pairs
    • Definition functions
    • Definition functions with dependencies
    • Define module as a function
    • Define a module with a name
  • Only one module should be defined per JavaScript file
  •  Normally you should not need to use require() to fetch a module, but instead rely on the module being passed in to the function as an argument.
  • You can use global function requirejs.undef() to undefine a module
  • RequireJS loads each dependency as a script tag, using head.appendChild()


loading text resources using text plugin

You can use text plugin to load text resources. 

Resources

Tuesday, January 17, 2012

Closures in JavaScript

Closures are not hard to understand once you understand the core concept behind it. You won't understand it better if you read academic papers or anything like that so lets start by looking at some examples. 

Most basic closure example

Here func1 creates local variable name and a function. the function doesn't have a local variable but reuses the variable defined in the parent function. 


In the func2 there's a slight difference. Unlike in func1 here you return the displayName function. so in the displayName function definition gets assigned to the variable myFunc. But it also alerts 'Chrome' which was not a local variable to the displayName function.

You'll see Chrome in the alert is because displayName has become a closure. Closure is a special kind of object which combines

  1. a function
  2. and the environment in which that function was created (environment consists of local variables that were in-scope at that time)
The environment consists of any local variable that were in-scope at the time that closure was created. It will be kept alive even after the function returns. In other words, whenever you see a function keyword within another function, the inner function has access to the variables in outer function. It's a stack-frame which is not de-allocated when the function returns. The local variables are not copied, they are kept by reference.



Closures in practice


Closures can be used to different things. You can emulate private methods using closures (module pattern)


Creating closures in loops


You must be careful when creating a closure inside a loop. Read more about it here at MDN article. Stackoverflow


Performance considerations

Creating closures will have some impact on the script performance from processing speed and memory consumption. When creating new object/class, methods should normally be associated to the object prototype rather than defined into the object constructor. This is because whenever constructor is called, the method will get reassigned for every object creation. (However redefining the prototype is not recommended). 

Closure vs object performance (marijnhaverbeke)

Resolving this with Closures

sources:

Thursday, January 12, 2012

MVC Framework and Application structure

ASP.NET MVC is an open source web application framework. MVC uses the ASP.NET routing engine, which provides flexibility for mapping URLs to controller classes. 

MVC does not use ASP.NET Web forms post-back model for interactions with the server. Instead, all end-user interactions are routed to a controller class. It Maintains separation between UI logic and business logic and helps testability. As a result, ASP.NET view state and ASP.NET web forms page life-cycle events are not integrated 

With MVC based views. Routes are initialized in the Application_Start method of Global.asax file


from MSDN
    Global.asax file
    • Also known as ASP.NET application file. This file is optional
    • Resides in the root directory
    • Derived from HttpApplication class

    HttpApplicationState (implements NameObjectCollectionBase)

    You can use HttpApplicationState to share global information across multiple sessions and requests. 

    A Single instance of an HttpApplicationState class is created first time a client requests any URL resource within a particular ASP.NET application virtual directory. A separate single instance is created for each ASP.NET application on Web server. Reference to each instance is then exposed via the Application object. 

    You can access this via HttpContext.Application property. (In MVC 3 like this). You can use this to store application data that does not change typically. But sometimes it is better not to use this in case you want to access data outside the ASP.NET request pipeline (see this). 

    Application state is not shared across either a Web farm or a Web garden


    Future of ASP.NET 

    In the latter versions of ASP.NET, ASP.NET MVC, ASP.NET Web API and ASP.NET Web Pages will merge into a unified MVC 6. This is also known as ASP.NET vNext. 


    Resources

    Saturday, January 7, 2012

    What you need to know about REST

    If you're in software industry you surely have heard about REST. You might not know what it actually even means but you might know its about designing an API to consume network calls.

    Representational state transfer protocol (REST) is an architectural style for designing networked application using simple* HTML protocols. REST relies on stateless, client-server architecture. You can think of it as a light weight web service. It is platform and language independent protocol.

    Difference between SOAP and REST



    Designing REST API

    APIs exposes functionality of an application or a service.




    * : I used simple with comparison to CORBA, RPC and SOAP which are bit complex to implement nowadays.

    COAP (COnstrained Application Protocol)
    Protocol intended to use in simple electronic devices that allow them to communicate over the internet. It's an application layer protocol. It uses UDP protocol (Check difference between TCP and UDP)
    http://www.slideshare.net/jvermillard/co-ap

    Sources

    Designing REST APIs
    The Increasing importance of APIs in web development 
    Web API growing trends 
    http://stackoverflow.com/questions/7551/best-practices-for-securing-a-rest-api-web-service



    last updated October 2014

    Thursday, December 22, 2011

    Access Modifiers in C#

    Access modifiers specifies access level for a type or type member. C# has 4 access modifiers,
    • public
    • protected
    • internal
    • private
     
    • Access modifiers are not allowed on namespaces. 
    • Top level types which are not nested in other types can only have internal or public accessibility. The default is internal

    public

    access modifier for types and type members. There is no restriction for accessing public members. 

    protected

    Is a member access modifier. A protected member is accessible within it's class and derived class type. 



    Since structs cannot be inherited its members cannot be protected. You can create protected classes as nested classes

    internal

    Access modifier for types and type members. Internal types or members are accessible within files of the same assembly. 

    Types or members with access modifier protected internal can be accessed within same assembly or through the types derived from containing class.

    private

    Member access modifier. Private members are accessible only within body of the class or the struct. Nested types also can access private members.

    Resources
    Access Modifiers

    Sunday, December 18, 2011

    Security in ASP.NET MVC

    Security is a major concern when developing web applications. 
    Here we'll talk about security in ASP.NET MVC

    Some of the main concepts to understand when dealing with security are,
    • Authentication
    • Authorization
    • XSS
    • CSRF (Cross site request forgery)

    Authentication

    In ASP.NET there are two main authentication mechanisms
    • Windows Authentication Provider
    • Forms Authentication Provider

    Authorization 

    Basically you can apply AuthorizeAttribute filter to actions and controllers to achieve authorization in MVC. See how to create Custom AuthroizeAttribute.

    Role based security #

    This is useful when you need to enforce policies where you have multiple users with different privileges. .NET framework role-based security supports authorization by making information about the Principal, which is constructed from an associated Identity.

    What is a principal object?

    A principal object represents the security context of the user. It includes the user's identity and the roles to which they belong. In .NET, IPrincipal defines the basic functionality of a principal object.

    Resources

    Principal and Identity objects (MSDN)
    Key security concepts (MSDN)
    Custom IIdentity or IPrincipal (SO)
    http://nipunasilva.blogspot.com/2012/07/filters-in-aspnet-mvc.html
    http://www.codeproject.com/Articles/654846/Security-In-ASP-NET-MVC 

    Wednesday, December 14, 2011

    Memory Basics : Stack and Heap

    Stack and heap are closely related with memory. Actually both are stored in computers RAM. Let's firstly look at what they are.

    The Stack

    Is a special region of the computer memory which holds temporary variables created by each function. This is managed and optimized by the CPU itself therefore you don't have to worry about allocating memory or anything as such. 

    When you enter a function the variables defined inside the function will be pushed into the stack and when you exit the function the variables will be cleared from the stack. 

    The stack is always reserved in LIFO (last in first out order). The stack is set aside for a thread. Each thread gets a stack.

     
    Understanding stack in  JavaScript (blog article)

    In JavaScript sometimes you'll encounter Maximum call stack exceeded in JavaScript error. This happens when you exceed the  call stack size in JavaScript. You can replicate this with a simple code like below



    The Heap

    Is the memory set aside for dynamic allocation. Unlike stack there is no pattern for allocation or deallocation of blocks from the heap. You must manually destroy variables on the heap. 

    Heap can have fragmentation when there are lot of allocations and deallocations happening. Heap is usually responsible for memory leaks as well. 

    In .NET unless you're building a compiler, knowing how stack and heap works is not needed much. (Stack vs. Heap in .NET - Stackoverflow).

    Resources

    Wednesday, December 7, 2011

    Interesting Findings - JavaScript

    Design

    Design considerations for JavaScript API (Smashing Magazine)
    • Fluent interfaces
      • Referred to as method chaining
    • Treating undefined as an expected value
    • Named arguments (Python has this but currently not possible in JavaScript)
    • Argument maps.
      • visual representation of the structure of an argument
    • Module Pattern Explained

    Other

    How JavaScript timers works
    Controlling Robots

    Testing

    Exception Handling 

    Here are some reference articles for Exception handling in JavaScript
    - http://eloquentjavascript.net/1st_edition/chapter5.html

    Catch JavaScript errors on server side. This way you can find more details about how your system performs in production environment. See articles.

    Debugging

    http://amasad.me/2014/03/09/lesser-known-javascript-debugging-techniques/

    Monday, November 28, 2011

    Events in JavaScript

    Events are the core of JavaScript. You use events to make the interaction between the DOM and the JavaScript. 

    Event capturing and Event bubbling

    Following diagram extracted from guistuff shows what is event capturing and bubbling are.



    Example1 - Using pure JavaScript - return false and event.stopPropogation

            var outer = document.getElementById('outer'), //Outer element
                inner = document.getElementById('inner'); //Inner element

            outer.addEventListener('click', function (event) {
                console.log('outer');
            });

            inner.addEventListener('click', function () {
                console.log('inner');

                //Without anything outer will get fired

                //event.stopPropagation(); //outer won't get fired

                //return false; //Doesn't do anything.
            });

    - When you use return false, it won't stop event from bubbling up.
    - See this google search,  this, this or this for more information.

    Event.preventDefault vs return false
    You can use either of above return statements to prevent other event handlers from executing after a certain event. 

    http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false

    document ready functions
    window.load vs document.ready


    Sources
    http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing
    http://www.quirksmode.org/js/events_order.html
    http://www.quirksmode.org/js/support.html
    http://stackoverflow.com/questions/tagged/javascript-events

    Saturday, August 27, 2011

    Transactions in Databases

    Transaction is databases is executing set of database instructions in a sequence which should be accomplished together. Transactions have following properties which are known as ACID (wiki).
    • Atomicity : Ensure all operations are completed successfully or in a failure, all operations are rolled back to its previous state
    • Consistency : Ensure database properly changes state upon a successful transaction completion
    • Isolation : Ensure transactions are operate independently 
    • Durability : Ensure result or effect of a committed  transaction persist in a case of a system failure

    Transactions in Entity Framework

    Whenever you execute SaveChanges(), the framework will wrap that operation in a transaction. Starting with EF6, Database.ExecuteSqlCommand() by default wrap the command in a transaction if one was not already present. Entity framework does not wrap queries in a transaction.

    Read below articles for more information Working with Transactions (Data Developer Center)
    Managing connections in Entity Framework (Visual Studio)
    Using Transactions or SaveChanges (SO)


    Transactions in SQL Server

    Implicit Transaction 
    http://dba.stackexchange.com/questions/43254/is-it-a-bad-practice-to-always-create-a-transaction
    http://www.codeproject.com/Articles/4451/SQL-Server-Transactions-and-Error-Handling
    http://stackoverflow.com/questions/10153648/correct-use-of-transactions-in-sql-server-2008
    http://www.tutorialspoint.com/sql/sql-transactions.htm
    http://www.dotnet-tricks.com/Tutorial/sqlserver/c2XF120412-SQL-Server-Transactions-Management.html


    SAP
    https://help.sap.com/saphelp_gateway20sp08/helpdata/en/41/7af4bca79e11d1950f0000e82de14a/frameset.htm

    Friday, August 19, 2011

    The most seamless tool set to develop applications


    Are you looking for the seamless set of tools to develop your applications? You have great languages like Java, C#. But what is the best tool set? Well, when it comes to that the obvious choice of yours would be Microsoft products. These MS products have such a nice compatibility with each other.

    Expression Blend, Visual Studio, Silverlight and .NET provide the most compelling and seamless design and development workflow on the market today. You will amazed by how easily they can be handled.

    Wednesday, August 10, 2011

    Introduction to Cloud Computing

    What is cloud computing?
    Large group of remote servers networked to allow centralize data storage and online access to computer services or resources. (Wikipedia). Cloud computing can be classified as private, public and hybrid.

    Fundamental models 

    Infrastructure as a service (IaaS)
    Provides Virtual Machines, Servers, Storage, Load balancer's etc.

    Platform as a service (PaaS)
    Typically provides execution runtime, database, web server

    Software as a service (SaaS)
    Provided access to software and databases. Cloud provider manages the infrastructure. Also known as On demand software. Usually priced pay per use. 



    Deployment models

    Private cloud
    Typically used for a single organization 


    Public cloud
    Open for public use. Technically there may not be any difference between between private and public clouds however security considerations are different. 

    Web Server, Garden and Farm

    Web Garden scales across multiple processes
    Web Farm scales across multiple servers

    Hybrid Cloud




    Some of the enterprise software companies include
    Hewlett Packed Enterprise - https://www.hpe.com/





    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