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 asp.net

 MailAddress SendFrom = new MailAddress("brijesh.singh879@gmail.com", "Brijesh");
        MailAddress SendTo = new MailAddress("brijesh.singh879@gmail.com");
        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("brijesh.singh879@gmail.com", "password");
        SmtpClient client = new SmtpClient("smtp.gmail.com", 25);//587
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        client.Credentials = authentication;
        client.Send(MyMessage);

Tuesday 8 April 2014

Directly Bind Byte[] Type Image data to Image control asp.net

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")) %>' />

            OR 

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

Friday 4 April 2014

Re-sized Image of byte[] array type in asp.net

I found the solutions of image re-sizing at run-time in asp.net 
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);
                Response.BinaryWrite(ResizeUploadedImage(stream));


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 C#.net

Write this code on .aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <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:ImageField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" Text="Export" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>





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

protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            FillGridview();
        }
    }

    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.Columns.Add("Image");

        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;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        DataTable dt = (DataTable)ViewState["dt"];
        GridView1.DataSource = dt;
        GridView1.DataBind();

        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");
        }
        GridView1.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }


Result:


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();
                    ddldt.Columns.Add("col1");
                    foreach (var row in query)
                    {
                        int i = 0;
                        DataRow dr = ddldt.NewRow();
                        dr["col1"] = row.AfterDistinct.ToString();
                        ddldt.Rows.Add(dr);
                        i++;
                    }
                    ddl1.Items.Clear();
                    ddl1.DataSource = ddldt;
                    ddl1.DataTextField = "col1";
                    ddl1.DataValueField = "col1";
                    ddl1.DataBind();
                    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 asp.net

Copy & Paste this on .aspx file :

 <asp:ListView ID="ListView1" runat="server" GroupItemCount="1" GroupPlaceholderID="groupPlaceHolder1"
                ItemPlaceholderID="itemPlaceHolder1" OnPagePropertiesChanging="ListView1_PagePropertiesChanging"
                OnItemDataBound="ListView1_ItemDataBound">
                <LayoutTemplate>
                    <table>
                        <asp:PlaceHolder runat="server" ID="groupPlaceHolder1"></asp:PlaceHolder>
                    </table>
                </LayoutTemplate>
                <GroupTemplate>
                    <tr>
                        <asp:PlaceHolder runat="server" ID="itemPlaceHolder1"></asp:PlaceHolder>
                    </tr>
                </GroupTemplate>
                <ItemTemplate>
                    <table align="center" cellpadding="0" cellspacing="0" width="730px">
                        <tr>
                            <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") %>'
                                        Visible="false"></asp:Label>
                            </td>
                            <td width="654px" valign="middle">
                                <table align="center" cellpadding="0" cellspacing="0">
                                    <tr>
                                        <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>
                                        <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>
                                        <td width="100px" align="center" valign="middle">
                                            <asp:Label ID="lblstatus" runat="server" Font-Bold="true" />
                                        </td>
                                        <td width="80px" align="center" valign="middle">
                                            <%# Eval("ActivationDate").ToString().Substring(0,9)%>
                                        </td>
                                        <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>
                                        <td width="60px" align="center">
                                            <asp:Label ID="lblreward" runat="server" Text='<%# Bind("Reward")%>'></asp:Label>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                            <td width="12px" >
                                &nbsp;
                            </td>
                        </tr>
                    </table>
                    </td>
                </ItemTemplate>
            </asp:ListView>
            <br />
<%-- DataPager---%>
            <asp:DataPager runat="server" ID="DataPager1" PageSize="8" PagedControlID="ListView1">
                <Fields>
                    <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowPreviousPageButton="false"
                        ShowLastPageButton="false" />
                    <asp:NumericPagerField ButtonType="Button" />
                    <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True" ShowNextPageButton="False"
                        ShowPreviousPageButton="False" />
                  
                </Fields>
            </asp:DataPager>


Write this code on pageload event with isPostBack property false:

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


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


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