जगदीश खोलिया

Wednesday, September 21, 2011

JQuery Concepts

How do I select an item using class or ID?

This code selects an element with an ID of "myDivId". Since IDs are unique, this expression always selects either zero or one elements depending upon whether or not an element with the specified ID exists.
 $('#myDivId')
This code selects an element with a class of "myCssClass". Since any number of elements can have the same class, this expression will select any number of elements.
 $('.myCssClass')
A jQuery object containing the selected element can be assigned to a JavaScript variable like normal:
 var myDivElement = $('#myDivId');
Usually, elements in a jQuery object are acted on by other jQuery functions:
 var myValue = $('#myDivId').val();    // get the value of a form input
 
 $('#myDivId').val("hello world");     // set the value of a form input

How do I select elements when I already have a DOM element?

If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object.
 var myDomElement = document.getElementById('foo'); // a plain DOM element
 $(myDomElement).find('a'); // finds all anchors inside the DOM element
Many people try to concatenate a DOM element or jQuery object with a CSS selector, like so:
 $(myDomElement + '.bar'); // WRONG! equivalent to $("[object HTMLElement].bar")
This is wrong. You cannot concatenate strings to objects.

How do I test whether an element has a particular class?

hasClass (added in version 1.2) handles this common use case:
 $("div").click(function(){
   if ( $(this).hasClass("protected") )
     $(this)
       .animate({ left: -10 })
       .animate({ left: 10 })
       .animate({ left: -10 })
       .animate({ left: 10 })
       .animate({ left: 0 });
 });
You can also use the is() method along with an appropriate selector for more advanced matching:
 if ( $('#myDiv').is('.pretty.awesome') )
   $('#myDiv').show();
Note that this method allows you to test for other things as well. For example, you can test whether an element is hidden (by using the custom :hidden selector):
 if ( $('#myDiv').is(':hidden') )
   $('#myDiv').show();

Use the length property of the jQuery collection returned by your selector:
 if ( $('#myDiv').length )
   $('#myDiv').show();
Note that it isn't always necessary to test whether an element exists. The following code will show the element if it exists, and do nothing (with no errors) if it does not:
 $('#myDiv').show();

How do I determine the state of a toggled element?

You can determine whether an element is collapsed or not by using the :visible and :hidden selectors.
 var isVisible = $('#myDiv').is(':visible');
 var isHidden = $('#myDiv').is(':hidden');
If you're simply acting on an element based on its visibility, just include ":visible" or ":hidden" in the selector expression. For example:
 $('#myDiv:visible').animate({left: '+=200px'}, 'slow');

How do I select an element by an ID that has characters used in CSS notation?

Because jQuery uses CSS syntax for selecting elements, some characters are interpreted as CSS notation. For example, ID attributes, after an initial letter (a-z or A-Z), may also use periods and colons, in addition to letters, numbers, hyphens, and underscores (see W3C Basic HTML Data Types). The colon (":") and period (".") are problematic within the context of a jQuery selector because they indicate a pseudo-class and class, respectively.
In order to tell jQuery to treat these characters literally rather than as CSS notation, they must be "escaped" by placing two backslashes in front of them.
 // Does not work
 $("#some:id")
 
 // Works!
 $("#some\\:id")
 // Does not work
 $("#some.id")
 
 // Works!
 $("#some\\.id")
The following function takes care of escaping these characters and places a "#" at the beginning of the ID string:
 function jq(myid) { 
   return '#' + myid.replace(/(:|\.)/g,'\\$1');
 }

The function can be used like so:
 $( jq('some.id') )

How do I disable/enable a form element?

There are two ways to disable/enable form elements.
Set the 'disabled' attribute to true or false:
 // Disable #x
 $('#x').attr('disabled', true);
 // Enable #x
 $('#x').attr('disabled', false);
Add or remove the 'disabled' attribute:
 // Disable #x
 $("#x").attr('disabled', 'disabled');
 // Enable #x
 $("#x").removeAttr('disabled');
You can try an example of enabling/disabling with the following demo:

and here's the source code to the demo:
 <select id="x" style="width:200px;">
   <option>one</option>
   <option>two</option>
 </select>
 <input type="button" value="Disable" onclick="$('#x').attr('disabled','disabled')"/>
 <input type="button" value="Enable" onclick="$('#x').removeAttr('disabled')"/>

How do I check/uncheck a checkbox input or radio button?

There are two ways to check/uncheck a checkbox/radio button.
Set the 'checked' attribute to true or false.
 // Check #x
 $('#x').attr('checked', true);
 // Uncheck #x
 $('#x').attr('checked', false);
Add or remove the 'checked' attribute:
 // Check #x
 $("#x").attr('checked', 'checked');
 // Uncheck #x
 $("#x").removeAttr('checked');

and here's the source code to the demo:
 <label><input type="checkbox" id="c"/> I'll be checked/unchecked.</label>
 <input type="button" value="Check" onclick='$("#c").attr("checked","checked")'/>
 <input type="button" value="Uncheck" onclick='$("#c").removeAttr("checked")'/>

How do I get the text value of a selected option?

Select elements typically have two values that you want to access. First there's the value to be sent to the server, which is easy:
 $("#myselect").val();
 // => 1
The second is the text value of the select. For example, using the following select box:
 <select id="myselect">
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
   <option value="5">Prof</option>
 </select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1"), you would do that in the following way:
 $("#myselect option:selected").text();
 // => "Mr"
You can see this in action in the following demo:

and here's the full source code to the demo:
 <select id="myselect">
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
   <option value="5">Prof</option>
 </select>
 <input type="button" value="Get Value" onclick="alert($('#myselect').val())"/>
 <input type="button" value="Get Text Value" onclick="alert($('#myselect option:selected').text())"/>

How do I replace text from the 3rd element of a list of 10 items?

Either the :eq() selector or the .eq() method will allow you to select the proper item. However, to replace the text, you must get the value before you set it:
  // This doesn't work; text() returns a string, not the jQuery object
  $(this).find('li a').eq(2).text().replace('foo','bar');

  // This works
  var $thirdLink = $(this).find('li a').eq(2);
  var linkText = $thirdLink.text().replace('foo','bar');
  $thirdLink.text(linkText);
The first example just discards the modified text. The second example saves the modified text and then replaces the old text with the new modified text. Remember, .text() gets; .text("foo") sets.



How do I get and use the server response from an AJAX request?

The 'A' in AJAX stands for asynchronous. When invoking functions that have asynchronous behavior you must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when (or even if) the response will be received.
The following snippet shows an example of making an AJAX call and alerting the response (or error):
 $.ajax({
     url: 'myPage.php',
     success: function(response) {
        alert(response);
     },
     error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);
     }
 });
But how can the response be used in context of a function? Consider this flawed example where we try to update some status information on the page:
 function updateStatus() {
     var status;
     $.ajax({
         url: 'getStatus.php',
         success: function(response) {
             status = response;
         }
     });
     // update status element?  this will not work as expected
     $('#status').html(status);
 }
The code above does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined. The next snippet shows how we can rewrite this function to behave as desired:
 function updateStatus() {
     $.ajax({
         url: 'getStatus.php',
         success: function(response) {
             // update status element
             $('#status').html(response);
         }
     });
 }
But how can I return the server response from an AJAX call? Here again we show a flawed attempt. In this example we attempt to alert the http status code for the url of 'getStatus.php':
 //...
 alert(getUrlStatus('getStatus.php'));
 //...
 function getUrlStatus(url) {
     $.ajax({
         url: url,
         complete: function(xhr) {
             return xhr.status;
         }
     });
 }
The code above will not work because you cannot 'return' data from a function that is called asynchronously. Instead, it must be rewritten to use a callback:
 //...
 getUrlStatus('getStatus.php', function(status) {
     alert(status);
 });
 // ...
 function getUrlStatus(url, callback) {
     $.ajax({
         url: url,
         complete: function(xhr) {
             callback(xhr.status);
         }
     });
 }

How do I pull a native DOM element from a jQuery object?

A jQuery object is an array-like wrapper around one or more DOM elements. To get a reference to the actual DOM elements (instead of the jQuery object), you have two options. The first (and fastest) method is to use array notation:
 $('#foo')[0]; // equivalent to document.getElementById('foo')
The second method is to use the get function:
 $('#foo').get(0); // identical to above, only slower
You can also call get without any arguments to retrieve a true array of DOM elements.

Why do ... ?


Why do my events stop working after an AJAX request?

Frequently, when you've added a click (or other event) handler to all links using $('a').click(fn), you'll find that the events no longer work after you've loaded new content into a page using an AJAX request.
When you call $('a'), it returns all the links on the page at the time it was called, and .click(fn) adds your handler to only those elements. When new links are added, they are not affected.
You have two ways of handling this:

Using event delegation

Event delegation is a technique that exploits event bubbling to capture events on elements anywhere in the DOM.
As of jQuery 1.3, you can use the live and die methods for event delegation with a subset of event types. As of jQuery 1.4, you can use these methods (along with delegate and undelegate starting in 1.4.2) for event delegation with pretty much any event type.
For earlier versions of jQuery, take a look at the Live Query plugin by Brandon Aaron. You may also manually handle event delegation by binding to a common container and listening for events from there. For example:
 $('#mydiv').click(function(e){
    if( $(e.target).is('a') )
       fn.call(e.target,e);
 });
 $('#mydiv').load('my.html');
This example will handle clicks on any <a> element within #mydiv, even if they do not exist yet when the click handler is added.

Using event rebinding

This method requires you to call the bind method on new elements as they are added. For example:
 $('a').click(fn);
 $('#mydiv').load('my.html',function(){
   $('#mydiv a').click(fn);
 });
Beware! As of jQuery 1.4.2, binding the same handler to the same element multiple times will cause it to execute more than once. This differs from previous versions of jQuery as well as the DOM 2 Events spec (which normally ignores duplicate event handlers).

Why doesn't an event work on a new element I've created?

As explained in the previous question about AJAX, events are bound only to elements that exist at the time when you issue your initial jQuery call. When you create a new element, you must bind the event to it separately, or use event delegation.

Why do animations set the display style to block?

Only block-level elements can have a custom width or height. When you do an animation on an element that animates the height or width (such as show, hide, slideUp, or slideDown), the display CSS property will be set to 'block' for the duration of the animation. The display property will be reverted to its original value after the animation completes. (This does not work properly for inline-block elements.)
There are two common workarounds:
If you want the element to stay inline, but you just want it to animate in or out, you can use the fadeIn or fadeOut animations instead (which only affect the opacity of an element).
 // Instead of this:
 $("span").show("slow");
 
 // do this:
 $("span").fadeIn("slow");
The other option is to use a block-level element, but to add a float such that it appears to stay inline with the rest of the content around it. The result might looks something like this:
 // A floated block element
 <div style="float:left;">...</div>
 
 // Your code:
 $("div").show("slow");

Threading Concepts

Multithreading or free-threading is the ability of an operating system to concurrently run programs that have been divided into subcomponents, or threads.
Technically, multithreaded programming requires a multitasking/multithreading operating system, such as GNU/Linux, Windows NT/2000 or OS/2; capable of running many programs concurrently, and of course, programs have to be written in a special way in order to take advantage of these multitasking operating systems which appear to function as multiple processors. In reality, the user's sense of time is much slower than the processing speed of a computer, and multitasking appears to be simultaneous, even though only one task at a time can use a computer processing cycle.

Objective

The objective of this document is:
  • A brief Introduction to Threading
  • Features of Threading
  • Threading Advantages

Features and Benefits of Threads

Mutually exclusive tasks, such as gathering user input and background processing can be managed with the use of threads. Threads can also be used as a convenient way to structure a program that performs several similar or identical tasks concurrently.
One of the advantages of using the threads is that you can have multiple activities happening simultaneously. Another advantage is that a developer can make use of threads to achieve faster computations by doing two different computations in two threads instead of serially one after the other.

Threading Concepts in C#

In .NET, threads run in AppDomains. An AppDomain is a runtime representation of a logical process within a physical process. And a thread is the basic unit to which the OS allocates processor time. To start with, each AppDomain is started with a single thread. But it is capable of creating other threads from the single thread and from any created thread as well.

How do they work

A multitasking operation system divides the available processor time among the processes and threads that need it. A thread is executed in the given time slice, and then it is suspended and execution starts for next thread/process in the queue. When the OS switches from one thread to another, it saves thread context for preempted thread and loads the thread context for the thread to execute.
The length of time slice that is allocated for a thread depends on the OS, the processor, as also on the priority of the task itself.

Working with threads

In .NET framework, System.Threading namespace provides classes and interfaces that enable multi-threaded programming. This namespace provides:
  • ThreadPool class for managing group of threads,
  • Timer class to enable calling of delegates after a certain amount of time,
  • A Mutex class for synchronizing mutually exclusive threads, along with classes for scheduling the threads, sending wait notifications and deadlock resolutions.
Information on this namespace is available in the help documentations in the Framework SDK.

Defining and Calling threads

To get a feel of how Threading works, run the below code:
using System;
using System.Threading;

public class ServerClass
{
    // The method that will be called when the thread is started.

    public void Instance Method()
    {
        Console.WriteLine("You are in InstranceMethod.Running on Thread A�);
        Console.WriteLine("Thread A Going to Sleep Zzzzzzzz�);

        // Pause for a moment to provide a delay to make threads more apparent.

        Thread. Sleep(3000);
        Console.WriteLine ("You are Back in InstanceMethod.Running on Thread A");
    }

    public static void StaticMethod()
    {
        Console.WriteLine("You are in StaticMethod. Running on Thread B.");
        // Pause for a moment to provide a delay to make threads more apparent.

        Console.WriteLine("Thread B Going to Sleep Zzzzzzzz");

        Thread.Sleep(5000);
        Console.WriteLine("You are back in static method. Running on Thread B");
    }
}

public class Simple
{
    public static int Main(String[] args)
    {
        Console.WriteLine ("Thread Simple Sample");
        ServerClass serverObject = new ServerClass();
        // Create the thread object, passing in the 

        // serverObject.InstanceMethod method using a ThreadStart delegate.

        Thread InstanceCaller = new 
             Thread(new ThreadStart(serverObject.InstanceMethod));

        // Start the thread.

        InstanceCaller.Start();

        Console.WriteLine("The Main() thread calls this " + 
          "after starting the new InstanceCaller thread.");

        // Create the thread object, passing in the 

        // serverObject.StaticMethod method using a ThreadStart delegate.

        Thread StaticCaller = new Thread(new 
               ThreadStart(ServerClass.StaticMethod));
        // Start the thread.

        StaticCaller.Start();
        Console.WriteLine("The Main () thread calls this " + 
                "after starting the new StaticCaller threads.");
        return 0;
    }
}
If the code in this example is compiled and executed, you would notice how processor time is allocated between the two method calls. If not for threading, you would have to wait till the first method slept for 3000 secs for the next method to be called. Try disabling threading in the above code and notice how they work. Nevertheless, execution time for both would be the same.
An important property of this class (which is also settable) is Priority.

Scheduling Threads

Every thread has a thread priority assigned to it. Threads created within the common language runtime are initially assigned the priority of ThreadPriority.Normal. Threads created outside the runtime retain the priority they had before they entered the managed environment. You can get or set the priority of any thread with the Thread.Priority property.
Threads are scheduled for execution based on their priority. Even though threads are executing within the runtime, all threads are assigned processor time slices by the operating system. The details of the scheduling algorithm used to determine the order in which threads are executed varies with each operating system. Under some operating systems, the thread with the highest priority (of those threads that can be executed) is always scheduled to run first. If multiple threads with the same priority are available, the scheduler cycles through the threads at that priority, giving each thread a fixed time slice in which to execute. As long as a thread with a higher priority is available to run, lower priority threads do not get to execute. When there are no more run able threads at a given priority, the scheduler moves to the next lower priority and schedules the threads at that priority for execution. If a higher priority thread becomes run able, the lower priority thread is preempted and the higher priority thread is allowed to execute once again. On top of all that, the operating system can also adjust thread priorities dynamically as an application's user interface is moved between foreground and background. Other operating systems might choose to use a different scheduling algorithm.

Pausing and Resuming threads

After you have started a thread, you often want to pause that thread for a fixed period of time. Calling Thread.Sleep causes the current thread to immediately block for the number of milliseconds you pass to Sleep, yielding the remainder of its time slice to another thread. One thread cannot call Sleep on another thread. Calling Thread.Sleep(Timeout.Infinite) causes a thread to sleep until it is interrupted by another thread that calls Thread.Interrupt or is aborted by Thread.Abort.

Thread Safety

When we are working in a multi threaded environment, we need to maintain that no thread leaves the object in an invalid state when it gets suspended. Thread safety basically means the members of an object always maintain a valid state when used concurrently by multiple threads.
There are multiple ways of achieving this � The Mutex class or the Monitor classes of the Framework enable this, and more information on both is available in the Framework SDK documentation. What we are going to look at here is the use of locks.
You put a lock on a block of code � which means that that block has to be executed at one go and that at any given time, only one thread could be executing that block.
The syntax for the lock would be as follows:
using System;
using System.Threading;

//define the namespace, class etc.


...
public somemethod(...)
{
    ...
    lock(this)
    {
        Console.WriteLine(Inside the lock now);
        ...
    }
}
In the above code sample, the code block following the lock statement will be executed as one unit of execution, and only one thread would be able to execute it at any given time. So, once a thread enters that block, no other thread can enter the block till the first thread has exited it.
This becomes necessary in the kind of database transactions required in banking applications and reservations systems etc.

Word of Caution

Although multithreading can be a powerful tool, it can also be difficult to apply correctly. Improperly implemented multithreaded code can degrade application performance, or even cause frozen applications.

Tuesday, September 20, 2011

Delete Duplicate Records – Rows(SQL Server)

SQL SERVER – Delete Duplicate Records – Rows

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.
DELETE
FROM
MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

Friday, September 2, 2011

UPDATE_STATISTICS in Sql Server


UPDATE_STATISTICS
updates the indexes on these tables accordingly. Basically this command is used when we have to do a large data process. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. Or we can say that it updates information about the distribution of key values in specified indexes, for all columns in an index, table, or partition.

Syntax:


update
statistics table_name
[[ partition data_partition_name ] [ (column_list ) ]
|
index_name [ partition index_partition_name ] ]
[ using step values ]
[ with consumers = consumers ][, sampling=N percent ]

Monday, August 8, 2011

Page Life Cycle events

Seq Events Controls Initialized View state
Available
Form data
Available
What Logic can be written here?
1 Init No No No Note: You can access form data etc. by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any setting initialization.Master pages and them settings. In this section, we do not have access to viewstate , posted values and neither the controls are initialized.
2 Load view state Not guaranteed Yes Not guaranteed You can access view state and any synch logic where you want viewstate to be pushed to behind code variables can be done here.
3 PostBackdata Not guaranteed Yes Yes You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.
4 Load Yes Yes Yes This is the place where you will put any logic you want to operate on the controls. Like flourishing a combobox from the database, sorting data on a grid, etc. In this event, we get access to all controls, viewstate and their posted values.
5 Validate Yes Yes Yes If your page has validators or you want to execute validation for your page, this is the right place to the same.
6 Event Yes Yes Yes If this is a post back by a button click or a dropdown change, then the relative events will be fired. Any kind of logic which is related to that event can be executed here.
7 Pre-render Yes Yes Yes If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.
8 Save view state Yes Yes Yes Once all changes to server controls are done, this event can be an opportunity to save control data in to view state.
9 Render Yes Yes Yes If you want to add some custom HTML to the output this is the place you can.
10 Unload Yes Yes Yes Any kind of clean up you would like to do here.

Wednesday, July 20, 2011

Abstract class

Abstract class is a class that has no direct instances, but whose descendants may have direct instances. There are case i which it is useful to define classes for which the programmer never intends to instantiate any objects; because such classes normally are used as bae-classes in inheritance hierarchies, we call such classes abstract classes These classes cannot be used to instantiate objects; because abstract classes are incomplete. Derived classes called concrete classes must define the missing pieces.

Abstract classes normally contain one or more abstract methods or abstract properties, such methods or properties do not provide implementations, but our derived classes must override inherited abstract methods or properties to enable obejcts ot those derived classes to be instantiated, not to override those methods or properties in derived classes is syntax error, unless the derived class also is an abstract class.

In some cases, abstract classes constitute the top few levels of the hierarchy, for Example abstract class Shape with abstract method Draw() has tow derived abstract classe Shape2D & Shape3D inherites the method Draw() & also do not provide any implementation for it. Now we have normal classes Rectangle, Square & Circle inherites from Shape2D, and another group of classes Sphere, Cylinder & Cube inherites from Shape3D. All classes at the bottom of the hierarchy must override the abstract method Draw().

A class is made abstract by declaring it with Keyword abstract.

Example:

public abstract class Shape
{
    //...Class implementation

    public abstract void Draw(int x, int y)
    {
        //this method mustn't be implemented here.
        //If we do implement it, the result is a Syntax Error.
    } 
}


public abstract class Shape2D : Shape
{
    //...Class implementation
    //...you do not have to implement the the method Draw(int x, int y)
}

public class Cricle : Shape2D
{
    //here we should provide an implemetation for Draw(int x, int y)
    public override void Draw(int x, int y)
    {
        //must do some work here
    }

}
Difference between an abstract method & virtual method:

Virtual method has an implementation & provide the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

important Notes:

(a)Any Class with abstract method or property in it must be declared abstract

(b)Attempting to instantiate an object of an abstract class retults in a compilation error

Example:

Shape m_MyShape = new Shape(); //it is Wrong to that.
But we can do that.
Shape m_MyShape = new Circle(); // True
Or
Shape m_MyShape; 
/*

declare refrences only, and the refrences can refer to intances of
any concrete classes derived from abstract class
*/

Circle m_MyCircle = new Circle();
m_MyShape  = m_MyCircle; // Also True
(d)An abstract class can have instance data and non-abstract methods -including constructors-.

Friday, July 15, 2011

CTE in Sql Server

Introduction:
The common table expression is one of the new features in sql server 2005. It can be used instead of temp table or table variables in the stored procedures in the circumstances. Let's see CTE with some example queries.

Background:

Most of the developers while writing the stored procedures they create the temp tables or table variables. They need some table to store the temporary results in order to manipulate the data in the other tables based on this temp result.

The temp variables will be stored on the tempdb and it needs to be deleted in the tempdb database.

The table variable is best when compare with the temp tables. Because the table variable initially will be there in the memory for the certain limit of size and if the size increase then it will be moved to the temp database. However the scope of the table variable is only up to that program. When compare with table variable the CTE is best. It just store the result set like normal view.

CTE (Common Table Expression):

The CTE is one of the essential features in the sql server 2005.It just store the result as temp result set. It can be access like normal table or view. This is only up to that scope.

The syntax of the CTE is the following.

WITH name (Alias name of the retrieve result set fields)
AS
(
//Write the sql query here
)
SELECT * FROM name

Here the select statement must be very next to the CTE. The name is mandatory and the argument is an optional. This can be used to give the alias to the retrieve field of the CTE.

CTE 1: Simple CTE

WITH
ProductCTE
AS(  SELECT ProductID AS [ID],ProductName AS [Name],CategoryID AS [CID],UnitPrice AS [Price]
  FROM Products
)SELECT * FROM ProductCTE

Here all the product details like ID, name, category ID and Unit Price will be retrieved and stored as temporary result set in the ProductCTE.

This result set can be retrieved like table or view.

CTE2:Simple CTE with alias

WITH
ProductCTE(ID,Name,Category,Price)AS(  SELECT ProductID,ProductName,CategoryID,UnitPrice
  FROM Products
)SELECT * FROM ProductCTE

Here there are four fieds retrieves from the Products and the alias name have given in the arqument to the CTE result set name.

It also accepts like the following as it is in the normal select query.

WITH
ProductCTE
AS(  SELECT ProductID AS [ID],ProductName AS [Name],CategoryID AS [CID],UnitPrice AS [Price]
  FROM Products
)SELECT * FROM ProductCTE

CTE 3: CTE joins with normal table

The result set of the CTE can be joined with any table and also can enforce the relationship with the CTE and other tables.

WITH
OrderCustomer
AS(  SELECT DISTINCT CustomerID FROM Orders
)SELECT C.CustomerID,C.CompanyName,C.ContactName,C.Address+', '+C.City AS [Address] FROM Customers C INNER JOIN OrderCustomer OC ON OC.CustomerID = C.CustomerID

Here the Ordered Customers will be placed in the CTE result set and it will be joined with the Customers details.

CTE 4: Multiple resultsets in the CTE

WITH
MyCTE1
AS(  SELECT ProductID,SupplierID,CategoryID,UnitPrice,ProductName FROM Products
), 
MyCTE2
AS(  SELECT DISTINCT ProductID FROM "Order Details"
)SELECT C1.ProductID,C1.ProductName,C1.SupplierID,C1.CategoryID FROM MyCTE1 C1 INNER JOIN MyCTE2 C2 ON C1.ProductID = C2.ProductID

Here, there are two result sets that will be filtered based on the join condition.

CTE 5: Union statements in the CTE

WITH
PartProdCateSale
AS(SELECT ProductID FROM Products WHERE CategoryID = (SELECT CategoryID FROM Categories WHERE CategoryName='Condiments')UNION ALL
SELECT
ProductID FROM Products WHERE CategoryID = (SELECT CategoryID FROM Categories WHERE CategoryName='Seafood')
)
SELECT OD.ProductID,SUM(OD.UnitPrice*OD.Quantity) AS [Total Sale] FROM "Order Details" OD INNER JOIN PartProdCateSale PPCS ON PPCS.ProductID = OD.ProductID
GROUP BY OD.ProductID

Normally when we combine the many result sets we create table and then insert into that table. But see here, we have combined with the union all and instead of table, here CTE has used.

CTE 6: CTE with identity column

WITH
MyCustomCTE
   AS   (      SELECT CustomerID,row_number() OVER (ORDER BY CustomerID) AS iNo FROM
         Customers
   )SELECT * FROM MyCustomCTE

ASP.NET Cookieless Session

Cookies are basically text data which a web site may store of the user's machine. Cookies are not considered as safe medium to store data as they could be dangerous in some scenario. Also there might be the case that user has cookies turned off on his machine or the browser doesn't supports the cookies. Our application might get failed if it is depended on cookies support on client side. Most of the time session id is stored at client side in cookies. Therefore we won't be able to retrieve session's data in the case when cookies are not enable.

ASP.NET Cookieless Support

ASP.NET support cookieless execution of the application when the client doens't have cookies support. When to chose cookieless, the session id is transferred via the request url. Each and every request of the application page contains the session id embedded in its url. So the web application need not to request the session from the cookies.
To set Cookieless session in an ASP.NET application set following value in web.config file
<sessionstate cookieless="true" />
When you have cookieless session then the url may look like this
http://www.dailycoding.com/Posts/(_entv9gVODTzHuenph6KAlK07..)/test.aspx

Monday, July 11, 2011

What is DLR in .NET 4.0 framework?

What is DLR in .NET 4.0 framework?
DLR
Due to DLR runtime, dynamic languages like ruby, python, JavaScript etc can integrate and run seamlessly with CLR. DLR thus helps to build the best experience for your favorite dynamic language. Your code becomes much cleaner and seamless while integrating with the dynamic languages. Integration with DLR is not limited to dynamic languages. You can also call MS office components in a much cleaner way by using COM interop binder. One of the important advantages of DLR is that it provides one central and unified subsystem for dynamic language integration. 

C# 4.0 Language Innovation

  • Dynamically Typed Objects
  • Optional and Named Parameters
  • Improved COM Interoperability
  • Co and Contra variance
Dynamic types

What are the advantages and disadvantage of dynamic keyword?

We all still remember how we talked bad about VB6 (Well I loved the language) variant keyword and we all appreciated how .NET brought in the compile time check feature, well so why are we changing now.  Well, bad developers will write bad code with the best programming language and good developers will fly with the worst programming language. Dynamic keyword is a good tool to reduce complexity and it's a curse when not used properly.
So advantages of Dynamic keyword:
Helps you interop between dynamic languages.
Eliminates bad reflection code and simplifies code complexity.
Improves performance with method call caching.
Disadvantages:
Will hit performance if used with strongly typed language.

Jquery Ajax Calling functions

there are 5 diffrent function that used to make ajax call to page and to fetch data. I am going to discuss about that five function one by one.

Following is list of that five function availale in jquery libaray to make ajax call.
  1. Load
  2. getJson
  3. GET
  4. POST
  5. Ajax
Load
Method allow to make ajax call to the page and allows to send using both Get and Post methods.
var loadUrl = "TestPage.htm";
$(document).ready(function () {
$("#load_basic").click(function () {
$("#result").html(ajax_load).load(loadUrl, function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#dvError").html(msg + xhr.status + " " + xhr.statusText);
}
}
);
return false;
});
As you can see in above code you can easily make call to any page by passing it Url. The call back function provide more control and allows to handle the error if any by making use of the Status value.

One of the important thing about the load method is its allow to load part of page rather than whole page. So get only part of the page call remains same but the url is
var loadUrl = "TestPage.htm #dvContainer";   
So by the passing above url to load method it just load content of the div having id=dvContainer. Check the demo code for detail.



Firebug shows the repose get return by when we call the page by Load method.

Important Feature
  • Allow make call with both Get and Post request
  • Allow to load part of the page.
getJson

Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed. One more thing this method treat the respose as Json.
var jsonUrl = "Json.htm";
$("#btnJson").click(function () {
$("#dvJson").html(ajax_load);
$.getJSON(jsonUrl, function (json) {
var result = json.name;
$("#dvJson").html(result);
}
);
return false;
});
Above code make use of getJSON function and displays json data fetch from the page.

Following is json data return by the Json.htm file.
{
"name": "Hemang Vyas",
"age" : "32",
"sex": "Male"
}

Following image displays the json Data return as respose.



Important Feature
  • Only send data using get method, post is not allowed.
  • Treat the response data as Json only

get

Allow to make ajax request with the get method. It handles the response of many formats including xml, html, text, script, json, and jonsp.
var getUrl = "GETAndPostRequest.aspx";
$("#btnGet").click(function () {
$("#dvGet").html(ajax_load);
$.get(getUrl, { Name: "Pranay" }, function (result) {
$("#dvGet").html(result);
}
);
return false;
});
As in code I am passing Name parameter to the page using get request.

On server side you can get the value of the Name parameter in request object querycollection.
if (Request.QueryString["Name"]!=null)
{
txtName.Text = Request.QueryString["Name"].ToString();
} 
The firebug shows the parameter passe by me as Get request  and  value of the parameter is pranay



Important Feature
  • Can handle any type of the response data.
  • Send data using get method only.

post

Allow to make ajax request with the post method. It handles the response of many formats including xml, html, text, script, json, and jonsp. post does same as get but just send data using post method.
var postUrl = "GETAndPostRequest.aspx";
$("#btnPost").click(function () {
$("#dvPost").html(ajax_load);
$.post(postUrl, { Name: "Hanika" }, function (result) {
$("#dvPost").html(result);
}
);
return false;
});
As in code I am passing Name parameter to the page using post request.

On server side you can get the value of the Name parameter in request object formcollection.
if (Request.Form["Name"] != null)
{
    txtName.Text = Request.Form["Name"].ToString();
}

The firebug shows the parameter passe by me as Get request  and  value of the parameter is Hanika



Important Feature
  • Can handle any type of the response data.
  • Send data using post method only.

ajax

Allow to make the ajax call. This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter.
var ajaxUrl = "Json.htm";
$("#btnAjax").click(function () {
$("#dvAjax").html(ajax_load);
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: "", //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (json) {//On Successfull service call
var result = json.name;
$("#dvAjax").html(result);
},
error: ServiceFailed// When Service call fails
});
return false;
});
In above code you can see the all the parameter and comment related to each parameter describe the purpose of each one.

Fire bug shows the called page return json data and Ajax function treat the respose as Json because in code datatype = json



Important Feature
  • Provide more control on the data sending and on response data.
  • Allow to handle error occur during call.
  • Allow to handle data if the call to ajax page is successful.
Summary

So each method of jQuery ajax is different and can use for the difference purpose.