Daniel Fisher presented information on creating custom ASP.NET server controls. He discussed the lifecycle of controls, using properties, viewstate, events, databinding, hierarchical and inheritance aspects. He demonstrated several custom controls covering resources, events, AJAX, databinding, navigation and exceptions. Server control development allows encapsulating reusable logic but introduces overhead from viewstate and postbacks.
2. 2
About me
• Software Engineer, newtelligence AG
• Developer
• Consultant
• Trainer
• Author for Developer Magazines
• Expert & Editor for CodeZone.de
• IIS, ADO.NET …
• Leader of INETA UG VfL-NiederRhein
• CLIP Member
3. 3
The Top 10 for better Webs
• 1. Creating an n-Tier Design
• 2. Working with Application Settings
• 3. Creating Maintainable User Interfaces
• 4. Creating Common Page Code
• 5. Tracking Users' Actions
• 6. Notifications of Exceptions
• 7. Using State Properly
• 8. Handling Unexpected Errors Gracefully
• 9. Assigning Roles and Securing Web Pages
• 10. There was no #10 ;-)
5. 5
ASP.NET Server Controls
• Compiled code that can be reused in any
ASP.NET web application.
• Classes contained in the namespace
System.Web.UI.WebControls are Server
Controls, developed by Microsoft.
• System.Web.UI.WebControls.Textbox
• (and many, many more)
• Use inheritance - all server controls come from
System.Web.UI.WebControls.Control
6. 6
Server Controls Usage
• Register Assembly, NS and TagPrefix
• Use the Control
<%@ Register Assembly=“MyAssembly”
Namespace=“MyNamespace” TagPrefix=“MyPrefix” %>
<MyPrefix:MyControl runat=“server” id=“MyControl1” />
7. 7
Server Controls Pro‘s
• Encapsulate logic in reusable
abstractions.
• Clean mechanism to divide work across a
team
• Market growth of 3rd
party products
• Allows ISPs to provide even more value to
for use in personal websites.
9. 9
Something new …
• Java Server Faces lent concepts from
ASP.NET ;-)
Quelle: Birgit Hauer
10. 10
Why Create Controls on your own
• Once did something twice?
• You need the functionality of two or more
controls working in tandem, without having to
write the logic in the web application.
• Existing server control almost meets your needs,
but only almost
• None of the existing server controls meet your
needs.
11. 11
Lifecycle of a control
Instantiate : Constructor
Initialize : OnInit method and Init Event
Begin Tracking View State : TrackViewState
Load View State : LoadViewState method
Load Postback Data : IPostBackDataHandler.LoadPostdata method
Load: OnLoad method and Load event
Raise Changed Events : IPostBackDataHandler.RaisePostDataChangedEvent method
Raise Postback Event : IPostBackEventHandler.RaisePostBackEvent method
PreRender : OnPreRender method and PreRender event
Save View State : SaveViewState method
Render : Render method
Unload : OnUnload method and Unload event
Dispose : Dispose Method
12. 12
Processing
• Control creation within the method
CreateChildControls()
• All display logic (aside from the necessary items
in above step) should be done in the method
OnPreRender().
• Rendering
• Custom: Override Render() method and provide
custom rendering logic
• Composite: Combining multiple controls into one
server control – Nothing to do?
15. 15
Properties
• Set variables to influence its
rendering.
• Almost all properties should be stored
within View State?
16. 16
ViewState
• ViewState is used to track and restore the state
values of controls that would otherwise be lost
• Base64 encoded - not easily readable, but not
encrypted!
• What to store
• Integers
• Strings
• Floats
• Decimals
• Arrays of the data types stated above
17. 17
ViewState in code
[Bindable(false),Category(“Appearance”),
DefaultValue(“This is the default text.”),
Description(“The text of the custom
control.”)]
public virtual string Text
{
get
{
object o = ViewState[“Text”];
if(o != null)
return (string) o;
else
return “This is the default text.”;
}
set { ViewState[“Text”] = value; }
}
20. 20
Server Controls - Events
• Event Handling is the best way of letting users
tap into the processes of your control.
• Providing events like Click for when a button is
clicked, or SelectedIndexChanged when a new
item has been selected in a drop down list
enables developers to program in a very object
oriented manner.
21. 21
Events in code
• Custom event eventargs and handler
• The On[Event] Method
• Raising an Event
public class MyEventArgs : EventArgs {
public MyEventArgs(string prop1, string prop2) { ... }
}
public delegate void MyEventHandler(object sender, MyEventArgs e);
public event MyEventHandler ItemChanged;
protected virtual void OnItemChanged(MyEventArgs e) {
if(Events != null) {
MyEventHandler eh = (MyEventHandler) Events[MyItemChangedEvent];
if(eh != null)
eh(this, e);
}
}
OnItemChanged(new MyEventArgs(“prop1”, “prop2”));
27. 27
AJAX in code
var request = new Request();
function _getXmlHttp(){
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
var progids =["Msxml2.XMLHTTP“,"Microsoft.XMLHTTP"];
for (i in progids){
try{
return new ActiveXObject(progids[i])
}
catch (e){}
}@end @*/
try{
return new XMLHttpRequest();
}catch (e2){ return null; }
}
35. 35
Hirarchical Controls - ChildControls
• Limited liberty to the user
• More control
• More possibilities
36. 36
Hirarchical Controls in code
public class SlideNavMenu : Control
{
private List<SlideNavMenuItem> m_MenuItems = new List<SlideNavMenuItem>();
protected override void OnPreRender(EventArgs e)
{
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is SlideNavMenuItem)
{
this.m_MenuItems.Add((SlideNavMenuItem)this.Controls[i]);
}
else if (this.Controls[i] is LiteralControl || this.Controls[i] is Literal)
{
// nice try or whitespaces...
}
else
{
throw new ApplicationException("Wrong inner controls.");
}
}
}
38. 38
HttpHandler
• HttpHandlers have nothing to do with
controls!
• But you can use them to realize controls
that
• call dialogs
• Do not need images or other resources in
some directory…
39. 39
HttpHandler in code
public class MembershipManagementAjaxHandler : IHttpHandler
{
public bool IsReusable{get{return true;}}
public void ProcessRequest(HttpContext context)
{
Assembly asm = Assembly.GetExecutingAssembly();
Stream stream = asm.GetManifestResourceStream(_parameter);
Image img = Image.FromStream(stream);
img.Save(context.Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Gif);
context.Response.End();
}
}
43. 43
Inheritance
• Whoever wants to extend your control,
should be freely able to do so.
• No matter who your target audience is or
what functionality and features that your
control provides, you will always find that
one developer who will want to extend it
for his/her own extra mile.
44. 44
Wrap-up
• Server Control development is easy
• The possibilities are endless
• Creating a fully functional server control can take
no longer than 15 minutes
• You don’t need any “cool” application, Notepad
can be your friend too – but intellisense is nice