jump to navigation

FindControl: Recursive DFS, BFS, and Leaf to Root Search with Pruning October 24, 2011

Posted by codinglifestyle in ASP.NET, C#, CodeProject, jQuery.
Tags: , , , , , , ,
add a comment

I have nefarious reason for posting this. It’s a prerequisite for another post I want to do on control mapping within javascript when you have one control which affects another and there’s no good spaghetti-less way to hook them together. But first, I need to talk about my nifty FindControl extensions. Whether you turn this in to an extension method or just place it in your page’s base class, you may find these handy.

We’ve all used FindControl and realized it’s a pretty lazy function that only searches its direct children and not the full control hierarchy. Let’s step back and consider what we’re searching before jumping to the code. What is the control hierarchy? It is a tree data structure whose root node is Page. The most common recursive FindControl extension starts at Page or a given parent node and performs a depth-first traversal over all the child nodes.

Depth-first search
Search order: a-b-d-h-e-i-j-c-f-k-g

/// <summary>
/// Recurse through the controls collection checking for the id
/// </summary>
/// <param name="control">The control we're checking</param>
/// <param name="id">The id to find</param>
/// <returns>The control, if found, or null</returns>
public static Control FindControlEx(this Control control, string id)
{
    //Check if this is the control we're looking for
    if (control.ID == id)
        return control;

    //Recurse through the child controls
    Control c = null;
    for (int i = 0; i < control.Controls.Count && c == null; i++)
        c = FindControlEx((Control)control.Controls[i], id);

    return c;
}

You will find many examples of the above code on the net. This is the “good enough” algorithm of choice. If you have ever wondered about it’s efficiency, read on. Close you’re eyes and picture the complexity of the seemingly innocent form… how every table begets rows begets cells begets the controls within the cell and so forth. Before long you realize there can be quite a complex control heirarchy, sometimes quite deep, even in a relatively simple page.

Now imagine a page with several top-level composite controls, some of them rendering deep control heirachies (like tables). As the designer of the page you have inside knowledge about the layout and structure of the controls contained within. Therefore, you can pick the best method of searching that data structure. Looking at the diagram above and imagine the b-branch was much more complex and deep. Now say what we’re trying to find is g. With depth-first you would have to search the entiretly of the b-branch before moving on to the c-branch and ultimately finding the control in g. For this scenario, a breadth-first search would make more sense as we won’t waste time searching a complex and potentially deep branch when we know the control is close to our starting point, the root.

Breadth-first search

Search order: a-b-c-d-e-f-g-h-i-j-k

/// <summary>
/// Finds the control via a breadth first search.
/// </summary>
/// <param name="control">The control we're checking</param>
/// <param name="id">The id to find</param>
/// <returns>If found, the control.  Otherwise null</returns>
public static Control FindControlBFS(this Control control, string id)
{
    Queue<Control> queue = new Queue<Control>();
    //Enqueue the root control            
    queue.Enqueue(control);

    while (queue.Count > 0)
    {
        //Dequeue the next control to test
        Control ctrl = queue.Dequeue();
        foreach (Control child in ctrl.Controls)
        {
            //Check if this is the control we're looking for
            if (child.ID == id)
                return child;
            //Place the child control on in the queue
            queue.Enqueue(child);
        }
    }

    return null;
}

Recently I had a scenario where I needed to link 2 controls together that coexisted in the ItemTemplate of a repeater. The controls existed in separate composite controls.

In this example I need to get _TexBoxPerformAction’s ClientID to enable/disable it via _ChechBoxEnable. Depending on the size of the data the repeater is bound to there may be hundreds of instances of the repeater’s ItemTemplate. How do I guarantee I get the right one? The above top-down FindControl algorithms would return he first match of _TextBoxPerformAction, not necessarily the right one. To solve this predicament, we need a bottom-up approach to find the control closest to us. By working our way up the control hierarchy we should be able to find the textbox within the same ItemTemplate instance guaranteeing we have the right one. The problem is, as we work our way up we will be repeatedly searching an increasingly large branch we’ve already seen. We need to prune the child branch we’ve already seen so we don’t search it over and over again as we work our way up.

To start we are in node 5 and need to get to node 1 to find our control. We recursively search node 5 which yields no results.

Next we look at node 5’s parent. We’ve already searched node 5, so we will prune it. Now recursively search node 4, which includes node 3, yielding no results.

Next we look at node 4’s parent. We have already searched node 4 and its children so we prune it.

Last we recursively search node 2, which includes node 1, yielding a result!

So here we can see that pruning saved us searching an entire branch repeatedly. And the best part is we only need to keep track of one id to prune.

/// <summary>
/// Finds the control from the leaf node to root node.
/// </summary>
/// <param name="ctrlSource">The control we're checking</param>
/// <param name="id">The id to find</param>
/// <returns>If found, the control.  Otherwise null</returns>
public static Control FindControlLeafToRoot(this Control ctrlSource, string id)
{
    Control ctrlParent = ctrlSource.Parent;
    Control ctrlTarget = null;
    string pruneId = null;

    while (ctrlParent != null &&
           ctrlTarget == null)
    {
        ctrlTarget = FindControl(ctrlParent, id, pruneId);
        pruneId = ctrlParent.ClientID;
        ctrlParent = ctrlParent.Parent;
    }
    return ctrlTarget;
}

/// <summary>
/// Recurse through the controls collection checking for the id
/// </summary>
/// <param name="control">The control we're checking</param>
/// <param name="id">The id to find</param>
/// <param name="pruneClientID">The client ID to prune from the search.</param>
/// <returns>If found, the control.  Otherwise null</returns>
public static Control FindControlEx(this Control control, string id, string pruneClientID)
{
    //Check if this is the control we're looking for
    if (control.ID == id)
        return control;

    //Recurse through the child controls
    Control c = null;
    for (int i = 0; i < control.Controls.Count && c == null; i++)
    {
        if (control.Controls[i].ClientID != pruneClientID)
            c = FindControlEx((Control)control.Controls[i], id, pruneClientID);
    }

    return c;
}

Now we have an efficient algorithm for searching leaf to root without wasting cycles searching the child branch we’ve come from. All this puts me in mind jQuery’s powerful selection capabilities. I’ve never dreamed up a reason for it yet, but searching for a collection of controls would be easy to implement and following jQuery’s lead we could extend the above to search for far more than just an ID.

Advertisement

Pass a Name Value Pair Collection to JavaScript August 8, 2011

Posted by codinglifestyle in ASP.NET, CodeProject, Javascript.
Tags: , ,
1 comment so far

In my crusade against in-line code I am endevouring to clean up the script hell in my current project. My javascript is littered these types of statements:

var hid = <%=hidSelectedItems.ClientId%>;
var msg = <%=GetResourceString('lblTooManyItems')%>;

Part of the cleanup is to minimize script on the page and instead use a separate .js file. This encourages me to write static functions which take in ids and resources as parameters, allows for easier script debugging, and removes all in-line code making maintenance or future refactoring easier.

While moving code to a proper .js file is nice there are times we might miss the in-line goodness. Never fear, we can build a JavaScript object containing properties for anything we might need with ease. This equates to passing a name/value pair collection to the JavaScript from the code behind. Take a look at this example:

    ScriptOptions options = new ScriptOptions();
    options.Add("ok", GetResourceString("btnOK"));
    options.Add("oksave", GetResourceString("btnOkSave"));
    options.Add("cancel", GetResourceString("btnCancel"));
    options.Add("viewTitle", GetResourceString("lblAddressEditorView"));
    options.Add("editTitle", GetResourceString("lblAddressEditorEdit"));
    options.Add("createTitle", GetResourceString("lblAddressEditorCreate"));
    options.RegisterOptionsScript(this, "_OptionsAddressEditorResources");

Here we’re using the ScriptOptions class to create an object called _OptionsAddressEditorResources we can access in our script. Now let’s see these options in use:

function fnAddressEditDialog(address, args) {
    //Define the buttons and events
    var buttonList = {};
    buttonList[_OptionsAddressEditorResources.ok]     = function() { return fnAddressEditOnOk(jQuery(this), args); };
    buttonList[_OptionsAddressEditorResources.oksave] = function() { return fnAddressEditOnOkSave(jQuery(this), args); };
    buttonList[_OptionsAddressEditorResources.cancel] = function() { jQuery(this).dialog("close"); };

    //Display the dialog
    jQuery("#addressEditorDialog").dialog({
        title: _OptionsAddressEditorResources.editTitle,
        modal: true,
        width: 535,
        resizable: false,
        buttons: buttonList
    });
}

Above we see the jQuery dialog using the resources contained within the _OptionsAddressEditorResources object.

So this seems simple but pretty powerful. Below is the ScriptOptions class which simply extends a Dictionary and writes out the script creating a named global object. Good luck cleaning up your script hell. Hopefully this will help.

    /// <summary>
    /// Class for generating javascript option arrays
    /// </summary>
    public class ScriptOptions : Dictionary<string, string>
    {
        /// <summary>
        /// Adds the control id to the options script
        /// </summary>
        /// <param name="control">The control.</param>
        public void AddControlId(WebControl control)
        {
            this.Add(control.ID, control.ClientID);
        }

        /// <summary>
        /// Registers all the key/values as an options script for access in the client.
        /// </summary>
        /// <param name="page">The page</param>
        /// <param name="optionsName">Name of the options object</param>
        public void RegisterOptionsScript(Page page, string optionsName)
        {
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), optionsName))
            {
                StringBuilder script = new StringBuilder(string.Format("var {0} = new Object();", optionsName));
                this.Keys.ToList().ForEach(key => script.Append(string.Format("{0}.{1}='{2}';", optionsName, key, this[key])));
                page.ClientScript.RegisterStartupScript(page.GetType(), optionsName, script.ToString(), true);
            } 
        }
    }

CustomValidator and the ValidationSummary Control April 26, 2010

Posted by codinglifestyle in ASP.NET, jQuery, Uncategorized.
Tags: ,
3 comments

ASP.NET validators can be tricky at times.  What they actually do isn’t particularly hard, but we have all had issues with them or quickly find their limits when they don’t meet our requirements.  The CustomValidator control is very useful for validating outside the constraints of the pre-defined validators: required fields, regular expressions, and the like which all boil down to canned javascript validation.  CustomValidators are brilliant as you can write your own client-side functions and work within the ASP.NET validation framework.  They are also unique in that they allow for server-side validation via an event.

However, there is a common pitfall when used in combination with the ValidationSummary control.  Normally, I would avoid using ShowMessageBox option as I believe pop-ups are evil.  However, where I work this is the norm and the problem is the CustomValidator’s error isn’t represented in the summary popup. 

When the ASP.NET validators don’t live up to our requirements we really must not be afraid to poke around Microsoft’s validation javascript.  It contains most of the answers to the questions you read about on the net (to do with ASP.NET validation… it isn’t the new Bible/42).  Quickly we identify the function responsible for showing the pop-up.  ValidationSummaryOnSubmit sounds good, but as the name implies it occurs only on submit.  However my validator failed after submit and now I need the popup to show what errors occurred.  I could see from the script window that this function could be called but programmatically registering the startup script wasn’t working.  So I used a jQuery trick to call the function after the DOM had loaded.

So drumroll please, there is the information you want to copy and paste in to your CustomValidator event:

if (!args.IsValid)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), “key”, “$(function() { ValidationSummaryOnSubmit(‘MyOptionalValidationGroup’)});”, true);
}

Now my server-side validation will bring up the ValidationSummary messagebox.

Cascading Dropdown Lists with jQuery (parent / child select options) March 9, 2009

Posted by codinglifestyle in ASP.NET, C#, CodeProject, Javascript, jQuery.
Tags: , , , , , , , ,
add a comment

 

Recently I was tasked with merging 3 similar screens in to one.  I took stock of the commonalities and decided a Category and Subcategory dropdown list would suffice.   As you’d expect the contents of the Subcategory dropdown depend on the selected Category.  Obviously I wanted to avoid postbacks so I first looked to the Ajax Control Toolkit’s CascadingDropDown extender to link the parent to the child.  In my case, there were only a dozen subcategories so a webservice seemed like overkill.

After attending Tech-Ed 2008 and seeing Microsoft throwing its weight behind jQuery I decided to have a look.  So what follows is my first foray in to jQuery and I’m quite pleased with the results.

First, we define an enum in the codebehind which can be used for bitwise operations.

public enum Category

{

Invoice     = 1,

Order       = 2,

Shipment    = 4   //Fourth item would be 8, then 16, 32, …

}

Next I wanted to be able to use the enum to specify the Category (only specifying one) and Subcategory items (bitwise OR any combination).

_DropDownCategory.Items.Add(GenerateListItem(“Orders”, Category.Order, false));

_DropDownCategory.Items.Add(GenerateListItem(“Invoices”, Category.Invoice, false));

_DropDownCategory.Items.Add(GenerateListItem(“Shipments”, Category.Shipment, false));

_DropDownSubcategory.Items.Add(GenerateListItem(“Purchase Orders”, Category.Invoice | Category.Order | Category.Shipment, false));

_DropDownSubcategory.Items.Add(GenerateListItem(“Quote Number”, Category.Order, false));

_DropDownSubcategory.Items.Add(GenerateListItem(“Customer Project Number”, Category.Shipment, true));

The enum was converted to a number and added as a custom attribute to the new list item in GenerateListItem():

li.Attributes.Add(“Category”, ((int)eCat).ToString());

Enter jQuery, first we’re going to need to keep a copy of all the available Subcategory items.  Each time we change the Category we will be showing a subset of this array which we must keep separate in memory.

var optSubCat = null;

$(function() {

//Make a copy in memory of all the subcat options

optSubCat = $(“#_DropDownSubcategory”).children().clone();

//Default subcat to “Orders”

ddSubcategoryUpdate(2);

});

Then we need an event to fire when the Category is changed.

$(function() {

$(“#_DropDownCategory”)

.bind(“change”, function(event) {

var eCat = this[this.selectedIndex].attributes(“Category”).value;

ddSubcategoryUpdate(eCat);

});

});

Note how jQuery allows us to wire up DOM events after the fact to our .NET controls.  Here we add an onchange event dynamically rather than injecting this via the codebehind which forces us to put javascript code in the wrong place.  All we’re doing is pulling the value of the enum from the selected Category and then passing it to a function which will update the Subcategory items.

function ddSubcategoryUpdate(eCat) {

//Remove all items from drop down

$(“#_DropDownSubcategory”).children().remove();

//For each subcat item: test if it belongs in eCat, if so add it

$(optSubCat).each(function() {

if (($(this).attr(“Category”) & eCat) > 0) {

$(“#_DropDownSubcategory”).append($(this).clone()[0]);

}

});

}

And finally, in the if statement we see we test each Subcategory item previously saved in memory to see if it matches the enum value of the Category.

What we’ve ended up with is a very powerful yet simple mechanism for cascading dropdowns using enums in our codebehind.  It’s easier to wire up than what the Ajax Control Toolkit provides, its all script so the UI looks good, and while this could have been done in straight javascript it demonstrates the power and simplicity of the jQuery library.

Tech-ed 2008 November 17, 2008

Posted by codinglifestyle in ASP.NET, C#, IIS, jQuery, Parallelism, Security, SharePoint, Visual Studio 2010.
Tags: , , , , , , , , , , , , , , , , ,
3 comments

Last week I had the opportunity to attend TechEd 2008.  I have compiled a set of notes from the keynote and sessions I attended below.  Most of the information presented at these conferences is not really instructive for addressing today’s problems but talks about future problems and the technologies we will use to address them.  There are some interesting technologies coming down the pipe in the not so distant future and these notes may provide you with enough information to google more information about the topics which interest you.

 

I skipped a lot of older information about the VS2008 release, C# v3.0, and Linq which can all be found here.

 

Keynote

·         Testing Activity Center application

o   Pillar: No more no-repro

o   Generate test cases that tester can click off

o   Bug recording including video, call stack, system information

o   Generate a bug integrated in to Team System

§  Can start up debugger and reproduce tester’s scenario

§  Captures line of code, call stack, everything

·         Code buffering

o   Method shows history of changes (graphically too)

o   Integrates SCC versions in to IDE

·         MVC design pattern

o   Model                   =              data

o   View                     =              web page / UI

o   Controller             =              logic

·         SharePoint Integration

o   Server explorer includes lists, ect

o   Webpart template automatically contains ascx control for design support

o   SharePoint LINQ

o   List Event wizard

§  Auto-generate XML for site def??

·         Performance Profiler

o   Pillar: Leverage multi-core systems

o   See which method is taking time and core utilization

§  Graphically shows core usage including drill down

·         Will help with concurrency, deadlock debugging, ect

VS2008 Service Pack 1 Overview

·         ADO.NET Entity Framework release

o   Very similar to Linq To SQL

o   Generate data model

§  conceptual model static (actual db) model

o   Data Services

§  Data centric abstraction over web services (WFC)

§  Exposes and takes IQueryable so datasets very easy to work with in a LINQ like way

§  Routing lets URI act like a Linq query

·         http://Root/my.svc/Customers/35/FirstName

o   Dynamic Data

§  Given a data model will create aspx accessibility to defined objects

·         Security: all objects off by default but can dynamically access entire data model

·         Allow CRUD access via ASPX templates applied to all objects

o   CRUD = create, read, update, delete

o   Can create individual page for certain object

o   Can customize template to affect all objects

·         Ajax / other enhancements

o   Ajax

§  History Points

·         Addresses problem that users lose ability to hit back button

§  Script combining

·         To improve performance allows to dynamically combine js libraries

o   Improves javascript intellisense

o   Improves web designer performance (bugs/regressions addressed)

C# v4.0

·         History

o   V1 – Managed Code big emphasis

o   V2 – Generics; finished the language

o   V3 – LINQ

·         Pillars

o   Declarative programming: we are moving from “what?” to “how?”

§  LINQ is an example of this

o   Concurrency: Some of the parallelism extensions we will be getting

o   Co-Evolution: VB and C# will more closely evolve together vs. Features hitting languages at different times

o   Static vs. Dynamic Languages: aren’t necessarily a dichotomy

§  Static: C++, C#, VB – anything compiles

§  Dynamic: IronRuby, IronPython, Javascript

·         New keyword: dynamic

o   Call any method of a dynamic object and the compiler won’t complain

§  No intellisense possible

§  Will call during runtime

§  i.e.

·         dynamic calc = GetCalculator();

·         calc.Add(10,20);   //We know nothing about calc object

§  Lots of power to  be explored here

o   Optional Parameters

§  Like in C++ (and apparently VB)

§  Named parameters

·         Can also skip optional parameters

·         Public StreamReader OpenTextFile(string sFile, bool bReadOnly = true, int nBufferSize = 1024);

·         sr = OpenTextFile(“foo.txt”, buffersize:4096);

o   COM Interoperability

§  No more “ref dummy”!

·         Will get: doc.SaveAs(“Test.docx”);  //Winword saveas

·         Versus:   doc.SaveAs(“Test.docx”, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy);

§  Automatic dynamic mapping so less unnecessary casting

§  Interop type embedding

·         No more bringing in PIA

o   Safe Co and Contra-variance

o   Compiler as a service

§  Compiler black box opened up to be used and extended

§  In example created a command window with C#> prompt

·         Was able to define variables, functions, ect like in IronPython

Ajax v4.0

·         Introduction

o   Web app definition

§  Web site is a static collection of pages (such a BBC news)

§  Web application is something which replaces a traditional windows app

o    Traditional Server-Side ASP.NET vs. AJAX

§  Pros

·         Safe: Guaranteed browser compatibility

·         Powerful: All the power of a .NET language in code-behind

§  Cons

·         Response: User must wait for postback

·         Performance: All page content rendered for each interaction

·         Update Panels: Use Wisely

o   An update panel uses sneaky postbacks so while it looks better it is still as bad as traditional server side asp.net

o   Don’t wrap an entire page in an update panel

§  Wrap the smallest region required

§  Use triggers to set what controls will fire a sneaky postback

o   Turn ViewState OFF

§  Down the line this will not be on by default

§  We often send a lot of unnecessary information over the wire in ViewState

·         Ajax Calls (Services)

o   Consider using an Ajax control to update data as needed

o   Calling a web service from javascript is not considered dangerous or bad practice

o   Example

§  Have a datagrid with postback bound to a dropdown list.  Instead of a postback on ddlist use Ajax call

·         Instead of a datagrid use a straight html table

·         Via script we make a call to the web service

·         Use stringbuilder to format return to build up new rows

§  Kinda horrible!  Too much mixing of mark-up and script

·         Client Side Controls

o   Clean way of separating Ajax related script from the web page

o   Allows you to bind to Ajax calls in a template way

o   Example

§  From above we now separate js in to a client side control which is now cleanly referenced on our web page

·         Declarative Client Side Controls

o   “X” in XML stands for extensible; but not often extended!

o   Use XML to bring in namespaces like System and DataView

o   Can define a datagrid purely in html by adding attributes to the

tag in a table

·         Fail over

o   Problem with Ajax is not it is not always supported for reasons of accessibility, search engines, or disabled javascript (mobile devices)

o   Does require double implementation of Ajax and traditional solution but it is an option when needed

·         New features in SP1

o   Back button support!

§  As of VS2008 SP1 Ajax now has back button support

§  ScriptManager property EnableHistory=true and onNavigate event

§  AddHistoryPoint(key,value);

§  AddHistoryPoint(key,value,“Text seen in back button history instead of url”)

§  Process

·         Enable history and add event

·         When page event fires store value (index, ect) with AddHistoryPoint() in provided history cache

·         Use history event to set page back up with value retrieved from HistoryEventArgs

o   Example: set a form to display an item from the last selected index

o   Script Combining

§  Combine scripts for better performance

·         Example showed initial 15sec down to 3

§  Must tell ScriptManager all libraries and it will combine/compress them in to one server call

§  Must explicitly tell which scripts to use – even separate AJAX libraries

·         ScriptReferenceProfiler

o   Free webcontrols which will tell you all the libraries a page uses to make the above less painful

·         Factoids

o   Ajax initiative started to address Outlook Web Access (OWA); a good example of a web application

o   Script Manager is just a way to make sure the page includes the Ajax javascript libraries

§  Ajax script commands prefixed with $

·         $get(“my id”) looks to be handy

§  Can dynamically add event handlers in javascript using Ajax js library

·         $addHandler($get(“dropdownlist1”), “change”, myFunc);

·         Cool “must have” tools

o   Fiddler (www.fiddler2.com)

§  Shows response time, requests/responses, statistics

§  Tip: must place a dot in uri for Fiddler to capture localhost

·         http://localhost./default.aspx

o   Firebug – Firefox extension

 

Visual Studio Tips & Tricks

·         Ppt slides: http://code.msdn.microsoft.com/karenliuteched08

·         A lot more keyboard shortcuts: http://blogs.msdn.com/karenliu/

·         MS and partnered with DevExpress which is offering CodeRush Express for free

o   Required for a lot of the shortcuts and refactoring shown

·         Editing

o   Tools>Options>Editors>C#>Formatting>Set Other Spacing Options>Ignore Spaces

o   Keyboard tricks

§  Ctrl M,O               Toggle collapse all

§  Ctrl M,M              Expand region

§  F12                         Go to definition

§  Shift F12              Final all references

§  Ctrl Shift F8        Jump up Go to definition stack

§  Ctrl [ or ]              Jump between brackets

§  Ctrl Alt = or –      Smart Select

§  Ctrl .                      See smart tag (Implement a missing function, add using statements)

§   

o   Snippets

§  Lots of boilerplate goodies are there.  Really need to start using them

·         Ctor

§  Lots more smart HTML snippets coming

·         Debugging

o   Step OVER properties (r-click at breakpoint to check option)

o   Step into Specific – list of all functions down the chain you can jump to step in to

o   Tools

§  Tinyget – mini stress test

§  Adphang – get memory dump of w3wp

§  Windbg – open dump

·         Loadby SOS mscorwks

o   Need sos.dll for windbg to interpret stack

·         Deployment

o   Web.config transform for release, uat, ect

o   Powerful web deployment publishing options

§  Http, ftp, fpse

§  Msdeploypublish

·         New MS protocol for host supporting includes database, iis settings, access control lists (ACL), ect

·         Free test account at http://labs.discountasp.net/msdeploy

·         Other

o   www.VisualStudioGallery.com  – IDE extensions gallery

§  PowerCommands for VS08

o   VS2008 SDK application

§  Samples tab

·         Click to open sample straight in VS ready to go

Silverlight v2 101

·         XAML

o   A subset of WPF

o   Read-only designer view

§  Must edit  XAML by hand

§  Proper designer on the way

o   Can at least drag XAML text templates for many controls

·         Silverlight Controls

o   Greatly extended in Silverlight v2

§  Visit: www.silverlight.net for a demo

§  Most of what you’d expect in ASP.NET is available in Silverlight

o   Of Note

§  StackPanel

·         Previously on Canvas available requiring static x,y position designation

·         Operates like a panel with z-order

·         Security

o   Lives in a sandbox which can’t be extended for security reasons

o   There are ways to safe access local (isolated) storage, have a file dialog, sockets, cross domain access

·         Nifty

o   Can easily stream media content with one line of XAML

o   Can easily spin any element

Parallelism

·         Introduction

o   Sequential performance has plateaued

o   When we have 30 cores this may lead to dumber cores where we have a situation that today’s software runs slower on tomorrow’s hardware

o   Need  to start thinking about parallelism

§  Understand goals vs. usage

§  Measure existing performance.  VS2010 has tools to do this

§  Tuning Performance

·         Typically we start with sequential programming and add parallelism later

·         VS2010 has Profiler tool for tuning performance

§  Identify opportunities for parallelism

§  Use realistic datasets from the outset; not only on site with the customer

§  Parallelize only when necessary, but PLAN for it as it does introduce race conditions, non-determinism, timing issues, and a slew of other potential bugs

§  Once code is written for parallelism it can scale to any size automatically without any code changes

·         New technologies to help

o   Parallel API

§  Task

·         Like a thread but more optimal with a richer API

o   Has a value for threads which must return a value

§  Accessing the value automatically the same as Thread.Join or Task.Wait

§  ThreadPool

·         Just pass a delegate and let Microsoft worry about the hardware and how to best allocate and spawn threads

·         The ideal number of threads = number of cores

§  TimingBlock class makes it easy to test performance

·         No more: (end time – start time) / 1000

§  Decorate code w/ measurement blocks which appear in Profiler

o   Parallel Extensions

§  First class citizen in VS2010 (SDK today?)

§  Parallel.For and Parallel.ForEach

·         Still need to use critical sections around shared resources inside loop

·         Tip: Best practice is to parallelize the outer for loop only

·         Automatically adds measurement blocks to profiler to see results

§  Parallel.Invoke

§  Parallel extended IEnumerable to perform queries much faster

·         var q = from n in arr.AsParallel() where IsPrime(n) select n;

§  Task group

·         i.e.  For a quick sort instead of using a recursive algorithm use task groups to leverage parallelism with little change to code

o   Debugging – Parallel Stacks

§  Richer API to display tasks or threads and view a holistic mapping of their execution

o   Tools

§  Performance Wizard

·         CPU sampling, timing, ect

§  Profiler

·         Thread Blocking Analysis

o   Shows each thread’s parallel execution revealing race conditions affecting performance

§  Displays information about critical sections in tooltip

§  Can show dependencies for resources/locks across threads

jQuery

·         Ships in future VS but available now

·         Will not be changed by Microsoft but will be supported so we can use it with customers requiring support

·         VS intellisense available from jquery.com

·         Selectors

1.       $(“:text”)             tag          Select all text boxes

2.       $(.required)       class      Select any element with this class tag

3.       $(“#name”)        id            Select with this ID

·         Animations

1.       $(…).Show()

2.       $(…).Hide()

3.       $(…).slideDown()

4.       $(…).slideUp()

5.       $(…).fadeIn()

6.       $(…).fadeOut

7.       Massive open source libraries with hundreds more

§  Plugins.jquery.com

MVC 101

·         MVC

o   Controller (input) pushes to model and view

o   View (UI)

o   Model (logic)

·         An alternative, not replacement, to traditional web forms

·         Easier to test

o   No dependencies on request/response or viewstate as this everything is explicit and therefore testable

·         No server side controls (or designer support), postbacks, or events.

o   Think back to classic ASP

o   What is all this by-hand crap?  XAML (WPF and Silverlight) is only notepad as well

·         Action, instead of event, fires not in View but in the Controller. 

o   The View, aka aspx page, has no code behind.

·         In Controller can define a action and use wizard to create it’s view (web page)

·         ViewUserControl is a collection of html and inline asp which is reusable

IIS v7

·         Modules

o   ASP.NET managed HttpModules can be plugged in directly to IIS v7

§  No more unmanaged ISAPI filters

o   Modules can be managed within IIS v7 Manager

o   Configuration for modules can be exposed through manager

§  Customer WinForm configuration can also be exposed

·         Config

o   No more meta-base

§  All settings exists in central applicationHost.config – similar to a web.config

·         C:\windows\system32\inetsrv\config\schema

§  Can share IIS config for farm scenario

o   www.iis.net contains a configuration pack which allows you to show the config file within the IIS manager

Security

·         Concept of Security Development Lifecycle (SDL)

·         Threat Modelling – package available for formalized  security reviews

o   Talks about prioritizing risks

·         Multi-Pass Review Model

o   1 – Run fuzz and code analysis tools

o   2 – Look for ‘patterns’ in riskier code

o   3 – Deep review of riskiest code

·         Golden rule: What does the bad guy control?

o   What if he controls x & j (resources obtained from user, port, pipeline, compromised file system or database)

§  Char [] f = new char[3];

§  f[3] = 0;                                 bug

§  f[x] = 0;                                 can write a null to anywhere in memory

§  f[x] = y;                                 can write anything anywhere in memory

·         Accepted encryption

o   AES and SHAXXX only

o   Everything else is banned!  So long TripleDES

·         Do not use:  try { } catch (Exception ex) { }

o   Hides bugs and security flaws

o   Catch only exceptions we can handle

IE v8

·         Debug tools included out of the box

o   Hit F12

§  Debug javascript

§  Solve style issues

·         Compatibility – new rendering engine following widely-accepted standard

o   Get prepared for our apps look and feel to break

o   www.msdn.com/iecompat

o   Set meta-tag to tell IE8 to continue to render using v7 engine

·         Accelerators

o   Can develop own accelerators which can highlight a name and pass to a website as a parameter.  Employee staff directory, for example.

Cool Stuff

·         Ctrl-,

o   Quick search feature in 2010

·         Ctrl-.

o   Refactoring: infers using statement.  Generate a new method as your developing

·         Web.config

o   Release version compiles debug/standard web.config and turns off debug, hardens security, replaces config and connection strings

o   Part of the installer

Other Stuff

·         Ribbon support in VS2008 Feature Pack

·         Vista Bridge

o   Wrapper to get access to Vista controls and features

o   TaskDialog and CommandLinks

§  Standard now so will be seen in Win v7

§  Backwards compatible, just extra messages to standard native button

o   Restart/Recovery API

§  Get notified of a reboot

§  Register delegate called in separate thread when app crashes/reboots

§  OS will run app with a command line argument you catch to load saved info

o   Power Management

§  Get notified about all power related info, low battery, ect

Biz Stuff

·         StepUp Program

o   Allows customers to upgrade current SKU

§  i.e. VS Pro to Team Foundation Server

§  30% discount until June 2009