Friday, June 10, 2011

JQuery



What is jQuery?
jQuery is a light weight javascript library which provides fast and easy way of HTML DOM traversing and manipulation, event handling, client
side animations, etc. One of the greatest features of jQuery is, it supports an efficient way to implement AJAX applications because of its light
weight nature. According to the jQuery official site, “jQuery is designed to change the way that you write JavaScript.”

Advantages of jQuery
1.      It’s lightweight, easy and fast.
2.      Write less but do more.
3.      Cross Browser Compatibility.
4.      Separate javascript code from HTML mark-up.
5.      Easy and Light-weight Ajax Application.
6.      Availability of various plug-in’s.
7.      You can extend it.
8.      We can use CDN (Content Distribution Network) for internet site.
9.      Microsoft and Intellisense support in Visual Studio 2008.
10.  Easy Integration with ASP.Net Ajax projects.


var optons={
method:'post',
url:'chanName.aspx',
after:funtion(responce){
$("div#divView").html(responce).show();
$("div#divEdit").empty().hide();
$(a#editName").show();
}

$("form#ChangeName").ajaxForm(options);
%("a#editName").hide();
$("a#lnkCancel").click(function(){
$("div#divView").show();
$("div#divEdit").empty().hide();



$("a#editName").click(function(){
$.get("ChangeName.aspx",function(responce){
$("div#divEdit").html(responce).show();
$("div#divView").hide();



var options={
method: 'post',
url: 'changeName.aspx',
after: function(responce){
$("div#divView").html(responce).show();
$("div#divEdit").empty().hide();
}
};
----------------------------------------------------------------------
GET:   $('#<%=DropDownList1.ClientID%>').val()
SET:   $('#<%=DropDownList1.ClientID%>').val("value_to_set")

----------------------------------------------------------------------
get: $('#<%=ddl1.clientid%>').attr("selectedIndex")
get:$('#<%=ddl1.clientid%>')[0].selectdIndex;

set:$('#<%=ddl1.clientid%>').attr("selectedIndex","0")
set:$('#<%=ddl1.clientid%>').attr("selectdIndex")=0

----------------------------------------------------------------------
get:$("input[name='<%=radiobuttonlist1.uniqueid%>']:checked").vlaue()
set: $("input[name='<%=radiobuttonlist1.uniqueid%>'][value='value_to_set']").attr("checked",true)

----------------------------------------------------------------------
$('#<%=button1.ClientId%>').attr("disabled",true/false);
----------------------------------------------------------------------
get: $('#<%=label1.ClientId%>').text()

set:$('#<%=lable1.ClientId%>').text("value_to_set")

-----------------------------------------------------------------------
get:$('#<%=TextBox1.clientid%>').val()
set:$('#<%=textbox.clientId%>').val("value_to_set")
---------------------------------------------------------------------
if($('#<%=Button1.ClientID%>').is(':visible'))
-----------------------------------------------------------------------
$(function(){
$('#startdate').datepick({dateFormat:'dd/mm/yyyy'});
$('#enddate').datepick({dateFormat:'dd/mm/yyyy'});
});

-----------------------------------------------------------------------
$('#startdate').datepick({dateFormat:'mm/dd/yyyy',showAnim:'fadeIn'});

$('#startdate').datepick({datepick({dateformat:'mm/dd/yyyy',showSpeed:'fast'});
mindate--maxdate
$('#startdate').datepick({minDate:'07/01/2010',maxDate:'07/15/2010'});


POST Method
     <script src="_scripts/jQuery-1.2.6.js" type="text/javascript"></script>
        <script language="javascript">
            $(document).ready(function() {

$("#txtNoOfTicketsByPOST").change(function() {
                    $("#Error2").html("");
                    var ticketsReq = $("#txtNoOfTicketsByPOST").val();
                    $.post("GetAvailableTicketsByPOST.aspx", { TicReq: ticketsReq }, function(result) {
                        if (result != "") {
                            $("#Error2").html(result);                          
                        }
                    });
                });
            });           
        </script>

    <div>
    <div id="TicketsByPOST ">
    No of Tickets:<asp:TextBox ID=" txtNoOfTicketsByPOST" runat="server"></asp:TextBox>
    <div id="Error2" style="color:Red;"></div>
    </div>
    </div>

public partial class GetAvailableTicketsByPOST : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ticReq = Request["TicReq"];
        int tics = int.Parse(ticReq);
      
        int NoOfTicketsAvailable = 5;
        if (tics > NoOfTicketsAvailable)
        {
            Response.Write("Only " + NoOfTicketsAvailable.ToString()+" are available!");
            Response.End();
        }
    }
}

------------------------------------------------------------------------------------------------
Implementing PageMethods in ASP.Net AJAX
The page methods should be defined as a public static method and it should be decorated with WebMethod attribute. Refer the below page
method that returns a string of available number of tickets at that moment.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    
    }
    [WebMethod]
    public static string GetAvailableTickets()
    {
        int NoOfTicketsAvailable = 5;
        return NoOfTicketsAvailable.ToString();
    }
}

Include System.Web.Services namespace for the above web method to work.

Calling the PageMethod using JQuery
We can use JQuery.ajax() method to call the PageMethod from client side,

<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>
        <script language="javascript">
            $(document).ready(function() {
                $("#txtNoOfTickets").blur(function() {
                    var ticketRequired = this.value;
                    var options = {
                        type: "POST",
                        url: "Default.aspx/GetAvailableTickets",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(response) {
var avilabletic = parseInt(response.d);                          
                            if (ticketRequired > avilabletic) {
                                alert("Only " + response.d + " tickets available!");
                            }
                            else {
                                alert(response.d);
                            }

                        }
                    };
                    //Call the PageMethods
                    $.ajax(options);

                });
            });
        </script>




Calling PageMethods with parameters
The code in previous section discussed about calling a page method without passing parameters. In this section, we will see how to call
PageMethods with parameters.
We will have 2 PageMethods, one will check for available number of tickets for males and the other will check for the available number of tickets
for females.
 ------------------------------------------------------------------------------------
Codebehind
public partial class CallServerWithParameters : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static string GetAvailableTicketsForMales(int no)
    {
        string result = "";
        int NoOfTicketsAvailable = 5;
        if (no > NoOfTicketsAvailable)
        {
            result = "Only " + NoOfTicketsAvailable.ToString() + " Male ticket(s) avaialable. Please enter a lower number!";
        }
        return result;
    }
    [WebMethod]
    public static string GetAvailableTicketsForFemales(int no)
    {

        string result = "";
        int NoOfTicketsAvailable = 5;
        if (no > NoOfTicketsAvailable)
        {
            result = "Only " + NoOfTicketsAvailable.ToString() + " Female ticket(s) avaialable. Please eneter a lower number!";
        }
        return result;
    }
}
<form id="form1" runat="server">
        <asp:TextBox ID="txtNoOfTickets" runat="server"></asp:TextBox>
</form>

As I have said earlier, the JQuery.ajax() method will use JSON to communicate to the server. This method will return the number of tickets
available at that moment. In this example, I have hard-coded the available number of tickets. You can replace this value from the one got from
the database.

Download the source code attached in the download section of this article.


aspx:
<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>
        <script language="javascript">
            $(document).ready(function() {
                $("#txtNoOfMales").change(function() {
                    var ticketRequired = this.value;
                    var options = {
                        type: "POST",
                        url: "CallServerWithParameters.aspx/GetAvailableTicketsForMales",
                        data: "{no:" + ticketRequired + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(response) {
                            if (response.d != "") {
                                alert(response.d);
                                $("#txtNoOfMales").focus();
                            }
                        }
                    };
                    //Call the PageMethods
                    $.ajax(options);

                });

                $("#txtNoOfFemales").change(function() {
                    var ticketRequired = this.value;
                    var options = {
                        type: "POST",
                        url: "CallServerWithParameters.aspx/GetAvailableTicketsForFemales",
                        data: "{no:" + ticketRequired + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(response) {
                            if (response.d != "") {
                                alert(response.d);
                                $("#txtNoOfFemales").focus();
                            }
                        }
                    };
                    //Call the PageMethods
                    $.ajax(options);

                });

            });
        </script>

<div>
    No of Male Tickets:<asp:TextBox ID="txtNoOfMales" runat="server"></asp:TextBox>
    No of Female Tickets:<asp:TextBox ID="txtNoOfFemales" runat="server" ></asp:TextBox>
    </div>
-------------------------------------------------------------
GridView Style Edit Update in Repeater Control Using jQuery and Ajax:
http://www.codedigest.com/Articles/jQuery/261_GridView_Style_Edit_Update_in_Repeater_Control_Using_jQuery_and_Ajax.aspx
-----------------------------------------------------------------
Get Lable value:    $('#<%=Lables1.ClientID%>').text();
Set Lable value:     $('#<%=Lable1.ClientID%>').text("New Value");
Get Textbox value: $('#<%=TextBox1.ClientID%>').val();
Set Textbox value: $('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value: $('#<%=ddl1.ClientID%>').val();
Set Dropdown value: $('#<%=ddl1.ClientID%>').val("New value");
Get text of selected item in dropdown: $('#ddl1.ClientID%> option:selected').text();
Get Checkbox Status: $('#<%=CheckBox1.ClientID%>').attr('checked');
Check the checkbox: $('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Radiobutton: $('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control: $('#<%=TextBox1.ClientID%>').attr('disabled',true);
Enable any control: $('#<%=TextBox1.ClientId%>').attr('disabled',false);
Make textbox read only: $('#<%=TextBox1.clientid%>').attr('readonly','readonly');






Tuesday, April 12, 2011

Custom exceptions in c#.net


Custom exceptions in c#.net

Define custom exception class:
[Serializable]
public class
CustomException : Exception
{
    public CustomException()  : base() { } 
    public CustomException(string message)  : base(message) { }  
    public CustomException(string format, params object[] args)  :
        base(string.Format(format, args)) {  }  
    public CustomException(string message, Exception innerException) :
                                                         base(message, innerException) {  }

    public CustomException(string format, Exception innerException, params object[] args)  :
                                                         base(string.Format(format, args), innerException) { }  
    protected CustomException(SerializationInfo info, StreamingContext context) :
           base(info, context) { }
}
Example:
1. Throw exception with
out message:
         throw new CustomException()
2. Throw exception with
simple message:
       throw new CustomException(message)
3. Throw exception with
message format and parameters:
      throw new CustomException("Exception with parameter value '{0}'", param)
4. Throw exception with
simple message and inner exception:
      throw new CustomException(message, innerException)
5. Throw exception with message
format and inner exception. Note that, the variable length params
    are always floating
:
     throw new CustomException("Exception with parameter value '{0}'", innerException, param)
6. The last flavor of custom exception constructor is used during exception   
    serialization/deserialization.

Tuesday, March 29, 2011

Count Charactes in a TextBox by using JavaScript.

<asp:TextBox ID="txt_message" runat="server" CssClass="textarea" Height="100px" onkeyup="validatelimit(this)" TextMode="MultiLine" Width="250px"></asp:TextBox>

//Key Press Event
 function validatelimit(obj)
 {
    if(this.id)
    obj=this;   
    var i=obj.value.length;
    document.getElementById('<%= lbl_ccount.ClientID %>').innerHTML=i;
    if(1>0)
    {
        var q=i/160;
        var r=i%160;       
         if(r==0)
         {
            q=Math.round(q);
            document.getElementById('<%= lbl_mcount.ClientID%>').innerHTML=q;
         }
         else
         {
           q=Math.floor(q);                   
           document.getElementById('<%=lbl_mcount.ClientID%>').innerHTML=q+1;
          }   
       }
    else
    {
        document.getElementById('<%= lbl_mcount.ClientID %>').innerHTML=0;
    }
 }

Saturday, March 26, 2011

How to catch return value by using Asp.net and Stored procedure(sqlserver)?



Create procedure CheckEmpId
(
@EmpId_sp varchar(10)
)
as
begin
declare @count int
select @count=count(EmpId_db) from dbo.EmployeeMaster where EmpId_db=@EmpId_sp
return @count
end

#region To display Customer names
        public Boolean getCusNo()
        {
            try
            {
                sqlcmd = new SqlCommand("getCusName_sp", sqlcon);
                sqlcmd.CommandType = CommandType.StoredProcedure;
                sqlcmd.Parameters.Add("@CusNo_sp", SqlDbType.VarChar).Value = cusNo_cl;
                sqlcmd.Parameters.Add("return_value", SqlDbType.Int).Direction=ParameterDirection.ReturnValue;
                sqlcon.Open();
                sqlcmd.ExecuteNonQuery();
                int i = Convert.ToInt32(sqlcmd.Parameters["return_value"].Value);
                if (i == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                sqlcon.Close();
            }

        }