Tuesday 19 November 2013

Custom Column Filter only with a single textbox on each column without any operators and buttons.







Here i find custom search functionality for KendoUI grid. Hope you really find helpfull.

HTML
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.rtl.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.dataviz.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.mobile.all.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://cdn.kendostatic.com/2012.3.1114/js/kendo.all.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div id="grid"></div>
</body>
</html>
 

JavaScript
  dataSource:[ {
      foo: "Foo 1",
      bar: "Bar 1"
    } , {
      foo: "Foo 2",
      bar: "Bar 2"
    }
  ]
});

var grid = $("#grid").data("kendoGrid");

$("<tr><th class='k-header' data-field='foo'><input /></th><th data-field='bar' class='k-header' ><input /></th></tr>").appendTo($("#grid thead")).find("input").keyup(function() {
 
  grid.dataSource.filter({
    operator: "contains",
    value: $(this).val(),
    field: $(this).parent("th").data("field")
  });
 
});


http://www.kendoui.com/forums/kendo-ui-complete-for-asp-net-mvc/grid/custom-column-filter-only-with-a-single-textbox-on-each-column-without-any-operators-and-buttons.aspx


Another link is

http://jsbin.com/ihanun/1/edit

Wednesday 13 November 2013

Wednesday 30 October 2013

Make CSS3 Creatures

Something really amazing with css3 is one of here. You can see below.




So here you go for Html page code

 
Style for it
 




For reference link
http://bennettfeely.com/csscreatures/

Tuesday 29 October 2013

Which command using Query Analyzer will give you the version of SQL server and operating system?

This one is very important question for interview.

Here you go,

SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition').

Saturday 19 October 2013

MVC demo

This example for add and search record using entity framework in MVC3 using JSON.

Entity frame work database design is given below:


http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/creating-model-classes-with-the-entity-framework-cs

HomeController Page
namespace MvcAppVehicleSystem.Controllers

{
    public class HomeController : Controller
    {
        VehicleSysHireEntities2 _db;
        public HomeController()
        {
            _db = new VehicleSysHireEntities2();
        }

        public ActionResult Index()
        {
            var query = _db.VehicleRentTypes.ToList();

            var query2 = _db.VehicleCategories.ToList();

            var model = new Models.SelectViewModel
            {
                CategoryList = query2,
                RentTypeList = query
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(VehicleMasterModel role)
        {
            VehicleMaster currentVehicle = new VehicleMaster();
            currentVehicle.Brand = role.Brand;
            currentVehicle.Category = role.Category;
            currentVehicle.Model = role.Model;
            currentVehicle.Color = role.Color;
            currentVehicle.NoOfYear = role.NoOfYear;
            currentVehicle.RentType = role.RentType;
            _db.AddToVehicleMasters(currentVehicle);
            _db.SaveChanges();

            if (currentVehicle.ID > 0)
            {
                VehicleFacility currentfacility = new VehicleFacility();
                currentfacility.VehicleMasterID = currentVehicle.ID;
                currentfacility.HasABS = role.HasABS;
                currentfacility.HasAirCon = role.HasAirCon;
                currentfacility.HasCTX = role.HasCTX;
                _db.AddToVehicleFacilities(currentfacility);
                _db.SaveChanges();
            }
            return Json(true);
        }

        public ActionResult About()
        {
            var query = _db.VehicleRentTypes.ToList();
            var query2 = _db.VehicleCategories.ToList();
            var model = new Models.SelectViewModel
            {
                CategoryList = query2,
                RentTypeList = query
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult About(VehicleMaster role)
        {
            List objList = (from m in _db.VehicleMasters select m).ToList();
            return Json(objList);
        }

        [HttpPost]
        public ActionResult AboutResult(VehicleMasterModel role)
        {
            var objList = (from m in _db.VehicleMasters
                           where m.RentType == role.RentType
                           select new VehicleMasterModel()
                           {
                               Brand = m.Brand,
                               Model = m.Model
                           }).ToList();
            return Json(objList, JsonRequestBehavior.AllowGet);
        }
    }
}

Model-> SelectViewModel
 public class SelectViewModel

    {

        public List CategoryList { get; set; }

        public List RentTypeList { get; set; }

        public VehicleFacility currentvehiclefacility { get; set; }

        public VehicleMaster currentvehiclemaster { get; set; }

    }

Model-> VehicleCategoryModel
public class VehicleCategoryModel

    {

        public int ID { get; set; }

        public string Category { get; set; }

        public List VehicleCategoryList { get; set; }

    }

Model-> VehicleFacilityModel
  public class VehicleFacilityModel

    {

        public List VehicleMasterList { get; set; }

        public int ID { get; set; }

        public bool HasAirCon { get; set; }

        public bool HasABS { get; set; }

        public bool HasCTX { get; set; }

        public int VehicleMasterID { get; set; }

    }
 
Model-> VehicleMasterModel
 public class VehicleMasterModel

    {

        public int ID { get; set; }

        public int Category { get; set; }

        public string Brand { get; set; }

        public string Model { get; set; }

        public string Color { get; set; }

        public int NoOfYear { get; set; }

        public int RentType { get; set; }

        public bool HasAirCon { get; set; }

        public bool HasABS { get; set; }

        public bool HasCTX { get; set; }

        public int VehicleMasterID { get; set; }

    }

Model-> VehicleRentTypeModel
 public class VehicleRentTypeModel

    {

        public int ID { get; set; }

        public string RentType { get; set; }

        public List  VehicleRetTypeList { get; set; }

    }

Home->Index
@{
    ViewBag.Title = "Home Page";
}

@ViewBag.Message

@model MvcAppVehicleSystem.Models.SelectViewModel
Type @Html.DropDownList("ddlType", new SelectList(Model.RentTypeList, "ID", "RentType"), "Select Type", new { required = "required" }) Category @Html.DropDownList("ddlCategory", new SelectList(Model.CategoryList, "ID", "Category"), "Select Category", new { required = "required" })
Model @Html.DropDownList("ddlModel", new[] { new SelectListItem() {Text = "Audi",Value = "Audi"}, new SelectListItem() {Text = "Maruti",Value = "Maruti" }, new SelectListItem() {Text = "Suzuki",Value = "Suzuki" } }, "Choose model", new { required = "required" }) No of year @Html.DropDownList("ddlNoofYear", new[] { new SelectListItem() {Text = "2010",Value = "2010"}, new SelectListItem() {Text = "2011",Value = "2 011" }, new SelectListItem() {Text = "2012",Value = "2012" }, new SelectListItem() {Text = "2013",Value = "2013" } }, "Choose year", new { required = "required" })
Brand Has AirCon Has ABS Has CTX
Colour

Home->About
@{
    ViewBag.Title = "Search";
}
@model MvcAppVehicleSystem.Models.SelectViewModel

Search

Type @Html.DropDownList("ddlType", new SelectList(Model.RentTypeList, "ID", "RentType"), "Select Type")
No of year @Html.DropDownList("ddlNoofYear", new[] { new SelectListItem() {Text = "2010",Value = "2010"}, new SelectListItem() {Text = "2011",Value = "2011" }, new SelectListItem() {Text = "2012",Value = "2012" }, new SelectListItem() {Text = "2013",Value = "2013" } }, "Choose year")




Thursday 17 October 2013

For client side checkbox check all or uncheck all in girdview

 

Gridview header checkbox select and deselect all rows using client side JavaScript and server side C#

In this article, I will show you how to add checkbox in gridview header template then select and deselect all rows in gridview using clients side JavaScript and server side as well. 

Introduction


Adding checkbox in gridview header template and select/deselect all rows is a common requirement in most of the asp.net projects and frequently asked questions also. Here I will explain how to add checkbox in header template of gridview and select/deselect all rows using client side javascript and server side code.

Add Checkbox in Gridview header template


Create the asp.net project and drag the gridview control then format as likes below.

                
                
                
                
                
                    
                    
                    
                    
                        
                            
                        
                        
                        
                            
                        
                    
                
            

Using HeaderTemplate of gridview I had added checkbox and also added in Itemtemplate of same column.

Select and deselect using Client side


I’m loading the few sample employee records in gridview to select/deselect all rows. Below javascript CheckAllEmp function will do select and deselect when check and uncheck in header checkbox. Call this function in gridview headertemplate, checkbox onclick event as shown above.


Above javascript code will get gridview client id and loop the each row and get the checkbox id which is available in itemTemplate and make it select/deselect rows. This is the one of the way using client side script.

Select and deselect using Server side

Same functionality we can able to do with server side also. To do this make the changes in HeaderTemplate as like below.

                        
                            
                        
                        
                        
                            
                        
                    

Make it autopostback as true and create OnCheckedChanged event in checkbox and add the below code in chkboxSelectAll_CheckedChanged event in code behind part.
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox ChkBoxHeader = (CheckBox)GridVwHeaderChckboxSrvr.HeaderRow.FindControl("chkboxSelectAll");
            foreach (GridViewRow row in GridVwHeaderChckboxSrvr.Rows)
            {
                CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
                if (ChkBoxHeader.Checked == true)
                {
                    ChkBoxRows.Checked = true;
                }
                else
                {
                    ChkBoxRows.Checked = false;
                }
            }
        }

Above checked changed event will get the header checkbox id and if header checkbox is checked then find all rows checkbox id and make it all select else deselect all rows

For Jquery select and deselect
 function CheckAll(obj) {
   $('#<%=grdData.ClientID %> tbody tr td input:checkbox').attr('checked', obj.checked);
}

  function childclick() {
            if ($("#<%=grdData.ClientID %> input[name$='chkuser']").length == $("#<%=grdData.ClientID %> input[name$='chkuser']:checked").length) {
                $("#<%=grdData.ClientID %> input[name$='chkheaduser']").attr('checked', true);
            } else {
                $("#<%=grdData.ClientID %> input[name$='chkheaduser']").attr('checked', false);
            }
        }

For that grid have this one
  
                
                    
                
                
                    
                
 

All grid action server side events

Here i am going to show you simple asp grid all inline editing with sorting. Like CRUD operation in MVP structure.


.cs Page code


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex; BindData();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            GridViewRow row = GridView1.Rows[e.RowIndex];
            CurrentUserData = new Entity.UserData();
            CurrentUserData.UserId = Convert.ToInt64(GridView1.DataKeys[e.RowIndex].Value);
            _presenterData.GetCurrentData();

            CurrentUserData.FirstName = ((TextBox)(row.Cells[1].FindControl("TextBox1"))).Text;
            CurrentUserData.LastName = ((TextBox)(row.Cells[2].FindControl("TextBox2"))).Text;
            CurrentUserData.CompanyName = ((TextBox)(row.Cells[3].FindControl("TextBox3"))).Text;
            CurrentUserData.ContactNo = Convert.ToDecimal(((TextBox)(row.Cells[4].FindControl("TextBox4"))).Text);
            CurrentUserData.Address = ((TextBox)(row.Cells[5].FindControl("TextBox5"))).Text;
            CurrentUserData.Country = ((TextBox)(row.Cells[6].FindControl("TextBox6"))).Text;
            CurrentUserData.DOB = Convert.ToDateTime(((TextBox)(row.Cells[7].FindControl("TextBox7"))).Text);

            FileUpload fp = ((FileUpload)row.Cells[7].FindControl("fup"));
            if (fp.HasFile)
            {
                fp.SaveAs(Server.MapPath("Temp/" + fp.FileName)); CurrentUserData.ImgUrl = fp.FileName;
            }

            _presenterData.Update();
            GridView1.EditIndex = -1;
            BindData();

        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1; BindData();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            CurrentUserData = new Entity.UserData();
            CurrentUserData.UserId = Convert.ToInt64(GridView1.DataKeys[e.RowIndex].Value);
            _presenterData.Delete(); BindData();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                #region Old code

                _presenterData.GetAllData();

                if (lastSortExpression.Value == e.SortExpression.ToString())
                {
                    if (lastSortDirection.Value == SortDirection.Ascending.ToString())
                    {
                        e.SortDirection = SortDirection.Descending;
                    }
                    else
                    {
                        e.SortDirection = SortDirection.Ascending;
                    }
                    lastSortDirection.Value = e.SortDirection.ToString();
                    lastSortExpression.Value = e.SortExpression;
                }
                else
                {
                    lastSortExpression.Value = e.SortExpression;
                    e.SortDirection = SortDirection.Ascending;
                    lastSortDirection.Value = e.SortDirection.ToString();
                }


                switch (e.SortExpression)
                {
                    case "FirstName":
                        if (e.SortDirection == SortDirection.Ascending)
                        {
                            GridView1.DataSource = UserDatas.OrderBy(x => x.FirstName).ToList();
                            GridView1.DataBind();
                        }
                        else
                        {
                            GridView1.DataSource = UserDatas.OrderByDescending(x => x.FirstName).ToList();
                            GridView1.DataBind();
                        }
                        break;

                    case "LastName":
                        if (e.SortDirection == SortDirection.Ascending)
                        {
                            GridView1.DataSource = UserDatas.OrderBy(x => x.LastName).ToList();
                            GridView1.DataBind();
                        }
                        else
                        {
                            GridView1.DataSource = UserDatas.OrderByDescending(x => x.LastName).ToList();
                            GridView1.DataBind();
                        }
                        break;
                    case "CompanyName":
                        if (e.SortDirection == SortDirection.Ascending)
                        {
                            GridView1.DataSource = UserDatas.OrderBy(x => x.CompanyName).ToList();
                            GridView1.DataBind();
                        }
                        else
                        {
                            GridView1.DataSource = UserDatas.OrderByDescending(x => x.CompanyName).ToList();
                            GridView1.DataBind();
                        }
                        break;
                    case "ContactNo":
                        if (e.SortDirection == SortDirection.Ascending)
                        {
                            GridView1.DataSource = UserDatas.OrderBy(x => x.ContactNo).ToList();
                            GridView1.DataBind();
                        }
                        else
                        {
                            GridView1.DataSource = UserDatas.OrderByDescending(x => x.ContactNo).ToList();
                            GridView1.DataBind();
                        }
                        break;
                    case "Address":
                        if (e.SortDirection == SortDirection.Ascending)
                        {
                            GridView1.DataSource = UserDatas.OrderBy(x => x.Address).ToList();
                            GridView1.DataBind();
                        }
                        else
                        {
                            GridView1.DataSource = UserDatas.OrderByDescending(x => x.Address).ToList();
                            GridView1.DataBind();
                        }
                        break;
                    case "Country":
                        if (e.SortDirection == SortDirection.Ascending)
                        {
                            GridView1.DataSource = UserDatas.OrderBy(x => x.Country).ToList();
                            GridView1.DataBind();
                        }
                        else
                        {
                            GridView1.DataSource = UserDatas.OrderByDescending(x => x.Country).ToList();
                            GridView1.DataBind();
                        }
                        break;
                    case "DOB":
                        if (e.SortDirection == SortDirection.Ascending)
                        {
                            GridView1.DataSource = UserDatas.OrderBy(x => x.DOB).ToList();
                            GridView1.DataBind();
                        }
                        else
                        {
                            GridView1.DataSource = UserDatas.OrderByDescending(x => x.DOB).ToList();
                            GridView1.DataBind();
                        }
                        break;
                    default:
                        break;
                }

                #endregion

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

       

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                CurrentUserData = new Entity.UserData();
                CurrentUserData.FirstName = ((TextBox)GridView1.FooterRow.FindControl("txtFirstName")).Text;
                CurrentUserData.LastName = ((TextBox)GridView1.FooterRow.FindControl("txtLastName")).Text;
                CurrentUserData.CompanyName = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;

                CurrentUserData.ContactNo = Convert.ToDecimal(((TextBox)GridView1.FooterRow.FindControl("txtContact")).Text);
                CurrentUserData.Address = ((TextBox)GridView1.FooterRow.FindControl("txtAddress")).Text;
                CurrentUserData.Country = ((TextBox)GridView1.FooterRow.FindControl("txtCountry")).Text;
                CurrentUserData.DOB = Convert.ToDateTime(((TextBox)GridView1.FooterRow.FindControl("txtDOB")).Text);

                FileUpload fup = ((FileUpload)GridView1.FooterRow.FindControl("fupImg"));
                if (fup.HasFile)
                {
                    fup.SaveAs(Server.MapPath("Temp/" + fup.FileName)); CurrentUserData.ImgUrl = fup.FileName;
                }
                _presenterData.Add();

                BindData();

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

.aspx page
    Select
Name : <%# Eval("FirstName") %>   <%# Eval("LastName") %>
Company : <%# Eval("CompanyName") %>
 

Style
  .tooltip
        {
            position: relative; /* color: Black;*/
        }
        
        .tooltip span td
        {
            text-align: left;
        }
        .tooltip span
        {
            display: none;
        }
        .tooltip:hover span
        {
            display: block;
            position: absolute;
            color: Black;
            width: 200px;
            background-color: rgba(251,251,251,0.9);
            border: 1px solid #a2a2a2;
            z-index: 100;
            border-radius: 7px;
            box-shadow: 2px 1px 3px 2px #a2a2a2;
        }
        input[type="text"]
        {
            width: 100px;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 3px;
        }
        
        td
        {
            text-align: center;
        }


For custom paging in grid view
http://www.codeproject.com/Articles/16238/GridView-Custom-Paging
http://www.dotnetcurry.com/ShowArticle.aspx?ID=345 

Tuesday 15 October 2013

Count words and reverse operation in Char Array

In interview sometimes asked logical question. One of is here.
  • Get the count of word in given char array in c#. So here you go..
char[] arr = "My name is ABC XYZ.".ToCharArray();
               
 string str = "";
 ArrayList lst = new ArrayList();
 foreach (var item in arr)
  {
  if (item.ToString() == " " || item.ToString() == ".")
   {
       lst.Add(str);
       str = "";
   }
  else
  {
   str += item.ToString();
  }

 }
 Response.Write(lst.Count);

Output :  5
  • Get the reverse order of char array
 //For reverse array
 lst.Reverse();
 var mystr = "";
 foreach (var item in lst)
 {
  mystr += item + " ";
 }
 Response.Write("Count : " + lst.Count + " Reverse : " + mystr);

Output : XYZ ABC is name My
  • Get the reverse order of char array with single string
 //Reverse string
 char[] abc = "HiralSavaria".ToCharArray();
 Array.Reverse(abc);
 Response.Write("
" + new string(abc));

Output : airavaSlariH

Monday 30 September 2013

Date function in c#

List the First Monday of every month using C# 

Here’s some code for listing down the first Monday of every month in an year using C# .NET. The Monday’s listed in this example are for the year 2010

public static void Main(string[] args)
{
    for (int mth = 1; mth <= 12; mth++)
    {
        DateTime dt = new DateTime(2010, mth, 1);
        while (dt.DayOfWeek != DayOfWeek.Monday)
        {
            dt = dt.AddDays(1);
        }
        Console.WriteLine(dt.ToLongDateString());
    }
    Console.ReadLine();
}

Calculate the Monday in the first week of the year

private DateTime GetFirstMondayOfYear(int year)
{
    DateTime dt = new DateTime(year, 1, 1);

    while (dt.DayOfWeek != DayOfWeek.Monday)
    {
        dt = dt.AddDays(1);
    }

    return dt;
}

Calculate week of month in .NET

There is no built in way to do this but here is an extension method that should do the job for you:

static class DateTimeExtensions {
    static GregorianCalendar _gc = new GregorianCalendar();
    public static int GetWeekOfMonth(this DateTime time) {
        DateTime first = new DateTime(time.Year, time.Month, 1);
        return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
    }

    static int GetWeekOfYear(this DateTime time) {
        return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
    }
}
Usage:
DateTime time = new DateTime(2010, 1, 25);
Console.WriteLine(time.GetWeekOfMonth());

Thursday 12 September 2013

Store array in LocalStorage (HTML5)

Sometimes we need to store an array at client side so the best way to store array in localstorage just like temp storage container. So here is code.

localStorage only supports strings. Use JSON.stringify() and JSON.parse().
var names = [];
names[0] = prompt("New member name?");
localStorage["names"] = JSON.stringify(names);

//...
var storedNames = JSON.parse(localStorage["names"]);

Tuesday 3 September 2013

Display JSON data direct to table formate

I had found a lot but not find appropriate solution. But now i have done such good thing.
Here you can load your JSON data to table .

For that In HTML

  <div id="example">
    </div>

For Style

 td,th
        {
            padding: 3px;border:1px solid #dedede;
        }

For Script

 var Data = '[{ "User_Code": "abenns1", "First_Name": "Aaron", "Last_Name": "Benns", "Is_Supervisor": 0 }, { "User_Code": "ahansen3", "First_Name": "Alan", "Last_Name": "Hansen", "Is_Supervisor": 1 }, { "User_Code": "ADamasc", "First_Name": "Armel", "Last_Name": "Damasco", "Is_Supervisor": 0 }, { "User_Code": "cjohnso267", "First_Name": "Cliff", "Last_Name": "Johnson", "Is_Supervisor": 0 }, { "User_Code": "dkane", "First_Name": "Donald", "Last_Name": "Kane", "Is_Supervisor": 0 }, { "User_Code": "epangil", "First_Name": "Edgar", "Last_Name": "Pangilinan", "Is_Supervisor": 0 }, { "User_Code": "EBayara", "First_Name": "Enrique", "Last_Name": "Bayaras", "Is_Supervisor": 0 }, { "User_Code": "fcabanl", "First_Name": "Fernando", "Last_Name": "Cabanlig", "Is_Supervisor": 0 }, { "User_Code": "hcabuan1", "First_Name": "Henry", "Last_Name": "Cabuang1", "Is_Supervisor": 1 }, { "User_Code": "ibaaqee", "First_Name": "Ibrahim", "Last_Name": "Baaqee", "Is_Supervisor": 0 }, { "User_Code": "JGangan2", "First_Name": "Jaime", "Last_Name": "Gangano", "Is_Supervisor": 0 }, { "User_Code": "mgaite", "First_Name": "Marcel", "Last_Name": "Gaite", "Is_Supervisor": 0 }, { "User_Code": "mmorris18", "First_Name": "Michael", "Last_Name": "Morris", "Is_Supervisor": 0 }, { "User_Code": "psabido1", "First_Name": "Philip", "Last_Name": "Sabido", "Is_Supervisor": 1 }, { "User_Code": "rcuento", "First_Name": "Reginald", "Last_Name": "Cuento", "Is_Supervisor": 0}]';

  var newdb = JSON.parse(Data);
            //alert(newdb.length);
            $("#example").html("<table>");

            var firstrow = newdb[0];
            $("#example").append("<tr>");
            $.each(firstrow, function (index) {
                $("#example").append("<th>" + index + "</th>");
            });
            $("#example").append("</tr>");


            $.each(newdb, function (index, val) {
                $("#example").append("<tr>");
                $.each(val, function (index) {
                    var code = index;
                    var country = val[index];
                    // $("#example").append("<b>" + code + " : </b>" + country + "&nbsp;&nbsp;");                  
                    $("#example").append("<td>" + country + "</td>");
                });
                $("#example").append("</tr>");
                // $("#example").append("<br/>");

            });
            $("#example").append("</table>");



Here you can give your JSON result to Data.



Friday 30 August 2013

Custome Error 404 Page

Its been hard stuff to handle 404 error in our web application. I found one good solution. I would like to share with you.

Detecting HTTP 404 Errors in Global.asax

While I realize this is a simple task and once you see how to do it you will immediately say, I knew that, but for those of you who have not discovered how to detect http 404 errors let me show you.
The following code may be inserted into your Global.asax file.

protected void Application_Error(object sender, EventArgs e)
{
Exception ex = null;
if (HttpContext.Current.Server.GetLastError() != null)
{
ex = HttpContext.Current.Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(HttpException))
{
HttpException httpException = (HttpException)ex;
if (httpException.GetHttpCode() == 404)
{
Server.Transfer(“~/ErrorPage.htm”);
return;
}
}
}

The above code if placed into you Global.asax file will intercept Http 404 errors and transfer to your page that handles that particular error.  You may also check for any other particular http error and transfer to another page if you choose.
You see, it is a simple task, now that you know how.


You can also do it another way
In WebConfig


 <customErrors mode="On"  defaultRedirect="http://localhost:60876/ErrorPage.htm">     
      <error statusCode="403" redirect="http://localhost:60876/ErrorPage.htm" />
      <error statusCode="404" redirect="http://localhost:60876/ErrorPage.htm" />
  </customErrors>

 

 

Wednesday 31 July 2013

Get NameValueCollection collection of Webconfig To Clientside

I had one issue that i had to get NameValueCollection  at client side. I get all this array at server side  perfactly. But i want that at client side. So i had lots of RND but not getting proper result. So here i am sharing you one of good solution.

My Web config

<configuration>
  <configSections>
    <section name="MyDictionary" type="System.Configuration.NameValueSectionHandler" />
  </configSections>
  <appSettings>
    <add key="test" value="test"/>
   
  </appSettings>
  <MyDictionary>
    <add key="Regular" value="10"/>
    <add key="Senior" value="11"/>
    <add key="Under25" value="17"/>
    <add key="Child" value="35"/>
    <add key="Educator" value="28"/>
    <add key="Child2" value="134"/>
  </MyDictionary>

</configuration>

MyTest.aspx.cs



    public NameValueCollection section { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            section = (NameValueCollection)ConfigurationManager.GetSection("MyDictionary");
            str = section["Regular"];
            keys = section.AllKeys;
         
            for (int i = 0; i < section.Keys.Count; i++)
            {
                Page.ClientScript.RegisterArrayDeclaration("myArray", "'" + section[i] + "'");
                Page.ClientScript.RegisterArrayDeclaration("myArray1", "'" + section.Keys[i] + "'");               
            }

        }


    }

MyTest.aspx

 <script type="text/javascript">
        $(document).ready(function () {           
            myfunction();
        });
        function myfunction() {
            for (var i = 0; i < myArray.length; i++) {
                alert(myArray[i]);
            }
        }
    </script>


Monday 22 July 2013

Show loading image while Page is loading using jQuery

Web pages takes time to load and sometimes when page is heavy (full of images) then it takes more time to load. Would it not be nice to show loading images or message while your page is loading. It creates responsive webpage and gives nice user experience. The user will come to know that something is loading. In this post, I will show you how to show loading icon/image while page is loading using jQuery.

Related Post:

How to do it?


First create a div element and assign an ID to it. I have assigned ID as "dvLoading". This div element will be used to show the loading icon.


Now create a style which will be applied to the div element. Basically, this CSS style will set the div position in the middle of the page and also assign width and height. And the background of the div will be an loading gif image.
#dvLoading
{
   background:#000 url(images/loader.gif) no-repeat center center;
   height: 100px;
   width: 100px;
   position: fixed;
   z-index: 1000;
   left: 50%;
   top: 50%;
   margin: -25px 0 0 -25px;
}

Now, comes the jQuery part. The div element will be always visible but we need to hide it as soon as our page is loaded completely. In this case, we can't use $(document).ready() to show the loading div. Read here why? Therefore, we need to use window.load event to hide the loading div element. Remember to put this code before closing head tag.


That's it!!!!! 
Feel free to contact me for any help related to jQuery, I will gladly help you.