Aug 14, 2015

WinJS : JavaScript library from Microsoft


WinJS


The Windows Library for JavaScript (abbreviated as WinJS) is an open source JavaScript library developed by Microsoft. It has been designed with the primary goal to ease development of Windows Store apps for Windows 8 and Windows Phone apps for Windows Phone 8.1 and Xbox One[1] applications using HTML5 and JavaScript, as an alternative to using XAML and C#, VB.NET or C++ (CX).

What is WinJS?
WinJS is an open-source JavaScript library that can assist you in building HTML, CSS, and JavaScript applications for the Windows Store with a consistent look and performance across all Windows devices. WinJS will work in any browser and can be used as a standalone solution or with other frameworks and libraries.

What can WinJS do?
WinJS makes it possible to add Windows UI controls in HTML, such as ListView, FlipView, and Semantic Zoom, features like virtualizing collections, and high-quality infrastructure like page controls, promises, data-binding, and a template engine.

Where can I use WinJS?
Use WinJS not only for your Universal Windows apps with HTML/JS, but also for your websites, and when using HTML-based app technologies like Apache Cordova. The library consists of modules that bring JavaScript coding conventions to Windows Runtime functionality.

Node.js is a required component of building WinJS on your local machine. Presumably, by working on top of Node, WinJS is able to deal especially well with asynchronous tasks, like chat and other user interactions, within apps.

Try WinJS here.




Jul 14, 2015

Windows 10 - Global event

Windows 10


Microsoft's Windows 10 operating software is "going to transform how we use devices", the technology giant's CEO Satya Nadella said, as he announced plans for its celebratory global debut this month. 

Celebratory events marking the launch, Nadella's first major product launch since he took over as CEO in February 2014, will be held in New Delhi as well Sydney, Tokyo, Singapore, Beijing, Dubai, Nairobi, Berlin, Johannesburg, Madrid, London, Sao Paolo and New York. 

Windows 10 will be launched across the world on July 29 amid global fan celebrations, joint efforts with thousands of retailers, including all Microsoft store locations, a new global advertising campaign and a new year-long initiative to celebrate people and organisations "making a difference around the world," Microsoft said. 

Read more at:
http://economictimes.indiatimes.com/articleshow/48067152.cms?utm_source=contentofinterest&utm_medium=text&utm_campaign=cppst


Jul 2, 2015

Docker


Docker

Docker, an open-source technology, isn't just the darling of Linux powers such as Red Hat and Canonical. Proprietary software companies such as  Microsoft have also embraced Docker .


In a nutshell, here's what Docker can do for you: It can get more applications running on the same hardware than other technologies; it makes it easy for developers to quickly create, ready-to-run container applications; and it makes managing and deploying applications much easier.

Reference Links:


Jun 26, 2015

DNX - .NET Execution Environment and ASP.Net 5


DNX - .NET Execution Environment and ASP.Net 5



The .NET Execution Environment (DNX) is a software development kit (SDK) and runtime environment that has everything you need to build and run .NET applications for Windows, Mac and Linux. It provides a host process, CLR hosting logic and managed entry point discovery. DNX was built for running cross-platform ASP.NET Web applications, but it can run other types of .NET applications, too, such as cross-platform console apps.



ASP.NET 5 you gain the following foundational improvements:
·         New light-weight and modular HTTP request pipeline
·         Ability to host on IIS or self-host in your own process
·         Built on .NET Core, which supports true side-by-side app versioning
·         Ships entirely as NuGet packages
·         Integrated support for creating and using NuGet packages
·         Single aligned web stack for Web UI and Web APIs
·         Cloud-ready environment-based configuration
·         Built-in support for dependency injection
·         New tooling that simplifies modern Web development
·         Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
·         Open source and community focused

Source:

Jul 2, 2014

Windows Communication Foundation (WCF) Tools


Windows Communication Foundation Tools


Microsoft Windows Communication Foundation (WCF) tools are designed to make it easier for you to create, deploy, and manage WCF applications. You can run all the tools from the command line.

WCF Test Client (WcfTestClient.exe)
A GUI tool that allows you to input parameters of arbitrary types, submit that input to the service, and view the response the service sends back.
You can locate this tool in below location:
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

WCF Service Host (WcfSvcHost.exe)
Hosts WCF services contained in libraries (*.dll) files. WCF Service Host enumerates the services in a WCF service project, loads the project’s configuration, and instantiates a host for each service that it finds. The tool is integrated into Visual Studio through the WCF Service template and is invoked when you start to debug your project. By using WCF Service Host, you can host a WCF service (in a WCF service library project) without writing extra code or committing to a specific host during development.

Service Trace Viewer Tool (SvcTraceViewer.exe)
Helps you view, group, and filter trace messages so that you can diagnose, repair, and verify issues with WCF services.

ServiceModel Registration Tool (ServiceModelReg.exe)
Manages the registration and un-registration of ServiceModel on a single machine. This command-line tool provides the ability to manage the registration of WCF and WF components on a single machine. Under normal circumstances you should not need to use this tool as WCF and WF components are configured when installed. But if you are experiencing problems with service activation, you can try to register the components using this tool.
Examples:
ServiceModelReg.exe -ia
  Installs all components
ServiceModelReg.exe -i -c:httpnamespace -c:etw
  Installs HTTP namespace reservation and ETW manifests
ServiceModelReg.exe -u -c:etw
  Uninstalls ETW manifests
ServiceModelReg.exe -r
  Repairs an extended install


Configuration Editor Tool (SvcConfigEditor.exe)
Creates and modifies configuration settings for WCF services. The Windows Communication Foundation (WCF) Service Configuration Editor (SvcConfigEditor.exe) allows administrators and developers to create and modify configuration settings for WCF services using a graphical user interface. With this tool, you can manage settings for WCF bindings, behaviors, services, and diagnostics without having to directly edit XML configuration files. Service Configuration Editor can be found in the C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin folder.



Jul 1, 2014

Visual Studio Online


Visual Studio Online


Visual Studio Online (VSO) is a cloud based offering from Microsoft for teams that are developing software. It includes foundation services like source repository, tools for project planning and tracking and execution of build for Continuous Integration. Since Team Foundation Service (TFS) is in the cloud, teams can start working on these features without spending any time in installation and configuration.The infrastructure provisioning and maintenance required for these services is taken care of by Microsoft. 

Visual Studio Online connects to Visual Studio, Eclipse, Xcode, and other Git clients to support development for a variety of platforms and languages. Each Visual Studio Online account comes with five free users. As your team expands or your needs grow, mix and match user plans and resources to give each user what they need. Visual Studio with MSDN subscribers are free to join account projects exclusive of the included five free users.


Host your code in the cloud (Code Repository)
Host your code in the cloud to access it anytime, anywhere. Pick a traditional, centralized version control system using Team Foundation Version Control, or if you prefer a distributed approach, use Git repository. Whether you need to support a few, or a few thousand developers, host your source control in the cloud with advanced branching, merging and visualization capabilities.

Manage your work in one place (Agile Portfolio Management)
Manage your project in the cloud, too. Quickly plan, manage, and track work across all your backlogs and teams with easy-to-use, fully integrated tools for agile planning and portfolio management.

Build your applications in the cloud (Continuous Integration)
Create and manage build processes that automatically compile and test your applications in the cloud, either on demand or as part of an automated continuous integration strategy. Automate your cloud builds to run nightly or after every check-in to ensure your code builds and is ready for deployment.

Visual Studio Online Application Insights is a new cloud-based service (currently in preview) that collects rich operational, performance, and customer usage information from client/device apps or server applications – whether they run on-premises, in Microsoft Azure, a third-party cloud provider, or a combination of all three. See how your application is behaving behind the scenes and pinpoint bottlenecks with rich dashboards that allow you identify potential issues.

You can download Visual Studio online from here. 


Jun 30, 2014

IIS 8.5 Features

IIS 8.5 Features



Microsoft has released IIS 8.5 with Windows Server 2012 R2 and Windows 8.1, This version includes lot of useful features like Idle worker-Process page-out, Dynamic Site Activation, Enhanced Logging, ETW logging, and Automatic Certificate Rebind.


Idle worker-Process page-out
In IIS 8.5, the administrator has the option of suspending an idle worker process rather than terminating it. To do this, need to select desired AppPool and click on "Advanced Settings" under Process Model, select Suspend for the value of "Idle Time-out Action" to suspend a worker process when the time-out value is reached, paging it out to disk. Select Terminate to shut down the worker process. Apart from this you can enter value in minutes for "Idle Time-out(minutes)", default value is 20 minutes.

Dynamic Site Activation
In IIS 8.5, when there are a large number of configured sites (100 or greater, by default), the service will not activate any of the sites when the service is started. IIS will activate each site only when it receives the first request for the site. We can do this mentioning value for "dynamicRegistrationThreshold" under "system.applicationHost/webLimits" in "Configuration Editor" for a server in IIS.


Enhanced Logging
Administrator has the option of logging additional custom fields from request or response headers, or from server variables. Need to follow below steps to do this:
  1. Select the site or server in the Connections pane, and then double-click Logging. Note that enhanced logging is available only for site-level logging - if you select the server in the Connections pane, then the Custom Fields section of the W3C Logging Fields dialog is disabled.
  2. In the Format field under Log File, select W3C and then click Select Fields....
  3. In the W3C Logging Fields dialog, click Add Field.... Note that enhanced logging is available only for site-level logging - if you selected the server in the Connections pane, then Add Field... is disabled. 
  4. In the Add Custom Field dialog, enter a Field Name to identify the custom field within the log file. Please note that the field name cannot contain spaces.
  5. Select the Source Type. You can select Request Header, Response Header, or Server Variable (note that enhanced logging cannot log a server variable with a name that contains lower-case characters - to include a server variable in the event log just make sure that its name consists of all upper-case characters).
  6. Select Source, which is the name of the HTTP header or server variable (depending on the Source Type you selected) that contains a value that you want to log. You also can enter your own custom source string. For example, to record the custom HTTP Header "X-FORWARDED-FOR", enter that string in Source.


Event Tracing for Windows (ETW) logging
Administrator has the option of sending logging information to Event Tracing for Windows (ETW). This option gives the administrator the ability to use standard query tools, or create custom tools, for viewing real-time logging information in ETW. This provides a significant advantage over parsing text-based log files that are not updated in real time.

Instructions to install IIS 8.5 can be found here.



Jun 26, 2014

ASP.Net MVC 5

ASP.Net MVC 5


ASP.NET MVC 5 is a framework for building scalable, standards-based web applications using well-established design patterns and the power of ASP.NET and the .NET Framework.

For detailed life cycle of ASP.Net MVC 5 click here.

Main Features:
ASP.NET Identity: The MVC project templates have been updated to use ASP.NET Identity for authentication and identity management. ASP.NET MVC 5 enables users to log in using OAuth 2.0  with credentials from an external authentication provider, such as Facebook, Twitter, LinkedIn, Microsoft, or Google.

Attribute Routing: ASP.NET MVC now supports attribute routing. Attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application.
For example:
{productId:int}/{productTitle} 
Mapped to ProductsController.Show(int id)
{username} 
Mapped to ProfilesController.Show(string username)

ASP.NET Scaffolding: ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. It makes it easy to add boilerplate code to your project that interacts with a data model. In previous versions of Visual Studio, scaffolding was limited to ASP.NET MVC projects. With Visual Studio 2013, you can now use scaffolding for any ASP.NET project, including Web Forms.

Filter Override: One can now override which filters apply to a given action method or controller, by specifying an override filter. Override filters specify a set of filter types that should not run for a given scope (action or controller). This allows you to add global filters, but then exclude some from specific actions or controllers.

Bootstrap: The MVC project template has been updated to use Bootstrap to provide a sleek and responsive look and feel that you can easily customize. Bootstrap makes front-end web development faster and easier. It's made for folks of all skill levels, devices of all shapes, and projects of all sizes.

For further details about ASP.Net MVC 5 click here.

Google Web Starter Kit

Google Web Starter Kit


Google recently announced Web Starter Kit in San Francisco.  
It's a  toolkit to develop multi-device responsive boilerplate with better performance. It uses HTML5 boilerplate.

Main Features:
Responsive Layout: Responsive layout is included with the kit that adapts to fit the device your user is viewing it on. This helps you hit the ground running with an experience that looks good everywhere.
Cross-device Synchronization: Synchronize clicks, scrolls, forms and live-reload across multiple devices as you edit your project. Powered by BrowserSync.
Live Browser Reloading: Reload the browser in real-time anytime an edit is made without the need for an extension.
Built in HTTP Server: A built in server for previewing your site means you can test your pages without messing with other tools.
PageSpeed Insights Reporting: Web performance metrics showing how well your site performs on mobile and desktop.

To understand about setting up environment and building your site, click on below URL:
https://developers.google.com/web/fundamentals/tools/


Apr 28, 2014

Humanizer



Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities.
One can install Humanizer as a nuget package: 
Install-Package Humanizer

Features
  • Humanize: Humanize string extensions allow you turn an otherwise computerized string into a more readable human-friendly one.
  • Dehumanize: Much like you can humanize a computer friendly into human friendly string you can dehumanize a human friendly string into a computer friendly one
  • Transform: There is a Transform method that supersedes LetterCasing, ApplyCase and Humanize overloads that accept LetterCasing.
  • Truncate: You can truncate a string using the Truncate method
  • Humanize DateTime: You can Humanize an instance of DateTime and get back a string telling how far back or forward in time.
  • Inflector methods: There are also a few inflector methods:
    • Pluralize: Pluralize pluralizes the provided input while taking irregular and uncountable words into consideration.
    • Singularize: Singularize singularizes the provided input while taking irregular and uncountable words into consideration.
    • ToQuantity: Many times you want to call Singularize and Pluralize to prefix a word with a number; e.g. "2 requests", "3 men".
    • Ordinalize: Ordinalize turns a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
  • Number to words: Humanizer can change numbers to words using the ToWords extension



Few examples of above features:
  • "PascalCaseInputStringIsTurnedIntoSentence".Humanize() => "Pascal case input string is turned into sentence"
  • "CanReturnTitleCase".Humanize(LetterCasing.Title) => "Can Return Title Case"
  • "Pascal case input string is turned into sentence".Dehumanize() => "PascalCaseInputStringIsTurnedIntoSentence"
  • "Sentence casing".Transform(To.SentenceCase) => "Sentence casing"
  • "Long text to truncate".Truncate(10) => "Long text…"
  • "Long text to truncate".Truncate(2, Truncator.FixedNumberOfWords, TruncateFrom.Left) => "…to truncate"
  • DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
  • DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"
  • "Man".Pluralize() => "Men"
  • "Men".Singularize() => "Man"
  • "case".ToQuantity(0) => "0 cases"
  • 1.Ordinalize() => "1st"
  • 122.ToWords() => "one hundred and twenty-two"


You can download from here also.

Apr 8, 2014

WebMaker


WebMaker is a Mozilla project dedicated to helping you create something amazing on the web. Tools, events and teaching guides allow webmakers to not only create the content that makes the web great, but — perhaps more importantly — understand how the web works. With this knowledge, everyone can make a web without limits. That's the philosophy behind webmaker.org.

Few related links:

Apr 7, 2014

.Net Foundation


Microsoft announced the formation of the .NET Foundation, an independent organization created to foster open development and collaboration around the growing collection of open source technologies for .NET.  The .NET Foundation will serve as a forum for commercial and community developers alike with a set of practices and processes that strengthen the future .NET ecosystem.

The .NET Foundation will start with 24 .NET open source projects under its stewardship, including the .NET Compiler Platform (“Roslyn”) and the ASP.NET family of open source projects, as well as the MimeKit and Mailkit libraries from Xamarin.

.NET Foundation goals:

  • Open the development process for .NET: The .NET Foundation brings under a common umbrella existing and new relevant open source projects for the .NET platform, such as ASP.NET, Entity Framework and the recently released .NET Compiler Platform (“Roslyn”). The .NET Foundation will help establish this as the norm moving forward, so more and more .NET components and libraries can benefit from an open process that is transparent and welcomes participation.
  • Encourage customers, partners and the broader community to participate: The .NET Foundation will foster the involvement and direct code contributions from the community, both through its board members as well as directly from individual developers, through an open and transparent governance model that strengthens the future of .NET.
  • Promote innovation by a vibrant partner ecosystem and open source community: The .NET Foundation will encourage commercial partners and open source developers to build solutions that leverage the platform openness to provide additional innovation to .NET developers. This includes extending .NET to other platforms, extending Visual Studio to create new experiences, providing additional tools and extending the framework and libraries with new capabilities.


Apr 3, 2014

Dynamic Website Activation in IIS 8.5

Dynamic Website Activation in IIS 8.5 


Recently I heard about very interesting new feature in IIS 8.5 i.e., Dynamic Website Activation. IIS will activate all the websites which are configured in it. This means automatic activation of all the configured sites is ready to respond whenever the first request arrives. This will help in proper memory management by IIS.

Even we can set threshold level i.e, number of sites to be started at system boot-up using proper configuration. 

Source: http://www.iis.net/learn/get-started/whats-new-in-iis-85/dynamic-site-activation-in-iis85

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.