Thursday, 24 November 2016

hyperlink in image

<a href="BookCvDetails.aspx?adidd=4&ef=wqgs&adid=<%#Eval("Ac_Id") %>&xz3=fds6766 &ad=78"> <img alt="" src="images/search.png" /></a>

Email send

 protected void btnSubmit_Click(object sender, EventArgs e)
    {
        MailMessage msg;
        SqlCommand cmd = new SqlCommand();
        string ActivationUrl = string.Empty;
        string emailId = string.Empty;
        try
        {
            //SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ToString());
            //cmd = new SqlCommand("insert into Tb_Registration (Name,EmailId,Address,ContactNo) values (@Name,@EmailId,@Address,@ContactNo) ", con);
            //cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
            //cmd.Parameters.AddWithValue("@EmailId", txtEmailId.Text.Trim());
            //cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
            //cmd.Parameters.AddWithValue("@ContactNo", txtContactNo.Text.Trim());
            //if (con.State == ConnectionState.Closed)
            //{
            //    con.Open();
            //}
            //cmd.ExecuteNonQuery();
            //Sending activation link in the email
            msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            emailId = txtEmailId.Text.Trim();
            //sender email address
            msg.From = new MailAddress("mohammed.akram52@gmail.com");
            //Receiver email address
            msg.To.Add(emailId);
            msg.Subject = "Confirmation email for account activation";
            //For testing replace the local host path with your lost host path and while making online replace with your website domain name
            ActivationUrl = Server.HtmlEncode("http://localhost:8665/MySampleApplication/ActivateAccount.aspx?UserID=" + FetchUserId(emailId) + "&EmailId=" + emailId);

            msg.Body = "Hi " + txtName.Text.Trim() + "!\n" +
                  "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " +
                  " Please <a href='" + ActivationUrl + "'>click here to activate</a>  your account and enjoy our services. \nThanks!";
            msg.IsBodyHtml = true;
            smtp.Credentials = new NetworkCredential("mohammed.akram52@gmail.com", "saheenakram");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            smtp.Send(msg);
            clear_controls();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Confirmation Link to activate your account has been sent to your email address');", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
            return;
        }
        finally
        {
            ActivationUrl = string.Empty;
            emailId = string.Empty;
            con.Close();
            cmd.Dispose();
        }
    }
  

Insert image in binary format

.....................................................aspx....................................................................

<div>
     <fieldset style="width:400px;">
    <legend>Save and retrieve image from database</legend>
    <table>
    <tr><td>Book Name: </td><td><asp:TextBox ID="txtBookName" runat="server"></asp:TextBox></td>
        </tr>
    <tr><td>Author: </td><td><asp:TextBox ID="txtAuthor" runat="server"></asp:TextBox></td></tr>
    <tr><td>Publisher: </td><td><asp:TextBox ID="txtPublisher" runat="server"></asp:TextBox></td></tr>
    <tr><td>Price: </td><td><asp:TextBox ID="txtPrice" runat="server"></asp:TextBox></td></tr>
    <tr><td>Book Picture: </td><td>
        <asp:FileUpload ID="flupBookPic" runat="server" /></td></tr>
        <tr><td></td><td>
            <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
            <asp:Button ID="btnCancel" runat="server" onclick="btnCancel_Click"
                Text="Cancel" />
            </td></tr>
        <tr><td>&nbsp;</td><td>
            <asp:Label ID="lblStatus" runat="server"></asp:Label>          
            </td></tr>
      
        <tr><td colspan="2">
            <asp:GridView ID="grdBooks" runat="server" AutoGenerateColumns="false">
            <Columns>
            <asp:TemplateField>
            <ItemTemplate>
           <center>  <asp:Image ID="ImgBookPic" runat="server" Height="80px" Width="80px" /><br />
             <asp:Label ID="lblBookPicName" runat="server" Text='<%#Eval("BookPicName") %>'></asp:Label>
             </center>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="BookName"  HeaderText="Book Name"  ItemStyle-HorizontalAlign="Center"/>
            <asp:BoundField DataField="Author"  HeaderText="Author" ItemStyle-HorizontalAlign="Center" />
            <asp:BoundField DataField="Publisher"  HeaderText="Publisher" ItemStyle-HorizontalAlign="Center" />
            <asp:BoundField DataField="Price"  HeaderText="Price" ItemStyle-HorizontalAlign="Center" />          
            </Columns>
            </asp:GridView>         
            </td></tr>
    </table> 
    </fieldset>
    </div>

................................................................cs   ................................................................................

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGridView();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string fileName = string.Empty;
        string filePath = string.Empty;
        string getPath = string.Empty;
        string pathToStore = string.Empty;
        string finalPathToStore = string.Empty;
        Byte[] bytes;
        FileStream fs;
        BinaryReader br;
      
        SqlCommand cmd = new SqlCommand("InsertBookDetails_Sp", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@BookName", txtBookName.Text.Trim());
        cmd.Parameters.AddWithValue("@Author", txtAuthor.Text.Trim());
        cmd.Parameters.AddWithValue("@Publisher", txtPublisher.Text.Trim());
        cmd.Parameters.AddWithValue("@Price", Convert.ToDecimal(txtPrice.Text));

        try
        {
            if (flupBookPic.HasFile)
            {
                fileName = flupBookPic.FileName;
                filePath = Server.MapPath("BookPictures/" + System.Guid.NewGuid() + fileName);
                flupBookPic.SaveAs(filePath);

                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                br = new BinaryReader(fs);
                bytes = br.ReadBytes(Convert.ToInt32(fs.Length));
                br.Close();
                fs.Close();

                cmd.Parameters.AddWithValue("@BookPic", bytes);
                cmd.Parameters.AddWithValue("@BookPicName", fileName);
                int getPos = filePath.LastIndexOf("\\");
                int len = filePath.Length;
                getPath = filePath.Substring(getPos, len - getPos);
                pathToStore = getPath.Remove(0, 1);
                finalPathToStore = "~/BookPictures/" + pathToStore;
                cmd.Parameters.AddWithValue("@BookPicPath", finalPathToStore);
            }
            con.Open();
            cmd.ExecuteNonQuery();
            lblStatus.Text = "Book Record saved successfully";
            lblStatus.ForeColor = System.Drawing.Color.Green;
            ClearControls();
            BindGridView();
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Book Record could not be saved";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        finally
        {
            con.Close();
            cmd.Dispose();
            fileName = null;
            filePath = null;
            fs = null;
            br = null;
            getPath = null;
            pathToStore = null;
            finalPathToStore = null;
        }
    }
  
    private void BindGridView()
    {
        DataTable dt = new DataTable();
        byte[] bytes;
        string base64String = string.Empty;
        SqlCommand cmd = new SqlCommand("GetBookDetails_Sp", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        try
        {
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                grdBooks.DataSource = dt;
                grdBooks.DataBind();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (!string.IsNullOrEmpty(Convert.ToString(dt.Rows[i]["BookPic"])))
                    {
                        bytes = (byte[])dt.Rows[i]["BookPic"];
                        base64String = Convert.ToBase64String(bytes, 0, bytes.Length);

                        Image img = (Image)grdBooks.Rows[i].FindControl("ImgBookPic");
                        img.ImageUrl = "data:image/png;base64," + base64String;
                    }
                }
           }
        }
        catch (Exception)
        {
            lblStatus.Text = "Book record could not be retrieved";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        finally
        {
            con.Close();
            dt.Clear();
            dt.Dispose();
            cmd.Dispose();
            bytes = null;
            base64String = null;
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearControls();
        lblStatus.Text = string.Empty;
    }

    private void ClearControls()
    {
        txtAuthor.Text = string.Empty;
        txtBookName.Text = string.Empty;
        txtPrice.Text = string.Empty;
        txtPublisher.Text = string.Empty;     
        txtBookName.Focus();
    }

..............................................sql..........................................................................................


talble

CREATE TABLE [dbo].[BookDetails](
    [BookID] [int] IDENTITY(1,1) NOT NULL,
    [BookName] [varchar](50) NULL,
    [Author] [varchar](50) NULL,
    [Publisher] [varchar](50) NULL,
    [Price] [decimal](18, 2) NULL,
    [BookPic] [varbinary](max) NULL,
    [BookPicName] [varchar](100) NULL,
    [BookPicPath] [varchar](200) NULL,

procedure


USE [Ekram]
GO
/****** Object:  StoredProcedure [dbo].[InsertBookDetails_Sp]    Script Date: 11/24/2016 22:30:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 ALTER PROCEDURE [dbo].[InsertBookDetails_Sp]
                @BookName                    VARCHAR(100),
                @Author                             VARCHAR(100),
                @Publisher                        VARCHAR(100),
                @Price                                 DECIMAL(18,2),            
                @BookPic                          VARBINARY(MAX)=NULL,
                @BookPicName              VARCHAR(100)=NULL,
                @BookPicPath                                VARCHAR(200)=NULL
AS
BEGIN
                SET NOCOUNT ON;
                INSERT INTO BookDetails(BookName,Author,Publisher,Price,BookPic,BookPicName,BookPicPath)
    VALUES (@BookName,@Author,@Publisher,@Price,@BookPic,@BookPicName,@BookPicPath)
END

GridView Operation in as.net

...............................................................aspx..............................................................................

<div class="GridviewDiv">
<asp:GridView runat="server" ID="gvDetails" ShowFooter="true" AllowPaging="true" PageSize="10" AutoGenerateColumns="false" DataKeyNames="productid,productname" OnPageIndexChanging="gvDetails_PageIndexChanging" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowEditing="gvDetails_RowEditing" OnRowUpdating="gvDetails_RowUpdating" OnRowDeleting="gvDetails_RowDeleting" OnRowCommand ="gvDetails_RowCommand" >
<HeaderStyle CssClass="headerstyle" />
<Columns>
<asp:BoundField DataField="productid" HeaderText="Product Id" ReadOnly="true" />
<asp:TemplateField HeaderText="Product Name">
<ItemTemplate>
<asp:Label ID="lblProductname" runat="server" Text='<%# Eval("productname")%>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProductname" runat="server" Text='<%# Eval("productname")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtpname" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("price")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProductprice" runat="server" Text='<%# Eval("price")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtprice" runat="server" />
<asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>


..........................................................cs file ......................................................
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    protected void BindGridview()
    {
        DataSet ds = new DataSet();
        using (SqlConnection con = new SqlConnection("Data Source=AKRAM-PC;Integrated Security=true;Initial Catalog=Ekram"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("crudoperations", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@status", "SELECT");
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            con.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                gvDetails.DataSource = ds;
                gvDetails.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                gvDetails.DataSource = ds;
                gvDetails.DataBind();
                int columncount = gvDetails.Rows[0].Cells.Count;
                gvDetails.Rows[0].Cells.Clear();
                gvDetails.Rows[0].Cells.Add(new TableCell());
                gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
                gvDetails.Rows[0].Cells[0].Text = "No Records Found";
            }
        }
    }
    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtname = (TextBox)gvDetails.FooterRow.FindControl("txtpname");
            TextBox txtprice = (TextBox)gvDetails.FooterRow.FindControl("txtprice");
            crudoperations("INSERT", txtname.Text, txtprice.Text, 0);
        }
    }
    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindGridview();
    }
    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindGridview();
    }
    protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvDetails.PageIndex = e.NewPageIndex;
        BindGridview();
    }
    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int productid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["productid"].ToString());
        TextBox txtname = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtProductname");
        TextBox txtprice = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtProductprice");
        crudoperations("UPDATE", txtname.Text, txtprice.Text, productid);
    }
    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int productid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["productid"].ToString());
        string productname = gvDetails.DataKeys[e.RowIndex].Values["productname"].ToString();
        crudoperations("DELETE", productname, "", productid);
    }
    protected void crudoperations(string status, string productname, string price, int productid)
    {
        using (SqlConnection con = new SqlConnection("Data Source=AKRAM-PC;Integrated Security=true;Initial Catalog=Ekram"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("crudoperations", con);
            cmd.CommandType = CommandType.StoredProcedure;
            if (status == "INSERT")
            {
                cmd.Parameters.AddWithValue("@status", status);
                cmd.Parameters.AddWithValue("@productname", productname);
                cmd.Parameters.AddWithValue("@price", price);
            }
            else if (status == "UPDATE")
            {
                cmd.Parameters.AddWithValue("@status", status);
                cmd.Parameters.AddWithValue("@productname", productname);
                cmd.Parameters.AddWithValue("@price", price);
                cmd.Parameters.AddWithValue("@productid", productid);
            }
            else if (status == "DELETE")
            {
                cmd.Parameters.AddWithValue("@status", status);
                cmd.Parameters.AddWithValue("@productid", productid);
            }
            cmd.ExecuteNonQuery();
            lblresult.ForeColor = Color.Green;
            lblresult.Text = productname + " details " + status.ToLower() + "d successfully";
            gvDetails.EditIndex = -1;
            BindGridview();
        }
    }





Sunday, 13 November 2016

Upload mp3 by using asp.net

web.config

<configuration>
  <system.web>

    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5" executionTimeout="240" maxRequestLength="20480"/>
  </system.web>
  <connectionStrings>
    <add name="constr" connectionString="server=AKRAM-PC;database=Ekram;uid=sa;pwd=akram" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="3000000000" />
      </requestFiltering>
    </security>
  </system.webServer>

</configuration>

aspx
<div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" RowStyle-BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
    HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="FileName" />
            <asp:TemplateField>
                <ItemTemplate>
                    <object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=FileCS.ashx?Id=<%# Eval("Id") %>'
                        width="240" height="20" id="dewplayer">
                        <param name="wmode" value="transparent" />
                        <param name="movie" value='dewplayer-vol.swf?mp3=FileCS.ashx?Id=<%# Eval("Id") %>'/>
                    </object>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/FileCS.ashx?Id={0}" HeaderText="Download" />
        </Columns>
    </asp:GridView>
        </div><div><asp:FileUpload ID="Fump3" runat="server" /> <asp:Button ID="btnup" runat="server" Text="Upload" OnClick="btnup_Click" /></div>
    </div>


ADD THE WEB HANDLER (ashx) in project

<%@ WebHandler Language="C#" Class="FileCS" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
public class FileCS : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        int id = int.Parse(context.Request.QueryString["id"]);
        byte[] bytes;
        string contentType;
        string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string name;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=@Id";
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.Connection = con;
                con.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                sdr.Read();
                bytes = (byte[])sdr["Data"];
                contentType = sdr["ContentType"].ToString();
                name = sdr["Name"].ToString();
                con.Close();
            }
        }
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
        context.Response.ContentType = contentType;
        context.Response.BinaryWrite(bytes);
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}


.cs
private void BindGrid()
    {
        string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select Id, Name from tblFiles";
                cmd.Connection = con;
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
            }
        }
    }
    protected void btnup_Click(object sender, EventArgs e)
    {
        using (BinaryReader br = new BinaryReader(Fump3.PostedFile.InputStream))
        {
            byte[] bytes = br.ReadBytes((int)Fump3.PostedFile.InputStream.Length);
            string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
                    cmd.Parameters.AddWithValue("@Name", Path.GetFileName(Fump3.PostedFile.FileName));
                    cmd.Parameters.AddWithValue("@ContentType", "audio/mpeg3");
                    cmd.Parameters.AddWithValue("@Data", bytes);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
        Response.Redirect(Request.Url.AbsoluteUri);
  
    }


Database sql 
CREATE TABLE [dbo].[tblFiles](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](200) NULL,
    [ContentType] [varchar](50) NULL,
    [Data] [varbinary](max) NULL,
 CONSTRAINT [PK_tblFiles] PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
 

Tuesday, 8 November 2016

java script email validation

<script type="text/javascript">
        function checkEmail() {
            if (document.getElementById("<%=txtname.ClientID%>").value == "") {
                alert("Current Password Field is Required !")
                document.getElementById("<%=txtname.ClientID%>").focus();
                return false;
            }
            if(name.value==0){
                aler('enter name');
                return false;
            }

            var email = document.getElementById('txtemail');
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

            if (!filter.test(email.value)) {
                alert('Please provide a valid email address');
                email.focus;
                return false;
            }

        }
    </script>

<asp:Button ID="btnsubmit" Text="save" runat="server" OnClientClick="return checkEmail() " />