Monday 2 December 2013

jQuery For Beginners

Hai friends I'm going to post my small innovation that might help you .Here I'm going to present something called jQuery.

What is jQuery?

jQuery means simply what we say Write less Do more. jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

So lets start our task...:)

Components used for the development


  1. Visual Studio 2.0  or greater
  2. jQuery files  
                  jquery-1.7.1.js 
                 jquery-1.7.1.min .js
These files can be available from jquery website
Along with this file I created a custom js file called MyCustom.js. Here I created client side validations.

Step1

After adding respective js files into a new Asp.Net solution ,specify the components to a new default.aspx page.
In the source it should be like

Note(Never specify any custom js files above jQuery library.When you see the the tags you can see myCustom.js is placed below my jquery-1.7.1.js and jquery-1.7.1.min.js files )

<head runat="server">
    <title>Untitled Page</title>
    <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="Scripts/MyCustom.js" type="text/javascript"></script>
</head>

Step2

Inside body tag inside form tag add a div tag and inside that specify the code as shown below

<strong>Jquery Samples</strong>
    <table>
        <tr>
        <td><span style="color:Red">*</span>First Name</td>
        <td><asp:TextBox ID="txt_FName" runat="server" class="txt_FNameCls disable"></asp:TextBox></td>
        <td><span id="spn_FnameError" style="color:Red"></span></td>
    </tr>
        
        <tr>
        <td><span style="color:Red">*</span>Last Name</td>
        <td><asp:TextBox ID="txt_LName" runat="server" class="txt_LNameCls disable"></asp:TextBox></td>
        <td><span id="spn_LNameError" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td><span style="color:Red">*</span>Address</td>
        <td><asp:TextBox ID="txt_Address1" runat="server" class="txt_Address1Cls disable"></asp:TextBox></td>
        <td><span id="spn_AddError" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td></td>
        <td><asp:TextBox ID="txt_Address2" runat="server"></asp:TextBox></td>
        <td></td>
        </tr>
        
        <tr>
        <td></td>
        <td><asp:TextBox ID="txt_Address3" runat="server"></asp:TextBox></td>
        <td></td>
        </tr>
        
        <tr>
        <td><span style="color:Red">*</span>City</td>
        <td><asp:TextBox ID="txt_City" runat="server" class="txt_CityCls disable"></asp:TextBox></td>
        <td><span id="spn_txtCityError" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td><span style="color:Red">*</span>State</td>
        <td><asp:DropDownList ID="drp_State" runat="server" class="drp_StateCls" 
                Width="156px">
            <asp:ListItem>Select State</asp:ListItem>
            <asp:ListItem>Alaska</asp:ListItem>
            <asp:ListItem>NewYork</asp:ListItem>
            <asp:ListItem>Seattle</asp:ListItem>
            <asp:ListItem>Washington</asp:ListItem>
            <asp:ListItem></asp:ListItem>
            </asp:DropDownList></td>
        <td><span id="spn_StateError" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td><span style="color:Red">*</span>Day Phone</td>
        <td><asp:TextBox ID="txt_DPhone" runat="server" class="txt_DPhoneCls disable"></asp:TextBox></td>
        <td><span id="spn_DPhoneError" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td><span style="color:Red">*</span>Night Phone</td>
        <td><asp:TextBox ID="txt_NPhone" runat="server"  class="txt_NPhoneCls disable"></asp:TextBox></td>
        <td><span id="spn_NPhoneError" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td><span style="color:Red">*</span>Gender</td>
        <td><asp:RadioButtonList ID="rbtnListGender" runat="server" class="rbtnListGender" 
                RepeatDirection="Horizontal">
            <asp:ListItem>Male</asp:ListItem>
            <asp:ListItem>Female</asp:ListItem>
            </asp:RadioButtonList></td>
        <td><span id="spn_GenderError" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td><span style="color:Red">*</span>Qualification</td>
        <td><asp:CheckBoxList ID="chkQualification" runat="server" class="chkQualification">
            <asp:ListItem>HSE</asp:ListItem>
            <asp:ListItem>Degree</asp:ListItem>
            <asp:ListItem>PG</asp:ListItem>
            <asp:ListItem>Others</asp:ListItem>
            </asp:CheckBoxList></td>
        <td><span id="spn_qualification" style="color:Red"></span></td>
        </tr>
        
        <tr>
        <td colspan="2" align="center"><asp:Button ID="btn_Save" runat="server" Text="Save" class="btn_SaveCls" Width="160px"/></td>
        </tr>
        

    </table>

Step3

Place the below lines inside our custom js file ie MyCustom.js f


//Created By Marrit K John
//Version 0.5
//Date :2-12-2013


$(document).ready(function() {

    //Button Click Event
    $('.btn_SaveCls').click(function() {

        var retValue = CheckValidation();
        if (retValue == true) {
            alert('Successfully achieved');
        }
        return retValue;
    });

    //Remove All AutoFill if any browsers allows if any.
    $("input").attr("autocomplete", "off");

    //Border color get back if user made any focus on textbox control.
    $('input[type=text]').focus(function() {
        $(this).closest('td').next('td').find('span').text('');
        $(this).removeAttr('style');
    });
    
    //Click action for radio button list
    $('.rbtnListGender').click(function() {
        $('#spn_GenderError').text('');
    });
    //Click action for checkboxlist  
    $('.chkQualification').click(function() {
        $('#spn_qualification').text('');
    });

    //Click action for dropdownlist
    $('.drp_StateCls').click(function() {
        $('#spn_StateError').text('');
        $('.drp_StateCls').css({ "border-color": "none", "border": "1px solid" });
    });
    
    //Key Down event action for dropdown
    $('.drp_StateCls').keydown(function() {
        $('#spn_StateError').text('');
        $('.drp_StateCls').css({ "border-color": "none", "border": "1px solid" });
    });
    MaxLength();
    BlockCopyPaste();
    AllowNumbersOnly();
});
function CheckValidation() {
      //  alert('hi');
    var retvalue = true;
   
        var fname = $.trim($('.txt_FNameCls').val());
        var lname = $.trim($('.txt_LNameCls').val());
        var address = $.trim($('.txt_Address1Cls').val());
        var city = $.trim($('.txt_CityCls').val());
        var state = $.trim($('.drp_StateCls').val());
        var dPhone = $.trim($('.txt_DPhoneCls').val());
        var nPhone = $.trim($('.txt_NPhoneCls').val());
        if (fname == "") {
            $('#spn_FnameError').text('Please Enter First Name');
            $('.txt_FNameCls').css({ "color": "red", "border": "2px solid red" });
            retvalue = false;
        }
        if (lname == "") {
            $('#spn_LNameError').text('Please Enter Last Name');
            $('.txt_LNameCls').css({ "color": "red", "border": "2px solid red" });
            retvalue = false;
        }
        if (address == "") {
            $('#spn_AddError').text('Please Enter Address');
            $('.txt_Address1Cls').css({ "color": "red", "border": "2px solid red" });
            retvalue = false;
        }
        if (city == "") {
            $('#spn_txtCityError').text('Please Enter City');
            $('.txt_CityCls').css({ "color": "red", "border": "2px solid red" });
            retvalue = false;
        }
        if (dPhone == "") {
            $('#spn_DPhoneError').text('Please Enter Day Phone');
            $('.txt_DPhoneCls').css({ "color": "red", "border": "2px solid red" });
            retvalue = false;
        } else if (dPhone.length < 10) {
            $('#spn_DPhoneError').text('Please Enter a Valid Day Phone');
            $('.txt_DPhoneCls').css({ "border-color": "red", "border": "2px solid red" });
            retvalue = false;

        }

        if (nPhone == "") {
            $('#spn_NPhoneError').text('Please Enter Night Phone');
            $('.txt_NPhoneCls').css({ "color": "red", "border": "2px solid red" });
            retvalue = false;
        } else if (nPhone.length < 10) {
            $('#spn_NPhoneError').text('Please Enter a Valid Night Phone');
            $('.txt_NPhoneCls').css({ "border-color": "red", "border": "2px solid red" });
            retvalue = false;
        }
        var genderCheckedCount = $(".rbtnListGender :radio:checked").length;
            if (genderCheckedCount >0 ) {
                $('#spn_GenderError').text('');
            }
            else {
                $('#spn_GenderError').text('Please Select Any Gender');
                retvalue = false;
            }
            var qualificationCount = $(".chkQualification :checkbox:checked").length;
            if (qualificationCount > 0) {
                $('#spn_qualification').text('');
            }
            else {
                $('#spn_qualification').text('Please Select Any Qualification');
                retvalue = false;
            }
           
            if (state == "Select State") {
                $('#spn_StateError').text('Please Select Any State');
                $('.drp_StateCls').css({ "border-color": "red", "border": "2px solid red" });
                retvalue = false;
            }
            else {
                $('#spn_StateError').text('');
                $('.drp_StateCls').css({ "border-color": "none", "border": "1px solid" });
               
            }
        return retvalue;
    }

//For setting Max length in a text box

    function MaxLength() {
       
        $(".txt_FNameCls").attr('maxlength', '20');
        $(".txt_LNameCls").attr('maxlength', '20');
        $(".txt_Address1Cls").attr('maxlength', '40');
        $(".txt_DPhoneCls").attr('maxlength', '10');
        $(".txt_NPhoneCls").attr('maxlength', '10');
    }
    function BlockCopyPaste() {
        var controls = $(".disable");
        controls.bind("paste", function() {
            return false;
        });
        controls.bind("drop", function() {
            return false;
        });
        controls.bind("cut", function() {
            return false;
        });
        controls.bind("copy", function() {
            return false;
        });
    }
    function AllowNumbersOnly() {
        $('input[name="txt_DPhone"]').keyup(function(e) {
            
            if (/\D/g.test(this.value)) {
                this.value = this.value.replace(/\D/g, '');
            }
        });

        $('input[name="txt_DPhone"]').keypress(function(e) {
          
            if (this.value.length == 0 && e.which == 48) {
                $('#spn_DPhoneError').text('Please Enter valid Day Phone');
                return false;
            }
            else {
                $('#spn_DPhoneError').text('');
            }
        });
        $('input[name="txt_NPhone"]').keyup(function(e) {
            if (/\D/g.test(this.value)) {
                this.value = this.value.replace(/\D/g, '');
            }
        });
        $('input[name="txt_NPhone"]').keypress(function(e) {

            if (this.value.length == 0 && e.which == 48) {
                $('#spn_NPhoneError').text('Please Enter valid Night Phone');
                return false;
            }
            else {
                $('#spn_NPhoneError').text('');
            }
        });

    }


Sunday 16 December 2012

WCF Sample


Step  1:
Open  SQL Server management studio, then open new query editor and do the following operations,
--command to create new database
create database BookDB
--Shift to BookDB databse from Master DB
use BookDB
--Query to create new tables with colums
create table BookInfo(
book_id int primary key,
book_name  varchar(25),
book_author varchar(25),
book_publisher varchar(25),
book_price varchar(10),
book_availability bit
)
--Query to check any values in BookInfo table
select * from BookInfo
--Inserting first record into BookInfo table
insert into BookInfo(book_id,book_name,book_author,
            book_publisher,book_price,book_availability)
     values('1','ASP.NET','Michel Angel','TKL Publication',
            '255.50',1)
--Query to check any values in BookInfo table
select * from BookInfo
--Inserting second record into BookInfo table
insert into BookInfo(book_id,book_name,book_author,
            book_publisher,book_price,book_availability)
     values('2','C#.NET','Kuttan Pilla','Pilla Publication',
            '655.50',1)
--Query to check any values in BookInfo table
select * from BookInfo
--Inserting  third record into BookInfo table
insert into BookInfo(book_id,book_name,book_author,
            book_publisher,book_price,book_availability)
     values('3','SQL Server 2012','Moudin Kunjalli','Abud Publication',
            '659.50',1)
--Query to check any values in BookInfo table
select * from BookInfo


Step 2:

Create a WCF service Library and name it as WCFBookService and delete the default IServices interface ,Service class and App.conf files .

Step 3:

Create a new public class called BookReqEntity.cs and add System.Runtime.Serialization reference.

#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

#endregion

namespace WCFBookService
{
    /// <summary>
    /// BookReqEntity class is used for requesting book info on the criteria BookID
    /// </summary>
    [DataContract]
    public class BookReqEntity
    {
        #region Public Properties
        [DataMember]
        public int BookID
        {
            get;
            set;
        }
        #endregion
    }
}



Step 4:

Create a public class called BookResEntity.cs and add the following

#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

#endregion

namespace WCFBookService
{
    /// <summary>
    /// BookResEntity class is used for deliver book info on the criteria BookID
    /// </summary>
    [DataContract]
    public class BookResEntity
    {
        #region Public Properties
        [DataMember]
        public int BookID
        {
            get;
            set;
        }
        [DataMember]
        public string BookName
        {
            get;
            set;
        }
        [DataMember]
        public string BookAuthor
        {
            get;
            set;
        }
        [DataMember]
        public string BookPublisher
        {
            get;
            set;
        }
        [DataMember]
        public string BookPrice
        {
            get;
            set;
        }
        [DataMember]
        public bool BookAvailability
        {
            get;
            set;
        }
        #endregion
    }
}

Step 5:
Create an interface named it as  IBook and add  System.ServiceModel
#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

#endregion

namespace WCFBookService
{
    [ServiceContract]

    interface IBook
    {
        [OperationContract]

        BookResEntity GetBookInfo(BookReqEntity bookReqEntity);
    }
}
Step 6:

Add a application configuration file to the current application and modify to
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
      <connectionStrings>
            <add name="conStr" connectionString="Data Source=.;Initial Catalog=BookDB;User ID=sa;Password=abc"/>
      </connectionStrings>
</configuration>

Step 7:

Create its implemetation and named it as Book.cs also make it as public.
Add three additional namespaces

a) System.ServiceModel
b) System.Configuration
c) System.Data.SqlClient


#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Configuration;
using System.Data.SqlClient;

#endregion

namespace WCFBookService
{
    [ServiceBehavior]
    public class Book : IBook
    {
        [OperationBehavior]
        public BookResEntity GetBookInfo(BookReqEntity bookReqEntity)
        {
           
            BookResEntity bookResEntity = null;
            string Cstring = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(Cstring))
            {
                con.Open();
                string query = String.Format("select * from BookInfo where book_id ={0}", bookReqEntity.BookID);
                SqlCommand cmd = new SqlCommand(query, con);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    bookResEntity = new BookResEntity()
                    {
                        BookID = dr.GetInt32(0),
                        BookName = dr.GetString(1),
                        BookAuthor = dr.GetString(2),
                        BookPublisher = dr.GetString(3),
                        BookPrice = dr.GetString(4),
                        BookAvailability = dr.GetBoolean(5)
                    };
                }
            };
            return bookResEntity;
           
        }

    }
}

Step 8:

Add another console application and named it as  CustomerHost and make it as public

Add reference –WCFBookService

#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFBookService;
using System.ServiceModel;
#endregion

namespace BookHost
{
   public class BookHostClass
    {
        static void Main(string[] args)
        {
            ServiceHost sHost = null;
            Type t = null;
            try
            {
                t = typeof(Book);
                sHost = new ServiceHost(t);
                sHost.Opened += delegate(object sender, EventArgs er)
                {
                    Console.WriteLine("Book Service Hosted Successfully");
                };
                sHost.Closed += delegate(object sender, EventArgs er)
                {
                    Console.WriteLine("Book Service closed Successfully");
                };
                sHost.Open();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
            finally
            {
                if (sHost != null && sHost.State != CommunicationState.Closed)
                {
                    sHost.Close();
                    Console.ReadLine();
                }
            }
        }
    }
}


Step 9:
Add a appconfig file and specify connection string


<?xml version="1.0" encoding="utf-8" ?>

<configuration>
      <connectionStrings>
            <add name="conStr" connectionString="Data Source=.;Initial Catalog=BookDB;User ID=sa;Password=abc"/>
      </connectionStrings>
 <system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="BookBehaviour">
     <serviceDebug />
     <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8811/BookServiceAddress/Mex" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="BookBehaviour" name="WCFBookService.Book">
    <endpoint address="http://localhost:8811/BookServiceAddress"
     binding="basicHttpBinding" bindingConfiguration="" name="BookServiceEndPoint"
     contract="WCFBookService.IBook" />
   </service>
  </services>
 </system.serviceModel>
</configuration>


Then do the proccess same like 


Step 10:


Add another Client Console application which act as UI/Client ,name it as BookClient
Do the steps .
a) Add Service refence  your hosted application.
b)Open debug folder of hosted application.Click BookHost.exe.Do not close it just minimize it.
c) Add service reference ,specify 

http://localhost:8811/BookServiceAddress/Mex


Step 11:

On the client Program.cs file edit code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClientConsole.BookServiceReference;
namespace ClientConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            using (BookClient b = new BookClient())
            {
                BookReqEntity bReq = new BookReqEntity();
                Console.WriteLine("Enter the Book Id");
                int bId = Convert.ToInt32(Console.ReadLine());
                bReq.BookID = bId;
                BookResEntity bRes = new BookResEntity();
                bRes = b.GetBookInfo(bReq);
                if (bRes != null)
                {
                    Console.Write("Book Id:{0},\nBook Name:{1},\nBook Author :{2},\nBookPublisher :{3},\nBook Price{4},\nBook Availability:{5}", bRes.BookID, bRes.BookName, bRes.BookAuthor, bRes.BookPublisher,
                        bRes.BookPrice, bRes.BookAvailability);
                    Console.ReadLine();
                }
                Console.WriteLine("Search book not found!");
                Console.ReadLine();
            };
           
        }
    }
}

Debug Operations:

First debug the host application,then your client console application.