Showing posts with label UserControl. Show all posts
Showing posts with label UserControl. Show all posts

April 1, 2014

Ok, this one is interesting and not something that I prefer doing but on one the tasks that I was working on - I had to call a method on an aspx page from a user control within the page. It's not good practice to call page's methods from user controls as the user control should not have to know the page where it can be used. So, how can we do it.

March 16, 2011

In my last article – Creating a Captcha Control – Part 1, I discussed on the front end of the user control that creates the captcha. In this article, I will discuss on the code-behind of the control – that is, what properties are set and how and what methods are used.

The following code shows the properties that are used.

User Control - Properties
  1. #region field initialisation
  2.  
  3. public Captcha cc;
  4. private int captchaLength;
  5. private double fontSize;
  6. private string fontFamily;
  7. private string backgroundImagePath;
  8. private string textColor;
  9. private string successMessage;
  10. private string errorMessage;
  11. private string characterSet;
  12.  
  13. #endregion

Then, the setters and getters for these properties are created as per below.

User Control - Setter / Getter
  1. #region GetterSetter
  2. public string TestButtonText
  3. {
  4.     get { return B1.Text; }
  5.     set { B1.Text = value; }
  6. }
  7.  
  8. public string SpeakButtonText
  9. {
  10.     get { return BSpeak.Text; }
  11.     set { BSpeak.Text = value; }
  12. }
  13.  
  14. public string ReLoadButtonText
  15. {
  16.     get { return B2.Text; }
  17.     set { B2.Text = value; }
  18. }
  19.  
  20. public string SuccessMessage
  21. {
  22.     get { return successMessage; }
  23.     set { successMessage = value; }
  24. }
  25.  
  26. public string ErrorMessage
  27. {
  28.     get { return errorMessage; }
  29.     set { errorMessage = value; }
  30. }
  31.  
  32. public int CaptchaLength
  33. {
  34.     get { return captchaLength; }
  35.     set
  36.     {
  37.         try
  38.         {
  39.             int k = Convert.ToInt32(value);
  40.             if (k < 5 || k > 10)
  41.                 captchaLength = 6;
  42.             else
  43.                 captchaLength = k;
  44.         }
  45.         catch (Exception ex)
  46.         {
  47.             captchaLength = 6;
  48.         }
  49.     }
  50. }
  51.  
  52. public string FontFamily
  53. {
  54.     get { return fontFamily; }
  55.     set
  56.     {
  57.         if (value != string.Empty && value != null)
  58.             fontFamily = value;
  59.         else
  60.             fontFamily = "Arial";
  61.     }
  62. }
  63.  
  64. public double FontSize
  65. {
  66.     get { return fontSize; }
  67.     set
  68.     {
  69.         try
  70.         {
  71.             fontSize = Convert.ToInt32(value);
  72.             if (fontSize <= 10 && fontSize >= 24)
  73.                 fontSize = 16;
  74.         }
  75.         catch (Exception ex)
  76.         {
  77.             fontSize = 16;
  78.         }
  79.     }
  80. }
  81.  
  82. public string BackgroundImagePath
  83. {
  84.     get { return backgroundImagePath; }
  85.     set
  86.     {
  87.         if (System.IO.File.Exists(Server.MapPath(value)))
  88.             backgroundImagePath = value;
  89.         else
  90.             backgroundImagePath = System.Configuration.ConfigurationManager.AppSettings["defaultImagePath"];
  91.     }
  92. }
  93.  
  94. public string TextColor
  95. {
  96.     get { return textColor; }
  97.     set
  98.     {
  99.         if (value == string.Empty || value == null)
  100.             textColor = "Black";
  101.         else
  102.             textColor = value;
  103.     }
  104. }
  105.  
  106. public string CharacterSet
  107. {
  108.     get { return characterSet; }
  109.     set
  110.     {
  111.         if (value == "" || value == null)
  112.             characterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
  113.         else
  114.             characterSet = value;
  115.     }
  116. }
  117.  
  118. #endregion

The setters and getters are quite straight forward. The captcha length property defaults to 6 in case the value entered is not a number and if the value is less than 6 or greater than 10.

The default font family is set to Arial.

The default font size is set to 16. If fonts are too small – less than 10px – or too large – greater than 24px – the font is automatically set to 16.

The default colour is set to black.

The default character set consists of all letters in uppercase and number from 1 to 9. I have not included lower case letters and 0 as these are sometimes confusing.

The default background image is set within the web.config file. Note that the background image is expected to be within the solution and would require “~” notation to work properly.

Now, in the Page_Load event shown below, I am setting the default values and loading the captcha.

Page_Load event
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.  
  4.     B1.Text = TestButtonText;
  5.     B2.Text = ReLoadButtonText;
  6.     BSpeak.Text = SpeakButtonText;
  7.     
  8.     SetValues();
  9.  
  10.     cc = GetCaptchaClass();
  11.  
  12.     if (!IsPostBack)
  13.     {
  14.         LoadCaptcha();
  15.     }
  16. }

As can be seen, the Button’s text are set a SetValues method is called which sets values for other properties and the method – LoadCaptcha is called if it is not a postback. Another class Captcha is set to method GetCaptchaClass which initiates a Captcha object. I will talk about the Captcha object in a little while.

The SetValues method is below.

SetValues method
  1. private void SetValues()
  2. {
  3.     if (CharacterSet == null)
  4.         CharacterSet = "";
  5.     if(CaptchaLength == 0)
  6.         CaptchaLength = 6;
  7.  
  8.     if(BackgroundImagePath == null)
  9.         BackgroundImagePath = "";
  10.     
  11.     if(FontFamily == null)
  12.         FontFamily = "";            
  13.     
  14.     if(FontSize == 0)
  15.         FontSize = 0.0;
  16.  
  17.     if(TextColor == null)
  18.         TextColor = "";
  19. }

The LoadCaptcha method is interesting – it creates random text and adds it ViewState and Session, adds the Captcha object to Session and sets the path of the Image control to CaptchaHandler.ashx handler. The code for this method is below.

LoadCaptcha method
  1. private void LoadCaptcha()
  2. {
  3.     string text = GetRandomText();
  4.     
  5.     ViewState.Add("captcha", text);
  6.     Session.Add("CaptchaClass", cc);//add captcha object to Session
  7.     Session.Add("captcha", text);//add captcha text to session
  8.     Im1.ImageUrl = "CaptchaHandler.ashx";
  9. }

The random text for the captcha is generated by GetRandomText method which basically creates random text based on the CharacterSet property. The code for this method is below.

GetRandomText method
  1. private string GetRandomText()
  2. {
  3.     char[] letters = CharacterSet.ToCharArray();
  4.     string text = string.Empty;
  5.     Random r = new Random();
  6.     int num = -1;
  7.  
  8.     for (int i = 0; i < this.CaptchaLength; i++)
  9.     {
  10.         num = (int)(r.NextDouble() * (letters.Length - 1));
  11.         text += letters[num].ToString();
  12.     }
  13.     return text;
  14. }

The Captcha class basically properties for the captcha text. The GetCaptchaClass method initiates the Captcha class and set its properties. The code for this method is below.

GetCaptchaClass method
  1. private Captcha GetCaptchaClass()
  2. {
  3.     if (Session["CaptchaClass"] != null)
  4.         cc = (Captcha)Session["CaptchaClass"];
  5.     else
  6.         cc = new Captcha();
  7.  
  8.     cc.FontSize = this.FontSize;
  9.     cc.FontFamily = this.FontFamily;
  10.     cc.BackgroundImagePath = this.BackgroundImagePath;
  11.     cc.TextColor = this.TextColor;
  12.     return cc;
  13. }

That’s pretty much all the methods for the user control. When the Reload Button is clicked the LoadAnother method is run that simply calls the LoadCaptcha method as per below.

LoadAnother method
  1. protected void LoadAnother(object sender, EventArgs e)
  2. {
  3.     LoadCaptcha();
  4. }

When the Test button is clicked, the ValidateCaptcha method is run that compares the text entered with the text in the ViewState. The code is below.

ValidateCaptcha method
  1. protected void ValidateCaptcha(object sender, EventArgs e)
  2. {
  3.     string text = T1.Text;
  4.     if (text == (string)ViewState["captcha"])
  5.         LStatus.Text = SuccessMessage;
  6.     else
  7.         LStatus.Text = ErrorMessage;
  8. }

In my next article, I will explain how the reading out the captcha text works. The captcha control is also available for download from CodePlex at http://captchadotnet.codeplex.com/

The word CAPTCHA means “Completely Automated Public Turing to tell Computers and Humans Apart”.Captcha is commonly used in registration forms and other forms to disallow spiders and / or bots to automatically submit a form. Captcha is usually some text on an image that can be read by humans but unreadable by computers. An example image of a captcha is below.

Captcha 

Creating a captcha controls involves dynamically generating some text, converting the text into an image, passing the image to the client, pass on the text in some other format so it could be tested against. In this particular instance, I have created a captcha control through which we control properties like font size, colour, background image, character set to choose the characters from and number of characters to display. It will also control additional properties for setting text for various buttons like Test button, Reload button and success and error message. The control also contains option for reading out the text for accessibility reasons.

The control could be used like below:

Using the control
  1. <uc1:CaptchaControl ID="CaptchaControl1" runat="server" TestButtonText="Try" BackgroundImagePath="~/images/captcha2.png"
  2. ErrorMessage="Try Another Image" SuccessMessage="good job" CaptchaLength="10" CharacterSet="ABCDEFG123456"
  3. ReLoadButtonText="Reload" FontSize="20" FontFamily="Trebuchet MS" TextColor="Blue" />

After a new project is setup in Visual Studio, a user control is added to the project. The user control simply contains an Image control for displaying captcha, a TextBox control where a user would enter text for comparison, a Label control that displays status – correct or incorrect text entered, three Button controls – one for testing the user, one for reloading the captcha text in case the text cannot be read by the user and another button for reading out the captcha text. It’s important that the text could be read out as it helps visually impaired users to enter the information.

Code for the user control is below.

User Control - aspx
  1. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CaptchaControl.ascx.cs" Inherits="CaptchaApp.CaptchaControl" %>
  2. <asp:Image ID="Im1" runat="server" />
  3. <asp:TextBox ID="T1" runat="server"></asp:TextBox>
  4. <asp:Button ID="B1" runat="server" Text="Test" OnClick="ValidateCaptcha" />
  5. <asp:Label ID="LStatus" runat="server"></asp:Label><br /><br />
  6. <asp:Button ID="B2" runat="server" Text="Load Another Image" OnClick="LoadAnother" />
  7. <asp:Button ID="BSpeak" runat="server" Text="Speak" OnClick="ReadCaptcha" />

As can be seen, the ImageUrl property for the Image control is not set. It will be set from code-behind.

In my next post, I will discuss how I have created the various properties of the control through the code-behind of this user control.

The source code of the captcha control can be downloaded from CodePlex  at http://captchadotnet.codeplex.com/

July 14, 2009

Programmatically add usercontrol

After creating a user control as described in create usercontrol or create usercontrol from webpage, we may need to add the control programmatically from code-behind. To do so, we need to use the LoadControl method of the Page class. Assuming, a usercontrol is already created, here is the code to add it to a page dynamically.

  protected void Page_Load(object sender, EventArgs e)
        {
            Control uc = (Control)Page.LoadControl("~/usercontrol/WebUserControl1.ascx");//path to control
            form1.Controls.Add(uc);//add control
        }


July 5, 2009

In this example, I will first create a user control containing two TextBox controls and expose public properties for the control. Then, I will create a web form, add two instances of the user controls and display text entered in the TextBox controls of the user control.

Here is the user control,

First Name: <asp:TextBox ID="TextBoxFirstName" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RQV1" runat="server" ControlToValidate="TextBoxFirstName" ErrorMessage="*"></asp:RequiredFieldValidator><br />

Last Name: <asp:TextBox ID="TextBoxLastName" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RQV2" runat="server" ControlToValidate="TextBoxLastName" ErrorMessage="*"></asp:RequiredFieldValidator>


Here is the Code-behind for the page exposing public properties,

public string GetFirstName
        {
            get { return TextBoxFirstName.Text; }
            set { TextBoxFirstName.Text = value; }
        }

        public string GetLastName
        {
            get { return TextBoxLastName.Text; }
            set { TextBoxLastName.Text = value; }
        }


In the code-behind, I am creating two public string variables setting the value to the TextBox control's Text property and returning the Text property of the TextBox controls.

Then, in the main page,

<form id="form1" runat="server">
    <div>This is page to add multiple user controls.</div>
    <p>
        Customer1 Details:<br />
        <uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
    </p>
   
    <p>
        Customer2 Details:<br />
        <uc1:WebUserControl1 ID="WebUserControl12" runat="server" />          
    </p>
   
    <asp:Button ID="Button1" runat="server" Text="Continue" OnClick="GetCustDetails"/>
    <asp:Button ID="Button2" runat="server" Text="Clear" CausesValidation="false" OnClick="ClearFields" /><br />
   
    Customer1 FirstName: <asp:label ID="Label1" runat="server"></asp:label><br />
    Customer1 LastName: <asp:label ID="Label2" runat="server"></asp:label><br />
    Customer2 FirstName: <asp:label ID="Label3" runat="server"></asp:label><br />
    Customer2 LastName: <asp:label ID="Label4" runat="server"></asp:label><br />
    </form>


I am adding two instances of the user control to the page. Then there are four Label controls that will display the user control's properties on Button1 click. There is another Button2 that clears all the user control's TextBox controls.

protected void GetCustDetails(object sender, EventArgs e)
        {
            Label1.Text = WebUserControl11.GetFirstName;
            Label2.Text = WebUserControl11.GetLastName;
            Label3.Text = WebUserControl12.GetFirstName;
            Label4.Text = WebUserControl12.GetLastName;
        }

        protected void ClearFields(object sender, EventArgs e)
        {
            WebUserControl11.GetFirstName = string.Empty;
            WebUserControl11.GetLastName = string.Empty;
            WebUserControl12.GetFirstName = string.Empty;
            WebUserControl12.GetLastName = string.Empty;
        }


June 3, 2009

In the previous example, I showed how we can access data from user control. In this example, I will build on the previous example and load data from one user control to another.

I will add another user control to the application. The code for the user control is below.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControlPrac1.ascx.cs" Inherits="UserControlPrac1" %>
First name:
<asp:Label ID="LabelFirstName" runat="server" Text="First name label"></asp:Label><br />
Last Name:
<asp:Label ID="LabelLastName" runat="server" Text="Last name label"></asp:Label>


Code-behind:

public partial class UserControlPrac1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }

public string LastName
{
set { LabelLastName.Text = value; }
}

public string FirstName
{
set { LabelFirstName.Text = value; }
}
}

In the .ascx page, I have declared two Label controls LabelLastName and LabelFirstName. In the code behind, I have created two public methods that sets the value of the Label controls of the user control.

In the .aspx page, I am adding the user-control.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserControlPracTest.aspx.cs" Inherits="UserControlPracTest" %>

<%@ Register src="UserControlPrac.ascx" tagname="UserControlPrac" tagprefix="uc1" %>
<%@ Register src="UserControlPrac1.ascx" tagname="UserControlPrac1" tagprefix="uc2" %>

<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:UserControlPrac ID="UserControlPrac1" runat="server" />
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<p>
Second User Control:</p>
<p>
<uc2:UserControlPrac1 ID="UserControlPrac11" runat="server" />
</p>

</form>
</body>
</html>


In code-behind,

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

}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("first name: " + UserControlPrac1.FirstName);
Response.Write("<br/>last name: " + UserControlPrac1.LastName);

UserControlPrac11.FirstName = UserControlPrac1.FirstName;
UserControlPrac11.LastName = UserControlPrac1.LastName;

}
}

In code-behind for the page, when the Button is clicked, I am setting the public properties of the user control to values defined in the first user control.

June 2, 2009

Access Data From User Control

A user control can contain other controls like TextBoxes or Labels. These control are declared as protected members. This means that data from and for these controls are only available to the particular user control or to classes that extends this particular user control.

To access data from a page with a user control, the user control needs to expose the properties as public properties or public methods.
In this example, I will first create a user control containing a couple of TextBoxes and expose the properties publicly so they can be used by a page that contains the user control.

The code for the user control is below:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControlPrac.ascx.cs" Inherits="UserControlPrac" %>
FirstName: <asp:TextBox ID="TextBoxFirstName" runat="server"></asp:TextBox><br />
LastName: <asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox>

Here, there are 2 Textboxes with id TextBoxFirstName and TextBoxLastName.

The code for the code-behind for the page is below:

public partial class UserControlPrac : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {    }

    public string FirstName
    {
        get { return TextBoxFirstName.Text; }
        set { TextBoxFirstName.Text = "firstname"; }
    }

    public string LastName
    {
        get { return TextBoxLastName.Text; }
        set { TextBoxLastName.Text = "lastname"; }
    }
}

Here, I have 2 public properties FirstName and LastName. The properties returns the values for the Textbox controls on the page. I can also set the values to some default values.

Now, on the main, I register the usercontrol and then add a button to the page. The code is below:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserControlPracTest.aspx.cs" Inherits="UserControlPracTest" %>
<%@ Register src="UserControlPrac.ascx" tagname="UserControlPrac" tagprefix="uc1" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <uc1:UserControlPrac ID="UserControlPrac1" runat="server" />   
        </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html> 


On code-behind:

public partial class UserControlPracTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("first name: " + UserControlPrac1.FirstName);
        Response.Write("<br/>last name: " + UserControlPrac1.LastName);
    }
}


When the button is clicked, I am writing the values in the Textbox controls based on what was passed in by the user.

May 5, 2009

Create User Control from Web Page

To create a user control from a aspx web page, create a web page first.
default2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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 runat="server"><title>Untitled Page</title></head>

<body>

<form id="form1" runat="server">
<div> </div>
</form> </body> </html>

code behind

public partial class Default2 : System.Web.UI.Page
{
protected
void Page_Load(object sender, EventArgs e)
{ //page load event }
}
Then,

  • Remove the html, head, body and form tags.
  • Change the @Page directive in default2.aspx page to @Control.
  • Change the filename to default2.ascx.
  • In code-behind, change the Inherits tag to System.Web.UI.UserControl.
The resultant page (user control) will like below.
default2.aspx,

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Default2.ascx.cs" Inherits="Default2" >
code-behind,

public partial class Default2 : System.Web.UI.UserControl
{

protected
void Page_Load(object sender, EventArgs e)
{
//page load event}
}

April 13, 2009

Create User Control

To create a web user control, in visual studio, choose "Add New Item" > "Web User Control" and choose a name and then click on the Add button.
The following code is automatically generated.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UCWebUserControl.ascx.cs" Inherits="UCWebUserControl" %>
The code appears similar to adding a new web-form but a look on the HTML shows a Control directive instead of the Page directive.
Texts and controls can be added to the page similar to adding text and controls to a web form as shown below.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UCWebUserControl.ascx.cs" Inherits="UCWebUserControl" %>
<div>div element in a user control</div>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
This user control can now be added to a page.
Reference: Shahed Kazi at AspNetify.com