Friday, February 24, 2012

File Upload Control Tutorial in ASP.NET

code for .ASPX file
==================================================================
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="fileuploadc._Default" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:FileUpload ID="adi" runat="server" />
    <asp:Button runat="server" ID="btn" style="height: 26px" onclick="btn_Click" />
    </div>
    </form>
</body>
</html>

==================================================================
Download Tutorial 
code for .ASPX.CS
==================================================================
protected void btn_Click(object sender, EventArgs e)
        {try{
            if (CheckFileFormat(adi) == true)//checking for file type is pdf or not
            {
                if (_ContentType(adi) == true)//checking file content
                {
                    savedocument("aditya", "readwritedata", adi);//savedocument("filename","foldername","control_id")
                    //message showing in popup
                    ScriptManager.RegisterStartupScript(this, typeof(string), "alertUpdateStatus", "alert('file is uploaded successfully'); ", true);
                }
            }
        }
            catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, typeof(string), "alertUpdateStatus", "alert('error! file uploading is failed...message "+e.ToString()+"'); ", true);
            }
        }
        public bool CheckFileFormat(System.Web.UI.WebControls.FileUpload _UPDctl)
        {
            try
            {
                string FileExtension = null;
                string[] AllowedExtension = { ".pdf" };

                if (_UPDctl.HasFile)
                {
                    FileExtension = System.IO.Path.GetExtension(_UPDctl.FileName).ToLower();
                    for (int i = 0; i <= AllowedExtension.Length - 1; i++)
                    {
                        if (FileExtension != AllowedExtension[i])
                        {
                            return false;
                        }
                    }
                    //check for file size
                    if ((_UPDctl.PostedFile.ContentLength > 1048576))
                    {
                        return false;
                    }

                    if (!(_UPDctl.PostedFile.ContentType.ToString() == "application/pdf"))
                    {
                        return false;
                    }

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public bool _ContentType(System.Web.UI.WebControls.FileUpload uplTheFile)
        {
            try
            {
                int BUFFER_SIZE = 255;
                int nBytesRead = 0;
                byte[] Buffer = new byte[BUFFER_SIZE + 1];
                string strUploadedContent = null;
                Stream theStream = uplTheFile.PostedFile.InputStream;
                nBytesRead = theStream.Read(Buffer, 0, BUFFER_SIZE);
                strUploadedContent = Encoding.ASCII.GetString(Buffer).Substring(0, 4);
                if (!(strUploadedContent.Contains("PDF") | strUploadedContent.Contains("pdf")))
                {
                    return false;
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }

        }
        public bool savedocument(string id, string path, System.Web.UI.WebControls.FileUpload _UPDctl)
        {
            try
            {
                string RealFileName = null;
                string SaveAt = null;
                         
                RealFileName = id.Replace("/", "_").Trim();

                if (!Directory.Exists(Server.MapPath(".") + "\\" + "readwritedata"))//checking for folder exist or not. if not then create folder
                {
                    Directory.CreateDirectory(Server.MapPath(".") + "\\" + "readwritedata");
                }

                SaveAt = Server.MapPath(".") + "\\" + "readwritedata";
                _UPDctl.PostedFile.SaveAs(SaveAt + "\\" + RealFileName + ".pdf");
                return true;


            }
            catch (Exception ex)
            {
                return false;
            }
        }
        //function for creating folder of given name
        public string CreateFolder(string path, string fname)
        {
            if (!Directory.Exists(path + fname))
            {
                Directory.CreateDirectory(path + fname);
            }
            return fname;
        }
======================================================================= 
Download Tutorial 

Tuesday, February 14, 2012

Using javascript check uploaded file size

write function in JavaScript

Note:- Only working with FireFox,Crome,Safari,Opera 
for Internet Explorer check this page

function aditya(source, args)
    {
    arguments.isvalid = false;
    fileupload = document.getElementById('<%= FileUpload2.ClientID %>');
    file=fileupload.files[0];
    if (file.size<1048576)
    {
     args.IsValid =  true;
    }
    else
    {
     args.IsValid = false ;
    }
    return ;
    }

use this function in Custom Validator Field
<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:CustomValidator ID="abc" runat="server" ErrorMessage="Max File Size is 1 MB" ControlToValidate="FileUpload2" ClientValidationFunction="aditya"></asp:CustomValidator>




==========================================================================
Example:---

==========================================================================





<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!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 runat="server">
    <title>Untitled Page</title>

    <script language="javascript" type="text/javascript">
    function aditya(source, args)
    {
    arguments.isvalid = false;
    fileupload = document.getElementById('<%= FileUpload2.ClientID %>');
    file=fileupload.files[0];
    if (file.size<1048576)
    {
     args.IsValid =  true;
    }
    else
    {
     args.IsValid = false ;
    }
    return ;
    }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload2" runat="server" />
        <asp:RegularExpressionValidator ID="ValidateResume" runat="server" ErrorMessage="Only pdf files allowed."
            ValidationExpression="^.+\.(([pP][dD][fF]))$" ControlToValidate="FileUpload2" />
        <asp:CustomValidator ID="abc" runat="server" ErrorMessage="Max File Size is 1 MB" ControlToValidate="FileUpload2"
            ClientValidationFunction="aditya"></asp:CustomValidator>
    </div>
    </form>
</body>
</html>



Friday, February 10, 2012

Validate file upload field in ASP.NET using Regular Expression Validator

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="FileUpload1"
  Display="None" ErrorMessage="Please select a file" SetFocusOnError="True" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only pdf files allowed." ValidationExpression="^.+\.(([pP][dD][fF]))$" ControlToValidate="FileUpload1" />

Tuesday, February 7, 2012

To retrieve the values from a DataKeyNames collection

To retrieve the values from a DataKeyNames collection, you can use the following things. You can use the following code to get the DataKeys.



Here, You can input multiple values for DataKeyNames by separating with comma (‘,’). For example, DataKeyNames="ProductID,ItemID,OrderID"
You can now access each of DataKeys by providing its index like below:
string ProductID = gvNoteSheet.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvNoteSheet.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvNoteSheet.DataKeys[gvr.RowIndex].Values[2].ToString();

Wednesday, February 1, 2012

Use Ajax Slider as Paging in Grid View

for using Slider as paging in grid view first of all we have to use textbox/label control and ajax slider control in grid view .

<PagerTemplate>
    <asp:TextBox ID="txtSlide" runat="server" Text='<%# gvDispatch.PageIndex + 1 %>' OnTextChanged="txtSlide_Changed" AutoPostBack="true" />
         
    <ajaxToolkit:SliderExtender ID="ajaxSlider" runat="server" TargetControlID="txtSlide" Orientation="Horizontal"/>
     </PagerTemplate>


code behind code---c#

protected void txtSlide_Changed(object sender, EventArgs e)
{
    TextBox txtCurrentPage = sender as TextBox;
    GridViewRow rowPager = gvDispatch.BottomPagerRow;
    TextBox txtSliderExt = (TextBox)rowPager.Cells(0).FindControl("txtSlide");
    gvDispatch.PageIndex = Int32.Parse(txtSliderExt.Text) - 1;
    BindDispatchData();
}

protected void  gvDispatch_RowDataBound(object sender,System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    GridViewRow rowPager = gvDispatch.BottomPagerRow;
    if ((rowPager != null)) {
        AjaxControlToolkit.SliderExtender slide = (AjaxControlToolkit.SliderExtender)rowPager.Cells(0).FindControl("ajaxSlider");
        slide.Minimum = 1;
        slide.Maximum = gvDispatch.PageCount;
        slide.Decimals = true;
        slide.Length = gvDispatch.PageCount;
        slide.Steps = gvDispatch.PageCount;
    }
}

after rendering page slider take over Textbox/label control