Sunday, October 9, 2016

How to upload file without post back in asp.net

In this article I am going to explain how to upload file with the help of "Handler" in ASP. net c#, My main focus to write this article is that, if you work with file upload control,  the page requires full post back , and if your file upload control is inside update panel,  the you must specifies you button submit in trigger like,

<Triggers>
            <asp:PostBackTrigger ControlID=""/>
</Triggers>

and this also cause the full post back problem, for removing this problem use "Handler" in ASP. net c#

UploadFile.ashx Code

<%@ WebHandler Language="C#" Class="UploadFile" %>
 
using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
public class UploadFile : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        string filedata = string.Empty;
        if (context.Request.Files.Count > 0)
        {
            HttpFileCollection files = context.Request.Files;
          
            
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                if (Path.GetExtension(file.FileName).ToLower() != ".jpg"
                   && Path.GetExtension(file.FileName).ToLower() != ".png"
                   && Path.GetExtension(file.FileName).ToLower() != ".gif"
                   && Path.GetExtension(file.FileName).ToLower() != ".jpeg"
                    && Path.GetExtension(file.FileName).ToLower() != ".pdf"
                   )
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("Only jpg, png , gif, .jpeg, .pdf are allowed.!");
                    return;
                }
                decimal size = Math.Round(((decimal)file.ContentLength / (decimal)1024), 2);
                if (size > 2048)
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("File size should not exceed 2 MB.!");
                    return;
                 }
                string fname;
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = file.FileName;
                }
 
                //here UploadFile is define my folder name , where files will be store.
                string uploaddir = System.Configuration.ConfigurationManager.AppSettings["UploadFile"];
                filedata = Guid.NewGuid()+ fname;
                fname = Path.Combine(context.Server.MapPath("~/" + uploaddir + "/"), filedata);
                file.SaveAs(fname);
             
               
            }
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write("File Uploaded Successfully:" + filedata + "!");
       //if you want to use file path in aspx.cs page , then assign it in to session
        context.Session["PathImage"] = filedata;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

web.config code

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  <appSettings>
    <add key="Upload" value="UploadFile"/>
  </appSettings>
</configuration>

Default.aspx code
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 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></title>
   <%-- Should have internet connection for loading this file other wise inherit own js file for supporting js library--%>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        function onupload() {
            $(function () {
                var fileUpload = $('#<%=FileUpload.ClientID%>').get(0);
                var files = fileUpload.files;
                var test = new FormData();
                for (var i = 0; i < files.length; i++) {
                    test.append(files[i].name, files[i]);
                }
                $.ajax({
                    url: "UploadFile.ashx",
                    type: "POST",
                    contentType: false,
                    processData: false,
                    data: test,
                    success: function (result) {
                        if (result.split(':')[0] = "File Uploaded Successfully") {
                            document.getElementById("<%=lbl_smsg.ClientID%>").innerText = result.split(':')[0];
                        }
                        else {
                            document.getElementById("<%=lbl_emsg.ClientID%>").innerText = result;
                        }
 
                    },
                    error: function (err) {
                        alert(err.statusText);
                    }
                });
 
            })
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scmain" runat="server" ></asp:ScriptManager>
   <asp:UpdatePanel ID="upmain" runat="server">
   <ContentTemplate>
   <fieldset>
   <legend>Upload File WithOut PostBack inside Update Panel</legend>
    <asp:FileUpload ID="FileUpload" runat="server" />
    <input type="button" id="btnUpload" value="Upload Files" onclick="onupload();"/> 
    <asp:Label ID="lbl_emsg" runat="server" ForeColor="Red"></asp:Label>
    <asp:Label ID="lbl_smsg" runat="server" ForeColor="Green"></asp:Label>
     </fieldset>
   </ContentTemplate>
   </asp:UpdatePanel>
    </form>
</body>
</html>

Default.aspx code.cs code
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
}

After uploading image



Wednesday, September 7, 2016

css for file upload control in asp.net

In this article, I am going to explain how to implement css design in file upload control in asp.net.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUploadStyle.aspx.cs" Inherits="FileUploadStyle" %>
 
<!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></title>
    <style>
 /* { box-sizing: border-box; margin: 0; padding: 0; }
div { margin: 8px; }*/
input[type=file], input[type=file] + input {
    display: inline-block;
    background-color: #CC3;
    border: 1px solid #CC3;
    font-size: 15px; padding: 4px;
       cursor: pointer;
}
input[type=file] + input {
    padding: 13px;
    background-color: #00b7cd;
}
::-webkit-file-upload-button {
    -webkit-appearance: none;
    background-color: #CC3;
    border: 1px solid #CC3;
    font-size: 15px; padding: 8px;
       cursor: pointer;
}
::-ms-browse {
    background-color: #00b7cd;
    border: 1px solid #CC3;
    font-size: 15px; padding: 8px;
}
input[type=file]::-ms-value { border: none;  }
.test-head {
    position: relative
}
 
.test-head p {
font-size: 20px;
color: #353535;
font-weight: bold;
background: #CCCC33;
line-height: 60px;
display: inline-block;
padding-right: 24em;
position: relative;
margin-top: 0px;
}
 
.test-head:before {
    content: "";
    position: absolute;
    width: 50%;
    height: 100%;
    max-width: 260px;
    background: #CCCC33;
    top: 0;
    left: 0;
    z-index:0
}
 
.test-head p:after {
    content: " ";
    display: block;
    background: #CCCC33;
    position: absolute;
    bottom: 0px;
    right: -50px;
    border-top: 30px solid transparent;
    border-bottom: 30px solid transparent;
  
}
  </style>
</head>
<body>
    <form id="form1" runat="server">
    <fieldset>
    <legend>File Upload Control Css Style</legend>
    <asp:FileUpload ID="flbupload" runat="server" />
      </fieldset>
    </form>
</body>
</html>

Output:



Saturday, August 13, 2016

Exception handling in C#



An exception is the disruption that rises during the execution of program such as divide by zero. In C# provide the following keywords for exception handling: try, catch, finally and throw.

try – try block identifies the statement that throw and exception.

catch – the catch block handle the exception it any exists.

finally – the finally block is used to execute a set of statement whether the exception is thrown or not.

throw – The throw keyword is used to throw an exception programmatically.

The example of the exception handing is given below: - 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication20
{
    class program
    {
        public static void Main()
        {
            int x = 0;
            int y = 0;
            try
            {
                y = 100 / x;
                Console.WriteLine("Line is not executed");
            }
            catch (DivideByZeroException de)
            {
                Console.WriteLine("Exception rises");
            }
            finally
            {
                Console.WriteLine("Finally Block");
            }
            Console.WriteLine("Result is {0}", y);
            Console.ReadKey();
        }
       
    }
}
Output -  


                                                                Author - Sachin Pathak