Thursday, February 9, 2017

Hash table in C#



In C# hash table is the collection of key or values, which is used to map a key to value. We can use any non-null object as a key; we can retrieve the items from hash table by providing key.
The common function used in hash table is given below:

Add – used to add a pair of value to Hashtable
Syntax
HashTable.Add (Key, Value)
Hashtable h;
h.Add(“1”, “Sachin”);
  
ContainsKey – used to checked a specified key exist or not.
Syntax
bool HashTable.ContainsKey (key)
h.contains(“1”);

ContainsValue - used to checked a specified value exist or not.
Syntax 
bool HashTable.Containsvalue (value)
h.containsvalue(“Sachin”);

Remove – used to delete specified key or values.
Syntax 
HashTable.Remove(key)
h.remove(“1”)

Wednesday, February 1, 2017

Create a clone of asp controls in asp .net C# on button click

Create a clone of asp controls in asp .net C# on button click

I have faced a real time issue at my website, on button click the page creates duplicate control at my website. After searching, I found  that I have missed closing tag of div, so any html tag if you missed occur duplicate control generation problem.


Solution  : Missed any html closing tag.

Wednesday, January 18, 2017

What is tuple and how to declare it?



A tuple is s new data type introduced in .Net Framework 4.0. It is used when we want to store multiple values having different data type and without having a class to store the value, in this situation the tuple is best option. In other words a Tuple is a container that contains similar or different data type (7 items) and 1 Tuple.

Declaration of Tuple

The declaration of the Tuple is similar to dictionary <tkey, tvalue>
Tuple<t1>
Tuple<t1, t2, t3>
Tuple<t1, t2, t3, t4>
Tuple<t1, t2, t3, t4, t5>
Tuple<t1, t2, t3, t4, t5, t6>
Tuple<t1, t2, t3, t4, t5, t6, t7>
Tuple<t1, t2, t3, t4, t5, t6, t7, tRest>
T is any data type and tRest a tuple type.

Tuesday, January 17, 2017

Deconstruction in C# 7.0



 Deconstruction is a process of split a variables value into parts and store it on new variables. It is important when a variable stores multiple values such as tuple.
The method GetATuple returns a tuple with three values.

Example:
(string name, string city, int sal) GetATuple(int id)
{
String name =string.empty;
String city=string.emplty;
Int sal=0;
If (id ==1000)
{
name=”Sachin”;
city=”Kanpur”;
sal=2000;
}
return(name, city, sal)
}

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