Skip to main content

Posts

Showing posts from September, 2010

70-562 Dynamic Data

Object Relational Mappers,  for example Linq and Entity Framework are well integrated in VS 2008, and have project template available; Dynamic Data Web Site. Creating a dynamic data web site project is a good way to explore the server controls and datasources offered via the toolbox menu. This template starts out witha basic website shell, but the connection string isnt configured. The Linq to SQL and Entity to SQL are the ORM offered and by default use the default databse located in App_Data folder of this template project. The designer.cs file defines the data model and wraps the objects around it in order to access the data model via code. In the global.asax contains the RegisterRoutes method that comes with a default model.RegisterContext method of the type YourDataConectType, you will replace this one with your data context which, after having created the model pointing to your database should be avaialble in intellisence under the name yourDatabaseNameDataContext. Scaffo

70-562 Security Trimming

Security Triming is achieved by putting a web.config in each folder... each aspx file has its own folder denies * all users, and  db tables in the app_data folder can be maintained with the website administration tool wwebadmin tool can be started from website->configuration then you click on the security link, then manage users so there's two layers of security, the ones in the app_data folder and the ones in web.config that overide app_data. Web adminstration tool can use both both form and windows authentication, windows is handled by iis there is a control for the login button, and one to display the login user user in the sitemap section of the web.config needs to say securityTrimming enabled if a node doesnt have a page associated with it, the node needs to have roles attribute to allow to access to any pages in it's subfolder, or is this just to show the menu item in the sitepath control? Giving roles to a sitemap node just show the node doesnt give access to t

70-562 Navigation API

You can add custom attributes for each node in the xml file, like the sound and image of an animal to set to label and img you can check if there is a previous sibling to add a previous button(set the button to visible, do all this in page_load in general when testing new features, you can add a checkbox to display info to make sure you can read it, even it's if its irrevelant for the user to see, you just add labels at the bottom of the page, and you can even add this in the master page as a footer, you could put all this in the server div control and use innerHTML property you can use it for rewriting(rerouting) urls so they dont include query string, in the web.config in urlMappings element. Might want to put these mappings in an external .config (set the configSource attrtibute of the urlMappings elementconfiguration file, external config change doesnt cause an application restart. Setting the url in the sitemap file also allows to remap urls sitemap files to have child site

70-562 Navigation

Defining the structure of the site, can be done with sitemap, that can be stored in xml file  you can build your own, or create navigation controls. xmlsitemapprovide sitemapdatasource default xml file is web.sitemap, or can use other sources you can create your own from defiving from the SiteMapProvider , StaticSiteMapProvider  you would bind a menu or tree view to the sitemap file.   There is a difference  puting a slash before a relative url implies this slash is the root folder of the application  you can use the ~ to the root directory of the application, because the relative would be affected by location of the master page since it's the containter. Navigation features : create a sitemap file, containes siteMapNode elements, contains real and virtual page sitemap file integrates localization navigation controls, available from toolbox->Navigation siteMapNode attributes, title, url, and desctiption(tooltip) SiteMapPath, Menu, TreeVie, comonly put in the

70-562 Master Pages

New content placeholder control, need one for any place holding content We never navigate to a master page but to a content page and asp.net knows it should render the master page. Their exist two default content place holder. You can select a master page with the checkbox at the time you create a page.aspx. The new page will now have 2 content place holder one  for head and one for body. Note: There can't be any or head tag in a master page Master pages can specify default content for pages that don't use a specific place holder, you just add a place holder and add content in it, to generate the new place holder on the page you can select the default place holder, right click->add new place holder. Typically, the whole content of the master page is put in a table, each place holder in their own cell, in design mode you create a table bellow the place holders, adjust cells(merge cells if needed) and the master page content inside the table + place all the place hol

70-562 Themes

Theme applies to on the server side on the aspnet control while css client side by the browser themes are located in teh app_themes folder and defined in skin folders contained in subfolders of the app_theme name of the folder defines the name of the theme To make a label skin, you take a control markup(or style it through the UI first) and remove everything that's specific to the single control, because it's going to be reused for all control of that type, but it's possible to created named instances of a theme to apply to one instance of a control it is applied to the page, on the docuemnt(or page object?) object and theme property, can also be set in teh page directive, can also be set at runtime in teh preInit event by setting the Theme or StyleSheetTheme property, allowing the user to pick a theme, if you set in the session vairable is good, Page.Theme = Session{"SelecteTheme"].ToString(); to fill a listbox with themes, you do a DirectoryInfo dirThemes = D

70-562 CSS Style Tools

HTML can be styled by wrapping, lets say I want to style the the content of the body. For example a header in bold. Another way of doing this is to apply the style to the HTML using the style attribute of the HTML element. You can test those in split mode in the visual studio designer to see the effects right away Or i could make a file called something.css and copy my css elements to that stylesheet and reference it from my html file this file can be in the root if it's in subfolder just include the subfolder in the path it can also be on another web server you just reference it with a url rather than a path to a local file cascading order from lowest to highest precedence 1-browser 2-external stylesheet 3-internal stylesheet 4-inline styles note: within a sheet the order matter in the stylesheet, the last one encountered is the one applied note on xhtml validation: it is specified in the doctype at the top of the page, and visual studio also has it's validatio

70-562 Deployment

Deployment features in VS2008 Often a current version of visual studio will get new features with service packs and will later be included in the next release of visual studio, for example ajax in 2005 and deployment features. Copy Web site: http or ftp Publish web site: strong naming The web deploymenbt project allows to manage the build aslo, on top of the setup program, all this is contaikned into an msbuild file(xml) witht he wdprof file extension. It is possible to decide to include pdb or not, and manage output assemblies, for example, to remap which file will be put in which assembly. Strong name signing is possible, and this requires a key file. There is a configuration packager that allows to replace sections of the web.config file with replacement files, that need to go within the website directory. You can tell it to remove the App_Data folder if you dont use it. Sections can be added to run after build. Note on AJAX navigation history. States are not saved

70-562 Coding Web Parts

Coding Web Parts. The Web Part framework helps you write code to control all aspects of web parts behavior. Not all things are automaticaly handled, changing the display mode, changing the personalizing scope, reseting data, creating web parts with custom or user controls, and creating connections. PersonlizationADministration.FindSharedState method allows to find the personlization data using the FindUserState and ResetUser state. Web parts can be implement following those typical patterns, Master/Details(one shows the order, the other the items), Filter by Form(one shows the order, other allows to edit items, List/Form InputDisplay: one to edit, the other to view A web part can be a data provider, or consumer, or both. When using provider/consumer, The data is not guaranteed to be final until the prerender event. Custom controls as web parts allow to add new verbs to web parts, like, Verify. Specifying whether a control is a provider or cusumer is done in the cla

70-562 Web Parts

After the success of design move in visual studio with dragging and dropping controls to design them, Microsoft brought this to the end user in sharepoint and then to all web applications with Web Parts. The idea is that users should be able to personalize the page they visit often and tinker to their hearts content. In this section we will see web parts as a sever control and techniques to make web parts effective. Authorized users can make site wide changes(shared data) and individual users can override them. The information is stored in the same database as the membership data, simply in the App_Data directory by default. In the upper right corner a small arrow can allow to minize the Web Part. the webParts element in the web.config file contains the security that indicates which users have priviledged access. Design and Edit mode : are the two modes a web part page can be in. Design is rearange and edit allows to modify behaviors by setting properties. Users in edi

70-562 Anonymous Profiles

 Anonymous profiles How does asp.net track anonymous users and store their profiles? Setting anonymousIdentification to true in the web.config, asp.net stores a guid for each anonymous user, allowing concurent anymous users to log in, and those should be cleaned in your databse every once in a while. For each property that is available to anonymous user, the allowAnonymous must be set to true. How to carry the information of a anonymous user when he carries a new profile. The magic happens in the global.asax, and create an event handler, Profile_MigrateAnonymous, by getting the anonymous id from it's event args, get the profile with this id, we check one of properties to make sure we dont overwrite an existing profile. To store in other than SQL you need to create a custom profile provider that inherits from System.Web.Profile.ProfileProvider. For example an xml file could be used to store. There is a provider toolkit availble on microsoft sites that makes creating cu

70-562 Intro to profiles

Intro To Profiles The membership API has it's own databse, and should not be mixed with other data. The bride with business data like the users credit card or company, maybe the profile can be usefull. Using a session variable to contain the last visit is not ideal, the variable can be mistyped. While the Profile.LastVisitedDate; includes this information. In the system.web, create a profile element and properties element. They will be added with an add element name and type attribute. After having created those, to access the Profile object from code, it's required to compile first for the web.config to take effect. The information is stored permanently. By default the data is stored in App_Data\aspnetdb.mdf. To store in a different db, a custom provider needs to be writen. The App_Data sometimes needs to be refreshed in order to show it's content. Double clicking it opens the server explorer on this db. You have lots of options, you can use Session, Cache

70-562 Writting XMl

If your goal is to generate serialized XML, The XmlTextWRiter would allow to create using brute force and it would take care of quotes and angle brackets. Only the xmldocuement onect can creat new nodes. To start from scratch, the long way is to call 3 predefined methods of the docuement object, CreateProcessingInstruction to create an XmlProcessingInscrution, then append it to the doc. Then Create an XMLComment using the CreateComment method of the docuement, then append it. The add the first XMLElement using the doc.CreateElement. If it failed the expception can be used to read the line number, message, and line position.

70-562 Reading XML

System.Xml.XmlDocument provides methods required to access xml content directly. We will cover reading tree-based xml, in-memory. It is also possible to work with XMLReader/XMLWRitter classes. THE XML Document Object Model is Tree-Based, in-memory cache, represented by the XmlDocument class. Non-cached, forward-only, read-only accesss is done using XMLReader/XmlWriter classes. It is also possible use Linq to XML to work with XML. The XmlDocument class loads XML as a tree, that has a root node and mutliple child nodes. Each Xml element corresponds to one or more nodes in the tree. Each node except for the root node has a parent node. All the data is loaded in memory, provides random access to individual nodes and can search for any node at will. Three based structure represents the xml infoset. This is the data stored in teh serieallized XML format. The API doesn't care about angle brackets and quotes, just data and it's relationship. There is a difference betwe

70-562 ListView and Pager

One of the advantages of the listview over the gridview is the templates and integrates well with css. Lets say you want to display list items in a inline layout in flow mode with left and top margin of 10px, this defined by a css class. Now lets create this using a listview so we can have data in it, and still apply the style from the previous css class. To auto format the xml of the aspx, ctrl+a, ctrl+k, ctrl+f. To add sorting to the listview, add a button with CommandName set to Sort, CommandArgument set to sort expression. Add paging if there is too much data, the IPageableItemContainer interface is already implemented by the listview. You can go in the smart tag and click the Configure list view link, and check the box for paging. If you want to put the pager outside the listview, set the property that allows the pager to point to what it's paging(the ListView control), PageControlID is the name of the attribute. You can have mutliple pagers, get some of them to dis

70-562 ListView

List View is a versatile control that allows to work with a signle control rather than many smaller controls. Provides rich sorting, deleting, editing, it is one of the most flexible grid control. Design view can fill the ListView with fake data to give an overview. In designer, the configure list view link might not show, (currently a bug), to fix configure the datasource but cancel then click configure datasource again and this time click finish and the Cofnoigure ListView link will show up in the smarttag. You can choose templates, LayoutTemplate is crucial, ItemTemplate(a row is part of a table, in a list view they are called items since they don't have to correspond to a table row), AlternatingItemTemplate, ItemSeparatorTemplate, SelectedItem, EmptyItemTemplate, EditItemTemplate, InsertItemTemplate allows to customize what the user will be presented when creating an item, EmptyDataTemplate. The itemPlaceHolder and the groupPlaceHolder are important elements as the will b

70-562 Web Services

A single server can't handle it all, connecting many computers together is far more powerfull than in a mainframe. In distributed applications, One cluster may be for the database, then a group of servers might function as a specialized application server, and still others handle user interface and security logic. All those computers need to communicate together. There are 4 broad WS technollgies, 1) Universal access: The tcp/ip is most common protocol 2) Standard data representation: xml is intended to transport data. And XPath that allows to xtract a subset of data easily, while http was made for to transport markup(html). While 3) Standard message format: SOAP stadardizes the message envelope 4) Service description format: WSDL web services description language The web service has to derive from System.Webh.Services.WEbService and contain the WebSErvice and WebSErviceBinding attribute. The WebMethod attribute is added to each methods exposed to the outside world. T

Silverlight

SilverLight is a subset of WPF, and also a superSet of WPF, whatever that means. It is a cross-browser, cross-platform plug-in. Create rich interactive applications for the web(RIAs). Originaly invented as competitor to flash. Lightweight runtime (under 5MB) Based on XAML NIce interactive rich experience, like javascript runs on the client side, in the case of silverlight, there is a run time running on the client side. With content delivered to the browser. Why Silverlight, leverages the .net framewor, rich experience. Provides video, vector graphics, persepective 3d, feature like deep zoom. +100 controls. Allows 1080p true HD., or H.264 (MP4) WMV with smooth stream ing. They can also be ran on the desktop wihtout any current connectivity. CLR support was introled in silverlight 2 support. Silverlight 3 added navigation, validation modal windows, layout. Silverlight 4 adds, printing, new controls including datagrikd, enhanced data binding including drag and drop. Add

70-562 Repeater and DataList controls

The ListView includes the Repeater and DataList. In complexity Repeater->DataList->ListView->DataGrid Dalalist: HeaderTemplate, ItemTemplate, AlternatingTemplate, SelectedItemTemplate, SeperatorTemplate, EditItem, FooterTemplate. The repeater control has no templates, so you add a header, item and footer template, each has to be configured with html, and css. The item template can contain a listitem(li), can put a declarative databinding that will contain an expression To bind to data, you must indicate teh exact field, the repeateur loops through all the rows provided by the datasource. The EVal method requires the datafield and the formating with a {0}. CommandName, and CommandArgument is used to set a different hyperlink for each item, that will then be handled in the event handler. DataList: The repeater just layout items from a datasource, the datalist has more features than the repeater, and less compared to a datagrid. Adds style, can select, edit, delete,

70-562 Microsoft AJAX control toolkit, Client-Side AJAX

The toolkit is opensource on the Codeplex Open Source project community site. At last count the toolkit contained 40 controls, and control extenders providing controls for dynamic website. The extenders are not full interface controls, but instead modify the behaviors of existing controls. There is not much async calls to the server, instead, it makes use of the MS AJAX Control Library the client side Javascript API that provides AJAX, to perform client side work. Sometime pages have alot of big section, making it a big page even for a wide sceen, if sections are not dependant on each other, the Accordion control is the solution to save space. The accordion provides expandable panels to save space, easier than writting the Javascript. Like any HTML element, the content of the AccordionPane can be styled. The AccordionPane is a custom control and can be added from the toolbox, modified from the aspx page. The AutoSize property can constrain the vertical size. The Limit se

70-562 Server-side AJAX

Server-Side AJAX is conceptualy simialr to normal asp.net full page processing. But instead of posting data back to the server and recieving an entire page in response, the  server returns a small chunck of HTML to update only a small section of the page, code in teh client browser takes care of updating for that section of the page, without redering the whole page, with less data passed between client and server. One nice thing about Microsoft's implementation of server side AJAX, unless you're doing something unusual, you dont need to know javascript or even know AJAX mechanism that cause AJAX request and response. This makes it easy to both create new web pages or retro fit existing ones to make them more responsive to user without writing a single line of Javascript code. There is a cost for this simplicity of course, every action on the client requires a round trip to the server, admitedly it's a more lightweight request than response, but it has much of the same p

70-562 AJAX

Compared to a desktop application, ASP.Net web applications are too dependent on the web server to create and build pages, added to network overhead, and a waste to re-generate a page for a small change, and it causes the page to flash. Client side scripting and AJAX allows the browser to work more. The client use can become frustrated by too many postbacks that can ruin the web experience for the user. AJAX also frees the server of having to regenerate pages. AJAX can do async calls to update portions of the page. The server doesnt have the overhead, and resulting delay of creating a complex page from scratch. With the arrival of AJAX, th etradition full-page processing can sometimes be replaced by AJAX partial-page processing.  The intial full page comes from the server then can use either full or partial-page processing. The way the server and browser processes an AJAX request is different than a tradtionnal HTTP Post. AJAX uses a Javascript, and a client side ASP.Net AJA

70-562 Data Caching

If the data is control by other services, it can be delicate to cache. Data can be cached and automaticaly updated when sql changes. It depends on sql 2005 and later Query Notification, previous versions relies on database triggers. ASP.Net can poll changes to the table, and sql can be configureged with Aspnet_regsql tool. The the target table has to be configured with the aspnet_regsql tool, a changed id is added to the table. Polls based caching is very reliable and easy to configure. Datasource controls have properties to enable caching, this also requires the table to be configured with the aspreg tool. Table caching caches only tables, not the page. Can also be based on rows, to change only when specific row changes, for example products of a certain category. It will update only when this row is changed, this is custom caching rules. QueryNotification caching doesnt require to configure sql. The service broker has to be enabled. Alter database northwind set s

70-562 Advanced Caching

Advanced Caching can create complex caching policies. SqlCacheDependency, DataSource control support(gets data only when expired), Post Cache Substition.And mutliple caching configuration via web.config, like caching profiles, with different cache per folder. If using the Asp.net development server in visual studio, caching can give weird results, in this case, start with a fresh session of the server by rightlicking it in the taskbar and hit stop to reset it. The output cache being available programmaticaly, it's possible to change it at runtime. And the caching HttpCachePolicy is also accesible for controling cache at run time. Response.Cache.SetCAchebility(...). Objects and code are added with Insert and Add method of the cache object, it just neesd to be casted, just like using an application variable. The main requirement is to check that it exists first incase the cahe expired. Add wont replace if it exists, and has a return value, while insert will always replace

70-562 Page Fragments

ASP.Net can cache page fragments, caching page requests to content that doesn't change can increase speed and reduce flashing during postbacks. By caching these sections, you can improve the troughput of the site. The way to cache sections of the page is to create user controls that contain the page fragments, the user controls can contain the same caching directives and caching code that are available for any Asp.Net page. Since the user control is always the same, the VaryByParam is set to none for the OutputCache directive of the aspx page. If the user control needs to VaryByParam, it can be set to VaryByParam="nameOfTheUserControl$nameOfTheServerControl". Since the control can be used on different page, the name of the control changes, which is why VaryByControl can be used in user controls to replace VaryByParam, use the name of the server control without the name of the usercontrol. If mutliple instances of the same user control are used in a page, the

70-562 Caching

Caching is to improve performance, caching pages and framents, and also data can dramatically improve the performance of a website. The only cachin in classic asp were variables, and it's usefullness was very limited. Now, in asp.net, there are mutliple type of caching. 1)Caching pages and user controls by the OutputCache directive, for how long and how many version are kept 2)Caching from code, more control than by page, but only used if it needs to change at run time. 3)Caching data, data storage is always in process, dataset, arrays, custom objects, similar to store in sessions state, but application wide, can determine how long the object in cache, and the cache can be flushed when the memory gets low. Retriving a page from the cache is much faster than regenrating the page. Static pages need to be cached as they dont change, for pages that do change, mutliple versions can be kept. As a simple tutorial, output the page directive and it's duration in seconds

70-562 Custom Controls

Custom Controls A custom control will be an assembly, therefore to start a new custom control, add a new project, Web->Asp.Net Server Control. The Text property by default is set to get a value from the ViewState , if null return the control's ID, if not, the string found in the ViewState. The next method provided by default when creating a user control is the REnderContents method that takes HTMLTextWriter and will write that Text to it's stream, which is the HTML stream. If a server control has the attributes, after being built, VS can see it in the solution and makes it available in the toolbox. The class representing the Custom Control will inherit from WebControl class, and RenderContents method is one of it's base methods. To write explicit HTML tags, use the WriteFullBeginTag(HTMLTextWriterTag.) method, the 'full' methods allow attributes. The major goal of a web custom control is to 'spit' HTML. If the control will handle postback

70-562 User Controls

Copying and pasting a group of control might be ok if they have minimal business logic behind, but if the control has considerable business logic behind it, it might be better to group them in a user control and copy just this one control on each page. A user control is a like a little page that you embed within other page, they are inteded for use within a single site, so it's ok to put site specific business logic in them. Custom controls are, like the ones in the toolbox, created from scrach and inherit from a base class, and the result is an assembly containing the control. User controls are often used for header, footers, and side panels. To add a user control you can drag and drop it in the page in design mode, or add in the aspx page by adding a register directive that has a src, tagname, tagprefix. And will be referenced by it's prefix:tagname and an id specific to the instance of the control. An example,a user control can be as simple as a drop down list th

70-562 Health Monitoring

Programmatic access to trace output from System.Web.TraceContext, using the TraceFinished event. TraceContextRecord encapsulates a trace message, it can be put in CAtegory, ErrorInfo gets an exception, IsWarning indicates if it's a warning. One has to attach en avent heandler to the Trace.TraceFinihsed += new TraceContextEventHandler(ONTraceFinished); This handler recieves within it's event args a collection TraceContextRecord. It can be used to log events on a sql server database. First requires to run Aspnet_regsql.exe utility to create the db that will be used by listeners, Confiure SQL server for application Services, pick an instance to host on, you get a summary, and it will take care of confuring the database, now it's set to save health info on this db. In the web.config, a healthMonitoring element needs to be added within the system.web eleement, by specifiying the provider, it's type, connection string, and then rules for which events to log, and

70-562 Listeners

Listeners System.Diagnostics.Trace is collectted by TraceListeners. A TraceListener is an object that receives trace outpout and writes it out. Writes to a file, asp.net, databse, external monitoring system. When a trace listener is create it is added to the Trace.Listeners collection which lets the listener recieve all the output including asp.net. All listeners are derived from the TraceListener abstract class which has a variety of methods. The tracelisteners are the same but differ by the type of media they are writting to. The same data can go to mulitple listeners. Fail: writes including the call stack Write: Outputs the text WRiteLine: Outputes with a craiage returen Flush: Flushes the output buffer to the traget media Close: Closes the uput stream in order to stop recieving the debugging and traing data. DefaultTraceListener: ouputs to the output window, included in all the tracelisteners, others should be use to write elsewere TextWriterTraceListener: Writes to

70-562 Tracing

Tracing can be enabled from the page directive, programmatically or from the web.config. This will append the trace info to the bottom of the page. There several tables of grouped trace information: Life cycle events, controls used by page, sessions state, cookies, http reuqest headers, server variables. SessionID, Time spent in each event, and check that the events are executing in the expected order. The control tree give a hierarchy of the controls in the page, and how much the control is using in the viewstate, and render by tells how much room the control uses on the page. See cookie information. And can see the Header information incase you do any kind of header manipulation. Also see query string collection. Also see the server variables passed back and forth between the server and the client application, logon user, remote user. Enable tracing when not in production, (remember to disable it when building a release... that and the debug= true setting get forg