Friday 29 June 2012

Delegate and Events in C#

A delegate is a .NET class that encapsulates a method, but not in the same way other classes encapsulate methods. A delegate actually stores the address of a method that is contained in some other class. So, a delegate is really the equivalent of a function pointer in C++. However, they are also far more than that.

<from MSDN>
Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.


Declaring and using delegates 

You declare a delegate in a class or namespace using the delegate keyword and by specifying the signature of the method it will call. The following line declares a delegate named TestDelegate which will reference a method that returns void and accepts a string as the argument.

delegate void TestDelegate(string s);

Now that we have declared the TestDelegate, we can instantiate it to encapsulate a method of that signature.
 Then, we can invoke the method through the delegate, just as if we invoked the method itself. 
The next code sample creates an instance of TestDelegate and uses it to invoke the TestFun method.

class DelegateDemo {    
TestDelegate td = new TestDelegate(TestFun);
protected void Page_Load(object sender, EventArgs e) { td("Hello World"); } public void TestFun(string s) {
Console.WriteLine(s);
      }
}
Delegates only depend on the signature of the method, not on the class or object containing the method.
delegate can reference an instance method as well. The above example uses the TestDelegate to invoke an
method.

Events

One of the most common uses of delegates in .NET is event handling. Events are useful for notifying objects
of user interface events or state changes. The following example creates a Timer object that will fire an event
every second. The Timer class is defined in the System.Timers namespace.
class DelegateDemo {
   static void Main(string[] args) {
      Timer t = new Timer(1000);
      t.Elapsed += 
         new ElapsedEventHandler(Timer_Elapsed);
      t.Enabled = true;
      Console.WriteLine("Press enter to exit");
      Console.ReadLine();
      }
 
   static void Timer_Elapsed(object sender, ElapsedEventArgs e) {
      Console.WriteLine("tick");   
      }
   }
The Timer class contains the Elapsed event and fires it whenever its interval expires. In this example the 
Main method instantiates a Timer and registers an ElapsedEventHandler delegate with its Elapsed 
event. 

In this example, the method invoked by the ElapsedEventHandler delegate is the Timer_Elapsed 
method. Following the convention of all event handling delegates, the ElapsedEventHandler delegate 
returns void and accepts two parameters. The first is a reference to the object that signaled the event and 
the second is a argument derived of EventArgs which stores pertinent information about the event.

Monday 11 June 2012

How to post form data from HTML to ASP.Net page

For sending form data from HTML page to ASP.Net page ,


In HTML page , do the method type as POST and action should be full path of .aspx page.Like
Test.html page
<html>
<body>
 <form id="form1" action="../MailerTest.aspx" method="post"> 

     <input type="text" name="txtName" id="Name" />
    <br/>
    <input type="text" name="txtEmail" id="Email" />
    <br/>
  <input type="submit" name="btnPost" value="Submit" id="btnPost" />
</form>
</body>
</html> 


Default.aspx page
On aspx page , get html controls data on page_load event as
strName = Request.Form["txtName"].ToString();
strEmail = Request.Form["txtEmail"].ToString();


Thing which we need to take care of that Key value in Request.Form should be name
in <input> tag besides of id.After clicking on 'Submit' button HTML page will post data to
aspx page.

Difference between live() and delegate() in jQuery


.live() requires you run the selector immediately, unless you're using the result it's very wasteful. The event handler here is attached to document, so all event of that type from any elements bubbling must be checked. Here's a usage example:

$(".myClass").live("click", function() { alert("Hello World"); }); 

 Note that the statement $(".myClass") ran that selector to find all elements with that class even though we don't care about them, all we wanted was the string ".myClass" to match later when click events bubble up to document.

.delegate() actually uses .live() internally, but with a context. The selector is not run immediately, so it's more efficient already, and it doesn't attach to document (though it can) it's much more local...and all those other events from other element trees you don't care about are never even checked when bubbled...again more efficient. Here's a usage example:
$("#table").delegate("td", "click", function() { alert("Hello World"); }); 

 Now what happened here? We ran $("#table") to get the element to attach to ,admittedly more expensive than document, but we're using the result). Then we attach an event handler to that (or those in other cases) elements. Only clicks from within that element are checked against the "td" selector when they happen, not from everywhere like .live() does (since everything is inside document).

What is the difference between the .bind() and .live() methods in jQuery?


.bind() will only apply to the items you currently have selected in your jQuery object. .live() will apply to all current matching elements, as well as any you might add in the future.

The underlying difference between them is that live() makes use of event bubbling. That is, when you click on a button, that button might exist in a <p>, in a <div>, in a <body> element; so in effect, you're actually clicking on all of those elements at the same time.

live() works by attaching your event handler to the document, not to the element. When you click on that button, as illustrated before, the document receives the same click event. It then looks back up the line of elements targeted by the event and checks to see if any of them match your query.

The outcome of this is twofold: firstly, it means that you don't have to continue reapplying events to new elements, since they'll be implicitly added when the event happens. However, more importantly (depending on your situation), it means that your code is much much lighter! If you have 50 <img> tags on the page and you run this code:
$('img').click(function() { /* doSomething */ });

 ...then that function is copied into each of those elements. However, if you had this code:
$('img').live('click', function() { /* doSomething */ });

 ...then that function is stored only in one place (on the document), and is applied to whatever matches your query at event time.

Because of this bubbling behaviour though, not all events can be handled this way.

// BIND example 
$('div').bind('mouseover', doSomething); 
// this new div WILL NOT HAVE mouseover event handler registered 
$('<div/>').appendTo('div:last'); 
 
// LIVE example 
$('div').live('mouseover', doSomething); 
// this new appended div WILL HAVE mouseover event handler registered 
$('<div/>').appendTo('div:last');


Friday 8 June 2012

Sending form submissions to email using 'mailto:'

The simplest method to get the form submissions posted to you via email is by using "mailto:" in the action field of the form. However, this method has many drawbacks.
First let us see how we can use 'mailto' in a form.


How to set up 'mailto' in your HTML form
In the action field of the form, set the action as "mailto:<youremailaddress>" for example:

<form action="mailto:myforms@mydomain.com">
The sad part is that the behavior of such a form will be different in different browsers.


How to get the form data in plain text
We can make the form data sent to be in readable form by making a small change in the form.
Add 'enctype=text/plain' in the form attributes. The form code becomes:


<form action="mailto:myforms@mydomain.com" enctype="text/plain" >

When this form is submitted, you will get the email in readable form. Like this:


Name=john
Email=john@yahoo.com
Address=
Submit=Submit


How to show a 'Thank You' page
You have successfully submitted the form. Now you want to show a confirmation page to the visitor that the form is submitted. Here is how to do it:
Suppose the name of the confirmation page is thanks.html Update the code for the form tag to:


<form action="mailto:myforms@mydomain.com" enctype="text/plain"onsubmit="location.href='thanks.html';" >


How to customize the subject of the email
By default, the subject of the email that you receive from such a form will read something like: "Form posted from Microsoft Internet Explorer"
The following code shows the change:

<form action= "mailto:myforms@mydomain.com?subject=myform_submission" enctype="text/plain" onsubmit="location.href='thanks.html';" >


Drawbacks of 'mailto' email form
We have seen that using mailto is simplest way to get your HTML form submissions via email.
However, there are many disadvantages for this method.

  1. Your visitor must have Internet Explorer as the browser and Outlook Express as the default client for this to work correctly.
  2. Even if your visitor is using Internet Explorer, but the default mail client is different, your mailto form will not work.
  3. Even if your visitors have IE and has configured Outlook Express as default mail client, they may press cancel on the warning dialog that pops up.
  4. According to the HTML specifications, the action field of the form should be a correctly formed HTTP URL. So 'mailto:' is not valid for the action field.
Use a form mail script
The only consistent alternative to ensure that you get the email form the form submissions is to use a form mail script.

Thursday 7 June 2012

Difference between GROUP BY and PARTITION BY


GROUP BY modifies the entire query, like:
Select customerId, count(*) as orderCount 
from Orders 
group by customerId 

But PARTITION BY just works on a window function, like row_number:
select row_number() over (PARTITION BY customerId order by orderId) 
    as OrderNumberForThisCustomer 
from Orders 
A Group By normally reduces the number of rows returned by rolling them up and 
calculating averages or sums for each row.  Partition By does not affect the number of rows 
returned, but it changes how a window function's result is calculated.



Wednesday 6 June 2012

SQL SERVER - APPLY


  1. An APPLY is used to join a table-valued-function with a table. APPLY are of two types: CROSS APPLY and OUTER APPLY
    A CROSS APPLY is used when you want to return only those records from your table where a value is returned by your table valued function.
    Whereas, an OUTER APPLY is used to return all records from your table regardless of the values returned by your table valued function.



    SELECT name.User_Id,name.UserName,name.Email,name.MobileNo,name.VisitedDate
    FROM allocate_site lead
    outer apply dbo.fn_get_latest_response_userwise(lead.User_ID) sales 
    cross apply dbo.fn_get_user_details(lead.User_ID) name
    inner join UserDetails users on users.ID = lead.User_ID
    WHERE lead.ProductId = name.ProductID