Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

2006 - Basta!: Advanced server controls

Advanced server controls with ASP.NET

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all
  • Be the first to comment

  • Be the first to like this

2006 - Basta!: Advanced server controls

  1. 1. ASP.NET 2.0 Advanced Server Controls Daniel Fisher(lennybacon) newtelligence® AG
  2. 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. 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 ;-)
  4. 4. 4 Maintainable User Interfaces • It’s about reusability • Html mark-up • Server side code • Client side scripts
  5. 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. 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. 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.
  8. 8. 8 Server Controls Con‘s • No visual way of developing server controls, generated via code.
  9. 9. 9 Something new … • Java Server Faces lent concepts from ASP.NET ;-) Quelle: Birgit Hauer
  10. 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. 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. 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?
  13. 13. 13 Resources • Strings • Javascript • Images • HttpHandlers - later
  14. 14. 14 Demo • Resources
  15. 15. 15 Properties • Set variables to influence its rendering. • Almost all properties should be stored within View State?
  16. 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. 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; } }
  18. 18. 18 ViewState Concepts Send Request Send Response Send Request Send Response Ping Pong on the wire?
  19. 19. 19 ViewState alternatives • Query Request.Form and Request.QueryString on your own • Use local fields – most times they work fine
  20. 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. 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”));
  22. 22. 22 Demo • Events and delegates • EventControl
  23. 23. 23 The downside - Postbacks • Implement the IPostBackEventHandler • Create an event field • Create methods to relate to the event
  24. 24. 24 Postbacks - Alternatives • Server side only events • AJAX • Response.Redirect( http://example.org); • <a href=“…“>link</a>
  25. 25. 25 Demo • Server side only events • WaitScreen
  26. 26. 26 AJAX • AsyncrounousJavascriptAndXml
  27. 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; } }
  28. 28. 28 Demo • AJAX, Response.Redirect() • UserManagement
  29. 29. 29
  30. 30. 30 Demo • <a href=“…“>link</a> • Forum
  31. 31. 31 Databound Controls • ObjectDataSource • SqlDataSource • … • Abstract way to access data • A lot of overhead but a standard way… • Who is your target?
  32. 32. 32 Databound in code private ITemplate _itemTemplate; public ITemplate ItemTemplate{ get{return _itemTemplate;} set{_ itemTemplate=value;} } protected override void CreateChildControls(){ CreateControlHierarchy(true); } protected virtual void CreateControlHierarchy(bool dBind){ LoadFromDataSource(); foreach (object r in _dataSource){ RepeaterItem item1 = CreateItem(ListItemType.Item, dataBind, r); } } private RepeaterItem CreateItem(…) { _itemTemplate.InstantiateIn(item); Controls.Add(item); }
  33. 33. 33 Demo • Databound Controls • DataBoundControl
  34. 34. 34 Hirarchical Controls • Navigations, Tabs … • ITemplate • ChildControls
  35. 35. 35 Hirarchical Controls - ChildControls • Limited liberty to the user • More control • More possibilities
  36. 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."); } } }
  37. 37. 37 Demo • Hirachical controls • SlideNav
  38. 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. 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(); } }
  40. 40. 40 Demo • HttpHandlers • HumanInputValidator
  41. 41. 41 What ever you can imagine • …
  42. 42. 42 Demo • ExceptionVisualizer
  43. 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. 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
  45. 45. 45 Questions and Answers DanielF@newtelligence.net

    Be the first to comment

    Login to see the comments

Advanced server controls with ASP.NET

Views

Total views

230

On Slideshare

0

From embeds

0

Number of embeds

2

Actions

Downloads

0

Shares

0

Comments

0

Likes

0

×