Tuesday, April 12, 2011

Web Grid with Razor Engine,Paging and Customized Edit and Delete facility

In this post I will show you how to use web grid in Asp.Net MVC 3 with Razor Engine with customization it contains Edit ,Delete facilities as we find in normal Asp.Net Web Application :

@model IEnumerable<ContactMangerModel.ContactModel>

@{
          ViewBag.Title = "List";
    }
@{
   
    var grid = new WebGrid(source: Model,
                                           defaultSort: "First Name",
                                           rowsPerPage:5, fieldNamePrefix:"wg_",
                                           canPage:true,canSort:true,
                                           pageFieldName:"pg",sortFieldName:"srt"
                                           ); 
 }

 <table cellpadding="0" cellspacing="0" width="100%">
    <tr>
        <td>
            @grid.GetHtml(tableStyle:"listing-border",headerStyle:"gridhead",footerStyle:"paging",rowStyle:"td-dark",alternatingRowStyle:"td-light",
                            columns:
                                grid.Columns(
                                grid.Column(header:"", format: @<text><input id="chk" type="checkbox" value="@item.ID" /></text>),
                                    grid.Column("FirstName", "First Name", style: "colFirstName"),
                                    grid.Column("LastName", "Last Name", style: "colLastName"),
                                    grid.Column("Phone", "Phone", style: "colPhone"),
                                    grid.Column("Email", "Email", style: "colEmail"),
                                    grid.Column("ContactType_Name", "Contact Type", style: "colContactType"),
                                    grid.Column("IsActive", "Status",
                                                    format: (item) => (item.IsActive) ? Html.Raw("<img src='../../Content/images/active.png' />") :
                                                                                        Html.Raw("<img src='../../Content/images/inactive.png' />"),
                                                    style: "colOperation"),
                                    grid.Column(header: "Edit", format: @<text><a href="@Url.Action("Edit", "Contact", new { id = item.id })" ><img src="../../Content/images/edit.png" alt="" style="border:none;" /></a></text>, style: "colOperation"),
                                    grid.Column(header: "Delete", format: @<text><a href="@Url.Action("Delete", "Contact", new { id = item.id })" onclick="javascript:return ConfirmDelete();"><img src="../../Content/images/delete.png" alt="" style="border:none;" /></a></text>, style: "colOperation")
                                ),mode:WebGridPagerModes.Numeric)
        </td>
    </tr>
 </table>
<script type="text/javascript">
    function ConfirmDelete() {
        return confirm("Are you sure you want to delete contacts?");
    }
</script>

My Style Sheet :

.listing-border { background: #fd7d0f;}
.gridhead { background:#FFAA5F;  font: bold 13px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; height: 27px; text-align: left;}
.gridhead th a {text-decoration:none;color:#000000;}
.gridhead th a:hover {text-decoration:underline;color:#FF0000;}
.td-dark { background: #ffffff; height: 20px; }
.td-light { background: #FFE2BF; height: 20px; }
.paging { background: #fd7d0f;text-align: right;color:#000000;}
.paging span { font: bold 12px Arial, Helvetica, sans-serif; color:#FFFFFF; margin-right: 3px; padding: 1px 3px 1px 3px }
.paging a { font: bold 12px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; margin-right: 3px; border: 1px solid #ffffff; background: #fd7d0f; padding: 1px 3px 1px 3px }
.paging a:hover { font: bold 12px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; border: 1px solid #ffffff; background: #ffffff; }
.colFirstName{width:18%;text-align:left;}
.colLastName{width:18%;text-align:left;}
.colPhone{width:14%;text-align:left;}
.colEmail{width:19%;text-align:left;}
.colContactType{width:18%;text-align:left;}
.colOperation{width:50px;text-align:center;}


Final Output :







Download Link : Click Here


Thursday, February 10, 2011

How to make AJAX Call for Database Transaction

At Page Behind make your method :

[System.Web.Services.WebMethod]
public static string SavePopUpData(string Id)
{
     //-- Your Save Data Code

}


 //-- Put following code in script tag and it will call above method using AJAX request :

In url : ""
In data:""

$.ajax({
                    type: "POST",
                    url: "Test.aspx/SavePopUpData",
                    data: "{Id':'1'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        AlertMsg = msg.d;
                        if (AlertMsg.length > 0)
                           alert("Data Saved");
                    },
                    error: function(msg) {

                    }
                });

Friday, April 23, 2010

MD5 test application

On my Default.aspx page i have taken following controls:

1.) Label lblMessage
2.) TextBox txtPalinStr
3.) Button btnEncrypt
4.) Label lblEnryptedString
5.) TextBox txtcheck
6.) Button btncheck onclick="btncheck_Click"
7.) Label lblcheck


This is my Default.aspx.cs page :

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using MD5Encrypt;
public partial class _Default : System.Web.UI.Page
{
    private MD5 obj_MD5;

    protected void Page_Load(object sender, EventArgs e)
    {
        obj_MD5 = new MD5();
    }
    protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        lblEnryptedString.Text = obj_MD5.Encrypt(txtPalinStr.Text);
    }
    protected void btncheck_Click(object sender, EventArgs e)
    {
        lblcheck.Text = obj_MD5.verify(txtcheck.Text);

        if (lblEnryptedString.Text == lblcheck.Text)
        {
            lblMessage.Text = "You Are Authenticated";
        }
        else
        {
            lblMessage.Text = "Authentication Failed";
        }
    }
}


And Finally My MD5 Class :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace MD5Encrypt
{
    public class MD5
    {
        private Byte[] EncStringBytes;
        private UTF8Encoding Encoder = new UTF8Encoding();
        private MD5CryptoServiceProvider MD5Hasher = new MD5CryptoServiceProvider();
        private static string PasswordSalt;
        string MD5String;
      
        public MD5()
        { }

        public string Encrypt(string EncString)
        {
            Random RanGen = new Random();
            string RanString = "";           
            string RanSaltLoc;          

            while(RanString.Length<=3)
            {
                RanString = RanString + RanGen.Next(0, 9);
            }

            EncStringBytes = Encoder.GetBytes(EncString + RanString);

            EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes);
            MD5String = BitConverter.ToString(EncStringBytes);
            MD5String = MD5String.Replace("-", String.Empty);


            RanSaltLoc = (RanGen.Next(4, MD5String.Length)).ToString();
            MD5String = MD5String.Insert(Convert.ToInt32(RanSaltLoc),RanString);
           
            if (Convert.ToInt32(RanSaltLoc) < 10)
            {
                RanSaltLoc = "0" + RanSaltLoc;
            }

            MD5String = MD5String.Insert(3, RanSaltLoc);
            PasswordSalt = RanSaltLoc + RanString;
            return MD5String;
        }

        public string verify(string chkString)
        {
            string SaltString = PasswordSalt.Substring(2,4);
            string SaltLoaction = PasswordSalt.Substring(0, 2);

            EncStringBytes = Encoder.GetBytes(chkString + SaltString);

            EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes);
            MD5String = BitConverter.ToString(EncStringBytes);
            MD5String = MD5String.Replace("-", String.Empty);
            MD5String = MD5String.Insert(Convert.ToInt32(SaltLoaction), SaltString);
           
            MD5String = MD5String.Insert(3, SaltLoaction);

            return MD5String;
        }
    }
}

Sunday, April 18, 2010

How to generate XML document using Store Procedure in SQL Server

CREATE PROCEDURE  sp_getXML 
AS
BEGIN
    SELECT    C.CategoryID,
            C.CategoryName,
            F.FurnitureID,F.FurnitureName,
            SUM(F.FurniturePrice) FurniturePrice
    FROM tbl_Furniture F
    INNER JOIN tbl_Category  C ON F.CategoryID = C.CategoryID   
    GROUP BY C.CategoryID,C.CategoryName,F.FurnitureID,F.FurnitureName
    ORDER BY C.CategoryID
    FOR XML AUTO, ROOT('Furnitures')
END

Friday, April 16, 2010

How to change color of dates which are greater than current date in Ajax calender extender

The following code will help you ,just put in inside in your page :

Include folowing stylesheet in your page :


      .ajax_Ena div
      {
        background:gray;
        cursor:text;   
      }
    

Include following code inside script :

     AjaxControlToolkit.CalendarBehavior.prototype._performLayout = function()
            {                      
                             
                 var elt = this.get_element();                                                                                  
                 if (!elt) return;
                 else
                 {
                    if (!this.get_isInitialized()) return;  
                    if (!this._isOpen) return;              
                    var dtf = Sys.CultureInfo.CurrentCulture.dateTimeFormat;
                                       
                    var selectedDate = this.get_selectedDate();  
                    var visibleDate = this._getEffectiveVisibleDate();  
                    var todaysDate = this.get_todaysDate();                             
                         switch (this._mode)
                         {  
                             case "days":  
                                   
                                 var firstDayOfWeek = this._getFirstDayOfWeek();  
                                 var daysToBacktrack = visibleDate.getDay() - firstDayOfWeek;  
                                 if (daysToBacktrack <= 0)  
                                     daysToBacktrack += 7;  
                                       
                                 var startDate = new Date(visibleDate.getFullYear(), visibleDate.getMonth(), visibleDate.getDate() - daysToBacktrack, this._hourOffsetForDst);                   
                                 var currentDate = startDate;                            
                                  
                                 for (var i = 0; i < 7; i++)
                                 {  
                                     var dayCell = this._daysTableHeaderRow.cells[i].firstChild;  
                                     if (dayCell.firstChild)
                                     {  
                                         dayCell.removeChild(dayCell.firstChild);  
                                     }  
                                     dayCell.appendChild(document.createTextNode(dtf.ShortestDayNames[(i + firstDayOfWeek) % 7]));  
                                 }  
                                
                                 for (var week = 0; week < 6; week ++)
                                 {  
                                     var weekRow = this._daysBody.rows[week];  
                                     for (var dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++)
                                     {  
                                         var dayCell = weekRow.cells[dayOfWeek].firstChild;  
                                         if (dayCell.firstChild)
                                         {  
                                             dayCell.removeChild(dayCell.firstChild);  
                                         }  
                                         dayCell.appendChild(document.createTextNode(currentDate.getDate()));  
                                         dayCell.title = currentDate.localeFormat("D");  
                                         dayCell.date = currentDate;                                                                                                     
                                         $common.removeCssClasses(dayCell.parentNode, [ "ajax__calendar_hover" ,"ajax__calendar_other", "ajax__calendar_active"]);                       
                                        
                                     
                                         if(elt.id.toLowerCase().indexOf('sdate') > -1)
                                         {
                                            var today_date = ('<%=GetTodayDate(1) %>');                                                                                                
                                            if(currentDate > new Date())
                                            {
                                                Sys.UI.DomElement.addCssClass(dayCell.parentNode,"ajax_Ena");                                                                                                                      
                                            }
                                            else
                                            {
                                            $common.removeCssClasses(dayCell.parentNode,["ajax_Ena"]);
                                            }
                                          }                                          
                                         currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() + 1, this._hourOffsetForDst);  
                                     }  
                                 }  
                                   
                                 this._prevArrow.date = new Date(visibleDate.getFullYear(), visibleDate.getMonth() - 1, 1, this._hourOffsetForDst);  
                                 this._nextArrow.date = new Date(visibleDate.getFullYear(), visibleDate.getMonth() + 1, 1, this._hourOffsetForDst);  
                                 if (this._title.firstChild)
                                 {  
                                     this._title.removeChild(this._title.firstChild);  
                                 }  
                                 this._title.appendChild(document.createTextNode(visibleDate.localeFormat("MMMM, yyyy")));  
                                 this._title.date = visibleDate;  
                   
                                 break;  
                             case "months":                   
                                 for (var i = 0; i < this._monthsBody.rows.length; i++)
                                 {  
                                     var row = this._monthsBody.rows[i];  
                                     for (var j = 0; j < row.cells.length; j++)
                                     {  
                                         var cell = row.cells[j].firstChild;  
                                         cell.date = new Date(visibleDate.getFullYear(), cell.month, 1, this._hourOffsetForDst);  
                                         cell.title = cell.date.localeFormat("Y");                                                              
                                         $common.removeCssClasses(cell.parentNode, [ "ajax__calendar_other", "ajax__calendar_active" ]);  
                                         Sys.UI.DomElement.addCssClass(cell.parentNode, this._getCssClass(cell.date, 'M'));  
                                     }  
                                 }  
                                   
                                 if (this._title.firstChild)
                                 {  
                                     this._title.removeChild(this._title.firstChild);  
                                 }  
                                 this._title.appendChild(document.createTextNode(visibleDate.localeFormat("yyyy")));  
                                 this._title.date = visibleDate;  
                                 this._prevArrow.date = new Date(visibleDate.getFullYear() - 1, 0, 1, this._hourOffsetForDst);  
                                 this._nextArrow.date = new Date(visibleDate.getFullYear() + 1, 0, 1, this._hourOffsetForDst);  
                   
                                 break;  
                             case "years":  
                   
                                 var minYear = (Math.floor(visibleDate.getFullYear() / 10) * 10);  
                                 for (var i = 0; i < this._yearsBody.rows.length; i++)
                                 {  
                                     var row = this._yearsBody.rows[i];  
                                     for (var j = 0; j < row.cells.length; j++)
                                     {  
                                         var cell = row.cells[j].firstChild;  
                                         cell.date = new Date(minYear + cell.year, 0, 1, this._hourOffsetForDst);  
                                         if (cell.firstChild)
                                         {  
                                             cell.removeChild(cell.lastChild);  
                                         }
                                         else
                                         {  
                                             cell.appendChild(document.createElement("br"));  
                                         }  
                                         cell.appendChild(document.createTextNode(minYear + cell.year));  
                                         $common.removeCssClasses(cell.parentNode, [ ".ajax__calendar_other", ".ajax__calendar_active" ]);  
                                         Sys.UI.DomElement.addCssClass(cell.parentNode, this._getCssClass(cell.date, 'y'));  
                                     }  
                                }  
                   
                                if (this._title.firstChild)
                                {  
                                    this._title.removeChild(this._title.firstChild);  
                                }  
                                this._title.appendChild(document.createTextNode(minYear.toString() + "-" + (minYear + 9).toString()));  
                                this._title.date = visibleDate;  
                                this._prevArrow.date = new Date(minYear - 10, 0, 1, this._hourOffsetForDst);  
                                this._nextArrow.date = new Date(minYear + 10, 0, 1, this._hourOffsetForDst);  
                   
                            break;  
                         }  
                         if (this._today.firstChild)
                         {  
                             this._today.removeChild(this._today.firstChild);  
                         }  
                         this._today.appendChild(document.createTextNode(String.format(AjaxControlToolkit.Resources.Calendar_Today, todaysDate.localeFormat("MMMM d, yyyy"))));  
                         this._today.date = todaysDate;                                                           
                 }             
            }


 


If you have any query than just mail me or post comment....