Pages

Subscribe:

Tuesday, 28 January 2014

how to implement cookies on website open

 <div >
            <asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="12000">
            </asp:Timer>
        </div>
        <div class="clr">
        </div>
        <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server" ChildrenAsTriggers="true">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
            <ContentTemplate>
                <div id="topfade" runat="server">
                    This site uses cookies. For more information on why we use cookies, please read
                    our <a href="#">privacy and cookie policy.</a> By continuing to view this website
                    <br>you are in agreement with its terms..&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <span style="padding: 5px 10px 5px 10px; border: 1px solid #ffffff; background: #148ae4;">
                        <asp:LinkButton ID="cookies" runat="server" Text="Accept" OnClick="LinkButton_Clickcookies"
                            ForeColor="white" CausesValidation="false"></asp:LinkButton></span>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>


//code page

 protected void Timer1_Tick(object sender, EventArgs e)
    {
        topfade.Visible = false;
        Timer1.Enabled = false;
    }
    protected void LinkButton_Clickcookies(Object sender, EventArgs e)
    {
        HttpCookie myCookie = new HttpCookie("PetShow_cookies_policy");
        myCookie["Font"] = "Arial";
        myCookie["Color"] = "Blue";
        myCookie.Value = "The_PetShow14";
        myCookie.Expires = DateTime.Now.AddMonths(12);
        HttpContext.Current.Response.Cookies.Add(myCookie);
        topfade.Visible = false;
        topfade.InnerHtml = "";
    }

 protected void Page_Load(object sender, EventArgs e)
    {
 Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
        Response.Cache.SetNoStore();

 if (Request.Cookies["PetShow_cookies_policy"] != null)
        {
            topfade.Visible = false;
            Timer1.Enabled = false;
        }
        else
        {
            topfade.Visible = true;
        }
}

Sunday, 26 January 2014

Bind Country


export excel from sql database

Code :

 protected void Page_Load(object sender, EventArgs e)
    {
        ExportDataToExcel();
    }

 public void ExportDataToExcel()
    {
        // DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        Conn.Open();
        string query = "select row_number() over (order by entry_date desc)as [Sr no.],Name,designation as Designation,company as [Company Name],country as Country,email as Email,CONVERT(varchar(30),DATEADD(MI,30,dateadd(hh,4.30, entry_date))) as 'Add Date'  from tblName order by entry_date desc";
        SqlCommand cmd = new SqlCommand(query, Conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        Conn.Close();
        ExportToExcel(dt);
    }

    public void ExportToExcel(DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            string filename = "Report.xls";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

            GridView dgGrid = new GridView();
            dgGrid.HeaderStyle.BackColor = System.Drawing.Color.Navy;
            dgGrid.HeaderStyle.ForeColor = System.Drawing.Color.White;
            dgGrid.BackColor = System.Drawing.Color.White;
            dgGrid.RowStyle.Font.Name = "Arial";
            dgGrid.RowStyle.Font.Size = 9;
            dgGrid.AlternatingRowStyle.BackColor = System.Drawing.Color.White;
            dgGrid.DataSource = dt;
            dgGrid.DataBind();

            HttpResponse response = HttpContext.Current.Response;
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            System.Web.HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(1252);
            response.Clear();
            response.Charset = "";

            dgGrid.RenderControl(hw);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
    }

Design :

<div></div>

how to resize image

  int imgid1 = 0;
 string str = "select isnull(max(id)+1,1) as id from tblImageGalleryAddEdit";

                    SqlCommand cmdnew = new SqlCommand(str, conn);
                    conn.Open();
                    SqlDataReader rd = cmdnew.ExecuteReader();
                    while (rd.Read())
                    {
                        imgid1 = Convert.ToInt32(rd["id"]);
                    }
    conn.Close();
string  imgname = FileUpload1.FileName.Replace(" ", "_").Replace("'", "_");
string targetPath = Server.MapPath("GalleryImage/" + imgid1 + imgname);
 Stream strm = FileUpload1.PostedFile.InputStream;
 var targetFile = targetPath;
GenerateThumbnails(0.5, strm, targetFile);


 private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            var newWidth = (int)(image.Width * scaleFactor);
            var newHeight = (int)(image.Height * scaleFactor);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }

Validation using Regular expression

Single Email :

 <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please Enter Valid Email Address"
                                        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="Red"
                                        Display="Dynamic" ControlToValidate="txtEmail" SetFocusOnError="True">Please enter valid email address!</asp:RegularExpressionValidator>


Mutliple Email Id seprate with comma




<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                                ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="Enter valid email id"
                                SetFocusOnError="True" ValidationExpression="^(\s*,?\s*[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})+\s*$">*</asp:RegularExpressionValidator>


PDF : 



<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="FileUpload2" Display="Dynamic" ErrorMessage="Please Select  PDF."
                                            ValidationExpression=".*\.(pdf|PDF)">*</asp:RegularExpressionValidator> 



Image : 



 <asp:FileUpload ID="FileUpload1" runat="server" />
 <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="FileUpload1" Display="Dynamic" ErrorMessage="Please Enter a JPEG or GIF Image." ValidationExpression=".*\.(jpg|jpeg|gif|JPG|JPEG|GIF)">*</asp:RegularExpressionValidator> 



URL :



<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="Server" ControlToValidate="txtURL"  ValidationExpression="^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$" ErrorMessage="Please enter a valid URL"
            Display="Dynamic" />


<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="Server" ControlToValidate="txtURL"
            ValidationExpression="(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?" ErrorMessage="Please enter a valid URL"
            Display="Dynamic" />



Validate Number and greater than zero :


 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="Server" ControlToValidate="TextBox1"
            ValidationExpression="^\d+$"
            ErrorMessage="Enter only numeric number and greater than zero" Display="Dynamic" />


4 digit code :
 

 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="Server" ControlToValidate="TextBox1"
            ValidationExpression="^\d{4}$"
            ErrorMessage="Enter only 4 digit code" Display="Dynamic" />


 







how to display textbox on Checkboxlist other click and save into database

 <script type="text/javascript">
        function ChkBoxCheckChange2() {
            var CHK1 = document.getElementById("<%=chkinterest.ClientID%>");
            var checkbox1 = CHK1.getElementsByTagName("input");
            var label = CHK1.getElementsByTagName("label");
            var counter = 0;
            for (var i = 0; i < checkbox1.length; i++) {
                if (checkbox1[i].checked) {
                    if (label[i].innerHTML == "Others, please specify") {
                        document.getElementById("divorgprimary").style.display = (label[i].innerHTML == "Others, please specify") ? "block" : "none";
                    }
                    else {
                        document.getElementById("divorgprimary").style.display = (label[i].innerHTML == "Others, please specify") ? "none" : "none";
                    }
                }
                else {
                    document.getElementById("divorgprimary").style.display = (label[i].innerHTML == "Others, please specify") ? "none" : "none";
                }
                   
            }
        }
        function ValidateModuleList1(source, args) {
            var chkListModules = document.getElementById('<%= chkinterest.ClientID%>');
            var chkListinputs = chkListModules.getElementsByTagName("input");
            for (var i = 0; i < chkListinputs.length; i++) {
                if (chkListinputs[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }
    </script>
<div>
        <asp:CheckBoxList ID="chkinterest" runat="server" onclick="ChkBoxCheckChange2(this)"
            RepeatColumns="2" RepeatDirection="Horizontal">
            <asp:ListItem Value="A" Text="A"></asp:ListItem>
            <asp:ListItem Value="B" Text="B"></asp:ListItem>
            <asp:ListItem Value="C" Text="C"></asp:ListItem>
            <asp:ListItem Value="D" Text="D"></asp:ListItem>
            <asp:ListItem Value="Others, please specify">Others, please specify</asp:ListItem>
        </asp:CheckBoxList>
        <asp:CustomValidator runat="server" ID="CustomValidato1" ClientValidationFunction="ValidateModuleList1"
            ErrorMessage="Required!" Display="Dynamic"><span style="color:Red;">Required!</span></asp:CustomValidator>
        <div id="divorgprimary" style='display: none'>
            Others &nbsp;
            <asp:TextBox ID="txtinterest" Width="200px" runat="server" MaxLength="50"></asp:TextBox>
        </div>
    </div>

code----

 string prodInterest = string.Empty;
foreach (ListItem list in chkinterest.Items)
            {
                if (list.Selected)
                {
                    if (prodInterest == "" || prodInterest == null)
                    {
                        if (list.Value == "Others, please specify")
                            prodInterest = txtinterest.Text;
                        else
                            prodInterest = list.Value;
                    }
                    else
                    {
                        if (list.Value == "Others, please specify")
                            prodInterest = prodInterest + "," + txtinterest.Text;
                        else
                            prodInterest = prodInterest + "," + list.Value;
                    }
                }
            }

Sunday, 5 January 2014

Validate Checkbox using custom validator


<script type="text/javascript">
 function ValidateCheckBox(sender, args) {
            if (document.getElementById("<%=chkactivity.ClientID %>").checked == true) {
                args.IsValid = true;
            } else {
                args.IsValid = false;
            }
        }
         
    </script>

 <asp:checkbox id="chkactivity" runat="server" text="Privacy Plicy"></asp:checkbox>
                                            &nbsp;&nbsp;
                                            <asp:customvalidator clientvalidationfunction="ValidateCheckBox" display="Dynamic" errormessage="Required!" forecolor="Red" id="CustomValidator1" runat="server">Required!</asp:customvalidator>