Saturday, 31 May 2014

How to add Global.asax in Visual Studio 2012

This question and this post talks about Global.asax template missing in Visual Studio 2012. I have a similar problem in Visual Studio 2012. What you can do is download the default template of Global.asax file and add it to the project. Simply download and copy it to the project. Then choose right click “Add Existing”, select the two files and you are done.

Global.asax download

Make sure you change the namespace in this file to what you are using in your project.





That’s it!!…..Happy Programming...

Friday, 30 May 2014

Password and Confirm Password validation in ASP.NET using JAVASCRIPT

If you have a form with a ‘confirm password’ field and you want to match that with a simple Javascript code rather than to use a heavy validation than this solution will helpful for you. In this, 'onkeyup' event was used to match both fields while user entering input. if you want to match it after textbox loses their focus, you have to call it on 'onblur' event, nothing more than this. You have to do something Like this:-

aspx code

<form id="form1" runat="server">
        <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
        <asp:TextBox ID="txtPassword" ClientIDMode="Static" runat="server"></asp:TextBox>
        <asp:Label ID="lblConfirmPassword" runat="server" Text="Confirm Password"></asp:Label>
        <asp:TextBox ID="txtConfirmPassword" ClientIDMode="Static" runat="server" onkeyup="matchPassword();"></asp:TextBox>
    </form>

Javascript function

    <script type="text/javascript">
        function matchPassword() {
          //store both values into variables.
        var password1 = document.getElementById('txtPassword');
        var password2 = document.getElementById('txtConfirmPassword');

          //set color to differentiate both conditions.
        var matchColor = "#66cc66";
        var unmatchColor = "#ff6666";

        if (password1.value.trim() == password2.value.trim()) {
              //if passwords match. 

            password2.style.backgroundColor = matchColor;
        } else {
              //if passwords do not match.
            password2.style.backgroundColor = unmatchColor;
        }
      }
    </script>
matched password output

odd password output

That’s it!!…..Happy Programming...

Tuesday, 27 May 2014

Difference Between Eval() and Bind() in Asp.Net

In this article, i am going to explain difference between Eval() and Bind(). The main difference between the two is Bind must be assigned to a property of server side control (runat="server") while you can assign Eval to server side or client side control. See implementation below:-

Example 1 :- We can do this
      <asp:TemplateField HeaderText="Price">
                  <ItemTemplate>
                      <%# Eval("price") %>
                  </ItemTemplate>
      </asp:TemplateField>

Example 2 :- We can't do this
      <asp:TemplateField HeaderText="Price">
                  <ItemTemplate>
                      <%# Bind("price") %>
                  </ItemTemplate>
      </asp:TemplateField>
Output of Example 2
Example 3 :- We can do this
  <asp:TemplateField HeaderText="Price">
       <ItemTemplate>
            <asp:Label ID="lblPrice" runat="server" Text='<%# Bind("price") %>'></asp:Label>
       </ItemTemplate>
  </asp:TemplateField>
The difference between Example 2 and Example 3 was nothing expect one server side control. As i already told you, Bind must be assigned to a property of server side controls, that's why Example 3 is perfect but Example 2 not.


That’s it!!…..Happy Programming...

Saturday, 24 May 2014

How to align text under each image in CSS

In this article, i am going to give some overview on how to align text under image in CSS.

HTML Code

    <div class="images">
                <ul>
                    <li><span><a href="#">
                        <img src="http://i1.asp.net/images/ui/asplogo-square.png?cdn_id=2014-05-21-001" /></a></span>
                        <a href="">See More...</a>
                    </li>
                    <li><a href="#">
                        <img src="http://i1.asp.net/images/ui/asplogo-square.png?cdn_id=2014-05-21-001" /></a>
                        <a href="">See More...</a>
                    </li>
                    <li><span><a href="#">
                        <img src="http://i1.asp.net/images/ui/asplogo-square.png?cdn_id=2014-05-21-001" /></a></span>
                        <a href="">See More...</a>
                    </li>
                    <li><a href="#">
                        <img src="http://i1.asp.net/images/ui/asplogo-square.png?cdn_id=2014-05-21-001" /></a>
                        <a href="">See More...</a>
                    </li>
                    <li><span><a href="#">
                        <img src="http://i1.asp.net/images/ui/asplogo-square.png?cdn_id=2014-05-21-001" /></a></span>
                        <a href="">See More...</a>
                    </li>
                </ul>
    </div>


CSS Code

.images {
display:block;
}

.images ul li {
display:inline;
list-style:none;
float:left;
text-align:center;
color:#000;
margin:0 10px 10px 0;
}

.images ul li a img {
border:6px solid #e1d9ec;
border-radius:50%;
width:150px;
height:150px;
}

.images ul li a {
display:block;
margin-bottom:5px;
opacity:0.8;
font-family:Verdana;
font-size:12px;
text-decoration:none;
letter-spacing:1px;
}

.images ul li a:hover {
opacity:1.0;
}

Output



That’s it!!…..Happy Programming...

Friday, 23 May 2014

File upload control with UpdatePanel in ASP.NET

In this article I am explaining a common issue faced by many developers. The issue is how to use FileUpload control in ASP.Net UpdatePanel. I think, two Situations you might face when using it with UpdatePanel.


Situation 1

If the postback is caused by the control which placed inside UpdatePanel, FileUpload is always empty when it has come to the server, regardless whether a file has been selected by user or not.
Example:
       <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:FileUpload ID="FileUpload1" runat="server" />
                <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>

Solution

Thats because the FileuUpload does not retain the file inside the UpdatePanel.Workaround is to set a PostBackTrigger on the button that updates the UpdatePanel.
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:FileUpload ID="FileUpload1" runat="server" />
                <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="btnSave" />
            </Triggers>
        </asp:UpdatePanel>

Situation 2

FileUpload does not work if it is loaded not on the initial page load but appears only after asynchronous update of the page part. For example, Panel is invisible at the load time and is shown after clicking on btnShow button.
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="btnShow" runat="server" Text="Show" OnClick="btnShow_Click" />
                <asp:Panel ID="pnlUpload" runat="server" Visible="False">
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
                </asp:Panel>
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="btnSave" />
            </Triggers>
        </asp:UpdatePanel>

Solution

Workaround is to add a 'multipart' attribute to your form because during asynchronous postback the form is not updated. That is why it is required to set the form content type explicitly.
<form id="form1" runat="server" enctype="multipart/form-data">
OR
// set it on Page_load
Page.Form.Attributes.Add("enctype", "multipart/form-data");



That’s it!!…..Happy Programming...

Thursday, 22 May 2014

How to Generate Video Thumbnail with Title from url in C# ASP.NET

In this article, i am going to give overview on how to generate thumbnail dynamically
aspx page
<asp:Image ID="imgThumbnail" runat="server" />

aspx.cs page
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindThumbnailWithTitle();
        }
    }

    void BindThumbnailWithTitle()
    {
        string videoUrl = "https://www.youtube.com/watch?v=pA9QUnloZtw";
        imgThumbnail.ImageUrl = GenerateThumbnail(videoUrl);
        GenerateTitle(videoUrl);
    }

    // generate and return thumbnail by just getting the video url
    public string GenerateThumbnail(string videoUrl)
    {
        string imgLink = "http://img.youtube.com/vi/"; // Common part of every thumbnail url
        string[] videoLink = videoUrl.Split(new char[] { '=', '&' }); //Split code part from url
        imgLink = imgLink + videoLink[1] + "/1.jpg"; // '/1.jpg' is to choose thumbnail image
        return imgLink;
    }

    private void GenerateTitle(string url)
    {
        if (!string.IsNullOrEmpty(url))
        {
            string content = string.Empty;
            string firstCharacters = url.Substring(0, 3);
            if (firstCharacters.ToLower() == "www")
            {
                url = "http://" + url;
            }

            if (firstCharacters.ToLower() == "htt" || firstCharacters.ToLower() == "www")
            {
                try
                {
                    WebRequest webRequest = WebRequest.Create(url);
                    WebResponse webResponse = webRequest.GetResponse();
                    StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                    content = sr.ReadToEnd();// Content of page

                    //Split the content between the title tag
                    content = content.Substring(content.IndexOf("<title>") + 7);
                    content = content.Substring(0, content.IndexOf("</title>"));

                    //display it by using write method
                    Response.Write(content);
                }

                catch (Exception)
                {
                    content = "Url Provided by you is invalid";
                    Response.Write(content);
                }
            }

            else
            {
                content = "Url Provided by you is invalid";
                Response.Write(content);
                return;
            }
        }
    }


That’s it!!…..Happy Programming...

Sunday, 18 May 2014

How to apply dynamic text to the gridview empty data template in ASP.NET

In this article, i am going to give some overview on how to set text in EmptyDataTemplate DynamicallyFirst We have to define a label in EmptyDataTemplate and call the specified function in its Text Property. After that, just declare the specified function at anywhere in aspx.cs page. Something Like this:-
aspx page

aspx.cs page
    protected string BindEmptyText()
    {
        if (gvOrders.Rows.Count == 0)
        {
            return "No order was made!!"; // if no row found
        }
        return string.Empty; // if any row found
    }
To sort data in gridview http://dotnetcodingcircle.blogspot.in/2014/05/how-to-sort-data-in-gridview-in-aspnet.html


That’s it!!…..Happy Programming...

Thursday, 15 May 2014

How to Create Captcha with Refresh Button in C# ASP.NET

In this article, i am going to give completely idea about how to create captcha image with refresh button.Firstly, we have to create two pages one for creating captcha image and another one for creating randomly generated text inside captcha image.
CreateCaptcha.aspx
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
CreateCaptcha.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web.UI.WebControls;

public partial class CreateCaptcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DrawCaptcha();
    }

    void DrawCaptcha()
    {
        // Set the page's content type to JPEG files and clears all content output from the buffer stream
        Response.Clear();
        Response.ContentType = "image/jpeg";

        // Create integer variables
        int height = 40;
        int width = 100;

        // Create a bitmap and use it to create a Graphics object
        Bitmap bmp = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(bmp);

        // Set text positon inside rectangle
        Rectangle rect = new Rectangle(6, 8, 0, 0);
        g.Clear(Color.White);

        // Set graphic properties to produce high quality output
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        g.DrawString(Session["captcha"].ToString(), new Font("Thaoma", 15, FontStyle.Bold), Brushes.Green, rect);
        g.DrawRectangle(new Pen(Color.Purple), 2, 2, width - 5, height - 5);
        g.Flush();

        // Save the bitmap to the response stream and convert it to JPEG format
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg);

        // Release memory used by the Graphics object and the bitmap
        g.Dispose();
        bmp.Dispose();
    }
}
Now Create Signup Page in which captcha would be shown

Signup.aspx
<form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <table style="border: solid 1px black; padding: 20px; position: relative; top: 50px;"
                align="center">
                <tr>
                    <td>Name :
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Email ID :
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmailID" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Password :
                    </td>
                    <td>
                        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Confirm Password :
                    </td>
                    <td>
                        <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Enter Below Code :
                    </td>
                    <td>
                        <asp:TextBox ID="txtCaptcha" runat="server" Width="200px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td valign="middle">
                        <asp:UpdatePanel ID="UP1" runat="server">
                            <ContentTemplate>
                                <table>
                                    <tr>
                                        <td style="height: 50px; width: 100px;">
                                            <asp:Image ID="imgCaptcha" runat="server" />
                                        </td>
                                        <td valign="middle">
                                            <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
                                        </td>
                                    </tr>
                                </table>
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="btnRegiser" runat="server" Text="Register" OnClick="btnRegister_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
Signup.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public partial class Signup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CreateCapctha();
        }
    }

    // fucntion to create new captcha of 6 digits
    void CreateCapctha()
    {
        try
        {
            Random random = new Random();
            string letterCombination = "01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // combination of letters from which captcha will be made
            StringBuilder captcha = new StringBuilder();
            for (int i = 0; i < 6; i++)
            {
                captcha.Append(letterCombination[random.Next(letterCombination.Length)]);
            }

            Session["captcha"] = captcha.ToString();
            imgCaptcha.ImageUrl = "CreateCaptcha.aspx";
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

    // create new captcha by just calling the specified funtion
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        CreateCapctha();
    }

    // validate captcha against user entered text, if not match it creates another one
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        if (Session["captcha"].ToString() != txtCaptcha.Text)
        {
            Response.Write("Captcha Code is Invalid");
            CreateCapctha();
        }

        else
        {
            // Do Some Stuff Here...
        }
    }
}

That’s it!!…..Happy Programming...

Sunday, 11 May 2014

How first-child, last-child and nth-child Selectors works in CSS

Here is the markup which I'm going to use in this article:
<div class="outercontent">
            <div class="content">
                <p>RowAB</p>
                <p>RowBC</p>
                <p>RowCD</p>
                <p>RowDE</p>
                <a href="#">text in between</a>
                <p>RowEF</p>
            </div>
            <div class="content">
                <p>RowA</p>
                <p>RowB</p>
                <p>RowC</p>
                <p>RowD</p>
                <p>RowE</p>
                <a href="#">link at the end</a>
            </div>
</div>

FIRST-CHILD SELECTOR :- It allows us to target an element that is the first child element within its parent.
these styles will be applied to RowAB and RowA, because they are first child of p parent tag.

LAST-CHILD SELECTOR :- It works absolutely identical as first-child, except that it selects the last element within its parent.
these styles will be applied to RowEF. Why is that? It's because in the second .content div RowE is not the very last child. It's actually a link represented by a tag. Therefore, p:last-child became invalid.

NTH-CHILD SELECTOR :- It allows us to target an element that is the nth child element within its parent
these styles will be applied to RowCD and RowC(because of third element in its scope). We can also pass 2n+0 for example, which styles every element whose index is a multiple of 2.


That’s it!!…..Happy Programming...