Wednesday, August 27, 2014

Creating pdf in C# using itext

//  first add iText dll
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;
using System.Xml;
using System.Net;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    string strCon = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

    public static string customername = string.Empty;
    public static string sOrderId = string.Empty;
    public static string sCurrentStatus = string.Empty;
    public static string billingAddress = string.Empty;
    public static string billingAddress2 = string.Empty;
    public static string sPostalcode = string.Empty;
    public static string sCity = string.Empty;
    public static string sState = string.Empty;
    public static string sBookName = string.Empty;
    public static string sAddress1 = string.Empty;
    public static string sAddress2 = string.Empty;
    public static string sAddress3 = string.Empty;
    public static string sAddress4 = string.Empty;
    public static string sDeliver = string.Empty;
    public static string sSubtotal = string.Empty;
    public static string sGift = string.Empty;
    public static string sTotalPrice = string.Empty;
    public static string sDiscount = string.Empty;
    public static string sOrderDate = string.Empty;
    public static string sBookPrice = string.Empty;
    public static string smTotalPrice = string.Empty;

 
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(strCon);  
        if (!IsPostBack)
        {
           
            try
            {

                Int32 obj = 0;
                conn.Open();

                SqlCommand command = new SqlCommand();
                command.Connection = conn;
                SqlParameter param;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "usp_order_invoice";
                SqlDataAdapter adapter;
                DataSet ds = new DataSet();
                //param = new SqlParameter("@nCOId", obj1);
               // param.Direction = ParameterDirection.Input;
               // param.DbType = DbType.String;
               // command.Parameters.Add(param);

                adapter = new SqlDataAdapter(command);
                adapter.Fill(ds);

                //manipulate your data


                DataTable dt1 = ds.Tables[0];

                foreach (DataRow row in dt1.Rows)
                {
                    foreach (DataColumn col in dt1.Columns)
                   obj  = Convert.ToInt32(dt1.Rows[0]["nCOId"] );
                     LoadData(obj);
                }


        }

     

             
           

            catch (Exception ex)
            {
            }
            finally
            {
                conn.Close();
            }
        }
    }
    private void LoadData(int obj1)
    {

        SqlConnection conn = new SqlConnection(strCon);
       

        try
        {
            conn.Open();

            SqlCommand command = new SqlCommand();
            command.Connection = conn;
            SqlParameter param;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "usp_invoiceDetail";
            SqlDataAdapter adapter;
            DataSet ds = new DataSet();
            param = new SqlParameter("@nCOId", obj1);
            param.Direction = ParameterDirection.Input;
            param.DbType = DbType.String;
            command.Parameters.Add(param);

            adapter = new SqlDataAdapter(command);
            adapter.Fill(ds);

            //manipulate your data

         
            DataTable dt1 = ds.Tables[0];
            DataTable dt = ds.Tables[1];

            string sessionid = HttpContext.Current.Session.SessionID.ToString();
            string pdf_name = string.Empty;
            string file_name = string.Empty;
            string invoicepdfname = string.Empty;
            string orderpdfname = string.Empty;
            int intColumnCount = 0;

            file_name = Convert.ToString(obj1);//DateTime.Now.ToString("yyyyMMddHHmmss000000zz");
            file_name = file_name.Replace("+", "");
            pdf_name = file_name + ".pdf";
         
            string sPhysicalPath = HttpContext.Current.Server.MapPath("~/upload/invoice/");   // Request.PhysicalApplicationPath + "DocProcess\\" + sessionid;
            if (!Directory.Exists(sPhysicalPath))
            {
                Directory.CreateDirectory(sPhysicalPath);
            }
           
           


            string strFileName = sPhysicalPath + pdf_name;
            iTextSharp.text.Document pdfPaymentReceipt = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 15, 25);        
            PdfWriter writerPaymentReceipt = PdfWriter.GetInstance(pdfPaymentReceipt, new FileStream(strFileName, FileMode.OpenOrCreate));
            invoicepdfname = "PaymentReceipt" + pdf_name;
            pdfPaymentReceipt.Open();


            #region header
            intColumnCount = 1;
            iTextSharp.text.Table tblOrderConfHead = new iTextSharp.text.Table(intColumnCount);
            int[] tblOrderConfHeadWidths = { 100 };
            tblOrderConfHead.SetWidths(tblOrderConfHeadWidths);
            tblOrderConfHead.WidthPercentage = 100;
            tblOrderConfHead.BorderWidth = 0.2f;
            tblOrderConfHead.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.SkyBlue);
            tblOrderConfHead.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.SkyBlue);

            iTextSharp.text.List pdfwelcomeList = new iTextSharp.text.List(false, 1);
            pdfwelcomeList.Symbol = new Chunk("");

            pdfwelcomeList.Add(new iTextSharp.text.ListItem(new iTextSharp.text.Phrase("Bookfari (US) LLC", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 13, Font.BOLD))));

            Cell headerWelcome_cell = new Cell();
            headerWelcome_cell.BorderWidth = 0f;
            headerWelcome_cell.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.Transparent);
            headerWelcome_cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
            headerWelcome_cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_BOTTOM;
            headerWelcome_cell.AddElement(pdfwelcomeList);
            tblOrderConfHead.AddCell(headerWelcome_cell);
#endregion header

         

            #region Bookfari (US) LLC
            intColumnCount = 2;
            string address2 = dt.Rows[0]["cCompNbrDesc"].ToString() + dt.Rows[0]["cCompNbr"].ToString();
            string address3 = dt.Rows[0]["cTaxNbrDesc"].ToString() + dt.Rows[0]["cTaxNbr"].ToString();
            iTextSharp.text.pdf.PdfPTable tblOrderTypeTime = new PdfPTable(intColumnCount);
            tblOrderTypeTime.SetWidths(new int[] { 30, 70 });
            tblOrderTypeTime.WidthPercentage = 100;
            tblOrderTypeTime.DefaultCell.BorderWidth = 0f;
            tblOrderTypeTime.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
            InsertCellsToTable(ref tblOrderTypeTime
                , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
                , new iTextSharp.text.Phrase(dt.Rows[0]["cMailingAddress"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));
            InsertCellsToTable(ref tblOrderTypeTime
                , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
                , new iTextSharp.text.Phrase(address2, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));

            InsertCellsToTable(ref tblOrderTypeTime
                , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI,10))
                , new iTextSharp.text.Phrase(address3, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));

       

            PdfPTable tabTemp = new PdfPTable(2);
            tabTemp.WidthPercentage = 100;                                        
            PdfPCell cellTemp = new PdfPCell();
            cellTemp.BorderWidthBottom = cellTemp.BorderWidthTop = 1f;
            cellTemp.BorderWidthLeft = cellTemp.BorderWidthRight = 0f;
            cellTemp.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.Black);

            cellTemp.AddElement(tblOrderTypeTime);
            tabTemp.AddCell(cellTemp);
     


            #endregion Bookfari (US) LLC

            #region header2
            intColumnCount = 1;
            iTextSharp.text.Table tblOrderConfHead2 = new iTextSharp.text.Table(intColumnCount);
            int[] tblOrderConfHeadWidths2 = { 100 };
            tblOrderConfHead2.SetWidths(tblOrderConfHeadWidths2);
            tblOrderConfHead2.WidthPercentage = 100;
            tblOrderConfHead2.BorderWidth = 0.2f;
            tblOrderConfHead2.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.SkyBlue);
            tblOrderConfHead2.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.SkyBlue);

            iTextSharp.text.List pdfwelcomeList2 = new iTextSharp.text.List(false, 1);
            pdfwelcomeList2.Symbol = new Chunk("");

            pdfwelcomeList2.Add(new iTextSharp.text.ListItem(new iTextSharp.text.Phrase("Invoice", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 13, Font.BOLD))));

            Cell headerWelcome_cell2 = new Cell();
            headerWelcome_cell2.BorderWidth = 0f;
            headerWelcome_cell2.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.Transparent);
            headerWelcome_cell2.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
            headerWelcome_cell2.VerticalAlignment = iTextSharp.text.Element.ALIGN_BOTTOM;
            headerWelcome_cell2.AddElement(pdfwelcomeList2);
            tblOrderConfHead2.AddCell(headerWelcome_cell2);
            #endregion header2
            #region invoice

            PdfPTable tabDlvryBillDetail;
            PdfPCell tabDlvryBillDetailCell;
            tabDlvryBillDetail = new PdfPTable(4);
            tabDlvryBillDetail.WidthPercentage = 100;
            tabDlvryBillDetail.DefaultCell.BorderWidth = 0f;
            tabDlvryBillDetail.DefaultCell.BorderColorBottom = new iTextSharp.text.Color(System.Drawing.Color.Black);
         
            InsertCellsToTable(ref tabDlvryBillDetail
            , new iTextSharp.text.Phrase("Invoice", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
            , new iTextSharp.text.Phrase(dt.Rows[0]["cAddr1"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
            , new iTextSharp.text.Phrase("Invoice Number:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
            , new iTextSharp.text.Phrase(dt.Rows[0]["nCOId"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
            );

            InsertCellsToTable(ref tabDlvryBillDetail
           , new iTextSharp.text.Phrase("To:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase(dt.Rows[0]["cAddr2"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase("Invoice Date:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase(dt.Rows[0]["dOrderDate"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           );

            InsertCellsToTable(ref tabDlvryBillDetail
           , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase(dt.Rows[0]["SubUrnan"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase("Customer Code:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase(dt.Rows[0]["nCompId"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           );


            InsertCellsToTable(ref tabDlvryBillDetail
           , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase(dt.Rows[0]["cCountryCode"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase("Cust. OrderNo:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           , new iTextSharp.text.Phrase(dt.Rows[0]["cCompOrderNo"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
           );

            pdfPaymentReceipt.Add(tblOrderConfHead);
            pdfPaymentReceipt.Add(tblOrderTypeTime);          
            pdfPaymentReceipt.Add(tblOrderConfHead2);
            pdfPaymentReceipt.Add(tabDlvryBillDetail);
           


         
            #endregion invoice

            # region itemdetail

            PdfPTable tblItemsnew = new PdfPTable(6);
            tblItemsnew.SpacingBefore = 30;
            tblItemsnew.SpacingAfter = 20;
            tblItemsnew.DefaultCell.Padding = 1;
            float[] headerwidths_items_new = {2,7, 20, 6, 5, 5 };
            tblItemsnew.SetWidths(headerwidths_items_new);
            tblItemsnew.WidthPercentage = 100;
            tblItemsnew.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE;
            tblItemsnew.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE;
            //tblItemsnew.DefaultCell.BorderWidth = 0.001f;
            tblItemsnew.DefaultCell.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.Gray);
            tblItemsnew.HeaderRows = 0;

            // PdfPTable table = new PdfPTable(3); "TIMES_ROMAN", BaseFont.WINANSI, 7
           
            //PdfPCell cell = new PdfPCell(new Phrase("Qty", new Font(Font.TIMES_ROMAN, 8f, Font.NORMAL, Color.BLACK)));
            //cell.BackgroundColor = new Color(System.Drawing.Color.SkyBlue);
            //cell.BorderColor = new Color(255, 242, 0);
            //cell.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;
            //cell.BorderWidthBottom = 3f;
            //cell.BorderWidthTop = 3f;
            //cell.PaddingBottom = 10f;
            //cell.PaddingLeft = 20f;
            //cell.PaddingTop = 4f;
            //tblItemsnew.AddCell(cell);
            //PdfPCell cell1 = new PdfPCell(new Phrase("ISBN13", new Font(Font.TIMES_ROMAN, 8f, Font.NORMAL, Color.BLACK)));
            //cell1.BackgroundColor = new Color(System.Drawing.Color.SkyBlue);
            //cell1.BorderColor = new Color(255, 242, 0);
            //cell1.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;
            //cell1.BorderWidthBottom = 3f;
            //cell1.BorderWidthTop = 3f;
            //cell1.PaddingBottom = 10f;
            //cell1.PaddingLeft = 20f;
            //cell1.PaddingTop = 4f;
            //tblItemsnew.AddCell(cell1);
            //tblItemsnew.AddCell("ISBN13");
            //tblItemsnew.AddCell("Title");
            //tblItemsnew.AddCell("Condition");
            //tblItemsnew.AddCell("USD Sale Price");
            //tblItemsnew.AddCell("USD Ext Price");




            InsertCellsToTable(ref tblItemsnew
                , new iTextSharp.text.Phrase("Qty", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                , new iTextSharp.text.Phrase("ISBN13", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                , new iTextSharp.text.Phrase("Title", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                , new iTextSharp.text.Phrase("Condition", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                , new iTextSharp.text.Phrase("USD Sale Price", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                , new iTextSharp.text.Phrase("USD Ext Price", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7)));

           


            int i = 0;
            int sQty = 0;
       
            string total = string.Empty;
            string currency = string.Empty;
            for (i = 0; i <= dt1.Rows.Count - 1; i++)
            {
                Int32 check= Convert.ToInt32(dt1.Rows[i]["QtytoAccept"]);
                if (check > 0)
                {
                    decimal USDExtSale = 0;
                    sBookName = dt1.Rows[i]["cTitle"].ToString();
                    sQty = Convert.ToInt32(dt1.Rows[i]["QtytoAccept"]) == 0 ? 1 : Convert.ToInt32(dt1.Rows[i]["QtytoAccept"]);
                    decimal newprice = Convert.ToDecimal(dt1.Rows[i]["NewPrice"]);
                    currency = dt1.Rows[i]["cCurrDispNm"].ToString();


                    USDExtSale = sQty * newprice;
                    total = currency + USDExtSale.ToString();

                    InsertCellsToTable(ref tblItemsnew
                   , new iTextSharp.text.Phrase(sQty == 0 ? string.Empty : sQty.ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(dt1.Rows[i]["cISBN13"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(sBookName, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(dt1.Rows[i]["cCondition"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(dt1.Rows[i]["NewPrice"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(USDExtSale.ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7)));
                }

                else
                {
                    decimal USDExtSale = 0;
                    sBookName = dt1.Rows[i]["cTitle"].ToString();
                    sQty = Convert.ToInt32(dt1.Rows[i]["QtytoAccept"]) == 0 ? 1 : Convert.ToInt32(dt1.Rows[i]["QtytoAccept"]);
                    decimal newprice = Convert.ToDecimal(dt1.Rows[i]["NewPrice"]);
                    currency = dt1.Rows[i]["cCurrDispNm"].ToString();
                   
                    InsertCellsToTable(ref tblItemsnew
                   , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(sBookName, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(dt1.Rows[i]["cCondition"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(dt1.Rows[i]["NewPrice"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
                   , new iTextSharp.text.Phrase(USDExtSale.ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7)));
                }

            }

            InsertCellsToTable(ref tblItemsnew
           , new iTextSharp.text.Phrase(sQty == 0 ? string.Empty : sQty.ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
           , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
           , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
           , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
           , new iTextSharp.text.Phrase("Total: ", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 8, iTextSharp.text.Font.BOLD))
           , new iTextSharp.text.Phrase(total, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7)));

            InsertCellsToTable(ref tblItemsnew
        , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
        , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
        , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
        , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7))
        , new iTextSharp.text.Phrase("Tax Amount:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 8, iTextSharp.text.Font.BOLD))
        , new iTextSharp.text.Phrase(currency + "0.00", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7)));

#endregion itemdetail

            #region bottomblock

            intColumnCount = 2;
            iTextSharp.text.pdf.PdfPTable tblOrderTypeTime1 = new PdfPTable(intColumnCount);
            tblOrderTypeTime1.SetWidths(new int[] { 40, 70 });
            tblOrderTypeTime1.WidthPercentage = 100;
            tblOrderTypeTime1.DefaultCell.BorderWidth = 0f;
            tblOrderTypeTime1.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
            InsertCellsToTable(ref tblOrderTypeTime1
                , new iTextSharp.text.Phrase(dt.Rows[0]["cPayInstructions"].ToString() + ":", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
                , new iTextSharp.text.Phrase(string.Empty, iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));
            InsertCellsToTable(ref tblOrderTypeTime1
                , new iTextSharp.text.Phrase("Bank:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
                , new iTextSharp.text.Phrase(dt.Rows[0]["cBank"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));

            InsertCellsToTable(ref tblOrderTypeTime1
                , new iTextSharp.text.Phrase("Branch:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI,10))
                , new iTextSharp.text.Phrase(dt.Rows[0]["cBranch"].ToString() + dt.Rows[0]["cBranchAddress"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));

            InsertCellsToTable(ref tblOrderTypeTime1
                 , new iTextSharp.text.Phrase(dt.Rows[0]["cRefCodeNm"].ToString() + ":", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
                 , new iTextSharp.text.Phrase(dt.Rows[0]["cRefCode"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));

            InsertCellsToTable(ref tblOrderTypeTime1
              , new iTextSharp.text.Phrase("Account Name:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
              , new iTextSharp.text.Phrase(dt.Rows[0]["cAccountNm"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));


            InsertCellsToTable(ref tblOrderTypeTime1
              , new iTextSharp.text.Phrase("Account Number:", iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10))
              , new iTextSharp.text.Phrase(dt.Rows[0]["cAccountNo"].ToString(), iTextSharp.text.FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 10)));

            PdfPTable tabTemp1 = new PdfPTable(2);
            tabTemp1.WidthPercentage = 100;                                        
            PdfPCell cellTemp1 = new PdfPCell();
            cellTemp1.BorderWidthBottom = cellTemp.BorderWidthTop = 1f;
            cellTemp1.BorderWidthLeft = cellTemp.BorderWidthRight = 0f;
            cellTemp1.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.Black);

            cellTemp.AddElement(tblOrderTypeTime1);
            tabTemp.AddCell(cellTemp1);      
           
            #endregion bottomblock        
           
            pdfPaymentReceipt.Add(tblItemsnew);
            pdfPaymentReceipt.Add(tblOrderTypeTime1);      
            pdfPaymentReceipt.Close();
            //Response.Clear();
            //Response.AppendHeader("content-disposition", "attachment; filename=" + pdf_name);
            //Response.ContentType = "text/plain";
            //Response.WriteFile(Request.PhysicalApplicationPath + "/DocProcess/" + sessionid + "/" + pdf_name);

            //Response.Flush();

            //if (Directory.Exists(sPhysicalPath))
            //{
            //    System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(sPhysicalPath);
            //    foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            //    {
            //   //     file.Delete();
            //    }
            //    Directory.Delete(sPhysicalPath);

            //}

           // Response.End();
        }









        catch (Exception e)
        {
            Console.WriteLine("Error: " + e);
        }
        finally
        {
            conn.Close();
        }






    }

    #region InsertCellsToTable
    protected static void InsertCellsToTable(ref PdfPTable tbl, params iTextSharp.text.Phrase[] cells)
    {
        try
        {
            for (int i = 0; i < cells.Length; i++)
            {
                PdfPCell new_cell = new PdfPCell();              
                new_cell.BorderWidth = tbl.DefaultCell.BorderWidth;
                new_cell.BorderColor = tbl.DefaultCell.BorderColor;
                new_cell.BorderColor = tbl.DefaultCell.BackgroundColor;
                new_cell.BorderColorBottom = tbl.DefaultCell.BorderColorBottom;
                new_cell.HorizontalAlignment = tbl.DefaultCell.HorizontalAlignment;
                new_cell.Phrase = cells[i];
                tbl.AddCell(new_cell);
            }
        }
        catch (Exception ex)
        {
         
        }
    }
    #endregion
}
   

Tuesday, June 17, 2014

Master Page - User Control - Page

Master Page

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="CoOpMaster.master.cs" Inherits="CoOpMaster" %>

<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" TagPrefix="cc1" %>
<%@ Register TagPrefix="ux" TagName="header" Src="~/BuyBack/CoOp/CoOpHeader.ascx" %>
<%@ Register TagPrefix="ux" TagName="footer" Src="~/BuyBack/CoOp/CoOpFooter.ascx" %>
<%@ Register TagPrefix="ux" TagName="rightPanel" Src="~/BuyBack/CoOp/CoOpRightPanel.ascx" %>
<!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 id="Head1" runat="server">
    <title>
        <asp:Localize ID="meta1" runat="server">Buyback Bookstore | Sell Books Online </asp:Localize>
     
    </title>
    <link rel="stylesheet" href="../../Css/thickbox.css" type="text/css" media="screen" />
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
    <script type="text/javascript" src="../Js/jquery.js"></script>
    <script type="text/javascript" src="../Js/thickbox.js"></script>  
    <meta property="fb:admins" content="100000008072230" />
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <script language="javascript" type="text/javascript">
        function doClick(buttonName, e) {
            //the purpose of this function is to allow the enter key to
            //point to the correct button to click.
            var key;

            if (window.event)
                key = window.event.keyCode;     //IE
            else
                key = e.which;     //firefox

            if (key == 13) {
                //Get the button the user wants to have clicked
                var btn = document.getElementById(buttonName);
                if (btn != null) { //If we find the button click it
                    btn.click();
                    event.keyCode = 0
                }
            }
        }
    </script>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div id="fb-root">
    </div>
    <script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>
    <script type='text/javascript'>
        FB.init({ appId: '<%: Facebook.FacebookApplication.Current.AppId %>', status: true, cookie: true, xfbml: true });
        FB.Event.subscribe('auth.sessionChange', function (response) {
            if (response.session) {
                // A user has logged in, and a new cookie has been saved
                //window.location.reload();
            } else {
                // The user has logged out, and the cookie has been cleared
            }
        });
    </script>
    <div id="wpwrap">
    <ux:header ID="uxheader" runat="server"></ux:header>
       
    <div id="wpcontent">
   <section class="clearfix">
    <div class="container12">
        <div class="column12">
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
       <%-- <div class="column4">--%>
            <asp:UpdatePanel ID="upRight" runat="server" UpdateMode="Always">
                <ContentTemplate>
                    <ux:rightPanel ID="uxRight" Visible="false" runat="server"></ux:rightPanel>
                </ContentTemplate>
            </asp:UpdatePanel>
      <%--  </div>--%>
    </div>
   </section>
   </div>
    <ux:footer ID="uxfooter" runat="server"></ux:footer>
    </div>
    </form>

</body>
</html>



USER CONTROL


<%@ Control Language="C#" AutoEventWireup="true"  CodeFile="CoOpRightPanel.ascx.cs"
    Inherits="CoOpRightPanel" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<div class="right_green_section">
    <h1>
        Buyback Quote</h1>
    <div class="detail_wrapper">
    <asp:UpdatePanel ID="uptPanel" runat="server">
    <ContentTemplate>
        <div runat="server" id="BindBuybackdata">
        </div>
        <div class="info_text">
         <br />
            This is your quote, you can add more books and get more <strong>cash</strong>
            
        </div>
          
         <br />
        <div class="small_search_wrapper">
        <asp:Panel  ID="defauldBttn" runat="server" DefaultButton="BtnSearch">
            <asp:TextBox ID="TxtSearch" runat="server" class="small_input_search"></asp:TextBox>
            <asp:Button ID="BtnSearch" runat="server" CssClass="small_button" CausesValidation="false" Text="search" OnClick="BtnSearch_Click" />
            </asp:Panel>
            <asp:UpdateProgress ID="uprgchild" runat="server" AssociatedUpdatePanelID="uptPanel"
            DisplayAfter="0" DynamicLayout="false">
            <ProgressTemplate>
               <div class="rightSearchLoad"><img src="../../App_Themes/CoOp/images/gif-load.gif" class="loader" /></div>
                   
            </ProgressTemplate>
        </asp:UpdateProgress>
        </div>
        <asp:Label ID="LblMsg" runat="server" ForeColor="Red"></asp:Label>
        </ContentTemplate>
        </asp:UpdatePanel>
       
             
       
        <div class="info_text mr_bottom45">
        <br />
            How Used is USED? <br /> Learn about book condition
        </div>
    </div>
</div>


PAGE

<%@ Page Title="" Language="C#" MasterPageFile="~/BuyBack/CoOp/CoOpMaster.master"
    AutoEventWireup="true" CodeFile="CoOpLogin.aspx.cs" Inherits="CoOpLogin" CodeFileBaseClass="CoOpFrontBasePage"
    Culture="auto" UICulture="auto" EnableCheckLogIn="False" EnableSSL="True" Theme="CoOp"
    meta:resourcekey="PageResource2" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <script type="text/javascript" src="../Js/jquery-1.js" type="text/javascript"></script>
    <script type="text/javascript" src="../Js/jquery_002.js" type="text/javascript"></script>
     <link href="../../App_Themes/CoOp/style.css" rel="stylesheet" type="text/css" />
    <link href="../../App_Themes/CoOp/gumby.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    
    <script language="javascript" type="text/javascript">
        function doClick(buttonName, e) {
            var key;
            if (window.event)
                key = window.event.keyCode;     //IE
            else
                key = e.which;     //firefox

            if (key == 13) {
                var btn = document.getElementById(buttonName);
                if (btn != null) { //If we find the button click it
                    btn.click();
                    event.keyCode = 0
                }
            }
        }
        function isNumberKey(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode > 31 && (charCode < 47 || charCode > 57)) {
                return false;
            }
            return true;
        }
    </script>
    

    <div id="dvForPass" style="display: none;">
        <div class="contentHalf">
            <div class="panelBlue">
                <%--<asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>--%>
                <h2>
                    <%=GetLocalResourceObject("Message2")%></h2>
                <div class="dividerLineSmall">
                </div>
                <div class="formstyle">
                    <asp:Label ID="lblForMsg" runat="server" CssClass="err_msg" Visible="false"></asp:Label>
                    <h3>
                        <%=GetLocalResourceObject("Emailaddress")%>
                    </h3>
                    <asp:TextBox ID="txt_forpass_email" runat="server"  ValidationGroup="ForgotPass" MaxLength="100" CssClass="txtbox"
                        meta:resourcekey="txt_rst_emailResource1"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvForPass" runat="server" ControlToValidate="txt_forpass_email"
                        SetFocusOnError="True" ValidationGroup="ForgotPass" ErrorMessage="Enter valid Email Id"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="repForPass" runat="server" ControlToValidate="txt_forpass_email"
                        SetFocusOnError="True" ValidationExpression="<%$ Resources:RegularExpressions, Email %>"
                        ValidationGroup="ForgotPass" Display="Dynamic" ErrorMessage="Enter valid Email Id"></asp:RegularExpressionValidator>
                    
                      <%--  <asp:LinkButton ID="btnForPass" runat="server" OnClick="btnForPass_Click" CssClass="loginBtn"
                            Text="Click Here"  ValidationGroup="ForgotPass" OnClientClick="doPostBack(this);" ></asp:LinkButton>--%>
                             <asp:Button ID="btnForPass" runat="server"  OnClick="btnForPass_Click"
                                    CssClass="loginBtn" Text="Click Here"  
                                    OnClientClick="doPostBack(this);" ValidationGroup="ForgotPass" />
                   
                </div>
                 
            </div>
        </div>
    </div>
    <div id="dvPwdReset" style="display: none;">
        <div class="contentHalf">
            <div class="panelBlue">
                <%--<asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>--%>
                <h2>
                    <%=GetLocalResourceObject("reset")%>
                </h2>
                <div class="dividerLineSmall">
                </div>
                <div class="formstyle">
                    <asp:Label ID="lblrstMsg" runat="server" CssClass="err_msg" Visible="false"></asp:Label>
                    <h3>
                        <%=GetLocalResourceObject("Emailaddress")%>
                    </h3>

                    <asp:TextBox ID="txt_rst_email" runat="server" MaxLength="100" ValidationGroup="Reset"  CssClass="txtbox"
                        meta:resourcekey="txt_rst_emailResource1"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rvf_email_Reset" runat="server" ControlToValidate="txt_rst_email"
                        SetFocusOnError="True" ValidationGroup="Reset" meta:resourcekey="rfvEmailResource1"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="rev_email_Reset" runat="server" ControlToValidate="txt_rst_email"
                        SetFocusOnError="True" ValidationExpression="<%$ Resources:RegularExpressions, Email %>"
                        ValidationGroup="Reset" Display="Dynamic" meta:resourcekey="revEmailResource1"></asp:RegularExpressionValidator>
                  
                      <%--  <asp:LinkButton ID="btnReset" runat="server" OnClick="btnReset_Click" CssClass="loginBtn"
                            Text="Reset Password" ValidationGroup="Reset" OnClientClick="doPostBack(this);"   ></asp:LinkButton>--%>
                             <asp:Button ID="btnReset" runat="server"  OnClick="btnReset_Click" CssClass="loginBtn"
                                     Text="Reset Password" ValidationGroup="Reset" OnClientClick="doPostBack(this);" />

                    
                </div>
                   
                <%-- </ContentTemplate>
                </asp:UpdatePanel>--%>
            </div>
        </div>
    </div>
    <asp:HiddenField ID="hfReset" runat="server" />
    <asp:HiddenField ID="hfpass" runat="server" />
   

    <div class="column8 alpha omega">  
     
    <div style="clear:both"></div>

    <div class="login">
      <asp:Panel ID="login" runat="server" DefaultButton="btnLogin" >
                <ul class="loginForm2">

                <h3 align="left"> Login Here </h3>
                <p>
                    <asp:Label ID="lblMsgHeader" runat="server"  CssClass="loginErrMsg" Visible="False" meta:resourcekey="lblMsgHeaderResource1"></asp:Label>
                    </p>
                   
                    <li>
                        <label>
                            Email :</label>
                        <asp:TextBox ID="txtEmail" TabIndex="5" runat="server" class="detail_input wth245"
                            meta:resourcekey="txtEmailResource1"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfvEmail" runat="server" CssClass="err_msg" ControlToValidate="txtEmail"
                            SetFocusOnError="True" ValidationGroup="login" Display="Dynamic" 
                            Text="Enter Valid Email Id"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="revEmail" runat="server" ControlToValidate="txtEmail"
                            SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            ValidationGroup="login" Display="Dynamic" 
                            CssClass="err_msg" Text="Enter Valid Email Id"></asp:RegularExpressionValidator></li>
                    <li>
                        <label>
                            Password :</label>
                        <asp:TextBox ID="txtPwd" TabIndex="6" TextMode="Password" ValidationGroup="login"
                            runat="server" class="detail_input wth245" meta:resourcekey="txtPwdResource1"></asp:TextBox>
                        <div>
                            <asp:RequiredFieldValidator ID="rfvPwd" runat="server" ControlToValidate="txtPwd"
                                Display="Dynamic" SetFocusOnError="True" CssClass="err_msg" ValidationGroup="login"
                                Text="Enter Your Password" meta:resourcekey="rfvPwdResource2"></asp:RequiredFieldValidator></div>
                    </li>
                    
                    <li>
                        <label>
                            &nbsp;</label>
                            <a href="#" class="faceBookIcon">
                            <fb:login-button autologoutlink='true' perms='email' onlogin='window.location.reload()'>Login
                                                       Using Facebook</fb:login-button>
                        </a>
                        <asp:LinkButton ID="btnLogin" runat="server" ValidationGroup="login" TabIndex="7"  class="loginBtn"
                            meta:resourcekey="btnLoginResource1" OnClick="btnLogin_Click" Text="Login"  style="margin-right:0px !important;"></asp:LinkButton>
                        </li>
                        
                    <li style="max-height:30px">
                        <label>
                            &nbsp;</label>
                            <%--<span class="remember">
                                <input type="checkbox" id="chksghned" runat="server" />
                                Remember Me</span> --%>

                                 <label class="check-box" for="ctl00_ContentPlaceHolder1_chksghned">
                              <input type="checkbox" id="chksghned" runat="server" />
                                <span></span> Remember Me</label>

                               <div style="clear:both"></div>
                                <a href="#TB_inline?height=230&width=360&inlineId=dvForPass" class="thickbox">Forgot Password?</a> &nbsp; 
                                <a href="#TB_inline?height=230&width=360&inlineId=dvPwdReset" class="thickbox">Reset Password</a>
                                </li>
                  
                </ul>
                </asp:Panel>
    </div>

   
    <div class="column4 omega">
    <ul class="loginForm2 clearfix">

  
   


                      <asp:LinkButton ID="lnlCoopHome" runat="server"  TabIndex="17" PostBackUrl="https://www.coop.com.au/bookshop/action_sn/LoginPage"
                            class="loginBtn" Text="Continue" ></asp:LinkButton>


                    <div id="hide"  style="display:none;">
    <h3 align="left"> Create Web Account </h3>

                    <p>
                    <asp:Label ID="lblMsg" runat="server" CssClass="signUpErrMsg" Visible="False" meta:resourcekey="lblMsgResource1"></asp:Label></p>
                   
                    <li>
                        <label>
                            First Name : <span>*</span></label>
                          <asp:TextBox ID="txtDetail_FirstNm"  TabIndex="10"  ValidationGroup="Shipping"
                        runat="server" MaxLength="17" meta:resourcekey="txtDetail_FirstNmResource1"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rqvdetailFirstNm" runat="server" ControlToValidate="txtDetail_FirstNm"
                        ValidationGroup="Register" Display="Dynamic" CssClass="err_msg" Text="Enter First Name"></asp:RequiredFieldValidator></li>
                    <li>
                        <label>
                            Last Name : <span>*</span></label>
                         <asp:TextBox ID="txtdetail_lastNm"  TabIndex="11"  ValidationGroup="Shipping"
                        runat="server" MaxLength="17"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rqvdetailLastNm" runat="server" ControlToValidate="txtdetail_lastNm"
                        ValidationGroup="Register" CssClass="err_msg" Display="Dynamic" Text="Enter Last Name"></asp:RequiredFieldValidator></li>
                    <li>
                        <label>
                            Email : <span>*</span></label>
                        <asp:TextBox ID="txtREmail" runat="server" TabIndex="12" MaxLength="100" 
                            meta:resourcekey="txtEmailResource1" Onblur="return usernameChecker(this.value);"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtREmail"
                            SetFocusOnError="True" ValidationGroup="Register" Display="Dynamic" CssClass="err_msg"
                            Text="Please Enter Email" meta:resourcekey="RequiredFieldValidator1Resource1"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtREmail"
                            SetFocusOnError="True" ValidationExpression="<%$ Resources:RegularExpressions, Email %>"
                            ValidationGroup="Register" Display="Dynamic" CssClass="err_msg" Text="Please Enter Valid Email"
                            meta:resourcekey="RegularExpressionValidator1Resource1"></asp:RegularExpressionValidator></li>
                    <li>
                        <label>
                            Mobile : <span>*</span></label>
                       <asp:TextBox ID="txtMobile"   TabIndex="13" ValidationGroup="Shipping"
                        runat="server" MaxLength="15"  onkeypress="return isNumberKey(event)"></asp:TextBox>
                    <asp:RequiredFieldValidator runat="server" ID="rfvMob" ValidationGroup="Register"
                        ControlToValidate="txtMobile" Display="Dynamic" CssClass="err_msg fl mbottom15" Text="Please Enter Mobile Number"
                        ></asp:RequiredFieldValidator></li>
                    <li>
                        <label>
                            Password : <span>*</span></label><asp:TextBox ID="txtPassword" runat="server" TabIndex="14"
                                TextMode="Password" MaxLength="20" class="detail_input wth245" meta:resourcekey="txtPasswordResource1"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rvfPassword" runat="server" ControlToValidate="txtPassword"
                            SetFocusOnError="True" ValidationGroup="Register" CssClass="err_msg" Display="Dynamic"
                            Text="Please Enter Password" meta:resourcekey="rvfPasswordResource2"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="revPass" runat="server" ControlToValidate="txtPassword"
                            SetFocusOnError="True" ValidationExpression="<%$ Resources:RegularExpressions, UserPass %>"
                            ValidationGroup="register" CssClass="err_msg" Display="Dynamic" Text="Password must contain 6 characters"
                            meta:resourcekey="revPassResource2"></asp:RegularExpressionValidator></li>
                    <li>
                        <label>
                            RE-Password: <span>*</span></label>
                        <asp:TextBox ID="txtConfirmPass" runat="server" TabIndex="15" TextMode="Password"
                            MaxLength="20" meta:resourcekey="txtConfirmPassResource1"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rvfConfirmPass" runat="server" ControlToValidate="txtConfirmPass"
                            SetFocusOnError="True" ValidationGroup="Register" CssClass="err_msg" Display="Dynamic"
                            Text="Please Enter confirm Password" meta:resourcekey="rvfConfirmPassResource2"></asp:RequiredFieldValidator>
                        <asp:CompareValidator ID="cvConfPwd" runat="server" ControlToCompare="txtPassword"
                            ControlToValidate="txtConfirmPass" SetFocusOnError="True" ValidationGroup="Register"
                            CssClass="err_msg" Text="Password is Not Matched" Display="Dynamic" meta:resourcekey="cvConfPwdResource2"></asp:CompareValidator>
                    </li>
                   
                    <li>
                        <label>
                            Date of Birth : </label>
                           
                 
                         <asp:TextBox ID="txtDob"  TabIndex="16" runat="server"   class="sm"  onkeypress="return isNumberKey(event)"></asp:TextBox>
                         <cc1:CalendarExtender runat="server" ID="calenderExt" Format="dd/MM/yyyy" TargetControlID="txtDob">
                                                                                    </cc1:CalendarExtender> <span>dd/mm/yy</span> 
                         
                                                                              
      <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtDob"
                            SetFocusOnError="True" ValidationExpression="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\d\d)"
                            ValidationGroup="register" CssClass="err_msg" Display="Dynamic" Text="Please Enter Valid Date"
                            ></asp:RegularExpressionValidator>

                        </li>
                    <li>
                                               <p>
                            
                                Look at our terms and conditions if you wish<br />
<em>Check out our privacy policy too-we've nothing to hide! 
                                
                                </em></p>
                    </li>
                    <li>
                        <label>
                            &nbsp;</label>
                       
                        <asp:LinkButton ID="btnRegister" runat="server"  TabIndex="17" ValidationGroup="Register" OnClick="btnRegister_Click"
                            class="loginBtn" Text="Register" meta:resourcekey="btnRegisterResource1"></asp:LinkButton>
                    </li>
                    </div>


                </ul>
    </div>

            
            </div>      
   
    <script language="javascript" type="text/javascript">
        function doPostBack(element) {
            //tb_remove();
            document.getElementById('<%=hfpass.ClientID %>').value = document.getElementById('<%=txt_forpass_email.ClientID %>').value
            document.getElementById('<%=hfReset.ClientID %>').value = document.getElementById('<%=txt_rst_email.ClientID %>').value           
            setTimeout('__doPostBack(\'' + element.name + '\',\'\')', 500);

        }
    </script>
    <script language="javascript" type="text/javascript">

        var usernameCheckerTimer;
        var spanAvailability = $get("spanAvailability");
        var spanAvailabilityChecking = $get("spanAvailabilityChecking");
        var rfv = $('#<%= RegularExpressionValidator1.ClientID %>')
        function usernameChecker(username) {
            spanAvailability.innerHTML = "";
            clearTimeout(usernameCheckerTimer);
            if (username.length < 5)
                spanAvailability.innerHTML = "";
            else {
                if (!rfv.is(":visible")) {
                    spanAvailability.innerHTML = "";
                    spanAvailabilityChecking.innerHTML = "<span style='color:#009933; text-align:right;  background:url(/images/ajax-loader.gif) right center no-repeat; float:left; padding-right:50px;'>Checking...</span>";
                    usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
                    $('#<%=lblMsg.ClientID%>').hide();
                }
            }
        }
        function checkUsernameUsage(username) {
            PageMethods.set_path('buybacklogin.aspx'); // this code for the Local If you uplaod on Servers Kindly Use there Path for the login page

            if (!rfv.is(":visible")) {
                PageMethods.IsUserAvailable(username, OnSucceeded);
            }
        }
        function OnSucceeded(result, userContext, methodName) {
            if (methodName == "IsUserAvailable") {
                if (result == true) {
                    spanAvailability.innerHTML = "<span class='error-box-green fl' style='color: DarkGreen; display:block;'>User name is Available</span>";
                    spanAvailabilityChecking.innerHTML = "";

                }
                else {
                    spanAvailability.innerHTML = "<span class='err_msg fl' style='color: red;'>User name already exists. </span>";
                    spanAvailabilityChecking.innerHTML = "";
                }
            }
        }
    </script>
    <script language="javascript" type="text/javascript">
        function passwordChanged() {
            var strength = document.getElementById('strength');
            var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
            var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
            var enoughRegex = new RegExp("(?=.{6,}).*", "g");
            var pwd = document.getElementById("ctl00_ContentPlaceHolder1_txtPassword");
            if (pwd.value.length == 0) {
                strength.innerHTML = 'Please enter valid password,e.g (6-20 alphanumeric)';
            }
            else if (false == enoughRegex.test(pwd.value)) {
                strength.innerHTML = 'More Characters';
            }
            else if (strongRegex.test(pwd.value)) {
                strength.innerHTML = '<span style="color:green; display:block;  font-size:11px;  font-family: Arial,Helvetica,sans-serif; ">Strong!</span>';
            }
            else if (mediumRegex.test(pwd.value)) {
                strength.innerHTML = '<span style="color:#f94c10;  display:block;  font-size:11px;  font-family: Arial,Helvetica,sans-serif; ">Medium!</span>';
            }
            else {
                strength.innerHTML = '<span style="color:#225102;  display:block;  font-size:11px;  font-family: Arial,Helvetica,sans-serif; ">Weak!</span>';
            }
        }
    </script>
</asp:Content>




.CS PAGE

#region Namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Routing;
using ThisSite.BSLayer;
using ThisSite.Common;
using System.Data;
using System.Net;
using Facebook;
using Facebook.Web;
using System.Configuration;
using System.Globalization;
using System.Web.Configuration;
using System.ServiceModel;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Security;
using System.Net.Security;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.ServiceModel.Channels;
using System.IO;


#endregion

public partial class CoOpLogin : CoOpFrontBasePage
{
    #region variable dec
    static string prevPage = string.Empty;
    string result;
    #endregion
    public string FacebookAppID
    {
        get
        {
            return ConfigurationManager.AppSettings["AppID"];
        }
    }

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
   {
        string keywords = "Co-Op - Login";
        Localize lmeta = (Localize)Master.FindControl("meta1");
        ((UserControl)this.Master.FindControl("uxRight")).Visible = false;

        lmeta.Text = keywords;
        lblMsgHeader.Visible =false;
        //lblMsg.Visible = false;
        if (!IsPostBack)
        {
            try
            {
                txtEmail.Attributes.Add("onKeyPress", "doClick('" + btnLogin.ClientID + "',event)");
                txtPwd.Attributes.Add("onKeyPress", "doClick('" + btnLogin.ClientID + "',event)");
                txtREmail.Attributes.Add("onKeyPress", "doClick('" + btnRegister.ClientID + "',event)");
                txtPassword.Attributes.Add("onKeyPress", "doClick('" + btnRegister.ClientID + "',event)");
                txtConfirmPass.Attributes.Add("onKeyPress", "doClick('" + btnRegister.ClientID + "',event)");

                if (Request.QueryString["session"] != null && Request.QueryString["session"].ToLower() == "logout")
                {
                    if (ThisSite.BSLayer.CoOpUser.Current != null)
                    {
                        Session.Abandon();
                        Session.Clear();
                        ClearSession();
                        Session["logoutFB"] = false;
                        var fbWebContext = FacebookWebContext.Current;
                        if (FacebookWebContext.Current.AccessToken != null)
                        {
                            Response.Redirect("https://www.facebook.com/logout.php?next=http://ztest.bookfari.com/co-op/login?session=logout&access_token=" + fbWebContext.AccessToken, false);
                        }
                    }
                }

                if (ThisSite.BSLayer.CoOpUser.Current != null)
                {
                    if (Request.QueryString["zurl"] != null)
                    {
                        ThisSite.Utilities.Security objSec = new ThisSite.Utilities.Security();

                        if (ThisSite.BSLayer.CoOpUser.Current != null)
                        {
                            string sFullName = ThisSite.BSLayer.CoOpUser.Current.sFirstNm;
                            string sEmail = ThisSite.BSLayer.CoOpUser.Current.sEmail;
                            objSec.SendRequest(sFullName, sEmail);
                        }
                    }
                    else if (Request.QueryString["returnurl"] != null)
                    {
                        string sAbsoluteUri = Request.Url.AbsoluteUri;
                        string sFromPage = Server.UrlDecode(sAbsoluteUri.Substring(sAbsoluteUri.IndexOf("returnurl") + 10));
                        
                        Uri uri;
                        if (Uri.TryCreate(sFromPage, UriKind.Absolute, out uri))
                        {
                            VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOp_home, null);
                            Response.Redirect(vpd.VirtualPath, true);
                        }
                        else
                        {
                            Response.Redirect(sFromPage, false);
                        }
                    }
                    else
                    {
                        Session.Abandon();
                        Session.Clear();
                        ClearSession();
                        Session["logoutFB"] = false;
                        VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOP_Login, null);
                        Response.Redirect(vpd.VirtualPath, false);
                    }
                }
                else
                {
                    Session["logoutFB"] = null;
                }

                if (Request.Cookies["BookStoreLogin"] != null)
                {
                    txtEmail.Text = Request.Cookies["BookStoreLogin"].Values["UserEmail"];
                    Response.Cookies["BookStoreLogin"].Expires = DateTime.Now.AddSeconds(-1);
                }
                //string keywords = "Co-Op - Login";
                //Localize lmeta = (Localize)Master.FindControl("meta1");
                //lmeta.Text = keywords;
            }
            catch (Exception ex)
            {
                ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
                errLog.sErrMsg = ex.Message;
                errLog.sAbsoluteUri = Page.Request.Url.ToString();
                errLog.sStackTrace = ex.StackTrace;
                errLog.Create();
            }
        }
        
        if (!IsPostBack)
        {
            if (!IsPostBack)
            {
                if (Request.Cookies["BUYLoginNm"] != null)
                    txtEmail.Text = Request.Cookies["BUYLoginNm"].Value;

                if (Request.Cookies["BUYpwd"] != null)

                    txtPwd.Attributes.Add("value", Request.Cookies["BUYpwd"].Value);
                if (Request.Cookies["BUYuserid"] != null && Request.Cookies["BUYpwd"] != null)
                    chksghned.Checked = true;

                if (Request.Cookies["BUYLoginNm"] != null)
                {
                    txtEmail.Text = Request.Cookies["BUYLoginNm"].Value.ToString();
                    chksghned.Checked = true;
                }
            }

            txtEmail.Focus();
            try
            {
                if ((Request.QueryString["session"] != null && Request.QueryString["session"].ToLower() == "login") || (Request.QueryString["session"] == null))
                {
                    CheckIfFacebookAppIsSetupCorrectly();
                    var fbWebContext = FacebookWebContext.Current;
                    if (fbWebContext.IsAuthorized())
                    {
                        var fb = new FacebookWebClient(fbWebContext);
                        dynamic result = fb.Get("/me");
                        if (ThisSite.BSLayer.CoOpUser.Current == null)
                        {
                            Facebook.JsonObject me = result;
                            ThisSite.BSLayer.CoOpUser.TryFBLogin(me);
                            if (Session["logoutFB"] != null)
                            {
                                if (!Convert.ToBoolean(Session["logoutFB"].ToString()))
                                {
                                    Session["logoutFB"] = false;
                                }
                                else
                                {
                                    Session["logoutFB"] = true;
                                }
                            }
                            else
                            {
                                Session["logoutFB"] = true;
                            }

                            if (Session["BuyprevPage"] != null)
                            {
                                if (Request.QueryString["returnurl"] != null)
                                {
                                    string sAbsoluteUri = Request.Url.AbsoluteUri;
                                    string sFromPage = Server.UrlDecode(sAbsoluteUri.Substring(sAbsoluteUri.IndexOf("returnurl") + 10));

                                    Uri uri;
                                    if (Uri.TryCreate(sFromPage, UriKind.Absolute, out uri))
                                    {
                                      
                                        VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "default", null);
                                        Response.Redirect(vpd.VirtualPath, false);
                                    }
                                    else
                                    {
                                        Response.Redirect(sFromPage, false);
                                    }
                                }
                                else
                                {
                                   
                                    prevPage = Session["prevPage"].ToString();
                                  
                                    //VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOpMyAccountHome, null);
                                    //Response.Redirect(vpd.VirtualPath, false);
                                   
                                        Response.Redirect(prevPage, false);
                                }
                            }
                            else
                            {
                                if (Session["logoutFB"] != null)
                                {
                                    if (!Convert.ToBoolean(Session["logoutFB"].ToString()))
                                    {
                                        Session.Abandon();
                                        Session.Clear();
                                        ClearSession();
                                        Session["logoutFB"] = false;
                                       
                                        VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOpMyAccountHome, null);
                                        Response.Redirect(vpd.VirtualPath, false);
                                    }
                                    else
                                    {
                                        if (Request.QueryString["session"] != null && Request.QueryString["session"].ToLower() == "logout")
                                        {
                                            Session.Abandon();
                                            Session.Clear();
                                            ClearSession();
                                            Session["logoutFB"] = false;
                                          
                                            VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOpMyAccountHome, null);
                                            Response.Redirect(vpd.VirtualPath, false);
                                        }
                                        else if (Request.QueryString["session"] == null)
                                        {
                                              DataTable Dtsearch = ThisSite.BSLayer.CoOp.select_BuyBookDetail(HttpContext.Current.Session.SessionID.ToString());
                                              if (Dtsearch.Rows.Count > 0)
                                              {
                                                  VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOp_MyDetails, null);
                                                  Response.Redirect(vpd.VirtualPath, false);
                                              }
                                              else
                                              {
                                                  VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOpMyAccountHome, null);
                                                  Response.Redirect(vpd.VirtualPath, false);
                                              }
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
                else
                {
                    if (Request.QueryString["session"] != null && Request.QueryString["session"].ToLower() == "logout")
                    {
                        Session.Abandon();
                        Session.Clear();
                        ClearSession();
                        Session["logoutFB"] = false;
                        var fbWebContext = FacebookWebContext.Current;
                        if (FacebookWebContext.Current.AccessToken == null)
                        {
                            Response.Redirect("~/Co-Op/login?session=login", false);
                        }
                    }
                }
            }
            catch (Facebook.FacebookApiException ex)
            {
                ClearSession();
                ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
                errLog.sErrMsg = ex.Message;
                errLog.sAbsoluteUri = Page.Request.Url.ToString();
                errLog.sStackTrace = ex.StackTrace;
                errLog.Create();
            }
        }
    }
    #endregion

    #region btnRegister_Click
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        try
        {
            Page.Validate("Register");
            if (Page.IsValid)
            {
                CoOpUser CoOpUser = new CoOpUser();


                CoOpUser.sLoginNm = txtDetail_FirstNm.Text.Trim();
                CoOpUser.sPass = txtPassword.Text.Trim();
                CoOpUser.sFirstNm = txtDetail_FirstNm.Text.Trim();
                CoOpUser.sLastNm = txtdetail_lastNm.Text.Trim();
                CoOpUser.sEmail = txtREmail.Text.Trim();
                CoOpUser.lRollId = ThisSite.BSLayer.CoOpUser.GetRoleId("Customer"); //default role type is CUSTOMER
                CoOpUser.sAddress = ThisSite.BSLayer.CoOpUser.UserStatus.Anonymous.ToString();
                CoOpUser.lCountryId = 0;
                CoOpUser.sCity = ThisSite.BSLayer.CoOpUser.UserStatus.Anonymous.ToString();
                CoOpUser.sPhoneNo = string.Empty;
                CoOpUser.sMobileNo = txtMobile.Text;
                CoOpUser.sStatus = ThisSite.BSLayer.CoOpUser.UserStatus.Active.ToString();
                CoOpUser._dtModifiedDt = DateTime.Now;
                CoOpUser.sIsExists = "Exist";
                try
                {
                    CoOpUser.dtDOB = Convert.ToDateTime(txtDob.Text.Trim(), new CultureInfo("en-GB", true));// Convert.ToDateTime(txtDob.Text.Trim());
                }
                catch
                {
                    CoOpUser.dtDOB = null;
                }
                CoOpUser.sCulture = ThisSite.Utilities.Enumerations.DefaultCulture.English.ToString(); ;
                int buyBackUserId = CoOpUser.CreateCoOpUser(txtREmail.Text.Trim());

                
                if (buyBackUserId > 0)
                {
                    #region Email to BuyBackUser for new BuyBackUser Registration
                    ManageEmail.EmailDetail emailUsr = new ManageEmail.EmailDetail();
                    ThisSite.BSLayer.CMS Userscript = new ThisSite.BSLayer.CMS();
                    //DataRow drUser = Userscript.getEmailScript(Resources.Script.SelfRegistration);
                    DataRow drUser = Userscript.getEmailScript("CoopRegister");
                    if (drUser != null)
                    {
                        ThisSite.BSLayer.Cart cart = new ThisSite.BSLayer.Cart();
                        DataTable dtCartReview = cart.select_FeatureItem();
                        string s = string.Empty;
                        s = drUser["cScript"].ToString();

                        string[] sTOUsr = { CoOpUser.sEmail };
                        emailUsr.sTo = sTOUsr;
                        emailUsr.sFromAdr = Resources.EmailAddresses.No_Reply.ToString();
                        emailUsr.sSubject = drUser["cSubject"].ToString();
                        emailUsr.sDisNm = ThisSite.Common.Methods.GetConfigSetting("MailFromDisplayNm");
                        emailUsr.IsBodyHtml = Convert.ToBoolean(drUser["blsHtml"]);
                        s = s.Replace("{EMAIL}", CoOpUser.sEmail);
                        s = s.Replace("{EMAIL}", CoOpUser.sEmail);
                        s = s.Replace("{NAME}", CoOpUser.sFirstNm);
                        s = s.Replace("{PHONE}", CoOpUser.sMobileNo);

                        //string str = string.Empty;
                        //string str1 = string.Empty;
                        //string str2 = string.Empty;

                        //string ImagePath = string.Empty;
                        //ImagePath = "http://www.bookfari.com/ImageResize.ashx?isbn=";
                        //ImagePath = ImagePath + dtCartReview.Rows[0]["vIsbn"].ToString();
                        //ImagePath = ImagePath + "&width=145&height=200";

                        //str = str + "<img style='width:145px;height:200px;display:block' src='" + ImagePath + "' alt='Book'/>";

                        //string BookDesc = string.Empty;
                        //BookDesc = HttpUtility.HtmlDecode(dtCartReview.Rows[0]["vcDescription"].ToString().Replace("<div>", " ").Replace("</div>", " ").Replace("<P>", " ").Replace("</P>", " ").Replace("<i>", " ").Replace("</i>", " "));

                        //str1 = str1 + "<p style='margin: 0px; text-align: left; color: rgb(85, 85, 85); font-size: 13px; font-style: italic;'><strong><em>" + dtCartReview.Rows[0]["vTitle"].ToString() + "</em></strong> : " + BookDesc + ".</p>";

                        //str2 = "http://www.bookfari.com/Book/" + dtCartReview.Rows[0]["vIsbn"].ToString();
                        //s = s.Replace("{imagedetail}", str1);

                        //s = s.Replace("#image#", str);
                        //s = s.Replace("#Book#", str2);
                        emailUsr.sMessage = s;

                        try
                        {
                            ManageEmail.SendEmail(emailUsr);
                            ThisSite.Entitie.CoOPEntites.CommunicationLog commLog = new ThisSite.Entitie.CoOPEntites.CommunicationLog();
                            commLog.biUsrId = CoOpUser.lUserId;
                            commLog.vcUsrType = ThisSite.Utilities.Enumerations.UserType.customer.ToString();
                            commLog.vcClientIP = Request.UserHostAddress;
                            commLog.vcAbsoluteUri = Request.Url.AbsoluteUri; 
                            commLog.vcCommType = ThisSite.BSLayer.CommunicationLog.CommType.EMAIL.ToString();
                            commLog.nvcCommContent = emailUsr.sMessage;
                            commLog.vcUsrType = ThisSite.Common.Enumerations.UserType.User.ToString();
                            commLog.vcReceivers = sTOUsr[0];
                        }
                        catch (Exception ex)
                        {
                            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
                            errLog.sErrMsg = ex.Message;
                            errLog.sAbsoluteUri = Page.Request.Url.ToString();
                            errLog.sStackTrace = ex.StackTrace;
                            errLog.Create();
                        }
                    }
                    #endregion
                    
                    if (ThisSite.BSLayer.CoOpUser.TryToLogin(CoOpUser.sEmail, CoOpUser.sPass, false))
                    {
                        if (Request.QueryString["zurl"] != null)
                        {
                            ThisSite.Utilities.Security objSec = new ThisSite.Utilities.Security();

                            if (ThisSite.BSLayer.CoOpUser.Current != null)
                            {
                                string sFullName = ThisSite.BSLayer.CoOpUser.Current.sFirstNm;
                                string sEmail = ThisSite.BSLayer.CoOpUser.Current.sEmail;
                                objSec.SendRequest(sFullName, sEmail);
                            }
                        }
                        else if (Request.QueryString["returnurl"] != null)
                        {
                            string sAbsoluteUri = Request.Url.AbsoluteUri;
                            string sFromPage = Server.UrlDecode(sAbsoluteUri.Substring(sAbsoluteUri.IndexOf("returnurl") + 10));
                            Uri uri;
                            if (Uri.TryCreate(sFromPage, UriKind.Absolute, out uri))
                            {
                                Response.Redirect(Resources.Pages.A_Default, false);
                            }
                            else
                            {
                                Response.Redirect(sFromPage, false);
                            }
                        }
                        else
                        {
                            VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOp_MyDetails, null);
                            Response.Redirect(vpd.VirtualPath, false);
                        }
                    }
                }
                else
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = ThisSite.Common.Message.sMessage;
                }
            }
        }
        catch (Exception ex)
        {
            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
            errLog.sErrMsg = ex.Message;
            errLog.sAbsoluteUri = Page.Request.Url.ToString();
            errLog.sStackTrace = ex.StackTrace;
            errLog.Create();
        }
       // txtDob.Attributes.Add("readonly", "readonly");

    }
    #endregion


    #region Co-Op login

  private string CallPostMethod()
    {
         
        string username = txtEmail.Text.Trim().ToString();
        string password = txtPwd.Text.Trim().ToString();
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });  
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://staging1.javelin.coop.com.au:8080/bookshop/Services/verifyCredentials");
        request.Method = "POST";
        request.ContentType = "application/json";
        string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("bookfari" + ":" + "4cf98384b732f007c9ba540a47eb5ec3"));
        request.PreAuthenticate = true;
        request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
        request.Headers.Add("Authorization", auth);
        var datacontractserializer = new DataContractSerializer(typeof(userinformation));
        userinformation userinformation1 = new userinformation { email = username, secret = password, scheme = "PLAIN" };
        var json = new JavaScriptSerializer().Serialize(userinformation1);
        using (var streamwriter = new StreamWriter(request.GetRequestStream()))
        {
            streamwriter.Write(json);
        }
        WebResponse respons = request.GetResponse();
        System.IO.Stream stream11 = respons.GetResponseStream();
        StreamReader ttt = new StreamReader(stream11);
        var result = ttt.ReadToEnd();
        stream11.Dispose();
        ttt.Dispose();

        string data = result.ToString().Replace("{", " ");
        data = data.Replace("}", "");
        data = data.Replace(":", "");
        data = data.Replace("\"", "");



        char[] separator = new char[] { ',' };
        string[] app = data.Split(separator);
        string a = app[0].ToString();
        string b = app[1].ToString();
        string c = app[2].ToString();

        if (a.Trim() == "success true")
        {
            return a;
        }
        else
        {
            return b;
           
        }



    }
    #endregion

    #region btnLogin_Click
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            
            Page.Validate("login");
            if (Page.IsValid)
            {
                string val = ConfigurationManager.AppSettings["coop"].ToString();
                if (val == "true")
                {
                    result = CallPostMethod();          
                }
                else
                {
                    result = "success true";  
                
                }                  

                if (result.Trim() == "success true")
                {

                    ThisSite.BSLayer.CoOpUser.Co_OpLogin(txtEmail.Text.Trim(), txtPwd.Text.Trim());

                    bool bIsLogin = ThisSite.BSLayer.CoOpUser.TryToLogin(txtEmail.Text.Trim(), txtPwd.Text.Trim(), false);
                    if (bIsLogin)
                    {
                        HttpCookie cookieLogin1;
                        if (chksghned.Checked)
                        {
                            cookieLogin1 = new HttpCookie("LoginCoOpNm", txtEmail.Text.Trim());
                            cookieLogin1.Expires = DateTime.Now.AddYears(1);
                            Response.Cookies.Add(cookieLogin1);
                            Response.Cookies["userid"].Value = txtEmail.Text;
                            Response.Cookies["pwd"].Value = txtPwd.Text;
                            Response.Cookies["userid"].Expires = DateTime.Now.AddDays(15);
                            Response.Cookies["pwd"].Expires = DateTime.Now.AddDays(15);
                        }
                        else
                        {
                            Response.Cookies["userid"].Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies["pwd"].Expires = DateTime.Now.AddDays(-1);
                            if (Request.Cookies["LoginCoOpNm"] != null)
                                Response.Cookies["LoginCoOpNm"].Expires = DateTime.Now.AddSeconds(-1);
                        }
                        VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, Resources.Co_Op.CoOp_MyDetails, null);
                        Response.Redirect(vpd.VirtualPath, false);
                    }
                    else
                    {
                        lblMsgHeader.Visible = true;
                        lblMsgHeader.Attributes.Add("style", "margin-left:312px");
                        lblMsgHeader.Text = "The login detail you entered is incorrect";
                        ThisSite.Common.Message.sMessage = null;
                        lblMsgHeader.Visible = true;
                    }
                }


                else
                {
                    //lblMsgHeader.Text = lblMsgHeader.Text.Replace("message", "");
                   // lblMsgHeader.Visible = true;
                   // lblMsgHeader.Text = result;

                    lblMsgHeader.Visible = true;
                    lblMsgHeader.Attributes.Add("style", "margin-left:312px");
                    lblMsgHeader.Text = "The login detail you entered is incorrect";
                    ThisSite.Common.Message.sMessage = null;
                    lblMsgHeader.Visible = true;
                }

            }
        }
        catch (Exception ex)
        {
            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
            errLog.sErrMsg = ex.Message;
            errLog.sAbsoluteUri = Page.Request.Url.ToString();
            errLog.sStackTrace = ex.StackTrace;
            errLog.Create();
        }
    }
    #endregion 

    #region ClearSession
    private void ClearSession()
    {
        try
        {
            string cookieName = "fbs_" + ConfigurationManager.AppSettings["AppID"];
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                string[] cookies = new[] { "BuyBackUser", "session_key", "expires", "ss" };
                foreach (var c in cookies)
                {
                    HttpContext.Current.Response.Cookies[c.ToString()].Expires = DateTime.Now.AddMonths(-1);
                }
                HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddMonths(-1);
                HttpContext.Current.Request.Cookies[cookieName]["session_key"] = null;
                HttpContext.Current.Request.Cookies[cookieName]["uid"] = null;
                HttpContext.Current.Request.Cookies[cookieName]["\"access_token"] = null;
                HttpContext.Current.Request.Cookies.Remove("session_key");
                HttpContext.Current.Request.Cookies.Remove("uid");
                HttpContext.Current.Request.Cookies.Remove("\"access_token");
            }
        }
        catch (Exception ex)
        {
            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
            errLog.sErrMsg = ex.Message;
            errLog.sAbsoluteUri = Page.Request.Url.ToString();
            errLog.sStackTrace = ex.StackTrace;
            errLog.Create();
        }
    }
    #endregion

    #region CheckIfFacebookAppIsSetupCorrectly
    private void CheckIfFacebookAppIsSetupCorrectly()
    {
        try
        {
            bool isSetup = false;
            var settings = ConfigurationManager.GetSection("facebookSettings");
            if (settings != null)
            {
                var current = settings as IFacebookApplication;
                if (current.AppId != "{app id}" &&
                    current.AppSecret != "{app secret}")
                {
                    isSetup = true;
                }
            }

            if (!isSetup)
            {
                // redired to setup page !!
            }
        }
        catch (Exception ex)
        {
            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
            errLog.sErrMsg = ex.Message;
            errLog.sAbsoluteUri = Page.Request.Url.ToString();
            errLog.sStackTrace = ex.StackTrace;
            errLog.Create();

        }
    }
    #endregion

    #region WebMethod
    [System.Web.Services.WebMethod]

    public static bool IsUserAvailable(string sEmail)
    {
        try
        {
            List<CoOpUser> existingUsers = ThisSite.BSLayer.CoOpUser.PopulateSet(sEmail, null);
            if (existingUsers.Exists(u => u.sEmail.ToLower() == sEmail.ToLower()))
            {  
                ThisSite.Common.Message.sMessage = Resources.ErrorMessages.UsrAlreadyExists;
                return false;
            }
            else
            {
                return true;
            }
        }
        catch (Exception ex)
        {
            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
            errLog.sErrMsg = ex.Message;
            errLog.sStackTrace = ex.StackTrace;
            errLog.Create();
            return false;
        }
    }
    #endregion

    #region btnForPass_Click
    protected void btnForPass_Click(object sender, EventArgs e)
    {
        try
        {
            ThisSite.BSLayer.CoOpUser user = new ThisSite.BSLayer.CoOpUser();
            if (string.IsNullOrEmpty(txt_forpass_email.Text))
            {
                txt_forpass_email.Text = hfpass.Value;
            }

            DataRow row = user.getForgotUserPassword(txt_forpass_email.Text.Trim());
            if (row != null)
            {
                string password = row["cPassword"].ToString();
                if (password == "")
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = "This is yours facebook Id try to change your password in facebook account";
                    return;
                }
                string ToEmailId = row["cEmail"].ToString();


                ThisSite.Utilities.Security.RijndaelSimple rijndaelSimple = new ThisSite.Utilities.Security.RijndaelSimple();

                string sPassDecrypted = rijndaelSimple.Decrypt(password, Resources.EncryptionDecryption.passPhrase.Trim(),
                                                Resources.EncryptionDecryption.saltValue.Trim(),
                                                Resources.EncryptionDecryption.hashAlgorithm.Trim(),
                                                int.Parse(Resources.EncryptionDecryption.passwordIterations.Trim()),
                                                Resources.EncryptionDecryption.initVector.Trim(),
                                                int.Parse(Resources.EncryptionDecryption.keySize.Trim()));


                if (ToEmailId != null)
                {

                    lblMsgHeader.Visible = true;
                    lblMsgHeader.Text = GetLocalResourceObject("forgotpwd").ToString();

                    ManageEmail.EmailDetail email = new ManageEmail.EmailDetail();
                    ThisSite.BSLayer.CMS script = new ThisSite.BSLayer.CMS();
                    //DataRow drAdmin = script.getEmailScript("Forgot Paswword");
                    DataRow drAdmin = script.getEmailScript("Coopforgotpassword");
                    string[] sUserTO = { ToEmailId };
                    email.sTo = sUserTO;
                    email.sFromAdr = Resources.EmailAddresses.No_Reply.ToString();
                    email.sSubject = "Forgot Password";
                    email.sDisNm = ThisSite.Common.Methods.GetConfigSetting("MailFromDisplayNm");
                    email.IsBodyHtml = true;
                    email.sMessage = drAdmin["cScript"].ToString().Replace("{pwd}", "Password");
                    email.sMessage = drAdmin["cScript"].ToString().Replace("{EMAIL}", ToEmailId).Replace("{pwd}", sPassDecrypted).Replace("{NAME}", ToEmailId);

                    try
                    {
                        ManageEmail.SendEmail(email);

                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex);
                        Response.End();

                    }
                }
            }
            else
            {
                lblMsgHeader.Visible = true;
                lblMsgHeader.Text = Resources.ErrorMessages.ForgetUsrExist.ToString();
            }

        }
        catch (Exception ex)
        {
            lblMsg.Visible = true;
            lblMsg.Text = ex.Message;

            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
            errLog.sErrMsg = ex.Message;
            errLog.sAbsoluteUri = Page.Request.Url.ToString();
            errLog.sStackTrace = ex.StackTrace;
            errLog.Create();


        }
    }
    #endregion

    #region btnReset_Click
    protected void btnReset_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(txt_rst_email.Text))
            {
                txt_rst_email.Text = hfReset.Value;
            }

            List<CoOpUser> lstUser = ThisSite.BSLayer.CoOpUser.PopulateSet(txt_rst_email.Text.Trim(), string.Empty);
            if (lstUser.Count > 0)
            {
                ThisSite.BSLayer.CoOpUser user = new CoOpUser();
                user = lstUser[0];

                if (user.sEmail.ToLower().Trim() == txt_rst_email.Text.ToLower().Trim())
                {
                    //Random rnd = new Random(3);
                    string randomPwd = ResetPasswordMail.RandomPasswordGenerator(6);
                    ThisSite.Utilities.Security.RijndaelSimple rijndaelSimple = new ThisSite.Utilities.Security.RijndaelSimple();
                    string pwd = user.sEmail.ToLower().Trim() + "#" + randomPwd;
                    string sPassEncrypted = rijndaelSimple.Encrypt(pwd, Resources.EncryptionDecryption.passPhrase.Trim(),
                                           Resources.EncryptionDecryption.saltValue.Trim(),
                                           Resources.EncryptionDecryption.hashAlgorithm.Trim(),
                                           int.Parse(Resources.EncryptionDecryption.passwordIterations.Trim()),
                                           Resources.EncryptionDecryption.initVector.Trim(),
                                           int.Parse(Resources.EncryptionDecryption.keySize.Trim()));

                    string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
                   // if (ResetPasswordMail.PrevResetPassEmail(baseUrl + "/request?pwd=" + sPassEncrypted + "", user.sEmail))
                    if (ResetPasswordMail.PrevResetPassEmailCoop(baseUrl + "/BuyBack/CoOp/CoopResetPwdConfirmation.aspx?pwd=" + sPassEncrypted + "", user.sEmail))
                   // if (ResetPasswordMail.PrevResetPassEmailCoop(baseUrl + "/PassConfirm?pwd=" + sPassEncrypted + "", user.sEmail))
                    {
                        lblMsgHeader.Visible = true;
                        lblMsgHeader.Text = GetLocalResourceObject("ResetMessage").ToString();
                    }


                }
                else
                {
                    lblMsgHeader.Visible = true;
                    lblMsgHeader.Text = "Unable to reset your password. Please try again";
                }
            }
        }
        catch (Exception ex)
        {
            ThisSite.BSLayer.ErrorLog errLog = new ThisSite.BSLayer.ErrorLog();
            errLog.sErrMsg = ex.Message;
            errLog.sAbsoluteUri = Page.Request.Url.ToString();
            errLog.sStackTrace = ex.StackTrace;
            errLog.Create();

        }
    }
    #endregion
}