Flippantly, here they are:

  • One: Silverlight-enabled WCF Service (backing View Model collections with ObservableCollection<T> by default)
  • Two: WCF Data Service (OData, backing View Model collections with DataServiceCollection<T>)
  • Three: Domain Service Class (RIA Services, backing View Model collections with LoadOperation<T>)

ServiceReferences.ClientConfig Is Useless in a XAP That Is Loaded by Another XAP.

My Songhay.Silverlight.ApplicationLoader compiles into an 8KB XAP file and is designed to load a bigger XAP file—which in turn uses MEF to load even bigger XAP files. One of these MEF-composed XAP files may contain a Service Reference, which, by default, generates ServiceReferences.ClientConfig. This file is designed to be used by the initial XAP declared in the HTML markup used to call Silverlight. My initial XAP is only 8KB and has no room for one or more Service Reference entries.

My way around this issue is to replicate the ServiceReferences.ClientConfig declarations imperatively. I have written an extension method to System.Windows.Application that accomplishes this:

public static BasicHttpBinaryBinding GetServiceClientBinding(this Application app)
    var mode = app.Host.Source.Scheme.Equals("https",
        StringComparison.InvariantCultureIgnoreCase) ?
        BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None;
    var binding = new BasicHttpBinaryBinding(mode);
    binding.MaxReceivedMessageSize = int.MaxValue;
    binding.MaxBufferSize = int.MaxValue;
    return binding;

For more details, see “Silverlight ServiceReferences.ClientConfig Alternatives” by Manish Dalal. Notice the my extension method returns a binary HTTP binding—Silverlight requires this more payload-efficient binding, which is the chief characteristic of a Silverlight-enabled WCF service.

IEditableObject Moves CRUD Eventing into the View Model

Controls like the DataForm use IEditableObject by convention, defining three methods BeginEdit, CancelEdit and EndEdit. The “begin” method is an opportunity to cache the instance implementing IEditableObject such that the “cancel” method can be used to restore data from this cache. The “end” method passes the instance implementing IEditableObject to the data layer.

Based on my current level of experience with this IEditableObject pattern, I am recklessly confident that my “end” method will not need to distinguish between Insert and Update. This suggests that I am rather foolish and/or I am setting a default value for the primary key associated with my instance implementing IEditableObject—like this:

[Display(Name = "Primary Key", Order = 0)]
[Key, Editable(false)]
public int? PrimaryKey
    get { return this.GetPrimaryKey(ref this._key); }
        this._key = value;

My private method GetPrimaryKey() passes the key field by reference and should be able to derive a valid key for the real-world underlying database. In fact, it can actually perform an Insert operation and have an “empty” record persisted before the user begins an edit session. This technique strongly suggests that the “cancel” method in the IEditableObject contract needs a cleanup procedure to ensure that the underlying database is not littered with “empty” records. I may need to study how more experienced developers address these issues.

What I do notice is that there appears to be no way to use IEditableObject with Delete operations. I assume that one would have to fall back on control eventing to handle any ceremony around deletes. The DataForm, for example, has a DeletingItem event, described by Tim Heuer in “Silverlight DataForm and confirming deleting an item.” Another DataForm event to consider is the EditEnded event, covered by Dino Esposito in “The DataForm Control in Silverlight 3—Revisited.”

My Scroll-into-View Strategy for the DataGrid

As of this writing this is my scroll-into-view strategy for the DataGrid:

this.DataGridOne.SelectionChanged += (s, args) =>
    if(this.DataGridOne.SelectedIndex == this._previousSelectedIndex) return;
    this._previousSelectedIndex = this.DataGridOne.SelectedIndex;

This approach requires declaring an x:Name on the DataGrid.

PagedCollectionView Swallows Collections Whole!

As of this writing, I know of only ways to implement the classic Master-Detail relationship between, say, the DataGrid and DataForm: with a PagedCollectionView and with the simpler CollectionViewSource. Both of these types implement ICollectionView (for details, see the 2008 article “ICollectionView explained”).

Because the PagedCollectionView supports client-side paging (and the DataPager), I prefer the CollectionViewSource (however, when server-side paging is in effect the CollectionViewSource might be useful when a more lightweight design is required). With the PagedCollectionView, the initial problem for me was getting synchronization to work between the Master control and the Detail control—the ObservableCollection<T> was not working out of the box. However, passing an instance of ObservableCollection<T> into the constructor of PagedCollectionView did the trick!

DataServiceCollection<T> is not “Blendable”

Because DataServiceCollection<T> has a dependency on some data-service “context,” DataServiceCollection<T> is not “Blendable” because mocking up design-time data is non-trivial (it may require a live, local OData service always running). However, because DataServiceCollection<T> is a subclass of ObservableCollection<T>, the recommendation here is to use ObservableCollection<T> in View Models.

In my ever-changing world, there interview questions that are well placed and worth my time and then there are ‘trick’ questions that are (to me) more of a personality test than a technical test (based on the technology actually used in the workplace). It is better to ask about personality directly in an interview rather than indirectly inquiring (either deliberately or out of ignorance).

Adam is a Hash Table

These are the questions I’ve encountered (that I could not answer) over the last few weeks that are worth my time:

  • What is the difference between the Logical Tree and the Visual Tree? This question can be considered a fundamental WPF question—but it is the kind of question that only comes from experience with advanced scenarios—or by reading some extensive prose meditating on how WPF works. In 2007, Josh Smith does exactly that in “Understanding the Visual Tree and Logical Tree in WPF.” As Jason Dolinger of lab49 suggests in “Exploring the WPF Logical and Visual Trees,” the logical tree closely represents programmers intent (what is declared by the programmer in XAML) while the Visual Tree represents what WPF or Silverlight is doing under the hood to actually render what is intended.
  • What is _ViewStart.cshtml? I actually was very warm on this one. This is a great question to test for MVC3-level intimacy. I have not been working with MVC on a daily basis over the last three months so I’m not too upset for not getting this one.
  • What is the purpose of the yield keyword? This question opens a whole new subject of computer science under the heading “state machine”—according to stackoverflow.com: “Yield is implemented by the compiler as a custom class that implements a state machine.” Erik Forbes: “Yield is used to create implementations of the Enumerable pattern—a software pattern that allows you to treat a collection of things as an enumeration, over which you can perform some process.” MSDN: “The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor.” I really should know about this topic. No “excuses” here.
  • What is the difference between ref and out parameter modifiers? “…semantically, ref provides both ‘in’ and ‘out’ functionality, whereas out only provides ‘out’ functionality.” Where in refers to initializing the variable/parameter (with the expectation that it will be read inside the method accepting the parameter). This implies that out suggests that the parameter is write-only. I cannot think of a situation (outside of Interop and TryParse patterns) where using ref or out parameters are required. I prefer to use a struct or a class (stacking complexity vertically) over using multiple parameters (stacking complexity horizontally).
  • How can custom validation be centralized/reused by several view models? The CustomValidationAttribute accepts a Type and a method-name string where the Type points to a central validation class. I have actually written code using this kind of centralized custom validation—but clearly not enough to memorize this level of detail during a job interview.
  • What is the volatile keyword? “The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.” My limited understanding of threading is a known issue—I was actually relieved to find out that this question was related to threading.

Here are some parlor-trick questions that are not really worth my time (but they are apparently worth serious money):

  • How would you swap the contents of two variables? I am unable to think of any real-world situation where I would need to do this. I actually got angry when I was asked this question—which prevented me from answering the question properly.
  • Given a LinkedList, with a head and a tail, how would you make the head a tail and the tail a head? I assume that the short answer here is to use the Reverse() method (see MSDN). When you can’t use Reverse(), then you can (ha, ha) swap the contents of the Next and Previous properties of LinkedListNode<T> in a state machine with null checks—null implying a head/tail. When this question was presented to me, I assumed that the head was at the top of a hierarchy (like a parent node) and the tail was the last child in this hierarchy—this caused me to shut down and short circuit at the whiteboard in more inappropriate fits of anger. (This question, by the way, was not asked of me within the last few weeks but about four months ago—before I took my last job.)
  • What is the difference between a Dictionary and a HashTable? As far as I’m concerned, a Dictionary supports generics and HashTable does not (it boxes values in object)—that’s the difference. The lack of generics support implies that HashTable is irrelevant to me for most of my work (but this may imply that I’m ignorant of the use of HashTable in distributed cache systems—used in the real world of high-traffic Web sites).

So the personality test that I’m failing is that I get angry when people f around with me—such that my anger prevents me from protecting myself. My anger causes me to go into a form a paralysis that renders me useless. When sadists sense this, they attempt to press my buttons with abandon.

Beyond the anger, some of these parlor trick questions are really tests that look for computer science training over, say, physics training. So here are some ‘pure’ computer science subjects I’m sensing out there:

  • The technical history of collections. (Who invented the LinkedList and why?)
  • Memorializing sort algorithms. (What is a bubble sort?)
  • Bitwise operations. (What is the [Flags] attribute used for?)

I do admit that these subjects are of little interest to me and I maintain that it is unfair to refuse to hire a person based almost entirely on whether they are knowledgeable in these areas. To me, you don’t hire a person that is not aware of, say, how MVC3 works intimately (which I have been guilty of). I am also guilty of being afraid of confrontation in these interviews (turning my anger against me)—what I should do is ask this question:

I do not understand this question, is there another one?

In the real world there should always be another question. The real world always operates in holistic diversity. There is no perfect, one way in real life. When my tester says no, there are no other questions, I should have the courage to politely conclude the interview, stand up and leave the building.

Related Resources

@elijahmanor Elijah Manor

“Modernizr.js : Feature Detection” by @OdeToCode #webdev z-t.go.ly

@elijahmanor Elijah Manor

“KnockoutJS Custom Binding for Invoking an Action with Enter Key” by @smichelotti #javascript sd3.go.ly

@jongalloway Jon Galloway

JSON Formatter & Validator—can take a URL and return validated / formatted JSON – jsonformatter.curiousconcept.com

@elijahmanor Elijah Manor

“Setting up ASP.NET MVC 3 to work with jQuery UI 1.9” #jquery http://v8h.go.ly

@elijahmanor Elijah Manor

“Replacing Text Nodes With jQuery” by @bennadel #jquery http://t5v.go.ly

@mtaulty Mike Taulty

I missed this “Was .NET all a mistake” bit.ly/peV466—the background is well written and it’s a good (provocative) discussion

@elijahmanor Elijah Manor

“SassAndCoffee 1.1 Released for ASP.NET (MVC & WebForms)” by @xpaulbettsx #aspnetmvc http://j.mp/owcJ6A

@pluralsight Pluralsight

Free Webcast—Improving Web Performance with Robert Boedigheimer—starts in 30 minutes! http://ow.ly/66uND RT

@codinghorror Jeff Atwood

“HTML5 standardizes every terrible practice inflicted on us by browser authors, making them part of the web forever.” stackoverflow.com/questions/3434…

@pluralsight Pluralsight

Steve Michelotti @smichelotti has just published a new course: ASP.NET MVC Scaffolding bit.ly/qQf8zy

@kazuhito Kazuhito Kidachi

Don’t use IDs in CSS selectors? ❧ Oli.jp (@boblet) – http://icio.us/kLHLoH

@jongalloway Jon Galloway

Strange to see IE Conditional Comments go http://bit.ly/qka6HV—handy for IE6 specific stylesheets, hopefully no longer as necessary.

@LeaVerou Lea Verou

Microsoft removes conditional comments, behaviors and XML Data Islands from IE10, due to incompatibilities with HTML5 blogs.msdn.com/b/ie/archive/2…

@JohnBristowe John Bristowe

Awesome scrolling experience is awesome: http://www.newzealand.com/

@KyleMcClellan Kyle McClellan

Survey: Tell me what you think of the RIA DomainService Wizard http://bit.ly/ljXCEq #RIAServices

@martinfowler Martin Fowler

I’ve published an article on eradicating non-determinism in tests: http://martinfowler.com/articles/nonDeterminism.html

@mattpodwysocki Matthew Podwysocki

Erik Meijer’s CoSQL paper on the duality of SQL and NoSQL got Slashdotted: http://bit.ly/feNxRE #cosql

@maryjofoley Mary Jo Foley

Microsoft readies three new Office service packs: http://zd.net/eW2kPK

@JesseLiberty Jesse Liberty

Posted: Linq: SelectMany http://ow.ly/1bT14x

@mtaulty Mike Taulty

Building with WCF RIA Services? http://goo.gl/fb/B3ysB

@davewiner Dave Winer ☮

I’ve never understood what the browsers guys do with RSS. http://r2.ly/6zem

@amyhoy Amy Hoy

i hate watching smart, capable people defend crap—or refuse to express strong opinions—in the name of “professionalism”

I have tried and failed to include a simple Web Parts sample for ASP.NET Web Forms Basics and Esoterics in my studio. The error is:

Exception information: 
    Exception type: SqlException
    Exception message: Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)

It concerns me that System.Data.SqlClient is in use here instead of System.Data.SqlServerCe.4.0, which is specified in the connection string. This setting comes from installing the NuGet package, System.Web.Providers based on Scott Hanselman’s “Introducing System.Web.Providers—ASP.NET Universal Providers for Session, Membership, Roles and User Profile on SQL Compact and SQL Azure.” I have yet to find an article about using Web Parts with SQL CE.

Related Resources

MVP Chalermvong and his session - ASP.NET Performance Up!

Learning how to work with ASP.NET Web Forms is the other thing of “New Things Learned in the Labor Camp”… I’ve avoided confronting ASP.NET “classic” directly for years. Instead, I made the right decision to learn things about Web programming and Web design that Microsoft notoriously undervalued in its professional communication for years until the rise of Scott Guthrie from ASP.NET “classic” to ASP.NET MVC.

Sadly, there is a job market full of IT shops that are deeply invested (often emotionally invested) in ASP.NET “1.9”—the way of seeing the Web through the Microsoft looking glass just before ASP.NET 2.0 was released in 2005.

For years I’ve “run away” from confronting ASP.NET Web Forms directly. The following interview questions I’ve slapped together “finally” engage—directly. By the way to show that I’m super serious about this matter, I’ve literally spent hours over about two weeks building samples for ASP.NET for Web Forms in my studio.

What are ASP.NET Web Forms?

ASP.NET Web Forms is a technology that breaks down a plain-old HTTP Request into a series of clearly defined events (classified broadly under initialization, load and render)—these events describe the “life cycle” of a familiar model, the data-entry form in a Web page. ASP.NET is based on the event-driven programming paradigm made popular and traditional by Microsoft in the 1990s.

What is a ‘Post Back’?

The ‘Post Back’ is the concept developed by Microsoft that stands between the post HTTP verb and the first event recognized by an ASP.NET Page. Typically, the Page.IsPostBack Boolean is checked in the Page.OnLoad event handler. When Page.IsPostBack == false then the get HTTP verb is the request. Microsoft has defined a conventional Jscript function, __doPostBack(), that invokes the ‘Post Back.’ ASP.NET Web Forms seem crude and extravagant in the 21st century when a page-level post action is regarded as expensive and disruptive (ASP.NET AJAX was supposed to remedy this).

Why do ASP.NET controls require a parent form?

Without a parent form element, the ‘Post Back’ concept is not implemented. Conventional hidden fields in the form store event metadata (__EVENTTARGET, __EVENTARGUMENT, __VIEWSTATE).

See also:TRULY Understanding ViewState

What is the AutoPostBack property?

The AutoPostBack property is a Boolean that is apparently defined independently and conventionally in the System.Web.UI.WebControls.ListControl, System.Web.UI.WebControls.CheckBox and System.Web.UI.WebControls.TextBox. When AutoPostBack == true an event associated with these controls (select, check, blur) will cause a Post Back.

See also:
System.Web.UI.PostBackOptions and System.Web.UI.Page.AutoPostBackControl.

super smart msft peeps

What is a Cross-Page Post Back?

By default, an ASP.NET page “posts back” to itself (frequently). A Cross-Page Post Back declares that one Web Form should post to another Web Form—not back to itself. Input captured in the posting page can be captured in the receiving page via the Page.PreviousPage property.

Tip: The Page.IsCrossPagePostBack property is always null. During a cross page Post Back Page.PreviousPage.IsCrossPagePostBack will be true.

See also:

What is a Server Transfer?

An ASP.NET Server Transfer allows a Page executing on the Server to Transfer execution to another Page. It can be thought of as a call to another procedure from the currently executing procedure. In terms of a POCO class, a Server Transfer is a method call in a procedure of one class with a member from another class—the catch is that no arguments can be passed in the method call. After a Server Transfer, the new page running has access to all of the Request, Session and Application-scope data in the old page. Importantly, there is a Page.PreviousPage property which can be used with FindControl() to locate controls on the old page.

According to Microsoft MVP Karl Moore, “So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables. …Don’t confuse Server.Transfer with Server.Execute, which executes the page and returns the results. It was useful in the past, but, with ASP.NET, it’s been replaced with fresher methods of development. Ignore it.”

See also:ASP.NET Server.Transfer Method

What is a Master Page?

The ASP.NET Master helps keep Web Forms DRY. They share visual elements among several ASP.NET pages providing the “consistent look and feel” Web designers expect. ASP.NET Master pages also centralize HTML page “meta” information, much of the angle-bracketed ceremony that make Web page markup noisy.

How does a Master Page affect the Control.FindControl function?

The ASP.NET Master adds one or more ContentPlaceHolder controls to the visual tree. These in turn demand Content controls, which implement INamingContainer—a “naming container” affects the ID attributes of child controls “inside” the container. So: a control named foo inside a naming container, bar, can be located by Control.FindControl("bar$foo") where Control would be an instance of the Master page in our example.

The ASP.NET Dream Team

How do Web Forms handle Validation?

ASP.NET handles Validation with PostBack-dependent server controls. These server controls share a ControlToValidate property, pointing to the input-related server control to Validate. There are validation controls for marking input as required, checking input for a data type, testing input with a Regular Expression and testing input with custom code.

One little annoyance: custom validators don’t work with blank input—so they must be paired with the validation control for marking input as required (RequiredFieldValidator).

What are Validation groups?

Validation groups allow more than one “validation context” to exist in a Web Form. For example, a layout with a GridView might have an EditItemTemplate with one Validation Group for editing while another form used for inserting new rows into the grid will have another Validation Group. Validation groups are declared with the ValidationGroup property.

What is a “Partial Page Update”?

The “Partial Page Update” is made possible with the UpdatePanel and the ScriptManager, which is the heart of ASP.NET AJAX. This extension to ASP.NET introduced in version 2.0 dramatically reduces the need to do the “classic” PostBack by implementing the “asynchronous PostBack” a.k.a. the “Partial Page Update.”