About singleconcept

I am Aneesh Sivan a software developer from India. The reason behind my blog is very simple. As the part of my work there are many situations to search in net to find how to do a task, If I got a proper solution then it will implement on my project as well as put it my blog as a new post under the corresponding category. Here I use my blog "single concept" is a repository of such types of information scraps. I welcome you all to my blog.

Tracing and Logging web service request in ASP.Net

This topic describes how to enable tracing and message logging in Web services built with ASP.NET. Enable tracing to identify how to increase performance and stability as well as increasing the ability to troubleshoot Web service issues. Tracing is only enabled when the application is fully trusted. Enable logging to log all the requests, which are posted to the endpoint.
For enabling the logging and tracing we need to make some configuration in application WEB.Config file and also need to ensure the permission of folder, that we specified in tag.
Configurations are given below:

<configuration>
<system.serviceModel>
  <diagnostics>
    <messageLogging 
         logEntireMessage="true" 
         logMalformedMessages="true"
         logMessagesAtServiceLevel="true" 
         logMessagesAtTransportLevel="false"
         maxMessagesToLog="3000"
         maxSizeOfMessageToLog="20000"/>
  </diagnostics>
</system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelMessageLoggingListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
      <source propagateActivity="true" name="System.ServiceModel" switchValue="Warning,ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelTraceListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="C:\Messagelog\app_messages.svclog"
          type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
          name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
        <filter type="" />
      </add>
      <add initializeData="C:\Messagelog\app_tracelog.svclog"
          type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
         name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
        <filter type="" />
      </add>
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>
</configuration>

Clickjacking, Forgery and Phishing

CLICKJACKING

Clickjacking (User Interface redress attack, UI redress attack, UI redressing) is a malicious technique of tricking a Web user into clicking on something different from what the user perceives they are clicking on, thus potentially revealing confidential information or Black-Hat-Hackerstaking control of their computer while clicking on seemingly innocuous web pages. A clickjack takes the form of embedded code or a script that can execute without the user’s knowledge, such as clicking on a button that appears to perform another function.

How clickjacking works:
A user searches for a website, for eg: Amazon.com. The listed URL may contains some dummy URL. Once the user clicks on this URL the hacker opens the actual www. Amazon.com in an iFrame. And hence the user is tricked into believing that it is the actual site. Here he clicks on any button for eg: Submit Bank Details. This button will be masked by an invisible button which will redirect the user to the hackers web page and the user will unknowingly type in all the details and this will be captured by the hacker.

Proposed Fix:
To fix this issue execute a set of code which will check if the URL in the iFrame is same as the URL on the browser i.e self==top. If yes, then continue else the URL in the iFrame will replace the browser URL and hence the user will be redirected to the authentic website.
First apply an ID to the style element itself:

<style id="antiClickjack">body{display:none !important;}</style>

And then delete that style by its ID immediately after in the script:

if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}

Cross-site request FORGERY(CSRF)

Cross-site request forgery abbreviated as CSRF (sometimes pronounced sea-surf) or XSRF, is a type of malicious exploit, ie CSRF is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker’s choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

How CSRF works:
A simple example is, if a bank for eg: bank.com uses the below URL for transferring money to a particular user named ABC.

 http://bank.com/transfer.do?acct=ABC&amount=100000

A hacker can send an html email with the below link as some promotional campaign,

 <a href="“http://bank.com/transfer.do?acct=ABC&amount=100000"">View my Pictures!</a>

Once the user unknowingly clicks on this link, the amount gets transferred.

Proposed Fix:

  • Include a hidden form field on all forms of your site which are required when a user is logged in.
  • Include this form field or token value in the users session variables, so that they have a copy.
  • After every POST or GET evaluation you want to protect, make sure that the token from the browser (session) matches the token from the form (GET/POST value) If they do not match, then the page may have been submitted fraudulently (XSRF)
  • The token may be generated new for each form and stored server side or in a database.

PHISHING referrer trust

In phishing attacks, a hacker creates a website that resembles a victim web’s application. The fake website often reuses pages and images from the original website to seem authentic. Pages from the original site may be embedded in frames in the phishing site. The fake website can thus capture form information sent by users and forward the data to the authentic website.

How Phishing referrer trust works:
The HTTP Referrer field is a browser-passed value in an HTTP header meant to provide a basic means for logging and tracking the origin of HTTP requests. Web servers can be configured to allow requests originating only from specific sites based on the HTTP Referrer field. Some sites use the values of this variable as a part of their access-control measures. Check for HTTP Referrer allows a web server to add a barrier for attacks such as Cross-Site Request Forgery (CSRF).

Proposed Fix:
Always check for difference between the referrer domain and the current domain. If it is different, the user will be redirected to access denied page.

Reliable Messaging with MSMQ and .NET

MSMQ stands for Microsoft Message Queuing is one of the most reliable way to sending and receiving messages from one system to another system; both system can be located at different geographical locations. The benefit of MSMQ is that the receiving application doesn’t have to run at the time of sending the message. Messages are stored in the queue of the system (Microsoft Operating System) and once the receiving application runs, it starts peeking the messages one by one.

To perform a task asynchronously is to execute it without waiting for a result. This type of processing allows we to start a time-consuming process and continue working without having to wait for that process to finish executing.
Asynchronous processing is ideal to use in many situations—especially on the Web, where a user’s request could take a long time to process, but we want to provide a response back to the user immediately. By handling the user’s request asynchronously, our system can respond regardless of how long that request may actually take to execute.

To install Message Queuing 4.0 on Windows Server 2008 or Windows Server 2008 R2

In Server Manager, click Features.
In the right-hand pane under Features Summary, click Add Features.
In the resulting window, expand Message Queuing.
Expand Message Queuing Services.
Click Directory Services Integration (for computers joined to a Domain), then click HTTP Support.
Click Next, then click Install.

To install Message Queuing 4.0 on Windows 7 or Windows Vista

Open Control Panel.
Click Programs and then, under Programs and Features, click Turn Windows Features on and off.
Expand Microsoft Message Queue (MSMQ) Server, expand Microsoft Message Queue (MSMQ) Server Core, and then select the check boxes for the following Message Queuing features to install:
MSMQ Active Directory Domain Services Integration (for computers joined to a Domain).
MSMQ HTTP Support.
Click OK.
If we are prompted to restart the computer, click OK to complete the installation.

To install Message Queuing 3.0 on Windows XP and Windows Server 2003

Open Control Panel.
Click Add Remove Programs and then click Add Windows Components.
Select Message Queuing and click Details.
System_CAPS_noteNote
If we are running Windows Server 2003, select Application Server to access Message Queuing.
Ensure that the option MSMQ HTTP Support is selected on the details page.
Click OK to exit the details page, and then click Next. Complete the installation.
If we are prompted to restart the computer, click OK to complete the installation.

To Check MSMQ interface:
My Computer -> Manage -> Services and Applications -> Message Queueing.

There are two types of Messaging Queue:
1. Public Queue:
Provide Message routing.
Public queues are accessed through “Machine nameQueue name”
2. Private Queue:
Do not Provide any routing.
Private queues are accessed through “Machine namePrivate$Queue name”.
If MSMQ is installed on the same machine as our application then we can replace the machine name with a dot, for example “.Private$testQue”

Creating a Queue in the system
Creating a queue in the system is an easy task. Go to My Computer and right click, select Manage and explore the nodes as displayed in the picture below.
IC163748
Right click the Private Queues and select New > Priovate Queue and create a queue. Alternatively, this can be done using C# code as well. My code snippet below does that automatically (ie. if queue doesn’t exists, it creates otherwise use the existing one).

Creating Queues Programmatically
Although the MSMQ interface is available for creating, deleting, and exploring message queues, we can also work with queues through the System.Messaging namespace. Several static methods (meaning we can call them without creating an actual instance of the class) have been provided on the MessageQueue class that give we the ability to check if a queue exists (Exists), create a queue (Create), and delete a queue (Delete). Using these methods, our application can check for the existence of a queue, and create it automatically if it does not exist. The function, GetQ, listed next provides the exact functionality just described:

 if (MessageQueue.Exists(@".\Private$\MyQueue"))
 {
     myQueue = new MessageQueue(@".\Private$\MyQueue");
 }
 else
 {
     myQueue = MessageQueue.Create(@".\Private$\MyQueue");
 }
Delete
 MessageQueue.Delete(@".\Private$\MyQueue")

Now, let’s send a message to the MSMQ
The following code example shows how to  send a message, setting a few options including formatting and encryption before using the MessageQueue object’s Send method with the preconfigured Message object:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MessageSender
{
    class Program
    {
        static void Main(string[] args)
        {
            do
            {
                Console.WriteLine("Enter Message to be send");
                Console.WriteLine("High Priority Message should be start with HP:");
                string text = Console.ReadLine();

                MessageQueue myQueue;

                if (MessageQueue.Exists(@".\Private$\MyQueue"))
                {
                    myQueue = new MessageQueue(@".\Private$\MyQueue");
                }
                else
                {
                    myQueue = MessageQueue.Create(@".\Private$\MyQueue");
                }
                Message message = new System.Messaging.Message();
                message.Formatter = new BinaryMessageFormatter();
                message.Body = text;
                message.Label = "myTestMessage";

                if (text.Contains("HP:")) { message.Priority = MessagePriority.High; }
                else { message.Priority = MessagePriority.Normal; }
                myQueue.Send(message);
                Console.WriteLine("Message has sent");
            } while (Console.ReadKey().Key != ConsoleKey.Q);
        }
    }
}

One of the key message options we may wish to specify controls how the message is serialized for sending. By default, this is set to use XMLMessageFormatter, which serializes objects into an XML representation and is suitable for most purposes. Two other formatters are available, however: the BinaryMessageFormatter and ActiveXMessageFormatter, both of which serialize objects into a binary (not human-readable like XML) format.

Receiving messages from MSMQ
To receive a message from queue, we need to first instantiate the queue using MessageQueue. we will need to make sure that the queue exists, otherwise we shall get an error.
Once we have placed messages onto our queue, someone will likely wish to retrieve those messages, taking the data off the queue in the order in which it was added. To obtain a message from the queue, and then retrieve the data it contains, requires a few important steps:

* First, as with sending a message, obtain a MessageQueue object pointing at the       appropriate queue:
var myQueue = new MessageQueue(@”.\Private$\MyQueue”);
* Next, use the Receive method of the queue to obtain the first message from the queue:
Message message = myQueue.Receive();
* Then, if we are using the XML formatter (the default), set up the formatter of the Message object with a list of possible data types that might be contained in the message. In this case, we are expecting only one possible data type, String:
Message message = myQueue.Receive();
message.Formatter = new BinaryMessageFormatter();
* Finally, use the Body property to retrieve our data, casting it into the appropriate type:
Console.WriteLine(message.Body.ToString())

With large messages and slow network links in mind, the MessageQueue object provides an asynchronous way to receive messages in addition to the Receive method. To receive a message asynchronously, we proceed as before and obtain a reference to the appropriate queue, and then, instead of calling Receive, we will call BeginReceive (specifying a time-out if desired). This starts the receive process, and execution will continue immediately with the next line of code.
When a message has been successfully retrieved,and the MessageQueue object’s ReceiveCompleted event will fire and our event handler will be called. The retrieved message is sent to our event handler as part of one of its parameters, and we can use that object to retrieve the actual data as usual.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MessageReceiver
{
    class Program
    {
        private static MessageQueue myQueue = null;
        private static object lockObject = new object();

        static void Main(string[] args)
        {
            Console.WriteLine("Received Messages");

            myQueue = new MessageQueue(@".\Private$\MyQueue");
            // Setup an event to listen for new messages.
            myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);

            // Start listening.
            myQueue.BeginReceive();
            /*Message message = myQueue.Receive();
            message.Formatter = new BinaryMessageFormatter();
            Console.WriteLine(message.Body.ToString());*/
            while (Console.ReadKey().Key != ConsoleKey.Q)
            {
                // Press q to exit.
            }
        }


        static void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            lock (lockObject)
            {
                // The message is plain text.
                e.Message.Formatter = new BinaryMessageFormatter();
                string text = (string)e.Message.Body;
                Console.WriteLine("Message received: " + text);
            }

            // Listen for the next message.
            myQueue.BeginReceive();
        }
    }
}

tutorial: https://www.youtube.com/watch?v=ZHiu81Gqb_o

Browser Definition File

Browser definition files contain definitions for individual browsers. At run time, ASP.NET uses the information in the request header to determine what type of browser has made the request. Then ASP.NET uses browser files to determine the capabilities of the browser, and how to render markup to that browser. This is useful to Web developers who want to create applications that can be viewed on mobile devices, making use of control adapters that adapt the behavior of an ASP.NET Web server control depending on the type of device.

Note:
Browser definition files are new in the .NET Framework version 2.0. 
In earlier versions of the .NET Framework, the browserCaps element was used to define browser definitions in configuration files.

ASP.NET fails to detect IE10+ causing _doPostBack is undefined JavaScript error or maintain FF5 scrollbar positionimage_3
There is a bug in the browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10+) aren’t within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

We can fix this problem by updating Browser Definition File, One of the simplest way to update the Browser Definition File is just install the latest Frame Work version to the hosted server

Author : Rony T Sam

Internet Explorer 11: “Don’t call me IE”

internet-ExplorerWith Internet Explorer 11, you get better compatibility with web standards, other browsers, and real-world websites. There’s updated support for popular web standards and changes that prevent older websites from displaying incorrectly.
For the first time in a long time, Microsoft has actually removed features from Internet Explorer. The user-agent string has also changed. It seems that Microsoft has gone out of their way to ensure that all existing isIE() code branches, whether in JavaScript or on the server, will return false for Internet Explorer 11. The optimistic view of this change is that Internet Explorer 11 finally supports enough web standards such that existing IE-specific behavior is no longer needed.

User-agent changes
The user-agent string for Internet Explorer 11 is shorter than previous versions and has some interesting changes.

IE 11 user-agent string:
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko
IE 10 user-agent string (on Windows 7):
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)

The compatible ("compatible") and browser ("MSIE") tokens have been removed.
The "like Gecko" token has been added (for consistency with other browsers).
The version of the browser is now reported by a new revision ("rv") token.

The most glaring difference is the removal of the “MSIE” token, which has been part of the Internet Explorer user-agent from the beginning. Also noticeable is the addition of “like Gecko” at the end. This suggests that Internet Explorer would prefer to be identified as a Gecko-type browser if it’s not identified as itself. Safari was the first browser to add “like Gecko” so that anyone sniffing for “Gecko” in the user-agent string would allow the browser through.

Any sniffing code that looks for “MSIE” now will not work with the new user-agent string. You can still search for “Trident” to identify that it’s Internet Explorer (the “Trident” token was introduced with Internet Explorer 9). The true Internet Explorer version now comes via the “rv” token.

Legacy API additions, changes, and removals
Many websites look for browsers that support legacy (HTML4) features in order serve experiences optimized for earlier browsers. This can be a problem for browsers that support legacy features and modern standards, such as HTML5, CSS3, and so on. If a site detects legacy features before searching for modern standard support, it can serve legacy experiences to browsers that support modern standards and richer experiences.
As a result, IE11 adds, changes, and removes a number of legacy features by default:

=> The navigator.appName property now returns “Netscape” to reflect the HTML5 standard and to match behavior of other browsers.
=> The navigator.product property now returns “Gecko” in order to reflect the HTML5 standard and to match behavior of other browsers.
(This may seem like a sneaky attempt to trick developers, but this behavior is actually specified in HTML5. The navigator.product property must be “Gecko” and navigator.appName should be either “Netscape” or something more specific. Strange recommendations, but Internet Explorer 11 follows them. The side effect of these navigator changes is that JavaScript-based logic for browser detection may end up using these and will end up identifying Internet Explorer 11 as a Gecko-based browser)
=> The XDomainRequest object is replaced by CORS for XMLHttpRequest.
=> Supported for __proto__ has been added.
=> The dataset property has been added.
In addition, several legacy API features have been removed in favor of features specified by modern standards:

Removed API feature                   Replacement feature
============================================================
attachEvent                                     addEventListener
——————————————————————————————————-
window.execScript                           eval
——————————————————————————————————-
window.doScroll                               window.scrollLeft, window.scrollTop
——————————————————————————————————-
document.all                                    document.getElementById
——————————————————————————————————-
document.fileSize, img.fileSize         Use XMLHttpRequest to fetch the  source
——————————————————————————————————-
script.onreadystatechange              script.onload
& script.readyState
——————————————————————————————————-
document.selection                         window.getSelection
——————————————————————————————————-
document.createStyleSheet            dcument.createElement (“style”)                                                                               style.styleSheet style.sheet
——————————————————————————————————-
window.createPopup                       Use div or iframe with a high zIndex value
——————————————————————————————————-
Binary behaviors                             Varies; use a standards-based                                                                                equivalent,ie canvas, SVG, or CSS3                                                                        Animations
——————————————————————————————————-
Legacy data binding                       Use data binding from a framework, such                                                                 as WinJS
============================================================

URL character encoding
IE11 changes the character encoding for URLs. Specifically, query strings and XHR requests are now encoded using UTF-8 character encoding.
This change affects all URLs except for:

anchor name components (also called fragments).
username and password components.
file:// or ftp:// protocol links.

These changes match the behavior of other browsers and simplifies cross-browser XHR code.

Custom data attributes
IE11 adds support for HTML5 custom data attributes and the dataset property, which provides programmatic access to them. You can assign data attributes to elements using a data- prefix followed by the attribute name(HTML):

 <div data-example-data="Some data here"></div>

To get or set the value of the data attribute, use this syntax(JavaScript):

   // to get
   var myData = element.dataset.exampleData;
   // to set
   element.dataset.exampleData = "something new";

Ref: http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx
Ref: http://www.nczonline.net/blog/2013/07/02/internet-explorer-11-dont-call-me-ie/

Author : Rony T Sam

jQuery: ‘The Write Less, Do More’

What is jQuery?
jQuery is a lightweight, “write less, do more”, JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code .jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities

jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s). jQuery uses CSS syntax to select elements.

Basic syntax is: $(selector).action()

A $ sign to define/access jQuery, $ sign is a shortcut for ‘jQuery’
A (selector) to “query (or find)” HTML elements
A jQuery action() to be performed on the element(s)

Examples:
$(this).hide() – hides the current element.
$(“p”).hide() – hides all <p> elements.
$(“.test”).hide() – hides all elements with.
$(“#test”).hide() – hides the element with id=”test”.
The Document Ready Event

 $(document).ready(function(){
     // jQuery methods go here...
 });

This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
The jQuery team has also created an even shorter method for the document ready event:

$(function(){
    // jQuery methods go here...
});

but document ready event is easier to understand when reading the code.

jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to “find” (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more. It’s based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $(). The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:

$("p")

The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element. To find an element with a specific id, write a hash character, followed by the id of the element:

$("#test")

The .class Selector
The jQuery class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:

$(".test")

jQuery Events
All the different visitor’s actions that a web page can respond to are called events. An event represents the precise moment when something happens.
Examples:
moving a mouse over an element
selecting a radio button
clicking on an element

click()
The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element. The following example says: When a click event fires on a <p> element; hide the current <p> element:

$("p").click(function(){
    $(this).hide();
});

dblclick()
The dblclick() method attaches an event handler function to an HTML element. The function is executed when the user double-clicks on the HTML element:

$("p").dblclick(function(){
    $(this).hide();
});

mouseenter()
The mouseenter() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer enters the HTML element:

$("#p1").mouseenter(function(){
    alert("You entered p1!");
});

mouseleave()
The mouseleave() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer leaves the HTML element:

$("#p1").mouseleave(function(){
    alert("Bye! You now leave p1!");
});

mousedown()
The mousedown() method attaches an event handler function to an HTML element. The function is executed, when the left mouse button is pressed down, while the mouse is over the HTML element:

$("#p1").mousedown(function(){
    alert("Mouse down over p1!");
});

mouseup()
The mouseup() method attaches an event handler function to an HTML element. The function is executed, when the left mouse button is released, while the mouse is over the HTML element:

$("#p1").mouseup(function(){
    alert("Mouse up over p1!");
});

hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods. The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:

$("#p1").hover(function(){
   alert("You entered p1!");
},
function(){
   alert("Bye! You now leave p1!");
});

focus()
The focus() method attaches an event handler function to an HTML form field. The function is executed when the form field gets focus:

$("input").focus(function(){
    $(this).css("background-color","#cccccc");
});

blur()
The blur() method attaches an event handler function to an HTML form field. The function is executed when the form field loses focus:

$("input").blur(function(){
    $(this).css("background-color","#ffffff");
});

jQuery Hide/Show
hide() and show()
With jQuery, you can hide and show HTML elements with the hide() and show() methods:
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
The optional speed parameter specifies the speed of the hiding/showing, and can take the following values: “slow”, “fast”, or milliseconds.The optional callback parameter is a function to be executed after the hide() or show() method completes.

$("#hide").click(function(){
    $("p").hide();
});
$("#show").click(function(){
    $("p").show();
});
$("button").click(function(){
    $("p").hide(1000);
});
$("button").click(function(){
  $("p").hide("slow",function(){
    alert("The paragraph is now hidden");
  });
});

toggle()
With jQuery, you can toggle between the hide() and show() methods with the toggle() method.
$(selector).toggle(speed,callback);
The optional speed parameter can take the following values: “slow”, “fast”, or milliseconds.
The optional callback parameter is a function to be executed after toggle() completes.

$("button").click(function(){
    $("p").toggle();
});

jQuery Fade
With jQuery you can fade an element in and out of visibility. jQuery has the following fade methods:
fadeIn()
The jQuery fadeIn() method is used to fade in a hidden element.
$(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.The optional callback parameter is a function to be executed after the fading completes.The following example demonstrates the fadeIn() method with different parameters:

$("button").click(function(){
  $("#div1").fadeIn();
  $("#div2").fadeIn("slow");
  $("#div3").fadeIn(3000);
});

fadeOut()
The jQuery fadeOut() method is used to fade out a visible element.
$(selector).fadeOut(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.The optional callback parameter is a function to be executed after the fading completes.The following example demonstrates the fadeOut() method with different parameters:

$("button").click(function(){
  $("#div1").fadeOut();
  $("#div2").fadeOut("slow");
  $("#div3").fadeOut(3000);
});

fadeToggle()
The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.If the elements are faded out, fadeToggle() will fade them in. If the elements are faded in, fadeToggle() will fade them out.
$(selector).fadeToggle(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeToggle() method with different parameters:

$("button").click(function(){
  $("#div1").fadeToggle();
  $("#div2").fadeToggle("slow");
  $("#div3").fadeToggle(3000);
});

fadeTo()
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).
$(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1). The optional callback parameter is a function to be executed after the function completes. The following example demonstrates the fadeTo() method with different parameters:

$("button").click(function(){
  $("#div1").fadeTo("slow",0.15);
  $("#div2").fadeTo("slow",0.4);
  $("#div3").fadeTo("slow",0.7);
});

jQuery Slide
With jQuery you can create a sliding effect on elements. jQuery has the following slide methods:
slideDown()
The jQuery slideDown() method is used to slide down an element.
$(selector).slideDown(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the sliding completes. The following example demonstrates the slideDown() method:

$("#flip").click(function(){
  $("#panel").slideDown();
});

slideUp()
The jQuery slideUp() method is used to slide up an element.
$(selector).slideUp(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the sliding completes. The following example demonstrates the slideUp() method:

$("#flip").click(function(){
  $("#panel").slideUp();
});

slideToggle()
The jQuery slideToggle() method toggles between the slideDown() and slideUp() methods.If the elements have been slid down, slideToggle() will slide them up. If the elements have been slid up, slideToggle() will slide them down.
$(selector).slideToggle(speed,callback);
The optional speed parameter can take the following values: “slow”, “fast”, milliseconds. The optional callback parameter is a function to be executed after the sliding completes. The following example demonstrates the slideToggle() method:

$("#flip").click(function(){
  $("#panel").slideToggle();
});

jQuery Animate
The jQuery animate() method is used to create custom animations.
$(selector).animate({params},speed,callback);
The required params parameter defines the CSS properties to be animated. The optional speed parameter specifies the duration of the effect. It can take the following values:  slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the animation completes. The following example demonstrates a simple use of the animate() method; it moves a element to the right, until it has reached a left property of 250px:

$("button").click(function(){
  $("div").animate({left:'250px'});
});

jQuery animate() – Manipulate Multiple Properties
Notice that multiple properties can be animated at the same time:

$("button").click(function(){
  $("div").animate({
    left:'250px',
    opacity:'0.5',
    height:'150px',
    width:'150px'
  });
});

jQuery animate() – Using Relative Values
It is also possible to define relative values (the value is then relative to the element’s current value). This is done by putting += or -= in front of the value:

$("button").click(function(){
  $("div").animate({
    left:'250px',
    height:'+=150px',
    width:'+=150px'
  });
});

jQuery animate() – Using Pre-defined Values
You can even specify a property’s animation value as “show”, “hide”, or “toggle”:

$("button").click(function(){
  $("div").animate({
    height:'toggle'
  });
});

jQuery animate() – Uses Queue Functionality
By default, jQuery comes with queue functionality for animations. This means that if you write multiple animate() calls after each other, jQuery creates an “internal” queue with these method calls. Then it runs the animate calls ONE by ONE.
So, if you want to perform different animations after each other, we take advantage of the queue functionality:

$("button").click(function(){
  var div=$("div");
  div.animate({height:'300px',opacity:'0.4'},"slow");
  div.animate({width:'300px',opacity:'0.8'},"slow");
  div.animate({height:'100px',opacity:'0.4'},"slow");
  div.animate({width:'100px',opacity:'0.8'},"slow");
});

jQuery Stop Animations
The jQuery stop() method is used to stop an animation or effect before it is finished. The stop() method works for all jQuery effect functions, including sliding, fading and custom animations.
$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false. So, by default, the stop() method kills the current animation being performed on the selected element. The following example demonstrates the stop() method, with no parameters:

$("#stop").click(function(){
  $("#panel").stop();
});

jQuery HTML Get Content and Attributes
Get Content – text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation are:
text() – Sets or returns the text content of selected elements
html() – Sets or returns the content of selected elements (including HTML markup)
val() – Sets or returns the value of form fields
The following example demonstrates how to get content with the jQuery text() and html() methods:

$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

The following example demonstrates how to get the value of an input field with the jQuery val() method:

$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});

Get Attributes – attr()
The jQuery attr() method is used to get attribute values. The following example demonstrates how to get the value of the href attribute in a link:

$("button").click(function(){
  alert($("#w3s").attr("href"));
});

jQuery HTML Set Content and Attributes
Set Content – text(), html(), and val()
We will use the same three methods from the previous page to set content:
text() – Sets or returns the text content of selected elements
html() – Sets or returns the content of selected elements (including HTML markup)
val() – Sets or returns the value of form fields
The following example demonstrates how to set content with the jQuery text(), html(), and val() methods:

$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
  $("#test2").html("Hello world!");
});
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});

A Callback Function for text(), html(), and val()
All of the three jQuery methods above: text(), html(), and val(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value. You then return the string you wish to use as the new value from the function. The following example demonstrates text() and html() with a callback function:

$("#btn1").click(function(){
  $("#test1").text(function(i,origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")"; 
  });
});

$("#btn2").click(function(){
  $("#test2").html(function(i,origText){
    return "Old html: " + origText + " New html: Hello world!
    (index: " + i + ")"; 
  });
});

Set Attributes – attr()
The jQuery attr() method is also used to set/change attribute values. The following example demonstrates how to change (set) the value of the href attribute in a link:

$("button").click(function(){
  $("#w3s").attr("href","http://www.w3schools.com/jquery");
});

The attr() method also allows you to set multiple attributes at the same time. The following example demonstrates how to set both the href and title attributes at the same time:

$("button").click(function(){
  $("#w3s").attr({
    "href" : "http://www.w3schools.com/jquery",
    "title" : "W3Schools jQuery Tutorial"
  });
});

A Callback Function for attr()
The jQuery method attr(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) attribute value. You then return the string you wish to use as the new attribute value from the function. The following example demonstrates attr() with a callback function:

$("button").click(function(){
  $("#w3s").attr("href", function(i,origValue){
    return origValue + "/jquery"; 
  });
});

jQuery HTML Add Elements/Content
We will look at four jQuery methods that are used to add new content:
append() and prepend()
The jQuery append() method inserts content AT THE END of the selected HTML elements. The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.

$("p").append("Some appended text.");
$("p").prepend("Some prepended text.");

after() and before()
The jQuery after() method inserts content AFTER the selected HTML elements.
The jQuery before() method inserts content BEFORE the selected HTML elements.

$("img").after("Some text after");
$("img").before("Some text before");

jQuery HTML Remove Elements/Content
To remove elements and content, there are mainly two jQuery methods:
remove()
The jQuery remove() method removes the selected element(s) and its child elements.

$("#div1").remove();

empty()
The jQuery empty() method removes the child elements of the selected element(s).

$("#div1").empty();

Filter the Elements to be Removed
The jQuery remove() method also accepts one parameter, which allows you to filter the elements to be removed. The parameter can be any of the jQuery selector syntaxes. The following example removes all elements with class=”italic”:

$("p").remove(".italic");

jQuery Get and Set CSS Classes
jQuery has several methods for CSS manipulation. We will look at the following methods:
addClass()
The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

$("button").click(function(){
  $("h1,h2,p").addClass("blue");
  $("div").addClass("important");
});

You can also specify multiple classes within the addClass() method:

$("button").click(function(){
  $("#div1").addClass("important blue");
});

removeClass()
The following example shows how to remove a specific class attribute from different elements:

$("button").click(function(){
  $("h1,h2,p").removeClass("blue");
});

toggleClass()
The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:

$("button").click(function(){
  $("h1,h2,p").toggleClass("blue");
});

jQuery css() Method
Get a CSS Property
The css() method sets or returns one or more style properties for the selected elements.
css(“propertyname”);
The following example will return the background-color value of the FIRST matched element:

$("p").css("background-color");

Set a CSS Property
To set a specified CSS property, use the following syntax:
css(“propertyname”,”value”);
The following example will set the background-color value for ALL matched elements:

$("p").css("background-color","yellow");

Set Multiple CSS Properties
To set multiple CSS properties, use the following syntax:
css({“propertyname”:”value”,”propertyname”:”value”,…});
The following example will set a background-color and a font-size for ALL matched elements:

$("p").css({"background-color":"yellow","font-size":"200%"});

jQuery Dimensions
jQuery has several important methods for working with dimensions:
width() and height()
The width() method sets or returns the width of an element (includes NO padding, border, or margin). The height() method sets or returns the height of an element (includes NO padding, border, or margin). The following example returns the width and height of a specified element:

$("button").click(function(){
  var txt="";
  txt+="Width: " + $("#div1").width() + "";
  txt+="Height: " + $("#div1").height();
  $("#div1").html(txt);
});

innerWidth() and innerHeight()
The innerWidth() method returns the width of an element (includes padding). The innerHeight() method returns the height of an element (includes padding). The following example returns the inner-width/height of a specified element:

$("button").click(function(){
  var txt="";
  txt+="Inner width: " + $("#div1").innerWidth() + "";
  txt+="Inner height: " + $("#div1").innerHeight();
  $("#div1").html(txt);
});

outerWidth() and outerHeight()
The outerWidth() method returns the width of an element (includes padding and border). The outerHeight() method returns the height of an element (includes padding and border). The following example returns the outer-width/height of a specified element:

$("button").click(function(){
  var txt="";
  txt+="Outer width: " + $("#div1").outerWidth() + "";
  txt+="Outer height: " + $("#div1").outerHeight();
  $("#div1").html(txt);
});

The outerWidth(true) method returns the width of an element (includes padding, border, and margin). The outerHeight(true) method returns the height of an element (includes padding, border, and margin).

$("button").click(function(){
  var txt="";
  txt+="Outer width (+margin): " + $("#div1").outerWidth(true) + "";
  txt+="Outer height (+margin): " + $("#div1").outerHeight(true);
  $("#div1").html(txt);
});

More width() and height()
The following example returns the width and height of the document (the HTML document) and window (the browser viewport):

$("button").click(function(){
  var txt="";
  txt+="Document width/height: " + $(document).width();
  txt+="x" + $(document).height() + "\n";
  txt+="Window width/height: " + $(window).width();
  txt+="x" + $(window).height();
  alert(txt);
});

The following example sets the width and height of a specified element:

$("button").click(function(){
  $("#div1").width(500).height(500);
});

jQuery Traversing
jQuery traversing, which means “move through”, are used to “find” (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.
jQuery provides a variety of methods that allows us to traverse the DOM. The largest category of traversal methods are tree-traversal. The next chapters will show us how to travel up, down and sideways in the DOM tree.
jQuery Traversing Ancestor
An ancestor is a parent, grandparent, great-grandparent, and so on.
With jQuery you can traverse up the DOM tree to find ancestors of an element.
parent()
The parent() method returns the direct parent element of the selected element. This method only traverse a single level up the DOM tree. The following example returns the direct parent element of each elements:

$(document).ready(function(){
  $("span").parent();
});

parents()
The parents() method returns all ancestor elements of the selected element, all the way up to the document’s root element ().The following example returns all ancestors of all elements:

$(document).ready(function(){
  $("span").parents();
});

You can also use an optional parameter to filter the search for ancestors.
The following example returns all ancestors of all elements that are elements:

$(document).ready(function(){
  $("span").parents("ul");
}/);

parentsUntil()
The parentsUntil() method returns all ancestor elements between two given arguments. The following example returns all ancestor elements between a and a element:

$(document).ready(function(){
  $("span").parentsUntil("div");
});

jQuery Traversing Descendants
A descendant is a child, grandchild, great-grandchild, and so on. With jQuery you can traverse down the DOM tree to find descendants of an element.
Two useful jQuery methods for traversing down the DOM tree are:
children()
The children() method returns all direct children of the selected element. This method only traverse a single level down the DOM tree. The following example returns all elements that are direct children of each elements:

$(document).ready(function(){
  $("div").children();
});

You can also use an optional parameter to filter the search for children. The following example returns all elements with the class name “1”, that are direct children of:

$(document).ready(function(){
  $("div").children("p.1");
});

find()
The find() method returns descendant elements of the selected element, all the way down to the last descendant. The following example returns all elements that are descendants of:

$(document).ready(function(){
  $("div").find("span");
});

The following example returns all descendants of:

$(document).ready(function(){
  $("div").find("*");
});

jQuery Traversing Sideways
There are many useful jQuery methods for traversing sideways in the DOM tree:
siblings()
The siblings() method returns all sibling elements of the selected element. The following example returns all sibling elements of:

$(document).ready(function(){
  $("h2").siblings();
});

You can also use an optional parameter to filter the search for siblings. The following example returns all sibling elements of that are elements:

$(document).ready(function(){
  $("h2").siblings("p");
});

next()
The next() method returns the next sibling element of the selected element.This method only returns one element. The following example returns the next sibling of:

$(document).ready(function(){
  $("h2").next();
});

nextAll()
The nextAll() method returns all next sibling elements of the selected element. The following example returns all next sibling elements of:

$(document).ready(function(){
  $("h2").nextAll();
});

nextUntil()
The nextUntil() method returns all next sibling elements between two given arguments. The following example returns all sibling elements between a and a element:

$(document).ready(function(){
  $("h2").nextUntil("h6");
});

jQuery prev(), prevAll() & prevUntil() Methods
The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).

Narrow Down The Search For Elements
The three most basic filtering methods are first(), last() and eq(), which allow you to select a specific element based on its position in a group of elements. Other filtering methods, like filter() and not() allow you to select elements that match, or not match, a certain criteria.
first()
The first() method returns the first element of the selected elements. The following example selects the first element inside the first element:

$(document).ready(function(){
  $("div p").first();
});

last()
The last() method returns the last element of the selected elements. The following example selects the last element inside the last element:

$(document).ready(function(){
  $("div p").last();
});

eq()
The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 and not 1. The following example selects the second element (index number 1):

$(document).ready(function(){
  $("p").eq(1);
});

filter()
The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. The following example returns all elements with class name “intro”:

$(document).ready(function(){
  $("p").filter(".intro");
});

not()
The not() method returns all elements that do not match the criteria. Tip: The not() method is the opposite of filter(). The following example returns all elements that do not have class name “intro”:

$(document).ready(function(){
$("p").not(".intro");
});

jQuery and AJAX
AJAX is the art of exchanging data with a server, and updating parts of a web page – without reloading the whole page.
AJAX = Asynchronous JavaScript and XML. In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.
jQuery provides several methods for AJAX functionality.

load()
The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element.
$(selector).load(URL,data,callback);
The required URL parameter specifies the URL you wish to load. The optional data parameter specifies a set of querystring key/value pairs to send along with the request. The optional callback parameter is the name of a function to be executed after the load() method is completed.
The following example loads the content of the file “demo_test.txt” into a specific element:

$("#div1").load("demo_test.txt");

It is also possible to add a jQuery selector to the URL parameter. The following example loads the content of the element with id=”p1″, inside the file “demo_test.txt”, into a specific element:

$("#div1").load("demo_test.txt #p1");

The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
responseTxt – contains the resulting content if the call succeed
statusTxt – contains the status of the call
xhr – contains the XMLHttpRequest object
The following example displays an alert box after the load() method completes. If the load() method has succeed, it displays “External content loaded successfully!”, and if it fails it displays an error message:

$("button").click(function(){
  $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
    if(statusTxt=="success")
      alert("External content loaded successfully!");
    if(statusTxt=="error")
      alert("Error: "+xhr.status+": "+xhr.statusText);
  });
});

jQuery AJAX get() and post() Methods
Two commonly used methods for a request-response between a client and server
GET – Requests data from a specified resource
POST – Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. [The GET method may return cached data.]
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
$.get()
The $.get() method requests data from the server with an HTTP GET request.
$.get(URL,callback);
The required URL parameter specifies the URL you wish to request. The optional callback parameter is the name of a function to be executed if the request succeeds. The following example uses the $.get() method to retrieve data from a file on the server:

$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

The first parameter of $.get() is the URL we wish to request (“demo_test.asp”).
The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
$.post()
The $.post() method requests data from the server using an HTTP POST request.
$.post(URL,data,callback);
The required URL parameter specifies the URL you wish to request. The optional data parameter specifies some data to send along with the request. The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.post() method to send some data along with the request:

$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
  function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

The first parameter of $.post() is the URL we wish to request (“demo_test_post.asp”). Then we pass in some data to send along with the request (name and city). The ASP script in “demo_test_post.asp” reads the parameters, process them, and return a result. The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Ref: http://www.w3schools.com/jquery/default.asp

Author : Rony T Sam

C# and Framework Versions

FrameworkThere are lots of different versions of different elements of development. You need to distinguish between the versions of Visual Studio (the IDE), C# (the language) and .NET (the framework). It’s quite hard to talk about each of these individually without bringing in other pieces, but I’ll see what I can do… Note that I’ll avoid introducing the CLR versions as well, as most developers don’t really need to know about that.

These are the versions of C# known about at the time of this writing:

.NET Framework versions

There have been seven significant releases of the .NET Framework, excluding service packs. The framework includes the compilers, runtime, and libraries. Additionally, there are other profiles such Silverlight which complicate matters.

1.0 – released in 2002
1.1 – released in 2003
2.0 – released in 2005, with a new CLR (to handle generics and nullable types) and compilers for C# 2 and VB 8.
3.0 – released in 2006, this is just 2.0 plus new libraries: Windows Presentation Foundation, Windows Communication Foundation, Workflow Foundation, and Cardspace
3.5 – released in 2007, this is 3.0 plus new libraries (primarily LINQ and some extra “base” libraries such as TimeZoneInfo) and new compilers (for C# 3 and VB 9)
4.0 – released in 2010, this includes a new CLR (v4), new libraries, and the DLR (Dynamic Language Runtime)
4.5 – released in 2012, this allows for WinRT development on Windows 8 as well as extra libraries – with much wider async APIs
C# language versions

There are five significant language versions:

C# 1
C# 2, introducing generics, nullable types, anonymous methods, iterator blocks and some other more minor features
C# 3, introducing implicit typing, object and collection initializers, anonymous types, automatic properties, lambda expressions, extension methods, query expressions and some other minor features
C# 4, introducing dynamic typing, optional parameters, named arguments, and generic variance
C# 5, introducing asynchronous functions, caller info attributes, and a tweak to foreach iteration variable capture
See the specifications page for downloads for each version, from Microsoft and ECMA.

Visual Studio versions

For a long time, releases of Visual Studio were closely tied to framework releases. The picture has become a bit more flexible and complicated, however:

VS.NET 2002 – support for C# 1 and .NET 1.0
VS.NET 2003 – support for C# 1 and .NET 1.1
VS 2005 – support for C# 2 and .NET 2.0, and .NET 3.0 with an extension
VS 2008 – support for C# 3 and .NET 2.0, 3.0 and 3.5 (multi-targeting)
VS 2010 – support for C# 4 and .NET 2.0, 3.0, 3.5 and 4
VS 2012 – support for C# 5 and .NET 2.0 to 4.5 (including WinRT on Windows 8), and portable class libraries

More detailed information about the relationship between the language, runtime and framework versions is available on the C# in Depth site.

Author : Rony T Sam

Difference between & and && or | and || in c#

Logic

We know that a single | or & is a bitwise comparison.The double || or && is a logical comparison. More than this, these operators have another meaning.

&& or || Known as short-circuit-AND/OR logical operator
& or | Known as regular-AND/OR operator

Short-circuit-AND/OR logical operator
The && and || operators, which are the short-circuiting logical operators, are only defined for the type Boolean. Because of their short circuiting behavior, the second operand is not evaluated at run time if the operator result is known after evaluating the first operand.
The short-circuiting logical operators are evaluated as follows:
x && y
If the first operand in an && operation evaluates to False, the expression returns False. (because the result of the AND operation is false no matter what the value of y may be). Otherwise, the second operand is evaluated and a logical And operation is performed on the two results.
x || y
If the first operand in an || operation evaluates to True, the expression returns True. (because the result of the OR operation is false no matter what the value of y may be). Otherwise, the second operand is evaluated and a logical Or operation is performed on its two results.
When evaluating the && or || operators, the first operand is evaluated only once, and the second operand is either not evaluated or evaluated exactly once.

Regular-AND/OR operator
‘&’ and ‘|’ are more common for them to be used as bitwise operators, but can also be used as logical operators though. When they’re used as logical operators, both operands are always evaluated.

For example, consider the following code:

// cs_operator_logical_and.cs
 using System;
 class Test
 {
 static bool fn1()
 {
 Console.WriteLine("fn1 is false");
 return false;
 }
static bool fn2()
 {
 Console.WriteLine("fn2 is true");
 return true;
 }
public static void Main()
 {
 Console.WriteLine("regular AND:");
 bool regAnd = (fn1() & fn2());
 Console.WriteLine("result is {0}",regAnd);
 Console.WriteLine();
 Console.WriteLine("short-circuit AND:");
 bool sctAnd = (fn1() && fn2());
 Console.WriteLine("result is {0}",sctAnd);
 }
 }

Output will be

regular AND:
 fn1 is false
 fn2 is true
 result is False
short-circuit AND:
 fn1 is false
 result is False

Author : Rony T Sam

What is MongoDB?

images

MongoDB is a cross-platform document-oriented database system. Classified as a “NoSQL” database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open source software.
First developed by the New York City-based company 10gen (now MongoDB Inc.) in October 2007 as a component of a planned platform as a service product, the company shifted to an open source development model in 2009, with 10gen offering commercial support and other services.Since then, MongoDB has been adopted as backend software by a number of major websites and services, including Craigslist, eBay, Foursquare, SourceForge, and The New York Times, among others. MongoDB is the most popular NoSQL database system.

mongodb_stackMain features

The following is a brief summary of some of the main features:

Ad hoc queries
MongoDB supports search by field, range queries, regular expression searches. Queries can return specific fields of documents and also include user-defined JavaScript functions.

Indexing
Any field in a MongoDB document can be indexed (indices in MongoDB are conceptually similar to those in RDBMSes). Secondary indices are also available.

Replication
MongoDB supports master-slave replication. A master can perform reads and writes. A slave copies data from the master and can only be used for reads or backup (not writes). The slaves have the ability to select a new master if the current one goes down.

Load balancing
MongoDB scales horizontally using sharding. The developer chooses a shard key, which determines how the data in a collection will be distributed. The data is split into ranges (based on the shard key) and distributed across multiple shards. (A shard is a master with one or more slaves.)
MongoDB can run over multiple servers, balancing the load and/or duplicating data to keep the system up and running in case of hardware failure. Automatic configuration is easy to deploy, and new machines can be added to a running database.

File storage
MongoDB could be used as a file system, taking advantage of load balancing and data replication features over multiple machines for storing files. This function, called GridFS,is included with MongoDB drivers and available with no difficulty for development languages (see “Language Support” for a list of supported languages). MongoDB exposes functions for file manipulation and content to developers. GridFS is used, for example, in plugins for NGINX and lighttpd.

In a multi-machine MongoDB system, files can be distributed and copied multiple times between machines transparently, thus effectively creating a load balanced and fault tolerant system.

Aggregation
MapReduce can be used for batch processing of data and aggregation operations. The aggregation framework enables users to obtain the kind of results for which the SQL GROUP BY clause is used.
Server-side JavaScript execution
JavaScript can be used in queries, aggregation functions (such as MapReduce), are sent directly to the database to be executed.

Capped collections
MongoDB supports fixed-size collections called capped collections. This type of collection maintains insertion order and, once the specified size has been reached, behaves like a circular queue.

Main drawbacks

The following is a brief summary of some of the main drawbacks:

Database-level locking
MongoDB locks an entire database for each write, restricting concurrency.

Non-durable un-verifiable writes
MongoDB returns when not even data is securely written to non-volatile storage. Prior to version 2.2 it did not even wait for the data to be written to any server.

Scalability issues
It has scalability issues for more than 100GB of data.

Language support
MongoDB has official drivers for a variety of popular programming languages and development environments.Web programming language Opa also has built-in support for MongoDB, which is tightly integrated in the language and offers a type-safety layer on top of MongoDB.There are also a large number of unofficial or community-supported drivers for other programming languages and frameworks.

Read More: https://www.mongodb.com/products/mongodb

Source: Wikipedia                   Post by: Aneesh Sivan

What is NoSQL?

nosql_logo_0

A NoSQL database provides a mechanism for storage and retrieval of data that employs less constrained consistency models than traditional relational databases. Motivations for this approach include simplicity of design, horizontal scaling and finer control over availability. NoSQL databases are often highly optimized key–value stores intended for simple retrieval and appending operations, with the goal being significant performance benefits in terms of latency and throughput. NoSQL databases are finding significant and growing industry use in big data and real-time web applications. NoSQL systems are also referred to as “Not only SQL” to emphasize that they may in fact allow SQL-like query languages to be used.

NoSQL Database Types

  • Document databases pair each key with a complex data structure known as a document. Documents can contain many different key-value pairs, or key-array pairs, or even nested documents.
  • Graph stores are used to store information about networks, such as social connections. Graph stores include Neo4J and HyperGraphDB.
  • Key-value stores are the simplest NoSQL databases. Every single item in the database is stored as an attribute name (or “key”), together with its value. Examples of key-value stores are Riak and Voldemort. Some key-value stores, such as Redis, allow each value to have a type, such as “integer”, which adds functionality.
  • Wide-column stores such as Cassandra and HBase are optimized for queries over large datasets, and store columns of data together, instead of rows.

The Benefits of NoSQL

When compared to relational databases, NoSQL databases are more scalable and provide superior performance, and their data model addresses several issues that the relational model is not designed to address:

  • Large volumes of structured, semi-structured, and unstructured data
  • Agile sprints, quick iteration, and frequent code pushes
  • Object-oriented programming that is easy to use and flexible
  • Efficient, scale-out architecture instead of expensive, monolithic architecture

Dynamic Schemas

Relational databases require that schemas be defined before you can add data. For example, you might want to store data about your customers such as phone numbers, first and last name, address, city and state – a SQL database needs to know what you are storing in advance.

This fits poorly with agile development approaches, because each time you complete new features, the schema of your database often needs to change. So if you decide, a few iterations into development, that you’d like to store customers’ favorite items in addition to their addresses and phone numbers, you’ll need to add that column to the database, and then migrate the entire database to the new schema.

If the database is large, this is a very slow process that involves significant downtime. If you are frequently changing the data your application stores – because you are iterating rapidly – this downtime may also be frequent. There’s also no way, using a relational database, to effectively address data that’s completely unstructured or unknown in advance.

NoSQL databases are built to allow the insertion of data without a predefined schema. That makes it easy to make significant application changes in real-time, without worrying about service interruptions – which means development is faster, code integration is more reliable, and less database administrator time is needed.

Auto-sharding

Because of the way they are structured, relational databases usually scale vertically – a single server has to host the entire database to ensure reliability and continuous availability of data. This gets expensive quickly, places limits on scale, and creates a relatively small number of failure points for database infrastructure. The solution is to scale horizontally, by adding servers instead of concentrating more capacity in a single server.

“Sharding” a database across many server instances can be achieved with SQL databases, but usually is accomplished through SANs and other complex arrangements for making hardware act as a single server. Because the database does not provide this ability natively, development teams take on the work of deploying multiple relational databases across a number of machines. Data is stored in each database instance autonomously. Application code is developed to distribute the data, distribute queries, and aggregate the results of data across all of the database instances. Additional code must be developed to handle resource failures, to perform joins across the different databases, for data rebalancing, replication, and other requirements. Furthermore, many benefits of the relational database, such as transactional integrity, are compromised or eliminated when employing manual sharding.

NoSQL databases, on the other hand, usually support auto-sharding, meaning that they natively and automatically spread data across an arbitrary number of servers, without requiring the application to even be aware of the composition of the server pool. Data and query load are automatically balanced across servers, and when a server goes down, it can be quickly and transparently replaced with no application disruption.

Cloud computing makes this significantly easier, with providers such as Amazon Web Services providing virtually unlimited capacity on demand, and taking care of all the necessary database administration tasks. Developers no longer need to construct complex, expensive platforms to support their applications, and can concentrate on writing application code. Commodity servers can provide the same processing and storage capabilities as a single high-end server for a fraction of the price.

Replication

Most NoSQL databases also support automatic replication, meaning that you get high availability and disaster recovery without involving separate applications to manage these tasks. The storage environment is essentially virtualized from the developer’s perspective.

Integrated Caching

A number of products provide a caching tier for SQL database systems. These systems can improve read performance substantially, but they do not improve write performance, and they add complexity to system deployments. If your application is dominated by reads then a distributed cache should probably be considered, but if your application is dominated by writes or if you have a relatively even mix of reads and writes, then a distributed cache may not improve the overall experience of your end users.

Many NoSQL database technologies have excellent integrated caching capabilities, keeping frequently-used data in system memory as much as possible and removing the need for a separate caching layer that must be maintained.

NoSQL vs. SQL Summary

SQL Databases NoSQL Databases
Types One type (SQL database) with minor variations Many different types including key-value stores, document databases, wide-column stores, and graph databases
Development History Developed in 1970s to deal with first wave of data storage applications Developed in 2000s to deal with limitations of SQL databases, particularly concerning scale, replication and unstructured data storage
Examples MySQL, Postgres, Oracle Database MongoDB, Cassandra, HBase, Neo4j
Data Storage Model Individual records (e.g., “employees”) are stored as rows in tables, with each column storing a specific piece of data about that record (e.g., “manager,” “date hired,” etc.), much like a spreadsheet. Separate data types are stored in separate tables, and then joined together when more complex queries are executed. For example, “offices” might be stored in one table, and “employees” in another. When a user wants to find the work address of an employee, the database engine joins the “employee” and “office” tables together to get all the information necessary. Varies based on database type. For example, key-value stores function similarly to SQL databases, but have only two columns (“key” and “value”), with more complex information sometimes stored within the “value” columns. Document databases do away with the table-and-row model altogether, storing all relevant data together in single “document” in JSON, XML, or another format, which can nest values hierarchically.
Schemas Structure and data types are fixed in advance. To store information about a new data item, the entire database must be altered, during which time the database must be taken offline. Typically dynamic. Records can add new information on the fly, and unlike SQL table rows, dissimilar data can be stored together as necessary. For some databases (e.g., wide-column stores), it is somewhat more challenging to add new fields dynamically.
Scaling Vertically, meaning a single server must be made increasingly powerful in order to deal with increased demand. It is possible to spread SQL databases over many servers, but significant additional engineering is generally required. Horizontally, meaning that to add capacity, a database administrator can simply add more commodity servers or cloud instances. The database automatically spreads data across servers as necessary
Development Model Mix of open-source (e.g., Postgres, MySQL) and closed source (e.g., Oracle Database) Open-source
Supports Transactions Yes, updates can be configured to complete entirely or not at all In certain circumstances and at certain levels (e.g., document level vs. database level)
Data Manipulation Specific language using Select, Insert, and Update statements, e.g. SELECT fields FROM table WHERE… Through object-oriented APIs
Consistency Can be configured for strong consistency Depends on product. Some provide strong consistency (e.g., MongoDB) whereas others offer eventual consistency (e.g., Cassandra)

 Read More: http://www.mongodb.com/learn/nosql

                                   Auther: Aneesh Sivan