Pages

Thursday, October 9, 2014

How To: Raising Custom Events from Custom .Net UserControls

In the last few days I've been searching books and websites to get back to "object oriented programming" I remember in my head from back time in college java and C++ courses about classes, event handling, delegates, inheritance .. etc but can't seem to get what I have in mind done in current C# development work requirements as custom electronic request forms automation, built with custom .net controls in SharePoint environment to be reused among them all when needed.

in this post I'll be showing you how to raise an event from within usercontrol's native controls events and handle it with a custom code in webpage code file hosting the usercontrol.

watching Kudvenkat's YouTube videos below helped a lot to understand the event handling technique by following the 5 steps to raise an event from the usercontrol

  1. Step 1: Create XxEventArgs class that will contain the event data.
  2. Step 2: Create XxChangedEventHandler delegate that raises this event. 
  3. Step 3: Create XxChanged event that is a variable of type delegate.
  4. Step 4: Create a protected virtual method to raise the event that enables the derived classes to do some additional work before the event can be raised. 
  5. Step 5: Finally raise the event, whenever the usercontrol's controls is changed.
Let's say, we want to raise TimeChanged event every time the usercontrol ( from the previous post ) controls values changes. i.e, when hours TextBox's Text is changed, minutes TextBox's Text is changed, or time DropDownList's Index is Changed.
  1. Step 1: Create TimeChangedEventArgs class that will contain the event data:


    public class TimeChangedEventArgs : EventArgs
    {
        private string _ucTimeValue;

        // Constructor to initialize event data
        public TimeChangedEventArgs(string ucTimeValue)
        {
            this._ucTimeValue = ucTimeValue;
        }

        // Returns ucTimeValue   
        public string UcTimeValue
        {
            get { return this._ucTimeValue; }
        }
    }


  2. Step 2: Create TimeChangedEventHandler delegate that raises this event.


    public delegate void TimeChangedEventHandler(object sender, TimeChangedEventArgs e);

  3. Step 3: Create TimeChanged event that is a variable of type delegate inside the usercontrol's class:


    public
    event TimeChangedEventHandler TimeChanged;

  4. Step 4: Create a protected virtual method to raise the event that enables the derived classes to do some additional work before the event can be raised.
    Checking if TimeChanged is null is a good practice as it will give error message in cases when you don't need to have a custom event handling in usercontrol's host. 

    protected
    virtual void OnTimeChanged(TimeChangedEventArgs e)
        {
            if (TimeChanged != null)
            {
                TimeChanged(this, e);
            }
        }

  5. Step 5: Finally raise the event, whenever the usercontrol's controls is changed:
    by assigning the following event handlers to the controls and then raising the event 
    1. When hours TextBox's Text is changed:


        protected void hourTxtBx_TextChanged(object sender, EventArgs e)
          {
               OnTimeChanged(new TimeChangedEventArgs(this.hourTxtBx.Text + ":" + this.minTxtBx.Text + " " + timeDDL.SelectedValue));

          }

    2. When minutes TextBox's Text is changed:


        protected void minTxtBx_TextChanged(object sender, EventArgs e)
          {
               OnTimeChanged(new TimeChangedEventArgs(this.hourTxtBx.Text + ":" + this.minTxtBx.Text + " " + timeDDL.SelectedValue));

          }

    3. When time DropDownList's Index is Changed:


        protected void timeDDL_OnSelectedIndexChanged(object sender, EventArgs e)
          {
              OnTimeChanged(new TimeChangedEventArgs(this.hourTxtBx.Text + ":" + this.minTxtBx.Text + " " + timeDDL.SelectedValue));

          }

Now to consume the usercontrol custom event:
  1.  Step 1: Create an event handler method. The method signature must match the signature of the "TimeChangedEventHandler" delegate.


    protected
    void fromTimeUC_OnTimeChanged(object sender, TimeChangedEventArgs e)
        {
            string errMsg = "";
             
            timeErrLbl.Text = (!checkTime(e.UcTimeValue , out errMsg)) ? errMsg : "";
            timeErrLbl.Visible = (!string.IsNullOrEmpty(errMsg))
        }

  2. Step 2: Register the created event handler method to the usercontrol OnTimeChanged event:


  <uc1:jpTimeChooser35UC OnTimeChanged="fromTimeUC_OnTimeChanged" ID="fromTimeUC"  runat="server" />




That's it ..  hope it was helpful :)

Reference:

How To: Using asp.net Validation Controls to be used with Custom Usercontrols

To use asp.net Required Field Validator, Range Validator ..., etc you must have a ValidationProperty attribute that specifies which value from your custom user control the validation controls to be validated validate.

So.. In your custom usercontrol  class add the ValidationProperty attribute and a property that returns the data in a format that is suitable for the validation controls.

Usercontrol
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="jpTimeChooser35UC.ascx.cs"
    Inherits="jpTimeChooser35UC" %>
<table cellpadding="0" cellspacing="0" dir="rtl" style="text-align: center;">
            <tr>
                <td>
                    <asp:TextBox ID="minTxtBx" MaxLength="2" runat="server" Width="30px" CssClass="tblField" Text="30" Style="text-align: center" >
                    </asp:TextBox>
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:TextBox ID="hourTxtBx" runat="server" MaxLength="2" Width="30px" CssClass="tblField" Text="07" Style="text-align: center" >
                    </asp:TextBox>
                </td>
                <td style="padding-right: 5px">
                    <asp:DropDownList ID="timeDDL" CausesValidation="false" Font-Size="10pt" Width="50px" runat="server" CssClass="tblField">
                        <asp:ListItem Selected="True">ص</asp:ListItem>
                        <asp:ListItem>Ù…</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr style="color: Gray; text-align: center; padding: 0px; font-family: Tahoma; font-size: 9pt;">
                <td>
                    دقيقة
                </td>
                <td></td>
                <td>
                    ساعة
                </td>
            </tr>
        </table>
        
 
Preview 



Usercontrol's Code:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
[ValidationProperty("TimeValue")]
public partial class TmeChooser35UC : System.Web.UI.UserControl
{
    public object TimeValue
    {
        get
        {
            string TimeString = this.ucHours+":"+this.ucMinutes+" "+this.ucTime;
            if (TimeString == ": Øµ")
            {
                return "";
            }
            else
            {
                return TimeString;
            }
        }
    }
    public string ucMinutes
    {
        get { return minTxtBx.Text.ToString(); }
        set { minTxtBx.Text = ucMinutes; }
    }
    public string ucHours
    {
        get { return hourTxtBx.Text.ToString(); }
        set { hourTxtBx.Text = ucHours; }
    }
    public string ucTime
    {
        get { return timeDDL.SelectedValue.ToString(); }
        set { timeDDL.SelectedValue = (timeDDL.Items.Contains(new ListItem(ucTime))) ? timeDDL.SelectedValue = ucTime : ""; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

 
and then use a RequiredFieldValidator and the Usercontrol  in a WebPage 
<%@ Page Language="C#" Culture="ar-sa" Title="Untitled Page" %>
<%@ Register Src="jpTimeChooser35UC.ascx" TagName="jpTimeChooser35UC"   TagPrefix="uc1" %>

<uc1:jpTimeChooser35UC ID="fromTimeUC"  runat="server" />
<asp:RequiredFieldValidator runat="server"ErrorMessage="ERROR_MESSAGE" 
ID="RequiredFieldValidator1" ControlToValidate="fromTimeUC" 
SetFocusOnError="True"></asp:RequiredFieldValidator>

<asp:Button ID="submitBtn" runat="server" Text="submit"
CssClass="tblButtons" Visible="true" OnClick="submitBtn_Click"/>
Preview 


  













That's It .. Hope this was helpful :)

Reference: Microsoft Support #310082

Saturday, August 16, 2014

How To: Load SharePoint web part User Control Inside another SharePoint web part without C# Coding

simple way to Load SharePoint web part User Control Inside another  SharePoint web part without C# Coding is done by :

  1. registering the user control
    <%@ Register src="webPartUC.ascx" tagname="webPartUC" tagprefix="uc" %>

  2. loading the user control <uc:webPartUC ID="webPartUC1" runat="server" />
if you wanted to pass webpart properties.. all you have to do is to specify the values as follows:
<uc:webPartUC ID="webPartUC1" LabelText="TEXT" runat="server" />

if you wanted to pass webpart properties from within a DataList Control Items .. all you have to do is to specify the values as follows making sure to add the below line inside the DataList:

 <asp:DataList ID="usersDL" runat="server" Width="100%" >
   <ItemTemplate>
         <uc:webPartUC ID="webPartUC1"
              LabelText=<%# Eval("userName")%> runat="server" />

    </ItemTemplate>
 </asp:DataList>


Thats it :)

    

Saturday, May 17, 2014

Embed PDF in HTML Page


To Embed PDF files in HTML Page You can use below snippet of code, It works in most browser versions (Chrome, Firefox, IE,... ).

if it is not supported, it shows the message "The PDF cannot be displayed."

<div id="pdf">
<object width="900" height="1000" type="application/pdf" data="/filepath/filename.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0" id="pdf_content">
<p>The PDF cannot be displayed. <a href="/filepath/filename.pdf" target="_top">download</a>.</p>
</object>
</div>

Above snippet of code sets the zoom to 85%, removes scrollbars, toolbars and nav panes.

Hope it helps J