Tuesday 18 June 2013

Check for Duplicate Email ID using JQuery

Sometimes we need to check for duplicate EmailID or Username on Keypress. So this code will help you to check for duplicate and valid EmailID in your database.

First create teh textbox to enter the Email ID.

<asp:TextBox ID="txtEmail" runat="server" CssClass="input-text email duplicate-email txtemail"    MaxLength="100"></asp:TextBox>

Now add the following code to your header part.

<script type="text/javascript">

$(document).ready(function () {
     $('.duplicate-email').live('keypress blur', function (e) {
                if (e.keyCode === 9) {
                    emailvalidation();
                }
      });
});

 function emailvalidation() {
            SetLoader();
            var txtemail = $(".txtemail").val();
            var regemail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
            if (!regemail.test(txtemail)) {
                $('.lblmsg').text('Enter valid e-mail.');
                $(".msg_div").show();
                HideLoading();
            }
            else
                checkDupEmail(txtemail);
        }

function checkDupEmail(emailid) {
            SetLoader();
            $.ajax({
                type: "POST",
                url: "Registration.aspx/DuplicateEmailID",
                data: JSON.stringify({ EmailID: emailid }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (data) {
                    jAlert("er=" + data.d, siteTitle, '');
                    return false;
                },
                success: function (data) {
                    var status = data.d;
                    if (status == true) {
                        $('.lblmsg').text('Email Already exist.');
                        $(".msg_div").show();
                        HideLoading();
                        return false;
                    }
                    else {
                        $(".msg_div").hide();
                        HideLoading();
                        return true; ;
                    }
                }
            });
        }

</script>

Now add the webmethod tobe called by AJAX. Here DubplicateEmailID is a WebMethod. I used LINQ method I written the query in CheckDuplicateByEmailID method which will return true or false.

 [WebMethod]
        public static bool DuplicateEmailID(string EmailID)
        {
            try
            {
                UserInfoService objUserInfoService = new UserInfoService();
                bool IsExist = objUserInfoService.CheckDuplicateByEmailID(EmailID.Trim());
                return IsExist;
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError(ex);
                return false;
            }
        }

Friday 14 June 2013

Send Email with PDF Attachment

Sometimes we need to send mail with attachment. so if you need so here is the code.

First Create a common class to get the template that you want to use to create a PDF to send in attachement.

public class CommonFunction
  public string GetTemplate(string path)
  {
  WebClient client = new WebClient();
  string content = client.DownloadString(path);
  return content;
   }
}


Now write the code on button click to send the mail

protected void btnSend_Click(object sender, EventArgs e)
{
StringBuilder InvoiceTemplate = new StringBuilder(); CommonFunctions Functions = new CommonFunctions();
InvoiceTemplate.Append(Functions.GetTemplate(Server.MapPath("~/Templates/Invoice.htm")));
InvoiceTemplate.Replace("##MS##", "John");
InvoiceTemplate.Replace("##BILLNO##", "34");
InvoiceTemplate.Replace("", "");
string To = cutomer23@gmail.com;
SendInvoice(To, "", "", "Invoice", "This is Invoice", InvoiceTemplate);
}

Now create a method SendInvoice

public int SendInvoice(string To, string CC, string AttachmentFilePath, string Subject, string BodyText, StringBuilder InvoiceText)
{
string From = ConfigurationManager.AppSettings["from"].ToString();
string Password = ConfigurationManager.AppSettings["password"].ToString();

SmtpClient mailClient = new SmtpClient();
NetworkCredential basicAuthenticationInfo = new NetworkCredential();
basicAuthenticationInfo.UserName = From;
basicAuthenticationInfo.Password = Password;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicAuthenticationInfo;
mailClient.Host = ConfigurationManager.AppSettings["host"].ToString();
mailClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"].ToString());

System.Net.Mail.MailMessage mailmessage = new System.Net.Mail.MailMessage(From, To, Subject, BodyText);
           
if (CC.Trim() != "")
mailmessage.CC.Add(CC);

using (FileStream fs = new FileStream(Server.MapPath("~/Templates/Invoice.pdf"), FileMode.Create))
{
StringReader sr = new StringReader(Convert.ToString(InvoiceText));
Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlWorker = new HTMLWorker(document);
PdfWriter.GetInstance(document, fs);
document.Open();
htmlWorker.Parse(sr);
document.Close();
fs.Close();
fs.Dispose();
}

AttachmentFilePath = Server.MapPath("~/Templates/Invoice.pdf");
System.Net.Mail.Attachment Attach = null;

if (AttachmentFilePath.Trim() != "")
Attach = new System.Net.Mail.Attachment(AttachmentFilePath);
           
if (Attach != null)
mailmessage.Attachments.Add(Attach);

mailmessage.IsBodyHtml = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.EnableSsl = true;
mailmessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailmessage.BodyEncoding = System.Text.Encoding.UTF8;
mailClient.Send(mailmessage);
mailmessage.Dispose();
 
File.Delete(Server.MapPath("~/Templates/Invoice.pdf"));
}
}

Thursday 13 June 2013

File Upload Control not working

If you are using Update Panel on your webpage then File Upload Control will not work with Asynchronize Postback. so you need to set Postback trigger on the button click.

 

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="btnSubmit" />
</Triggers>
</asp:UpdatePanel>

Saturday 1 June 2013

Download with PDF

Sometimes we need to give option download with PDF for some table on website. so this will help you.

I am using iTextSharp to download with PDF.  You need to download it first and then after adding reference of that dll into your project you can use this codes.

protected void btnDownloadPDF_Click(object sender, EventArgs e)
{
StringBuilder str = new StringBuilder();
str.Append("<h1 align=\"center\" style=\"font-size:15;font-weight:bold;\"><u>Report</u></h1><br/><br/>");
str.Append("<table border=1 style=\"font-size:12;\">");
str.Append("<tr bgcolor=\"#43928D\" style=\"font-weight:bold;color:white;\">");
str.Append("<th>Name</th>");
str.Append("<th>Company</th>");
str.Append("<th>Date</th>");
str.Append("<th>Salary</th></tr>");
 
for (int i = 0; i < GridView1.Rows.Count; i++)
{
str.Append("<tr><td>" + GridView1.Rows[i].Cells[0].Text + "</td>");
str.Append("<td>" + GridView1.Rows[i].Cells[1].Text + "</td>");
str.Append("<td>" + GridView1.Rows[i].Cells[2].Text + "</td>");
str.Append("<td>" + GridView1.Rows[i].Cells[3].Text + "</td></tr>");
}
str.Append("</table>");
CommonFunctions Functions = new CommonFunctions();
Functions.ExportPDF(str, "SalaryReport"); 
}
 
Here ExportPDF is a function of my CommonFunctions Class.
 


using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

 
public class CommonFunctions
public void ExportPDF(StringBuilder html, string FileName)
{
//set the cotent type to PDF
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//load the html content to the string reader
StringReader sr = new StringReader(html.ToString());
//HTMLDocument
//Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom)
Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
//iText class that allows you to convert HTML to PDF
HTMLWorker htmlWorker = new HTMLWorker(document);
//When this PdfWriter is added to a certain PdfDocument,
//the PDF representation of every Element added to this Document will be written to the outputstream.
PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
//open the document
document.Open();
htmlWorker.Parse(sr);
//close the document stream
document.Close();
//write the content to the response stream
HttpContext.Current.Response.Write(document);
HttpContext.Current.Response.End();
}
}