Wednesday 10 April 2013

Show Loading Image while submit the Form

Here you will need to have one gif image to show.

Add the style in header part.
<style type="text/css">
        .centered
        {
            position: fixed;
            top: 50%;
            left: 50%;
            margin-top: -75px;
            margin-left: -75px;
        }
    </style>

Add script in your header part.
$(document).ready(function () {
            $(".btnSubmit").click(function () {
                $('#dvLoader').show();
                if ($("#aspnetForm").valid()) {
                    return true;
                }
                else {
                    $('#dvLoader').hide();
                    return false;
                }
            });
        });

Add the following code to your body area to show loader.
<div id="dvLoader" style="display: none;">
                <div id="updateProgressBackgroundFilter" style="background-color: Gray;
                    filter: alpha(opacity=80); opacity: 0.80; width: 100%; top: 0px; left: 0px; position: fixed;
                    height: 800px;">
                </div>
                <div class="centered" style="font-family: Trebuchet MS;
                    filter: alpha(opacity=100); opacity: 1; font-size: small; position: absolute;
                    color: #FFFFFF;">
                    <img alt="Loading" src="../Images/ajax_loader.gif" height="150" width="150" />
                </div>
            </div>

Now add CssClass attribute to your submit button with value "btnSubmit".
<asp:Button ID="btnSubmit" runat="server" CssClass="btnSubmit" Text="Submit" />

Important codes

To Register the JavaScript Function from code behind
ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "Javascript:AddDate();", true);

To Register the JavaScript Function in $(document).ready on every AJAX or Simple requests.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(DatePick);

To Delete all rows from Sql Table and start Identity from 1.
DBCC CHECKIDENT('TableName',RESEED,0)

To Confirm before any click event. 
OnClientClick='return confirm("Are you sure you want to Submit?")'


To get selected value of Dropdown list using JavaScript. 
var drpLeave = document.getElementById('<%= drpLeaveType.ClientID %>');           
var LeaveType = drpLeave.options[drpLeave.selectedIndex].value;

To get the cell value of Gridview using JavaScript. 
var AvailableLeaves = document.getElementById('<%= gvLeaveStatistics.ClientID %>').rows[1].cells[0].innerText;


To get the value of Label. 
var NoOfDays = document.getElementById('<%= lblNoOfDay.ClientID %>').innerText;


To Select & Deselect all the CheckBox in GridView on Header CheckBox select.
First Add Item Template for CheckBox in Column of GridView.
<asp:TemplateField HeaderText="Action">
 <HeaderTemplate>
<div>
<asp:CheckBox ID="chkSelectAll" runat="server" CssClass="styled headercheck" />                                  
</div>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Now Write this function in Header Part.
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=GridView1.ClientID%> input[id*='chkSelectAll']:checkbox").click(function () {
            if ($(this).is(':checked'))
                $("#<%=GridView1.ClientID%> input[id*='CheckSelect']:checkbox").attr('checked', true);
            else
                $("#<%=GridView1.ClientID%> input[id*='CheckSelect']:checkbox").attr('checked', false);
        });
    });
</script>


To get all the checked CheckBox and Id of that row from GridView on Button Click.
First Add Item Template for CheckBox in Column of GridView.
<asp:TemplateField HeaderText="Action">
 <HeaderTemplate>
<div>
<asp:CheckBox ID="chkSelectAll" runat="server" CssClass="styled headercheck" />                                  
</div>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Now write the following code on Button Click Event.
foreach (GridViewRow row in GridView1.Rows)
            {
                CheckBox Chk = (CheckBox)row.FindControl("CheckSelect");
                Label Lbl = (Label)row.FindControl("Label1");
                if (chk != null && chk.Checked)
                {
                    Id = Lbl.Text;
                }
            }


RowDatabound of GridView.
ImageButton Name = (ImageButton)e.Row.FindControl("imgUser");

RowComman of GridView
LinkButton Name = (LinkButton)e.Row.Cell[0].Controls[0];

GridViewRow ClickedRow = ((LinkButton)e.commandSource).NamingContainer as GridviewRow;
Label lblID = (Label)ClickedRow.FindControl("lblID");

ButtonClick of Gridview
GridViewRow ClickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblID = (Label


Give alert before Redirect the page
ScriptManager.RegisterStartupScript(this,this.GetType(),"redirect","alert('Time OutAlert'); window.location='" + Request.ApplicationPath +"Nextpage.aspx';",true);


Read Permission in IIS for Folders.
IUser
IISUser
NetworkService

Saturday 6 April 2013

Load Gridview on Scroll (Incremental Loading)

In this post I will explain loading gridview on scroll.

First of all create UI. Here I am giving sample,

<div>
        <asp:GridView ID="gvImage" runat="server" AutoGenerateColumns="false" ClientIDMode="Static">
            <Columns>
                <asp:TemplateField HeaderText="Sr No." HeaderStyle-HorizontalAlign="Center">
                    <HeaderStyle Width="100" />
                    <ItemStyle HorizontalAlign="Center" />
                    <ItemTemplate>
                        <asp:Label ID="lblID" CssClass="lblID" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <Columns>
                <asp:TemplateField HeaderText="Image Name" HeaderStyle-HorizontalAlign="Center">
                    <HeaderStyle Width="200" />
                    <ItemStyle HorizontalAlign="Center" />
                    <ItemTemplate>
                        <asp:Label ID="lblImageName" CssClass="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <Columns>
                <asp:TemplateField HeaderText="Image" HeaderStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Image ID="imgImage" CssClass="imgImage" runat="server" ImageUrl='<%# Eval("Image") %>'
                            Height="300" Width="300" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <div id="loader">
        <asp:Image ID="imgLoading" runat="server" ImageUrl="~/Images/loading.gif" AlternateText="Loading.." Height="100" Width="100"/>
        </div>
    </div>


Now you need to add this script in header part.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
        var pageIndex = 1;
        $(window).scroll(function () {            
            if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                {                  
                    GetRecords();
                }
            }
        });
        function GetRecords() {
            pageIndex++;
            if (pageIndex >= 1) {
                $("#loader").show();
                $.ajax({
                    type: "POST",
                    url: "LoadPageOnScrol.aspx/GetData",
                    data: '{pageIndex: ' + pageIndex + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    },
                    error: function (response) {
                        alert(response.d);
                    }
                });
            }
        }
        function OnSuccess(response) {           
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var Images = xml.find("ImageData");
            Images.each(function () {
                var Image = $(this);
                var table = "<tr><td align='center'><span id='lblID' class='lblID'>" + Image.find("ID").text() + "</span></td><td align='center'><span id='lblImageName' class='lblImageName'>" + Image.find("ImageName").text() + "</span></td><td><img id='imgImage' class='imgImage' style='height:300px;width:300px;' src=" + Image.find("Image").text().replace("~/", "") + "></td></tr>";
                $("#gvImage").find("tbody").append(table);
            });
            $("#loader").hide();
        }
    </script>

Finally add web method to code behind page.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DataSet ds = new DataSet();
                ds = GetImageData(1);
                gvImage.DataSource = ds;
                gvImage.DataBind();
            }
        }

[WebMethod]
        public static string GetData(int pageIndex)
        {
            return GetImageData(pageIndex).GetXml();
        }

public static DataSet GetImageData(int PageIndex)
        {
            int Start, End;
            Start = (PageIndex * 3) - 2;
            End = (PageIndex * 3);
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
            SqlDataAdapter da = new SqlDataAdapter("select * from ImageData where ID between " + Start + " AND " + End, con);
            DataSet ds = new DataSet();
            da.Fill(ds, "ImageData");
            return ds;
        }

Script to create table is

USE [DATABASE1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ImageData](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [varchar](50) NULL,
[Image] [varchar](100) NULL,
 CONSTRAINT [PK_ImageData] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

In table I have added path of Image in Image column.

If you have any doubt put comment......

Filter the Gridview as you type in the Textbox

In this post I will explain how to filter the Gridview synchronously while typing into the Textbox.

First of all create a Textbox, Gridview and a Button. here I have added a button to be clicked while we enter the text into the textbox. Add an Update panel and put Gridview into it to prevent the postback full page. set the trigger on the serverclick event of the button, so it will be updated while the button click even fires.

This is the code to create UI. 

<asp:ScriptManager ID="ScriptManager" runat="server">
    </asp:ScriptManager>
    <div>
        <button id="btnSearch" type="button" runat="server" class="SeachClick" onserverclick="btnSearch_Click"
            style="display: none;">
        </button>
        <asp:TextBox ID="txtSearch" runat="server" onkeyup="Search(this);" ClientIDMode="Static"></asp:TextBox>
        <br />
        <asp:UpdatePanel ID="upl" runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="serverclick" />
            </Triggers>
            <ContentTemplate>            
                <asp:GridView ID="gvImage" runat="server" AutoGenerateColumns="false" ClientIDMode="Static">
                    <Columns>
                        <asp:TemplateField HeaderText="Sr No." HeaderStyle-HorizontalAlign="Center">
                            <HeaderStyle Width="100" />
                            <ItemStyle HorizontalAlign="Center" />
                            <ItemTemplate>
                                <asp:Label ID="lblID" CssClass="lblID" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Image Name" HeaderStyle-HorizontalAlign="Center">
                            <HeaderStyle Width="200" />
                            <ItemStyle HorizontalAlign="Center" />
                            <ItemTemplate>
                                <asp:Label ID="lblImageName" CssClass="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Image" HeaderStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:Label ID="lblImage" CssClass="lblImage" runat="server" Text='<%# Eval("Image") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>


Now add the script to click the Button on text change of Textbox.

<script type="text/javascript">
        function Search(ctrl) {
            if ($(ctrl).val() != null)
                $(".SeachClick").click();
            $(ctrl).focus();
        }
    </script>


Now add the following code to your code behind page.

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {              
                SqlDataAdapter da = new SqlDataAdapter("select * from ImageData", con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                gvImage.DataSource = ds;
                gvImage.DataBind();
            }
        }
     
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string search = txtSearch.Text;
            SqlDataAdapter da = new SqlDataAdapter("select * from ImageData where ImageName like '%" + search + "%'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);              
            gvImage.DataSource = ds;
            gvImage.DataBind();
        }


Script to create table is

USE [DATABASE1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ImageData](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [varchar](50) NULL,
[Image] [varchar](100) NULL,
 CONSTRAINT [PK_ImageData] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

In table I have added path of Image in Image column.

If you have any doubt put comment......

Send Email with HTML Template in ASP.NET

In this post I will explain how to send the tutorial in ASP.NET. I have used GMail SMTP to send the mail.

First of all add the keys host and port to web.config file


<appSettings>
    <add key="host" value="smtp.gmail.com" />
    <add key="port" value="587" />
</appSettings>


Now create a class with name Helper and add common method to send the mail so that you can access this to any page in your application. First method is to specify the values to send the mail like From, To, Subject, Body etc. Second method is for getting the HTML template to create mail body.

public int SendMail(string From, string To, string CC, string AttachmentFilePath, string Subject, string Body, string Password)
        {
            int Result;
            try
            {
                SmtpClient mailClient = new SmtpClient();
                NetworkCredential basicAuthenticationInfo = new NetworkCredential();
                basicAuthenticationInfo.UserName = From;
                basicAuthenticationInfo.Password = Password;
                mailClient.UseDefaultCredentials = false;
                mailClient.Credentials = basicAuthenticationInfo;
                mailClient.Host = ConfigurationManager.AppSettings["host"].ToString();
                mailClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"].ToString());
                System.Net.Mail.MailMessage mailmessage = new System.Net.Mail.MailMessage(From, To,    
                Subject, Body);
                if (CC.Trim() != "")
                    mailmessage.CC.Add(CC);
                System.Net.Mail.Attachment Attach = null;
                if (AttachmentFilePath.Trim() != "")
                    Attach = new System.Net.Mail.Attachment(AttachmentFilePath);
                if (Attach != null)
                mailmessage.Attachments.Add(Attach);
                mailmessage.IsBodyHtml = true;
                mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                mailClient.EnableSsl = true;
                mailmessage.SubjectEncoding = System.Text.Encoding.UTF8;
                mailmessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailClient.Send(mailmessage);
                Result = 0;
                return Result;
            }
            catch (Exception)
            {
                Result = -1;
                return Result;
            }
        }

div style="margin: 0px;">         public string GetTemplate(string path)
        {
            WebClient client = new WebClient();
            string content = client.DownloadString(path);
            return content;
        }


Now create an HTML template for the Email. Here I have provided the sample.


<!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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title></title>
</head>
<body>  
Welcome ##UserName##
   <h2>This is the welcome email.</h2>  
</body>
</html>



Now add the method to in code behind page to call the method.
   
public int SendTheMail(string From, string To, string CC, string Body, string Password, string Attachment)
        {
            Helper obj = new Helper();
            int result;
            string body, subject;
            // getting the content of the Email template.        
            body = obj .GetTemplate(Server.MapPath("../EmailTemplate/ConfirmationMail.htm"));
            subject = "Confirmation Mail";
            string Username = "Ankit";
            // replace your content with dynamic content
            body = body.Replace("##UserName##", Username);
            result = obj.SendMail(From, To, CC, Attachment, subject, body, Password);
            return result;
        }


Now you can call this method(SendTheMail) on Button click or wherever you want

If you have any doubt please put comment...