Saturday, 10 May 2014

GET random Unique OTP(One Time Password) in C#.NET

Use this Code for random Unique OTP(One Time Password) generation:

private string generatePassword()
        int lenthofpass = 6;
        string allowedChars = "";
        allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
        allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
        allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";
        char[] sep = { ',' };
        string[] arr = allowedChars.Split(sep);
        string passwordString = "";
        string temp = "";
        Random rand = new Random();
        for (int i = 0; i < lenthofpass; i++)
            temp = arr[rand.Next(0, arr.Length)];
            passwordString += temp;
        return passwordString;

Tuesday, 29 April 2014

Send Mail with Attachment in

 MailAddress SendFrom = new MailAddress("", "Brijesh");
        MailAddress SendTo = new MailAddress("");
        System.Net.Mail.MailMessage MyMessage = new System.Net.Mail.MailMessage(SendFrom, SendTo);
        MyMessage.IsBodyHtml = true;
        MyMessage.Subject = "Send Mail with attachment ";
        MyMessage.Body = "Body";
        if (fupResume.HasFile)
            string FileName = Path.GetFileName(fupResume.PostedFile.FileName);
            MyMessage.Attachments.Add(new Attachment(fupResume.PostedFile.InputStream, FileName));
        System.Net.NetworkCredential authentication = new System.Net.NetworkCredential("", "password");
        SmtpClient client = new SmtpClient("", 25);//587
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        client.Credentials = authentication;

Tuesday, 8 April 2014

Directly Bind Byte[] Type Image data to Image control

Use this code for display image on both asp Image control and html img tag

<asp:Image ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("IMG_DATA")) %>' />


<img src='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("IMG_DATA")) %>' />

Friday, 4 April 2014

Re-sized Image of byte[] array type in

I found the solutions of image re-sizing at run-time in 
use this code to obtain re-sized image:

SqlCommand cmd = new SqlCommand("select ProductPicture from ProductDetails where Id=" + pdctid + "", con);
                byte[] product = (byte[])cmd.ExecuteScalar();
                MemoryStream stream = new MemoryStream(product);

private byte[] ResizeUploadedImage(Stream streamToResize)
            byte[] resizedImage;
            using (System.Drawing.Image orginalImage = System.Drawing.Image.FromStream(streamToResize))
                ImageFormat orginalImageFormat = orginalImage.RawFormat;
                int orginalImageWidth = orginalImage.Width;
                int orginalImageHeight = orginalImage.Height;
                int resizedImageWidth = 150; // Type here the width you want
                int resizedImageHeight = 90; // Type here the hight you want
                using (Bitmap bitmapResized = new Bitmap(orginalImage, resizedImageWidth, resizedImageHeight))
                    using (MemoryStream streamResized = new MemoryStream())
                        bitmapResized.Save(streamResized, orginalImageFormat);
                        resizedImage = streamResized.ToArray();

            return resizedImage;

Tuesday, 1 April 2014

Export GridView Data with Image in

Write this code on .aspx page

<html xmlns="">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Job" HeaderText="Job" />
                <asp:BoundField DataField="Location" HeaderText="Location" />
                <asp:ImageField DataImageUrlField="Image" HeaderText="Image">
        <asp:Button ID="Button1" runat="server" Text="Export" onclick="Button1_Click" />

copy & paste this code on .cs page....

protected void Page_Load(object sender, EventArgs e)

        if (!IsPostBack)

    private void FillGridview()
        DataTable table = new DataTable();
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Job", typeof(string));
        table.Columns.Add("Location", typeof(string));

        table.Rows.Add("JP", "XXX", "QQQQ", "http://localhost:10735/WebSite2/image/sub-menu-corner.png");
        table.Rows.Add("HP", "TTT", "AAAA", "http://localhost:10735/WebSite2/image/sub-menu-corner-2.png");
        table.Rows.Add("SQ", "YYY", "HHHH", "http://localhost:10735/WebSite2/image/section1-bg.jpg");
        table.Rows.Add("XS", "EEE", "UUUU", "http://localhost:10735/WebSite2/image/form-bg.png");
        GridView1.DataSource = table;
        ViewState["dt"] = table;
    protected void Button1_Click(object sender, EventArgs e)
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        DataTable dt = (DataTable)ViewState["dt"];
        GridView1.DataSource = dt;

        for (int i = 0; i < GridView1.Rows.Count; i++)
            GridViewRow row = GridView1.Rows[i];
            //Apply text style to each Row
            row.Attributes.Add("class", "textmode");
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
    public override void VerifyRenderingInServerForm(Control control)



Thursday, 13 February 2014

PRevent Re-submission of Data on Browser reload in C#.NET

On .aspx page write take a hidden field:

<asp:HiddenField id="hdncheckreload" runat="server" />

On .cs page write a function to check whether it's first time call event or reloaded......

public bool notIsRefresh()
            bool retVal = false;
            if (Session["match"] == null || Session["match"].ToString() == hdncheckreload.Value)
                retVal = true;
            Session["match"] = DateTime.Now.Ticks;
            hdncheckreload.Value = Session["match"].ToString();
            return retVal;

call this method on event which is reloaded such as button click event, form submission etc...

Wednesday, 22 January 2014

HOw to implement LINQ in C#.NET to Perform Aggregate Function as in SQL Server

First Add the namespace - System.Collections.Generic and System.Linq

Now we get data into datatable : 

DataTable dtt = new DataTable();
string _cquery = "Select * from table1";
dtt = du.getdatatable(_cquery);

Now apply group by clause on datatable dtt using LINQ :

var query = from row in dtt.AsEnumerable()
                                group row by row.Field<string>("col1") into grp
                                select new { AfterDistinct = grp.Key};
                    DataTable ddldt = new DataTable();
                    foreach (var row in query)
                        int i = 0;
                        DataRow dr = ddldt.NewRow();
                        dr["col1"] = row.AfterDistinct.ToString();
                    ddl1.DataSource = ddldt;
                    ddl1.DataTextField = "col1";
                    ddl1.DataValueField = "col1";
                    ddl1.Items.Insert(0, new ListItem("--Select--", "0"));

in this example we get data with group by clause from DataTable and bind this data to DropdownList ddl1.

Wednesday, 8 January 2014

HOw to Set ListView DataPager Page Index Property to specific Page Number in

Copy & Paste this on .aspx file :

 <asp:ListView ID="ListView1" runat="server" GroupItemCount="1" GroupPlaceholderID="groupPlaceHolder1"
                ItemPlaceholderID="itemPlaceHolder1" OnPagePropertiesChanging="ListView1_PagePropertiesChanging"
                        <asp:PlaceHolder runat="server" ID="groupPlaceHolder1"></asp:PlaceHolder>
                        <asp:PlaceHolder runat="server" ID="itemPlaceHolder1"></asp:PlaceHolder>
                    <table align="center" cellpadding="0" cellspacing="0" width="730px">
                            <td width="64px" height="80px" >
                                <asp:Image ID="imgtick" runat="server" ImageUrl="~/Image/tick.png" Height="35px"
                                    Width="35px" ImageAlign="AbsMiddle" /><asp:Label ID="lblid" runat="server" Text='<%# Bind("ID") %>'
                            <td width="654px" valign="middle">
                                <table align="center" cellpadding="0" cellspacing="0">
                                        <td width="110px" height="60px" align="left" valign="middle" style="border-right-style: solid;
                                            border-right-width: 1px; border-right-color: #CCCCCC">
                                                <asp:Image ID="Image2" runat="server" Height="50px" Width="100px" ImageUrl='<%#Eval("AdImage","../{0}")%>' />
                                        <td width="224px" height="60px" align="left" valign="top" style="padding-left: 5px;
                                            padding-right: 5px; word-wrap: break-word; border-right-style: solid; border-right-width: 1px;
                                            border-right-color: #CCCCCC; font-family: Arial; font-size: 9pt;">
                                            <span style="font-weight: bold">Title :</span>
                                                style="text-decoration: none; color: #023E7C"><%# Eval("Title")%><br />
                                            <span style="font-weight: bold">About : </span>
                                                style="text-decoration: none; color: Gray">
                                                <%# Eval("Description").ToString().Substring(0,70)%>
                                        <td width="100px" align="center" valign="middle">
                                            <asp:Label ID="lblstatus" runat="server" Font-Bold="true" />
                                        <td width="80px" align="center" valign="middle">
                                            <%# Eval("ActivationDate").ToString().Substring(0,9)%>
                                        <td width="80px" align="center" valign="middle" style="border-right-style: solid;
                                            border-right-width: 1px; border-right-color: #CCCCCC">
                                            <%# Eval("ExpiryDate").ToString().Substring(0,9)%>
                                        <td width="60px" align="center">
                                            <asp:Label ID="lblreward" runat="server" Text='<%# Bind("Reward")%>'></asp:Label>
                            <td width="12px" >
            <br />
<%-- DataPager---%>
            <asp:DataPager runat="server" ID="DataPager1" PageSize="8" PagedControlID="ListView1">
                    <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowPreviousPageButton="false"
                        ShowLastPageButton="false" />
                    <asp:NumericPagerField ButtonType="Button" />
                    <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True" ShowNextPageButton="False"
                        ShowPreviousPageButton="False" />

Write this code on pageload event with isPostBack property false:

  protected void Page_Load(object sender, EventArgs e)
                if (!IsPostBack)
                    _cMasterPageName = Page.MasterPageFile;
                    if (Session["pageno"] != null) /// set datapager to page 2
                        DataPager1.SetPageProperties(Convert.ToInt32(Session["pageno"]), 8, false);
            catch (Exception)

         protected void fillListView() /// fill listview
            SqlDataAdapter da= new SqlCommand("Select * from UserTable",con)
            DataTable dt = new DataTable();
            ListView1.DataSource = dt;

protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
                DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
                Session["pageno"] = e.MaximumRows; // save page size
            catch (Exception)