Aug 29, 2013

Overview of Design Patterns

Overview of Design Patterns

As per WIKI, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

Why do we need them?
Well, rather than having to re-invent the wheel, we can re-use an existing solution recognized across organizations as something that simply works. Since it is well documented, it is comparatively easier to solve the problem and solution in our mind.

How many are there? 
There is no definitive list of the patterns. People working on various challenges document them and spread the word about a possible solution. Over a period of time, this solution is recognized as a standard pattern for solving a particular problem. Obviously the most common patterns are the ones for Gang of Four or you can also look at Wikipedia for design patterns.

Design pattern is divided based on purpose and scope.


Purpose
Creational
Structural
Behavioural
Scope
Class
Factory Method
Adapter
Interpreter
Template Method
Object
Abstract Factory
Builder
Prototype
Singleton
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor





























Design patterns are divided into three fundamental groups.
  • Behavioral patterns are those patterns that are most specifically concerned with communication between objects.
  • All of the creational patterns deal with the best way to create instances of objects. This is important because your program should not depend on how objects are created and arranged.
  • Structural patterns describe how classes and objects can be combined to form larger structures. The difference between class patterns and object patterns is that class patterns describe how inheritance can be used to provide more useful program interfaces. Object patterns, on the other hand, describe how objects can be composed into larger structures using object composition, or the inclusion of objects within other objects. 

Each fundamental groups are further divided into multiple ways:

  Creational Patterns
  Creates an instance of several families of classes
  Builder
  Separates object construction from its representation
  Creates an instance of several derived classes
  A fully initialized instance to be copied or cloned
  A class of which only a single instance can exist

  Structural Patterns
  Adapter
  Match interfaces of different classes
  Bridge
  Separates an object’s interface from its implementation
  A tree structure of simple and composite objects
  Add responsibilities to objects dynamically
  Facade
  A single class that represents an entire subsystem
  A fine-grained instance used for efficient sharing
  Proxy
  An object representing another object

  Behavioral Patterns
  A way of passing a request between a chain of objects
  Command
  Encapsulate a command request as an object
  A way to include language elements in a program
  Sequentially access the elements of a collection
  Defines simplified communication between classes
  Memento
  Capture and restore an object's internal state
  A way of notifying change to a number of classes
  State
  Alter an object's behavior when its state changes
  Encapsulates an algorithm inside a class
  Defer the exact steps of an algorithm to a subclass
  Visitor
  Defines a new operation to a class without change


Useful websites:
GoF Patterns
DoFactory



Aug 27, 2013

Anti-Cross Site Scripting Library (AntiXSS)

Before understanding Anti-Cross Site Scripting Library (AntiXSS) let us understand Cross-Site Scripting(XSS).

Cross-site Scripting (XSS)
Cross-Site Scripting attacks are a type of injection problem, in which malicious scripts are injected into the otherwise benign and trusted web sites. Cross-site scripting (XSS) attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating or encoding it.
An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by your browser and used with that site. These scripts can even rewrite the content of the HTML page.

Cross-Site Scripting (XSS) attacks occur when:
1. Data enters a Web application through an untrusted source, most frequently a web request.
2. The data is included in dynamic content that is sent to a web user without being validated for malicious code.

The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may also include HTML, Flash or any other type of code that the browser may execute. The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to web content controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site.



AntiXSS helps you to protect your current applications from cross-site scripting attacks, at the same time helping you to protect your legacy application with its Security Runtime Engine. AntiXSS incorporates radically and innovatively rethought features, offering you a newer, more powerful weapon against the often employed cross-site scripting (XSS) attack. AntiXSS gives you:

  • Improved Performance. AntiXSS has been completely rewritten with performance in mind, and yet retains the fundamental protection from XSS attacks that you have come to rely on for your applications.
  • Secure Globalization. The web is a global market place, and cross-site scripting is a global issue. An attack can be coded anywhere, and Anti-XSS now protects against XSS attacks coded in dozens of languages.
  • Standards Compliance. AntiXSS is written to comply with modern web standards. You can protect your web application without adversely affecting its UI.


How it works?
Proper output encoding and good input validation will fix the XSS issue. For output encoding use AntiXSS Library for its comprehensive encoding capabilities. AntiXSS works by looking at all the characters in the input and encoding characters not in the whitelist.


XSS Vulnerability:
Response.Write(Request.Params["input"]);

To prevent XSS, we need to use below code (AntiXSS):
AntiXss.UrlEncode(TextBox1.Text)

AntiXss.HtmlAttributeEncode(TextBox1.Text)

AntiXss.XmlEncode(TextBox1.Text)

AntiXss.JavaScriptEncode(item)


You can download AntiXSS library from here.


Aug 26, 2013

OWIN and Katana



OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS.

An OWIN-compatible Web server is responsible for populating the environment dictionary with data such as the body streams and header collections for an HTTP request and response. It is then the responsibility of the application or framework components to populate or update the dictionary with additional values and write to the response body stream.

What is the difference between OWIN/Katana?

OWIN defines the structure and requirements of HTTP request and response interactions. The assembly codifies the definitions in the spec to allow you to avoid using type aliases in all of your files.

Katana is a flexible set of components for building and hosting OWIN-based web applications. It supports the Microsoft hosts and frameworks and provides a command line tool for running OWIN applications from the command line.

You need below components: 
Microsoft.Owin.Host.HttpListener package from NuGet. 

This is supported in Visual Studio 2012 and above.

Aug 23, 2013

Pineapple.io - website to watch

Pineapple.io

A central hub of Tutorials, Tools and Assets for developers and designers

Pineapple is a massive community-driven resource aggregator for designers and developers that strives to make it extremely EASY to find what you're looking for. When you come across a site you love, you can quickly favorite it, and have it show up on your profile for later, all neatly organized and broken down by topic with your other resources.

Features: 
  • Search by Tag
  • Scalable Categories
  • Organized Favorites
  • "Smart" Results
  • Discoverable Profiles
  • Lots of Topics like jquery,css,html5,python etc


Aug 22, 2013

Getting Browser Info in ASP.Net

Getting Browser details in ASP.Net

A Web application can access the current instance of the HttpBrowserCapabilities object using the HttpRequest.Browser property. This object is read-only, and contains properties for each capability. The HttpBrowserCapabilities object is cached and might be used again for a different request from the same type of browser.
Predefined browser definition files are stored in the %SystemRoot%\Microsoft.NET\Framework\version\CONFIG\Browsers directory. Application-level browser-definition files can be placed in the application's App_Browsers directory. In both locations, browser definition files must have a .browser file name extension.

How it works?
At run-time, browser-definition file information is merged into a collection of known browsers in a BrowserCapabilitiesFactory object. When a request is made, ASP.NET identifies the requesting browser by the request header, and compiles an HttpBrowserCapabilities object that corresponds to the type of the requested browser. This is done by starting with an empty dictionary, and applying the following recursive steps against the browser definition tree:
  1. Start at the default browser definition, which is always considered a successful match.
  2. Merge capability values specified in this browser definition into the capabilities dictionary for this browser. Values specified in a browser definition override values set in a parent.
  3. Evaluate each child definition to determine a match. For each matching child, start at step 1 again. Browser definitions are evaluated after gateway definitions. If the user agent matches more than one browser definition or more than one gateway definition, an exception is thrown at run-time.


Syntax for Browser Definition File:

<browsers>
   <browser id="browser name" parentID="parent browser name"             refID="reference ID">
       <identification>
           <userAgent match="regular expression"
                      nonMatch="regular expression" />
           <header match="regular expression"                   name="header name" nonMatch="regular expression" />
           <capability match="regular expression"            name="capability name" nonMatch="regular expression" />
       </identification>
       <capture>
           <userAgent match="regular expression" />
           <header match="regular expression" name="header name" />
           <capability match="regular expression" name="capability name" />
       </capture>
       <capabilities>
           <capability name="capability name" value="capability value" />
       </capabilities>
       <controlAdapters markupTextWriterType="type name">
           <adapter adapterType="name of adapter class" controlType="name of control class" />
       </controlAdapters>
       <sampleHeaders>
           <header name="header name" value="header value" />
       </sampleHeaders>
   </browser>
   <gateway id="gateway ID" parentID="parent browser ID">
       <!-- Same child elements as for <browser>.
       <identification></identification>
       <capture></capture>
       <capabilities></capabilities>
       <controlAdapters></controlAdapters>
       <sampleHeaders></sampleHeaders>
        -->
   </gateway>
   <defaultBrowser id="Default"  parentID="parent browser ID"
                   refID="reference ID" >
       <!-- Same child elements as for <browser>.
       <identification></identification>
       <capture></capture>
       <capabilities></capabilities>
       <controlAdapters></controlAdapters>
       <sampleHeaders></sampleHeaders>
        -->
   </defaultBrowser>
</browsers>



Sample C# code to read browser details in ASP.Net:

System.Web.HttpBrowserCapabilities browser = Request.Browser;
    string s = "Browser Capabilities\n"
        + "Type = "                    + browser.Type + "\n"
        + "Name = "                    + browser.Browser + "\n"
        + "Version = "                 + browser.Version + "\n"
        + "Major Version = "           + browser.MajorVersion + "\n"
        + "Minor Version = "           + browser.MinorVersion + "\n"
        + "Platform = "                + browser.Platform + "\n"
        + "Is Beta = "                 + browser.Beta + "\n"
        + "Is Crawler = "              + browser.Crawler + "\n"
        + "Is AOL = "                  + browser.AOL + "\n"
        + "Is Win16 = "                + browser.Win16 + "\n"
        + "Is Win32 = "                + browser.Win32 + "\n"
        + "Supports Frames = "         + browser.Frames + "\n"
        + "Supports Tables = "         + browser.Tables + "\n"
        + "Supports Cookies = "        + browser.Cookies + "\n"
        + "Supports VBScript = "       + browser.VBScript + "\n"
        + "Supports JavaScript = "     + 
            browser.EcmaScriptVersion.ToString() + "\n"
        + "Supports Java Applets = "   + browser.JavaApplets + "\n"
        + "Supports ActiveX Controls = " + browser.ActiveXControls 
              + "\n"
        + "Supports JavaScript Version = " +
            browser["JavaScriptVersion"] + "\n";

For more information refer below link:
http://msdn.microsoft.com/en-us/library/vstudio/ms228122(v=vs.100).aspx



Difference between Web Application and Web Site Projects


In Visual Studio we can create Web application projects or web site projects. We create or open a web application project by choosing New Project or Open Project in the Visual Studio File menu. We create or open a web site project by choosing New Web Site or Open Web Site in the File menu. It’s best to choose the right type before we create a web project, because it can be time-consuming, difficult, and error-prone to convert from one type to the other.

Scenarios

Scenarios in which web application projects are the preferred choice include the following:
  • We want to be able to use the Edit and Continue feature of the Visual Studio debugger.
  • We want to run unit tests on code that is in the class files that are associated with ASP.NET pages.
  • We want to refer to the classes that are associated with pages and user controls from standalone classes.
  • We want to establish project dependencies between multiple web projects.
  • We want the compiler to create a single assembly for the entire site.
  • We want control over the assembly name and version number that is generated for the site.
  • We want to use MSBuild or Team Build to compile the project. For example, we might want to add prebuild and postbuild steps.
  • We want to avoid putting source code on a production server.
Scenarios in which Web site projects are the preferred choice include the following:
  • We want to include both C# and Visual Basic code in a single web project. (By default, a web application is compiled based on language settings in the project file. Exceptions can be made, but it is relatively difficult.)
  • We want to open the production site in Visual Studio and update it in real time by using FTP.
  • We do not want to have to explicitly compile the project in order to deploy it.
  • If we do precompile the site, we want the compiler to create multiple assemblies for the site, which can include one assembly per page or user control, or one or more assemblies per folder.
  • We want to be able to update individual files in production by just copying new versions to the production server, or by editing the files directly on the production server.
  • If we precompile the site, we want to be able to update individual ASP.NET web pages (.aspx files) without having to recompile the entire site.
  • We like to keep your source code on the production server because it can serve as an additional backup copy.

Summary of Differences

The following table summarizes the main differences.
Area
Web application projects
Web site projects
Project file structure
A Visual Studio project file (.csproj or .vbproj) stores information about the project, such as the list of files that are included in the project, and any project-to-project references.
There is no project file (.csproj or .vbproj). All the files in a folder structure are automatically included in the site.
Compilation
  • We explicitly compile the source code on the computer that is used for development or source control.
  • By default, compilation of code files (excluding .aspx and .ascx files) produces a single assembly.
  • The source code is typically compiled dynamically (automatically) by ASP.NET on the server the first time a request is received after the site has been installed or updated.
We can precompile the site (compile in advance on a development computer or on the server).
  • By default, compilation produces multiple assemblies.
Namespaces
Explicit namespaces are added to pages, controls, and classes by default.
Explicit namespaces are not added to pages, controls, and classes by default, but we can add them manually.
Deployment
  • We copy the assembly to a server. The assembly is produced by compiling the application.
  • Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.
  • We copy the application source files to a computer that has IIS installed on it.
  • If we precompile the site on a development computer, we copy the assemblies produced by compilation to the IIS server.
  • Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.


Project File Structure
Web application projects use Visual Studio project files (.csproj or .vbproj) to keep track of information about the project. This makes it possible to specify which files are included in or excluded from the project, and therefore which files are compiled during a build.
For web site projects, all files in a folder structure are automatically considered to be included in the web site. If we want to exclude something from compilation, we must remove the file from the web site project folder or change its file-name extension to an extension that is not compiled and is not served by IIS.
An advantage of using project files in web application projects is the following:
  • It is easy to temporarily remove files from the site but still make sure that we do not lose track of them, because they remain in the folder structure. For example, if a page is not ready to be deployed, we can temporarily exclude it from the build without deleting it from the folder structure. We can deploy the compiled assembly, and then include the file in the project again. This is especially important if we are working with a source control repository.
An advantage of using folder structure without project files in Web site projects is the following:
  • We do not have to manage the project's structure exclusively in Visual Studio. For example, we can copy files into the project or delete them from the project by using File Explorer.

Compilation
For web application projects, we typically build the project in Visual Studio or by using the ASP.NET batch compiler on a computer that is not the production IIS server. All code-behind class files and standalone class files in the project are compiled into a single assembly, which is then put in the web application project's Bin folder. (The .aspx and .ascx files are compiled dynamically in a manner similar to what is done for web site projects.)
For web site projects, we do not have to manually compile the project. web site projects are typically compiled dynamically by ASP.NET (on both the development computer and the production IIS server). We can choose between batch compilation mode, which typically produces one assembly per folder, and fixed compilation mode, which typically produces one assembly for each page or user control.
Advantages of the compilation model for web application projects include the following:
  • We can use MSBuild to create a custom batch-compilation process.
  • It is easy to specify assembly attributes such as name and version.
  • Compiling in advance makes sure that users do not have to wait while the site compiles on the production server. (If the site is very large, dynamic compilation of a web site project might take a noticeable amount of time. Dynamic compilation occurs when a request for a site resource is received after an update to the site, and the request that triggers compilation might be delayed while the required resources are compiled. If the delay is unacceptable, we can precompile the site. However, then some of the advantages of dynamic compilation are lost.)
  • We have complete control over where we put code files in the project folder structure, and how we how classes in the project refer to each other. (Dynamic compilation requires that the source code for any classes that are used throughout the site must be in the App_Code folder. We cannot refer to a page or user control class from a class in App_Code.)
Advantages of the compilation model for Web site projects include the following:
  • We can test specific pages regardless of the state of other pages. This is because running an individual page does not require that the whole site compile successfully, only the page and any components it depends on, such as code in the App_Code folder or the Global.asax file. (In a web application project, if there are compilation errors anywhere in the site, we cannot create the assembly and therefore cannot test even the pieces of the site that compile.)
  • It is easy to update a Web site in production. We can update individual source code files on the production server without having to explicitly recompile the site. We can update individual files that are ready for deployment even if other files are not ready due to compile errors. We can also open the Web site on the production IIS server directly in Visual Studio and update the Web site in real time.
  • Precompiling to multiple assemblies can have a performance advantage in some scenarios. A typical example is a site that has many pages with lots of code written for them. Most of the pages are rarely requested and only some are used frequently. If we compile a site like this into multiple assemblies, the production server can load only the assemblies that are required for the current requests. If a page is not requested, its corresponding assembly is not loaded.