Dec 9, 2013

LESS CSS - Dynamic Stylesheet



LESS is a dynamic stylesheet language.


LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.

LESS runs on both the server-side (with Node.js and Rhino) or client-side (modern browsers only).

You can download LESS file(s) from here.


Repetition of information: In CSS, we often repeat color calues or height values in multiple places. One can eliminate these kind of issues using LESS.

Variables

Variables allow you to specify widely used values in a single place, and then re-use them throughout the style sheet, making global changes as easy as changing one line of code.

Example:

/* Compiled CSS */
#header {
  color: #4D926F;
}
h2 {
  color: #4D926F;
}

 // LESS
@color: #4D926F;

#header {
  color: @color;
}
h2 {
  color: @color;
}

Mixins


Mixins allow you to embed all the properties of a class into another class by simply including the class name as one of its properties. It’s just like variables, but for whole classes. Mixins can also behave like functions, and take arguments, as seen in the example below.

Example:

/* Compiled CSS */
#header {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -ms-border-radius: 5px;
  -o-border-radius: 5px;
  border-radius: 5px;
}
#footer {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -ms-border-radius: 10px;
  -o-border-radius: 10px;
  border-radius: 10px;
}


// LESS
.rounded-corners (@radius: 5px) {
  -webkit-border-radius: @radius;
  -moz-border-radius: @radius;
  -ms-border-radius: @radius;
  -o-border-radius: @radius;
  border-radius: @radius;
}

#header {
  .rounded-corners;
}
#footer {
  .rounded-corners(10px);
}


Functions & Operations


Are some elements in your style sheet proportional to other elements? Operations let you add, subtract, divide and multiply property values and colors, giving you the power to create complex relationships between properties. Operations should only be performed within parentheses in order to ensure compatibility with CSS. Functions map one-to-one with JavaScript code, allowing you to manipulate values however you want.

Example:

/* Compiled CSS */
#header {
  color: #333;
  border-left: 1px;
  border-right: 2px;
}
#footer {
  color: #114411;
  border-color: #7d2717;
}

// LESS
@the-border: 1px;
@base-color: #111;
@red:        #842210;

#header {
  color: (@base-color * 3);
  border-left: @the-border;
  border-right: (@the-border * 2);
}
#footer {
  color: (@base-color + #003300);
  border-color: desaturate(@red, 10%);
}

Setting up LESS in ASP.NET MVC
One can use below sample code to call LESS-CSS code.
<link content="" href="@Url.Content(" less="" mysite.less="" rel="stylesheet/less" type="text/css"></link>
<script content="" less-1.3.3.min.js="" scripts="" src="@Url.Content(" type="text/javascript"></script>

Nov 28, 2013

Curah!

Curah!

Microsoft developed Curah! as a way to help customers/developers discover great technical content. Curah! has a very specific purpose: to help people searching in Bing or Google find annotated collections of great content that specifically target common user questions. 

Curah! is a simple and fun way to help others find great content on the internet. It is a curation service that enables you to share your expertise with others, collecting the sources that are truly helpful, accurate and trustworthy, and adding your own notes and guidance.

Nov 12, 2013

Reading application details using PowerShell

Windows PowerShell

Windows PowerShell is a task-based command-line shell and scripting language designed especially for system administration. In simple, it is task automation and configuartion management framework. 

It helps IT professionals and power users control and automate the administration of the Windows operating system and applications like IIS etc that run on Windows with the help of Windows Management Instrumentation(WMI).

PowerShell can be downloaded from here.

PowerShell commands are called cmdlets. It lets you executes commands over command-prompt or Integrated Scripting Environment (ISE). Detailed list of cmdlets are available here

Below example displays list of applications and directories under given Application Pool.


Import-Module WebAdministration

function Get-WebAppPoolApplications($webAppPoolName) {
    $result = @()

    $webAppPool = Get-Item ( Join-Path 'IIS:\AppPools' $webAppPoolName )
    if ( $webAppPool -ne $null ) {
        
        #For all web sites
        #$webSites = Get-ChildItem 'IIS:\Sites'
        
        #For only 'Default Web Site'
        $webSites = Get-ChildItem 'IIS:\Sites' | where { $_.Name -eq 'Default Web Site' }
        
        $webSites | % {
            $webApplications = Get-ChildItem ( Join-Path 'IIS:\Sites' $_.Name ) |
                where { $_.NodeType -eq 'application' }

            $webFolders = Get-ChildItem ( Join-Path 'IIS:\Sites' $_.Name ) |
                   where { $_.NodeType -eq 'directory' }
            
                            
            $result += $webApplications |
                where { $_.applicationPool -eq $webAppPoolName }
                
             $result += $webFolders
                
        }
    }
    #Export to CSV file
    #$result | export-csv "list.csv"
    $result
}
Get-WebAppPoolApplications('ASP.NET V2.0')

WebAdministration: Importing a web administration module. It lets you access IIS app pools and using few commands we will be able to get information about IIS. Above example works only with IIS 7.

Sep 13, 2013

Google Book Downloader


Google Book Search is a tool from Google that searches the full text of books that Google scans, converts to text using optical character recognition, and stores in its digital database. Many popular books are available with Google Book. The books available can be read online only and cannot be downloaded for later use. You can download certain books as png that allows public-domain works and are free from copyright protection. Only few books are available with full preview based on agreements with publishers. 

Google Books Downloader Lite is a free, open-source utility that lets out download any book that's available in "full view" from Google Books. Of course, most of these books also feature download links right on the web page, but Google Books Downloader lets you queue up multiple jobs and convert all of the downloaded books to PNG files. 

You can download this tool from here. Need to install .Net Framework 3.5 SP1 before installing this tool. 

Sep 10, 2013

Interactive Extensions


LINQ provides lot of ways to query the objects or XML. But we might need some more features\extensions which will be handy in real development. Let us explore a library which provides more extensions\features to the existing framework.


Introduction

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences (provides notification information) and LINQ-style query operators.

The Interactive Extensions (Ix) is a .NET library which extends LINQ to Objects to provide many of the operators available in Rx but targeted for IEnumerable. In simple terms, it provides a lot of new features to LINQ to Object which is not available in Framework. Ix is sub-set of Rx.

This will install System.Interactive.dll file. EnumerableEx class provides a set of additional static methods that allow querying enumerable sequences.


Execute below command in Nuget Package Manager Console to install:
install-package Ix-Main


Let us discuss few features:

Do: This lazily invokes an action for each value in the sequence. That means it invokes\executes an action for each value in enumeration.


Sample Code:
static void Main(string[] args)
{
      DisplayNumbersDo();
}
static void DisplayNumbersDo()
{

      int addnumber = 10;
      //Let us create a set of numbers 
      var numbers = new int[] { 6, 1, 4, 2, 6 };

      var result = numbers.Do(n => Console.WriteLine(n + addnumber));
      Console.WriteLine("Before Enumeration");
      foreach (var item in result)
      {
          //The action will be invoked when we actually enumerate 
      }
      Console.WriteLine("After Enumeration");
      Console.ReadLine();
}


ForEach: Enumerates the sequence and invokes the given action for each value in the sequence.

Sample Code:
static void Main(string[] args) { List names = new List { "ram", "nagesh" }; names.ForEach(s => Console.WriteLine(s)); ; Console.ReadLine(); }


Scan: Generates a sequence of accumulated values by scanning the source sequence and applying an accumulator function. 

Sample Code:
static void Main(string[] args) { List names = new List { "ram ", "nagesh" }; names.Scan((x,y) => x + y).ForEach(s => Console.WriteLine(s)); Console.ReadLine(); }



Below are few more methods which might be useful:

Repeat: Repeats and concatenates the source sequence infinitely.

SkipLast: Bypasses a specified number of contiguous elements from the end of the sequence and returns the remaining elements.

TakeLast: Returns a specified number of contiguous elements from the end of the sequence.


You can install Interactive Extensions in Visual Studio 2010 also.





Sep 5, 2013

Code Contracts

Code Contracts

Code Contracts are static library methods used from any .NET program to specify the code’s behavior. Runtime checking and static checking tools are both provided for taking advantage of contracts. Code Contracts is a subset of a larger Microsoft Research Project called Spec# (pronounced "Spec Sharp"). 

In simple, its add-on that you can install in Visual Studio. This library offers number of attributes and helper classes to perform various validations/conditions at various levels.

You can download add-on from here

After installing make sure you have "Code Contracts" tab in project properties.


Make changes to project properties as below:



Add Using statement as below:
using System.Diagnostics.Contracts;


Preconditions:
Preconditions are those which needs to be executed at the beginning of the method. They generally used to validate parameter values like object is not null, Argument null exception, int > 0 etc.

Normal precondition looks like this:

public static int GetEmployeeCount(int intDeptId)   {
         if (intDeptId == 0)
           throw new Exception("Invalid Department Id");
            
        //logic here
        return 10;
}

We can write the same code in a better way as below:


public static int GetEmployeeCount(int intDeptId)   {        Contract.Requires(intDeptId > 0);
       //logic here
       return 10; }




Static Checking:
Instead of raising exception after callign method, it would be much easier if we can raise exception at the time of calling method. This is static checking. For this, you need to enable "Show squigglies" option in Project properties.

Code:
public static int GetEmployeeCount(int intDeptId)
  {
      Contract.Requires(intDeptId != 0,
             "Zero is not allowed for Department Id.");
      //logic here
      return intDeptId;
}

While performing static checking, error message will be shown as below:



Post-Condition:
These conditions are nothing but validations after executing a method. These are very useful in case of validation objects, dataset from database, etc. You have option to save old values in OldValue before calling method.
In below example, we are ensuring the output of the GetEmployeeCount is greated than 5.

Code:

Contract.Ensures(Dept.GetEmployeeCount(5) > 0);


Interface Contracts:
We can write contracts for interface methods required creating contract class to hold them.

We can use below attributes:
ContractClass: Need to defined for Interface. Ex: [ContractClass(typeof(IDeptContract))]

ContractClassFor: Need to defined for class implements interface. Ex: [ContractClassFor(typeof(IDept))]

Conclusion:
Code Contracts will be very useful, if we can use it in a proper manner and follow some guidelines. This can be used in Business Layer for validating objects before passing it to Data Layer. This will reduce lines of code and errors/mistakes while writing validation logic.

For complete documentation, please refer this link



Sep 3, 2013

Performance Tuning Techniques - ASP.Net


Performance Tuning Techniques in ASP.Net

Below presentation provides few performance tuning techniques related to ASP.Net.

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