May 2009 - Posts
If you've developed in JavaScript without the ASP.NET AJAX client-side additions, you know that you typically can't create an object like the following:
function MyNS.MyClass() { }
This is not a supported feature because of the dot notation. This can work in JavaScript by setting up the namespace like the following:
var MyNS = MyNS || { };
And then adding the class to the instance. Using a variable is one way to create the namespace; using the window object is another. By using the following setup of a class:
if (!window["MyNS"])
window["MyNS"] = {};
window["MyNS"].MyClass = function() { }
This approach creates a new object MyClass within the MyNS namespace. MyNS is actually an object that has a MyClass property, which MyClass happens to be a function. This is perfectly valid. So an object can be created via:
var obj = new MyNS.MyClass();
The ASP.NET AJAX way of doing things is using the following approach:
Type.registerNamespace("MyNS");
MyNS.MyClass = function() { .. }
MyNS.MyClass.prototype = { .. }
MyNS.MyClass.registerClass("MyNS.MyClass");
Behind the scenes, ASP.NET AJAX works a very similar way. The Type.registerNamespace static method actually works by creating any global namespaces, and storing a reference with the window. What is a global namespace? For instance, if you had a class named Department.Hardware.Tools.Screwdriver, it would break down as follows:
Department <- global namespace
Hardware <- local namespace
Tools <- local namespace
Screwdriver <- class
And thus, the registerNamespace method passes Department to the window object, creating a new class with the empty class "{}" notation. The Hardware namespace is a class that gets appended to Department, and so on. Notice that you assign the prototype the same way you would in both implementations. The prototype in ASP.NET AJAX and in JavaScript would be:
MyNS.MyClass.prototype = {
get_name: function () { return "my name"; }
}
This is because this is standard javascript; Microsoft does not attempt to replace any existing JavaScript conventions, but to supplement them.
We had a weird error with IE 6 in our web site. In order to figure out the issue, it required going back to IE 6, from IE 8. In order to do that, you can simply go to the control panel, add/remove programs, and unintall internet explorer. Rather than uninstalling it completely, it rolls back the version first to IE 7 and then to IE 6. However, there's a catch: if you've installed Windows XP Service Pack 3, you cannot uninstall IE 7 to get to 6. You must first uninstall XP Service Pack 3 to then be able to uninstall IE 6.
Weird.
In Silverlight, there are a variety of ways to target elements in Silverlight. For instance, if we want to change the color of a border, we can target it this way:
<Button x:Name="ContactButton" Content="Contact Us">
<Button.BorderBrush>
<SolidColorBrush x:Name="ContactButtonBrush" Color="Red" />
</Button.BorderBrush>
</Button>
The Button has a border brush that's a solid color brush with an added name. This name will be used to target it's Color property, as shown in the storyboard below.
<Storyboard x:Key="ContactButtonStoryboard">
<ColorAnimation Storyboard.TargetName="ContactButtonBrush"
Storyboard.TargetProperty="Color"
Duration="0:0:5"
AutoReverse="True"
To="Yellow" />
</Storyboard>
As you see, the storyboard can target that brush, by linking to it via it's name, and target the Color property. This animation is set to last 5 seconds (using the timespan notation), to auto reverse at the end back to the original color, and change to Yellow and back to Red.
Another way to target elements is via the longer form, as in the following example:
<Border x:Name="PicturesButtonBorder" Background="LightYellow" BorderThickness="1,5,1,5" CornerRadius="10">
<Border.BorderBrush>
<SolidColorBrush Color="Navy" />
</Border.BorderBrush>
</Border>
<ColorAnimation Duration="0:0:1" To="Navy"
Storyboard.TargetName="PicturesButtonBorder"
Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)"/>
Notice that in this example, the solid color brush does not have a name, but the animation targets the border itself. The long hand form is simply this:
(ElementType.PropertyName)
The first value is the type of element (border and solidcolorbrush), and the second property after the period (borderbrush and color) specify the properties. These notations can be strung together to drill down through the various complex properties. You can even access elements via an index like [0].
So these two options create more flexibility for you in targeting properties (not just for animations, but elsewhere as well).
You may have gotten this error when using LINQ to SQL. I personally hate this error, but surprisingly enough, out of 2 years of using LINQ to SQL, this is the first time I've gotten this (2 years later, I mean). This error happens in this scenario: imagine loading up an object Order. This object has a primary key relationship Customer, which you can access via:
Order.Customer
Under the scenes, the order class uses the EntityRef<Customer> class to store the order. It's default value is default(EntityRef<Customer>), which is it's default state (existing EntityRef reference, but null Customer reference within this class so no value gets assigned). Say you are accessing the customer in an order that already exists. When you do:
order.Customer
This reference gets loaded from the context, using the value from CustomerKey. if you assign a new value to Order.CustomerKey as in:
order.CustomerKey = 3;
The LINQ entity notices that the Customer object (underlying EntityRef<Customer> _Customer variable) has already been loaded (through its HasLoadedOrAssignedValue property, or similarly named). Because you are now changing the key, this exception gets thrown because LINQ is setup not to allow you to do this. The way to change this is by doing:
order.Customer = this.DataContext.Customers.First(i => i.Key == 1);
You have to assign the reference to the Customer, and this instead updates the key, the reverse way around. I don't like this because this forces me to perform an additional data query, and in a business app this may reduce performance just to update a reference. I chose an alternate way. By adding a partial class for the order, I add a ClearCustomer method that does the following (note all LINQ types implement partial keyword, which means you can create another partial class to add additional methods).
public partial class Order ...
{
public void ClearCustomer()
{
_Customer = default(EntityRef<Customer>);
}
}
And now, calling this method before changing the assignment clears the customer, and I can make the change. A bit of a hack, but it works. Unfortunately, because again the EntityRef is internal to the class, the method has to be in the class definition (can't use a static helper class to do this, at least easily). To update the reference, I can now do:
order.ClearCustomer();
order.CustomerKey = 7;
Reference data is a funny thing. In reality, reference data really serves no major purpose other than for display purposes, whether that be a report or in the UI. Yet we often have reference data in our backend databases, with relationships established for drill-down purposes. In reports, a report proc swaps out a reference key for a name value that's more user friendly (after all, users don't care about keys, especially if they are artificial). In the UI, reference data may be bound to a drop down list, and the selected key gets passed to the SelectedValue of the list, therefore ensuring that the list displays and restricts the reference data input.
The question then becomes, is this the most efficient way to handle this? Are there better ways of storing/representing data, and changing data over time? Even reference data changes at some point, as the standards for the business process changes.
An additional point of view also comes from the ORM of choice; each ORM treats relationships in a different way. I've seen displaying reference data handled different ways. In strongly-typed datasets, the reference data may be loaded in the UI by querying it directly. It may have a DataRelation setup or may not. Sometimes, custom datasets are created for select-only purposes that includes the pertinent reference data, which can be a hassle to maintain.
For LINQ to SQL, reference data is accessible through a property. A foreign key reference is represented by a collection using the EntitySet<> generic class, while a primary key relationship is represented as an EntityRef<> class, and as such, these properties are dynamically loaded. This means that LINQ serves up the primary/foreign data when it's accessed; this default behavior can be changed by specifying the LoadOptions property of the DataContext (One note, create and call all of the LoadWith<> or AssociateWith<> methods for that load options object before creating the DataModelDataContext, as the DataLoadOptions object that specifies the load options is tightly coupled to the data context instance). LINQ to Entities works similarly, but a little differently, in that it gives you more control over entity references.
And so reference data may be easily accessible, but it may still involve a performance hit for every record accessed (although it can be loaded at the same time as the parent record is loaded). And so a reference table structure needs plotted accordingly for performance reasons, as sometimes networking issues bog down the database (due to latency or other issues). To circumvent that, I've seen anything from using enumerations to reference the data (each key is assigned to an enumerated value) to using XML as an alternative reference data store, as disk IO can be cheaper than DB access. Of course, each solution needs weighed accordingly, and I'm not making one preference over another.
An XML-based solution can't be the entire solution, meaning the reference data still has to take up space on the server. This is because XML won't have the same benefit for reports in SSRS or Crystal, as it would for ASP.NET. Some process would need to ensure the data matches up, and that there is proper failover if the data doesn't succeed. An enumeration approach would require an application change for every data change, which could be a nightmare (proper versioning would help this).
Looking at reference data from another challenge can be due to varying data because of changing standards. For changing standards, a reference table may include the following data:
1 Accepted 1/1/1900 NULL
2 Rejected 1/1/1900 NULL
The field field is the key, the second the name of a status, the remaining are effective/end dates (null means open ended) for that data. In this scenario, at one point in time we have two values present, but in the future, we may have three different values, and now our table looks like:
1 Accepted 1/1/1900 1/1/2007
2 Rejected 1/1/1900 1/1/2007
3 Approved 1/1/2007 NULL
4 Denied 1/1/2007 NULL
5 Pending 1/1/2007 NULL
And now, we have two rewrites of existing values, and one new value Pending. For displaying purposes, using a date and a range would easily pull back the correct values; however, what if we want to check if the item is approved, or accepted (for past)? Do we hard code checks for 1 and 3 when checking for approved status? Do these values get stored in a separate DB table? An alternative idea to solve this problem may be due to a reference code. Imagine the following update:
1 Accepted AC 1/1/1900 1/1/2007
2 Rejected RJ 1/1/1900 1/1/2007
3 Approved AC 1/1/2007 NULL
4 Denied RJ 1/1/2007 NULL
5 Pending PN 1/1/2007 NULL
This third new value is a coded value that represents the (AC)cepted status, and even though it was rewritten, the code still points to that. We can now simply check the code to see if it's AC, and this value can be hard-coded into the application (as it's an arbitrary value to mean Accepted/Approved). This way, I can ensure that there will be an accepted reference value no matter how many times the name changes throughout the years (change is the biggest constant in application development).
I'm risking that this may make no inherant sense to anyone, but I hope to convey some ideas on how to handle changes to reference data, and concerns about reference data and latency/performance.
When creating script references for AJAX controls, you may have noticed this code a lot:
var r = new ScriptReference(Page.ClientScript.GetWebResourceUrl(...));
This method creates a unique URL using a custom HTTP handler that extracts scripts from within the DLL. This unique URL gets assigned to the path property. There is an easy alternative to this if you don't want to use GetWebResourceUrl.
By specifying the name of the assembly and the name of the type, the embedded script can be exctracted in this alternative way, as in:
var r = new ScriptReference();
r.Assembly = assemblyName;
r.Name = clientSideTypeName;
For me, this alternative approach circumvented a customized solution to registering AJAX components; for the average user, using GetWebResourceUrl will suffice in registering scripts. But it's not necessary. If you have the type of a component that has the embedded resource, you can extract a reference to the Assembly through the Type metadata class.
I tend to design components in a consistent way. I can be anal about this sometimes. What I like to do is name my server components the same as my client-components. This way, it becomes easier to register and describe these components in a logical way. So if I have a server control:
Nucleo.Web.ButtonControls.Button
as it's fully quantified name, I have a client-side component named
Nucleo.Web.ButtonControls.Button
and it's equivalent JS file resource name would be:
Nucleo.Web.ButtonControls.Button.js
This way, when I describe or reference the component, I can use the type name to pass to the descriptor/reference. One little shortcut, one way not to have to change something later, and it makes it a little more convenient.
for the contestant, who only had three avenues of help, or lifelines, to survive to the next round. If the user answered a question wrong, they lost the game. Luckily, various spots on the ladder were insurances to ensure the user got at least that amount of money.
I don't remember if this was one of the first, but in the US, this show was on the cutting edge of the game/reality show boom that happened in the television industry. ABC tried to cash in by airing the show 2 to 3 times a week to keep the viewers hooked. Unfortunately, this was a double-edged sword as viewers got tired of the same format night after night, and the show finally ended (at least the version with Regis Philbin).
One of the other popular television shows that survived is the show "Survivor" (ironically enough). This show pits contestants against each other to see who can survive fatigue, hunger, and the various challenges that each contestant had to participate in. The very first show featured Richard, a very conieving and sly contestant that most of the other contestants hated, but whom was capable enough to win the contest and be labeled the very first "survivor." Since then, the show has done really well over the years.
Reality TV created a boom across the industry: Real World, Big Brother, Amazing Race, the Apprentice, the Ultimate Fighter, and many more shows have exploded onto the market big time. Game shows, both new and remakes have had the same success: deal or no deal, name that tune, are you smarter than a 5th grader, and more have had some success too.
I don't know if the rate or incline has been the same, but the rate of new reality TV shows inclined in the early 2000's. It inclined to the point that people felt they were being bombarded by reality and/or game shows. This feeling didn't prevent people from watching, as reality shows maintained an high viewership over the years and spawned off all kind of interesting in show variety.
I feel that another market, one not within the television industry but in the IT industry, also has bombarded onto the scene: social networks. It seems like every major application has a social network. Google, Yahoo, Twitter, Facebook, MySpace, FriendFeed, and many more sites have their own social networks where you can follow and interact with your friends. Social Networks have taken a different turn though, as they seem to have more slowly come onto the market. For instance, people are slowly coming onto Facebook; I personally didn't even know facebook existed until 2008, which it's been in existence for 1990's.
So it seems like to the average joe, the person who isn't technology heavy, is just coming into some of these social network scenes. And these industries are big money makers, which is part of what causes this explosion. Look at how personalized Facebook provides advertising for; it reads the preferences and groups that you belong to, and serves up personal ads based upon this information. And lot of existing sites that are commerce-driven sites are including social networking features (or at least similar features) to feed into this frenzy of the social networking kick that the world seems to be on.
It makes sense; if people like it, replicate it. The average person probably has more than one social networking site that they belong to. But at some point, it's got to stop right? The next big thing will be around the corner and that will be the next great thing that the world will take advantage of.
C# or VB.NET is very handy when it comes to inheritance. Because structured programming languages provide a mechanism for inheritance, they also provide a mechanism to call methods, properties, or other constructs defined in the base class, if defined with the correct access level (protected, public, etc.). If a member is private, it cannot be called directly even though the derived class inherited from its base class.
JavaScript has no notion of protected or private scope of methods, and thus any method can be called. Private methods are usually prefixed with an underscore, but this is convention only and doesn't change access to a method. So any method can be called of a component on the client-side. Also, because ASP.NET AJAX supports inheritance, components can call base class methods from derived classes too, just like you have in structured programming languages.
In ASP.NET AJAX, this is done via the callBaseMethod method. For instance, take a look at the initialize and dispose methods of a component:
AjaxSamples.MyComp = function(el) { .. }
AjaxSamples.MyComp.prototype = {
initialize: function() {
AjaxSamples.MyComp.callBaseMethod(this, "initialize");
},
dispose: function() {
AjaxSamples.MyComp.callBaseMethod(this, "dispose");
}
}
AjaxSamples.MyComp.registerClass("AjaxSamples.MyComp", Sys.UI.Control);
Our component calls the initialize and dispose methods in the base class, then define any custom implementations. The callBaseMethod takes a third parameter: an array of parameters to pass to the method, which isn't needed for the initialize or dispose mehods. Parameters can be passed using the following syntax:
AjaxSamples.MyComp.callBaseMethod(this, "doThis", [param]);
Any parameters, whether one or more, have to be defined as an array.
If you have an understanding of developing components in JavaScript, the reasoning may be familiar to you. As you see, JavaScript doesn't support inheritance. The "base." syntax doesn't work because it doesn't know what the base class is. Other developers had created schemes for this, and ASP.NET AJAX has its own approach.
One such was is the use of mixin classes. This type of class mixes in the properties/methods defined in the base class by copying them to the base class directly. An example of this can be found here: http://www.web-articles.info/e/a/title/Implementing-Mixins-in-JavaScript/
This mixin approach copies members from the source to the destination; ASP.NET AJAX doesn't do this; rather, it separates the base type, and calls methods in the base type. This is where callBaseMethod comes into play because it allows you to perform that "base." functionality you have in C#. The other great benefit for ASP.NET AJAX is that the mixin approach pushes off the logic for the component to the new type; with this ASP.NET AJAX approach, the base class can have separated logic from the derived class, and thus separates the logic out. So you can call your base class method and override this method in the derived class to add to it, or override it altogether.
ASP.NET AJAX supports inheritance in components. While easy to setup, here's a little useful information regarding the script registration/description process for you to be aware of. To start, imagine this hierarchy of components:
Server
ScriptControl
BaseButtonControl
Button
Client
Sys.UI.Control
AjaxSamples.BaseButtonControl
AjaxSamples.Button
First, script registration is the process of selecting which JS files to download to the client in order for your components to work. Both the BaseButonControl and Button components need scripts downloaded to the client, unless it happens that the same script file is used for both. This means that both BaseButtonControl and Button server components would create their own instances of a ScriptReference object, which points to the scripts that it needs. If there are duplicates, no worries. Duplicate scripts get ignored.
Script Description, however, has to happen one per object. This means that the BaseButtonControl cannot create it's own ScriptDescriptor, and Button render its own component as well. There must be only one Descriptor object returned to the ScriptControl class. Here are some of the issues you may experience if you don't:
You may see something in the script like:
$create(AjaxSamples.Button, .... $get("buttonElement"));
$create(AjaxSamples.BaseButtonControl, ..... $get("buttonElement"));
An exception will be thrown that more than one control targets the same element, which is true, because two components reference "buttonElement" html element. In some instances, you may see something like:
$create(AjaxSamples.Button, .... $get("buttonElement"));
$create(AjaxSamples.Button, ..... $get("buttonElement"));
Which is a unique situation. Also, the create statement pushes up properties to the client using one of the $create parameters to do so. You may see something like the following as well.
$create(AjaxSamples.Button, { "text" : "click me", "tooltip" : "click me too" }, .. , $get("buttonElement"));
$create(AjaxSamples.BaseButtonControl, { "clientStateFieldID" : "buttonElement_Client" }, .. , $get("buttonElement"));
So why might all this happen? Let's first look at the right approach to setting up a descriptor. Each component should have one descriptor, and that one descriptor should contain the properties and client-side events from that object and all of its inherited members. This means that a descriptor has to be shared up the levels of hierarchy. That is the proper way to setup a descriptor, and it varies from the registration process.
The AJAX control toolkit actually handles this, using reflection to interpret the finalized type. This way, all of the logic concerning getting the correct descriptor is behind the scenes. I'm writing about this because I was trying to do something more complicated when it comes to registration, and as such I ran into an issue with the approach to describing the components. At first, I was creating a descriptor for the base class, then creating a descriptor for the derived class. This created two descriptors, one for the base class (which isn't supposed to be an instantiable component even on the client-side), and one for the derived.
So if you create a control hierarchy, you have to ensure that the Button component only creates one descriptor, and that it includes both Button and BaseButtonControl's information. There are a couple of ways to do this. Create a method in BaseButtonMethod that does:
protected ScriptControlDescriptor GetBaseDescriptor(string clientType, string clientID)
{
ScriptControlDescriptor desc = new ScriptControlDescriptor(clientType, clientID);
//Add properties/events to descriptor
.
.
return desc;
}
The Button class can call this method to get the descriptor with the base properties, but return the client-type's full name to append to it, as:
IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
{
var desc = this.GetBaseDescriptor("AjaxSamples.Button", this.ClientID);
//Add properties/events to descriptor
.
.
return desc;
}
This way, only one descriptor reference is created, but contains both base/derived type references.
You've made some changes to your web site, and nothing comes up. Instead, you see some action going on in the status bar, where the status bar freaks out. What in the world is going on, you might ask?
Certain types of changes to the application cause severe issues that cause the application not to load. These could be database structure (which causes issues with your ORM if out of sync), framework-related, or architecture-related. To figure out what's going on, an easy way is to use health monitoring, if you have it enabled. It logs this information to the event handler for easy retrieval. For more information on health monitoring, check these out:
http://dotnetslackers.com/articles/sql/HealthMonitoring.aspx
http://msdn.microsoft.com/en-us/library/ms998306.aspx
The web.config file in the Windows/Microsoft.NET/<version>/Config folder contains the following event mappings (<eventMappings> element), which log internal .NET framework errors. These are already built-in to the .NET framework, and are specifically mapped to the event log.
<add name="All Errors" type="System.Web.Management.WebBaseErrorEvent,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" startEventCode="0" endEventCode="2147483647"/>
By default, the event log provider is registered to handle these errors, so all errors will at least be logged to the event log. Going to the application event log will sniff out the error.
Depending on your architecture, there are various reasons why this happens. One of the reasons we experience is because a difference occurs between the database model and our LINQ model (using LINQ to SQL), and because of this LINQ throws an exception which prevents the application from loading. When querying using LINQ, the model differs from the database, the LINQ model detects this and throws an exception worded like: invalid column name <X>. Because this object being accessed throws the error from the master page, the error occurs in each and every page. Other errors could easily cause this to happen if vital enough.
So when your app may not load, instead of freaking out, check the event log. It will often directly prompt you to the issue, if you have health monitoring involved.
The Silverlight ListBox control is a pretty flexible control. Even though the out-of-the-box ListBox control isn't anything special necessarily, the control does give you a lot of power due to the nature of Silverlight and the ability to override control templates. Let's begin by looking at the markup:
<ListBox>
<ListBox.Items>
<ListBoxItem Content="First static item" />
<ListBoxItem>
<ListBoxItem.Template>
<ControlTemplate>
<TextBox Text="Second static item" />
</ControlTemplate>
</ListBoxItem.Template>
</ListBoxItem>
<ListBoxItem>
<ListBoxItem.ContentTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Third" />
<TextBlock Text="static item" />
</StackPanel>
</DataTemplate>
</ListBoxItem.ContentTemplate>
</ListBoxItem>
<ListBoxItem Template="{StaticResource ListBoxTemplateItem}" />
</ListBox.Items>
</ListBox>
This may look like a jumbled mess, and it may not be the best example, but let's break down the various types of items added to the list. First, content can be added directly to a list box item as:
<ListBoxItem Content="First static item" />
This type of list box item supports the full features of the list box, such as automatic mouseover styles, selection support via clicking, etc. All of those features are built-in to the ListBox element and ListBoxItem element (depending on the feature). The next list box item renders a custom template, using a TextBox control:
<ListBoxItem>
<ListBoxItem.Template>
<ControlTemplate>
<TextBox Text="Second static item" />
</ControlTemplate>
</ListBoxItem.Template>
</ListBoxItem>
The template property takes a ControlTemplate object. This control template overrides the default features of a ListBoxItem, but that doesn't matter necesarily. The TextBox provides any responsiveness that this item would need, such as updating the text, selecting the text, etc. It doesn't support selection styles on mouse over and other listbox features, because the template was overridden.
However, the third option does have full ListBoxItem support (mouse over styles, etc.):
<ListBoxItem>
<ListBoxItem.ContentTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Third" />
<TextBlock Text="static item" />
</StackPanel>
</DataTemplate>
</ListBoxItem.ContentTemplate>
</ListBoxItem>
The ContentTemplate can be used to provide custom content instead; this content renders a stack panel for the third item, which doesn't override any features, unlike the fourth option, which overrides the template also. However, it renders inline text, and because of that, no features are supported except of the underlying TextBlock. This template is supplied using the StaticResource attribute:
<ListBoxItem Template="{StaticResource ListBoxTemplateItem}" />
This means a resource has to exist in the UserControl or Application class, or any other resource alternative (such as control resources). In this example, the template exists in teh user control's list of resources. The ListBoxTemplateItem has to refer to an object with an x:Key designation, as shown below.
<UserControl.Resources>
<ControlTemplate x:Key="ListBoxTemplateItem">
<Border BorderBrush="Beige" BorderThickness="1">
<TextBlock Margin="20" Text="My templated content via resources" />
</Border>
</ControlTemplate>
</UserControl.Resources>
At runtime, this template replaces the template of the list item. You can view a screenshot of the results here: http://www.flickr.com/photos/36885451@N06/3493195440/