Tuesday, 13 January 2015

Upload and Resizing Image in C# (Without Losing Quality )

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <script src="../Include/JS/2.1JS.js"></script>

    <link href="../Include/CSS/bootstrap.css" rel="stylesheet" />


<script type="text/javascript">

    $(document).ready(function () {

        $("#BtnUpload").click(function (event) {

            var uploadfiles = $("#MultipleFilesUpload").get(0);

            var uploadedfiles = uploadfiles.files;

            var fromdata = new FormData();

           for (var i = 0; i < uploadedfiles.length; i++) {

        
            fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);

           }
        //   alert(fromdata);
            var choice = {};

            choice.url = "../Handler/hlrMultiImg.ashx";

            choice.type = "POST";

            choice.data = fromdata;

            choice.contentType = false;

            choice.processData = false;

            choice.success = function (result) {
               alert(result);
              //  document.getElementById("ok").src = result;
               // alert(result);
            };

            choice.error = function (err) { alert(err.statusText); };

            $.ajax(choice);

            event.preventDefault();

        });

    });

</script>
</head>
<body>
   

<form id="form1" runat="server">

    <h2>ASP.NET</h2>

    <p class="lead">Selcting Multiple Files using jQuery and Generic Handler</p>  



    <div class="form-group">

        <div>
            <img id="ok"/>
            <asp:Label ID="Label1" runat="server" AssociatedControlID="MultipleFilesUpload">Select Files</asp:Label>           

            <asp:FileUpload ID="MultipleFilesUpload" runat="server" AllowMultiple="true" />          

        </div>

    </div>

    <div class="form-group">

        <div class="col-md-offset-2 col-md-10">

            <asp:Button runat="server" ID="BtnUpload" Text="Upload Files" CssClass="btn btn-default" />

        </div>

    </div>  

 </form>
</body>
</html>










IN HANDLER ashx file





using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
public class hlrMultiImg : IHttpHandler
{



    public void ProcessRequest(HttpContext context)
    {

        if (context.Request.Files.Count > 0)
        {

            HttpFileCollection SelectedFiles = context.Request.Files;

            for (int i = 0; i < SelectedFiles.Count; i++)
            {

                HttpPostedFile PostedFile = SelectedFiles[i];
                string FileName = context.Server.MapPath("~/CartidgeImage/" + PostedFile.FileName);
                //   PostedFile.SaveAs(FileName);

                string filename = Path.GetFileName(PostedFile.FileName);
                string targetPath = context.Server.MapPath("~/CartidgeImage/" + filename);
                Stream strm = PostedFile.InputStream;
                var targetFile = targetPath;
                //Based on scalefactor image size will vary
                GenerateThumbnails(0.5, strm, targetFile);
                //   BindDataList();

                //   context.Response.Write("../CartidgeImage/"+PostedFile.FileName);

            }

        }



        else
        {

            context.Response.ContentType = "text/plain";

            context.Response.Write("Please Select Files");

        }



        context.Response.ContentType = "text/plain";

        // context.Response.Write(FileName);

    }



    public bool IsReusable
    {

        get
        {

            return false;

        }

    }




    private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
    {
        using (var image = Image.FromStream(sourcePath))
        {
            var newWidth = (int)(image.Width * scaleFactor);
            var newHeight = (int)(image.Height * scaleFactor);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }
}

Friday, 9 January 2015

Use Of OutPut Parameter in SQL Server Stored Procedure with C#

Introduction
This article introduces you to creating stored procedures for SQL Server 2008 and executing the stored procedure from C# code. Some stored procedures return values through parameters. When a parameter in a SQL statement or stored procedure is declared as out, the value of the parameter is returned back to the caller. First, we create a database table; after that create a stored procedure with an out parameter for insertiing records in the table.
Creating Table in SQL Server Database
Now create a table named UserDetail with the columns UserName, Email and Country. The table looks as below.
img1.gif
Creating a Stored Procedure with Out parameter
Now create a stored procedure with an out parameter to insert data into the table. We create an error out parameter.
USE [Rohatash]
GO
/****** Object:  StoredProcedure [dbo].[spuserdetail]    Script Date: 01/25/2012 01:37:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spuserdetail]
@UserName varchar(50),
@Password varchar(50),
@Email varchar(50),
@Country varchar(50),
@ERROR VARCHAR(100) OUT
AS
BEGIN   
         
SET NOCOUNT ON;

IF NOT EXISTS(SELECT * FROM UserDetail WHERE UserName=@UserName) //  To Check UserName is exits or not
BEGIN
INSERT INTO UserDetail(
UserName,
[Password],
Email,
Country
)
VALUES
(
@UserName,
@Password,
@Email,
@Country
)
SET @ERROR=@UserName+' Registered Successfully'
END
ELSE
BEGIN
SET @ERROR=@UserName + ' Already Exists'
END
END
In the above stored procedure, error is the out parameter and other are the input parameter. In this stored procedure we check UserName; if the UserName exists in the table then it will return the message as an Output Parameter.
SET @ERROR=@UserName + ' Already Exists'
If the UserName does not exist in the table then it will return the message as an Output Parameter.
SET @ERROR=@UserName+' Registered Successfully'
Executing the stored procedure from C# code
In order to demonstrate the process of executing a stored procedure from a C#, create a new web application project in Visual Studio 2010. Add using statements above the namespace declaration to enable the use of non-fully qualified references to other namespace types.
Now add the following namespace.
using System.Data.SqlClient;
using System.Data;

Now write the connection string to connect to the database.

string strConnection = "Data Source=.; uid=sa; pwd=wintellect;database=Rohatash;";

Now I need to display that output parameter message during user registration in ASP.NET. How to get that output parameter returned by a SQL query. For a sample design your aspx page might be like this:

aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication117.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
 UserName:<asp:TextBox ID="UserNameTextBox" runat="server"></asp:TextBox>
        <br />
        <br />
 Password:<asp:TextBox ID="PasswordTextBox" runat="server" TextMode="Password"></asp:TextBox>
        <br />
        <br />
        Confirm Password:<asp:TextBox ID="ConfirmPasswordTextBox" runat="server" TextMode="Password"></asp:TextBox>
        <br />
        <br />
  Email:<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
        <br />
        <br />
 Country:<asp:TextBox ID="CountryTextBox" runat="server"></asp:TextBox>
        <br />
        <br />
      <asp:Button ID="SaveButton" runat="server" Text="Save"
            onclick="SaveButton_Click" />
            <span style= "color:Red; font-weight :bold"> <asp:Label ID="lblErrorMsg" runat="server"></asp:Label></span>
    </div>
    </form>
</body>
</html>

To get output parameters in ASP.NET we need to write statements like this.

cmd.Parameters.Add("@ERROR", SqlDbType.Char, 500);
        cmd.Parameters["@ERROR"].Direction = ParameterDirection.Output;
        message = (string)cmd.Parameters["@ERROR"].Value;


In Codebehind write the following code in the SaveButton_Click like this.  Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace WebApplication117
{
   
    public partial class WebForm1 : System.Web.UI.Page
    {
      private string message = string.Empty;
      protected void Page_Load(object sender, EventArgs e)
        {

        }
protected void SaveButton_Click(object sender, EventArgs e)
{
    if (PasswordTextBox.Text == ConfirmPasswordTextBox.Text)
    {
        string UserName = UserNameTextBox.Text;
        string Password = PasswordTextBox.Text;
        string ConfirmPassword = ConfirmPasswordTextBox.Text;
        string Email = EmailTextBox.Text;
        string Country = CountryTextBox.Text;
        SqlConnection con = new SqlConnection("Data Source=.; uid=sa; pwd=wintellect;database=Rohatash;");
        con.Open();
        SqlCommand cmd = new SqlCommand("spuserdetail", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@UserName", UserName);
        cmd.Parameters.AddWithValue("@Password", Password);
        cmd.Parameters.AddWithValue("@Email", Email);
        cmd.Parameters.AddWithValue("@Country", Country);
        cmd.Parameters.Add("@ERROR", SqlDbType.Char, 500);
        cmd.Parameters["@ERROR"].Direction = ParameterDirection.Output;
        cmd.ExecuteNonQuery();
        message = (string)cmd.Parameters["@ERROR"].Value;
        con.Close();
    }
    else
    {
        Page.RegisterStartupScript("UserMsg", "<Script language='javascript'>alert('" + "Password mismatch" + "');</script>");
    }
    lblErrorMsg.Text = message;
}

    }
}
Now run the application and test it.
img2.gif
Now insert the data and click on the Save Button.
SET @ERROR=@UserName+' Registered Successfully'
img3.gif
The above message shows UserName with a message which is defined in the stored procedure as an output parameter. If we enter the same UserName again than it will display the following message as an output parameter.
SET @ERROR=@UserName + ' Already Exists'
img4.gif

Thursday, 8 January 2015

Events In JQURY

What are 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
The term "fires" is often used with events. Example: "The keypress event fires the moment you press a key".
Here are some common DOM events:
Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave   blur unload


jQuery Syntax For Event Methods

In jQuery, most DOM events have an equivalent jQuery method.
To assign a click event to all paragraphs on a page, you can do this:
$("p").click();
The next step is to define what should happen when the event fires. You must pass a function to the event:
$("p").click(function(){
  // action goes here!!
});


Commonly Used jQuery Event Methods

$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter.
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:

Example

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

Try it yourself »
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:

Example

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

Try it yourself »
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:

Example

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

Try it yourself »
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:

Example

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

Try it yourself »
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:

Example

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

Try it yourself »
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:

Example

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

Try it yourself »
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:

Example

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

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

Example

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

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

Example

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

Try it yourself »

jQuery Traversing And All Traversing Methods

What is 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.
The image below illustrates a family tree. With jQuery traversing, you can easily move up (ancestors), down (descendants) and sideways (siblings) in the family tree, starting from the selected (current) element. This movement is called traversing - or moving through - the DOM.
jQuery Dimensions
Illustration explained:
  • The <div> element is the parent of <ul>, and an ancestor of everything inside of it
  • The <ul> element is the parent of both <li> elements, and a child of <div>
  • The left <li> element is the parent of <span>, child of <ul> and a descendant of <div>
  • The <span> element is a child of the left <li> and a descendant of <ul> and <div>
  • The two <li> elements are siblings (they share the same parent)
  • The right <li> element is the parent of <b>, child of <ul> and a descendant of <div>
  • The <b> element is a child of the right <li> and a descendant of <ul> and <div>


An ancestor is a parent, grandparent, great-grandparent, and so on.
A descendant is a child, grandchild, great-grandchild, and so on.
Siblings share the same parent.


Traversing the DOM

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 - Ancestors

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.

Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:
  • parent()
  • parents()
  • parentsUntil()

jQuery parent() Method

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 <span> elements:

Example

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

Try it yourself »


jQuery parents() Method

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

Example

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

Try it yourself »
You can also use an optional parameter to filter the search for ancestors.
The following example returns all ancestors of all <span> elements that are <ul> elements:

Example

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

Try it yourself »


jQuery parentsUntil() Method

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

Example

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

Try it yourself »

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.

Traversing Down the DOM Tree

Two useful jQuery methods for traversing down the DOM tree are:
  • children()
  • find()

jQuery children() Method

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 <div> elements:

Example

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

Try it yourself »
You can also use an optional parameter to filter the search for children.
The following example returns all <p> elements with the class name "1", that are direct children of <div>:

Example

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

Try it yourself »


jQuery find() Method

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

Example

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

Try it yourself »
The following example returns all descendants of <div>:

Example

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

Try it yourself »

jQuery Traversing - Siblings

Siblings share the same parent.
With jQuery you can traverse sideways in the DOM tree to find siblings of an element.

Traversing Sideways in The DOM Tree

There are many useful jQuery methods for traversing sideways in the DOM tree:
  • siblings()
  • next()
  • nextAll()
  • nextUntil()
  • prev()
  • prevAll()
  • prevUntil()

jQuery siblings() Method

The siblings() method returns all sibling elements of the selected element.
The following example returns all sibling elements of <h2>:

Example

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

Try it yourself »
You can also use an optional parameter to filter the search for siblings.
The following example returns all sibling elements of <h2> that are <p> elements:

Example

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

Try it yourself »


jQuery next() Method

The next() method returns the next sibling element of the selected element.
The following example returns the next sibling of <h2>:

Example

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

Try it yourself »


jQuery nextAll() Method

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

Example

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

Try it yourself »


jQuery nextUntil() Method

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

Example

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

Try it yourself »

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 do not match, a certain criteria.

jQuery first() Method

The first() method returns the first element of the selected elements.
The following example selects the first <p> element inside the first <div> element:

Example

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

Try it yourself »


jQuery last() Method

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

Example

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

Try it yourself »


jQuery eq() method

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 <p> element (index number 1):

Example

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

Try it yourself »


jQuery filter() Method

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 <p> elements with class name "intro":

Example

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

Try it yourself »


jQuery not() Method

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 <p> elements that do not have class name "intro":

Example

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

Try it yourself »

Wednesday, 7 January 2015

jQuery delegate method And Bind Method Example/Demo

With jQuery 1.4.2 launch, a new method called "delegate()" was introduced. This method attaches a handler to one or more events for selected/specified elements. Let's take an example. I have created a table and using delegate method, I will attach the click event handler to every td element.

01<table border="1" width="200px" cellspacing="5" cellpadding="5">
02   <tr>
03       <td>Item 1</td>
04       <td>Item 2</td>
05   </tr>
06   <tr>
07       <td>Item 3</td>
08       <td>Item 4</td>
09   </tr>
10</table>
jQuery delegate() method code.
1<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
2<script type="text/javascript" language="javascript">  
3$(document).ready(function(){
4  $("table").delegate("td","click",function(){
5         alert('I am' + $(this).text());
6  });
7});
8</script>
It takes 3 arguments.

1. Selector
2. Event Type
3. Event Handler

See live Demo and Code.

You will say that this is very much possible with the bind() method. Below code will serve the purpose.
1$(document).ready(function(){        
2  $("table td").bind("click",function(){
3      alert('I am' + $(this).text());
4  });
5});
Then what's new with delegate() method?

bind() vs delegate()

bind() method will add event to element which are on the page when it was called. For example, there are only 4 td on the page when bind() was called. Later on, when you dynamically add more td in the table then bind() will not attach click event handler to those td. Let's extend our demo and place a button on the page which will add the td dynamically.
1<input type="button" value="Add TD" id="btnAdd" />
1$("#btnAdd").click(function(){
2   $("table").append("<tr><td>Item 5</td><td>Item 6</td></tr>");
3});
Now, when you run this page, you will not find click event for newly added td.

See live Demo and Code.

But with delegate(), you will find click event for newly added td. delegate() method adds event which are on the page and also listens for new element and add event to them.

See live Demo and Code.

jQuery - bind() vs live() vs delegate() methods

I had already posted about jQuery bind(), jQuery live() and  jQuery delegate() functions. All the three jQuery functions are used to attach events to selectors or elements. But just think why there are 3 different functions for same purpose? There can't be. right? So in this post, I will explain you how these functions are different from each other.


bind() vs live()

The basic difference between bind and live is bind will not attach the event handler to those elements which are added/appended after DOM is loaded. bind() only attach events to the current elements not future element.

bind() vs delegate()

The difference between bind and delegate is same as how bind differs from live function. I had explained the difference with an example in this post jQuery delegate function Example/Demo.

live() vs delegate()

As we had seen the advantage of live and delegate function that they attaches event to those elements also which are added/appended after DOM is loaded. But how they both are different?

Well, the difference between live and delegate is, live function can't be used in chaining. live function needs to be used directly on a selector/element. For example, if I have a div with id "dvContainer",which have a table in it with some other elements. And I want to attach a click event to tr tag of the table.
1$(document).ready(function(){        
2  $("#dvContainer")children("table").find("tr").live("click",function(){
3         alert('I am' + $(this).text());
4  });
5});
The above code will not work. However with delegate() you can achieve this functionality.
1$(document).ready(function(){        
2  $("#dvContainer")children("table").delegate("tr","click",function(){
3         alert('I am' + $(this).text());
4  });
5});
There is one more difference in terms of performance, if the context is not specified with the live function. Context means you are setting the search limit within a specific node. If you don't specify the context with live function then it attaches the handler to the document by default and when executed it traverse through the DOM which causes a performance issue.
1$(document).ready(function(){        
2  $("#tblData td").live("click",function(){
3         alert('I am' + $(this).text());
4  });
5});
In the above code, no context is specified so event gets attached to the document by default. It causes a huge performance issue. But with jQuery 1.4, you can specify the context with live function also.
1$(document).ready(function(){        
2  $("td",$("#tblData")[0]).live("click",function(){
3         alert('I am' + $(this).text());
4  });
5});
You can check the difference with FireQuery add-on for Firefox. With delegate, the context is always specified.
1$(document).ready(function(){        
2  $("#tblData").delegate("td","click",function(){
3         alert('I am' + $(this).text());
4  });
5});
Summary You can use any of these function but delegate function has advantage of performance, chaining issue and works for future created elements. Hope you find this article useful.