Casting Types in VB.Net and More

Source: Cheat Sheet - Casting in VB.NET and C#

Great little find, and since I’m a VB.Net whore, I’ll just post up the VB.Net version :)

Casting in VB.NET

  1. By default in VB, casting is automatically done for you when you assign objects to variables. The objects are then automatically casted to the variables' type.

    This behavior can be influenced by an option line on top of your code file:

    Option Strict On
    Option Strict Off

    When on, casting is strict and not automatic.

  2. Explicit casting can be done with the cast operator CType() or DirectCast():

    textbox = CType(obj, TextBox)
    textbox = DirectCast(obj, TextBox)


    The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. DirectCast throws an InvalidCastException error if the argument types do not match.

  3. Testing if an object is of a particular type, can be done with the TypeOf...Is operator:

    If TypeOf obj Is TextBox Then...
  4. Obtaining a System.Type object for a given type can be done with the GetType operator:

    Dim t As System.Type
    t = GetType(String)
    MessageBox.Show(t.FullName)
  5. Obtaining a System.Type object for a given object can be done with the GetType method:

    Dim t as System.Type
    t = obj.GetType()
    MessageBox.Show(t.FullName)

Now to build on and add one more of my own…

Get the type based on an arbitrary string.

System.Type.GetType("System.String")

Problem with this though is you can not use it to cast using CType or DirectCast. Looking at the CType Function..

typename - Any expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class, or interface.

You can only use types that are compiled and can’t use types that show up at runtime. So trying to use CType(obj, System.Type.GetType(“System.String”)) will only get you an error.  Array bounds cannot appear in type specifiers.

How to get around this? I have no freaking idea, yet. I’m think I might could create a custom type of my own and do something so that it converts to the proper method but for now I’ll just catch a few ArgumentExceptions and try different cast types then.

HTTP Error 404.17 Not Found – Using WCF .SVC Service

So you’re getting IIS error’s when trying to run a .svc file that’s coded to use WCF or Windows Communication Foundation.

HTTP Error 404.17 - Not Found

The requested content appears to be script and will not be served by the static file handler.

or maybe..

HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Took me awhile to realize I need to setup/configure IIS and WCF properly.  Here are the steps from MS, I went through and realized I had missed one component (IIS6 Scripting tools, who would have thought), which I probably didn’t need, but the big ones that I didn’t have WCF Http Activation installed.  After that, I registered WCF..

"%WINDIR%\Microsoft.Net\Framework\v3.5\WFServicesReg.exe" /c

and then I was golden, but there might be other things you are lacking or missing. So go through all the steps.

One-Time Set Up Procedure for the Windows Communication Foundation Samples

Set the DefaultButton inside a LoginView Control in a MasterPage

Ok if you google this you’ll get some solutions that say set the DefaultButton to ParentControlID$ButtonID

However, this didn’t work for me. I kept getting the same error no matter what I tried.

The DefaultButton of '<PanelID>' must be the ID of a control of type IButtonControl.

So I tried another approach that worked great.

On page load I found the Panel Control and found the button control and set the default button programmatically.

<asp:LoginView ID="LoginView1" runat="server">
    <AnonymousTemplate>
        <asp:Panel ID="pnlLogin" runat="server">
            <telerik:RadTextBox ID="tbUsername" runat="server" EmptyMessage="Username" />&nbsp;
            <telerik:RadTextBox ID="tbPassword" runat="server" EmptyMessage="Password" TextMode="Password" />&nbsp;
            <div id="SignIn" style="position: relative; z-index: 1; float: right; bottom: 21px;">
                 <asp:LinkButton ID="lbSignIn" runat="server" Font-Bold="true" Font-Size="Small" Text="SIGN IN" OnClick="lbSignIn_Click" />
            </div>
            <div id="divLoginLinks" style="position:relative; clear:both">
                <span class="GrayFooterFont"><asp:HyperLink ID="hlRegister" runat="server" Text="Register" NavigateUrl="~/Registration.aspx" /> | <asp:HyperLink ID="hlForgot" runat="server" Text="Forgot Password" NavigateUrl="~/ForgotPassword.aspx" /></span>
            </div>
        </asp:Panel>
    </AnonymousTemplate>
    <LoggedInTemplate>
        <small><asp:Label ID="lblLoggedInUsername" runat="server" /> | <asp:LinkButton ID="lbSignOut" runat="server" Text="SIGN OUT" OnClick="lbSignOut_Click" /></small>
        <asp:LinkButton ID="lbSignIn" runat="server" Font-Bold="true" Font-Size="Small" Text="SIGN IN" OnClick="lbSignIn_Click" CssClass="hidden" />
    </LoggedInTemplate>
</asp:LoginView>

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'If User is not logged in do this        
    Dim pnlLogin As Panel
    Dim lbSignIn As LinkButton
    pnlLogin = CType(LoginView1.Controls(0).FindControl("pnlLogin"), Panel)
    lbSignIn = CType(LoginView1.Controls(0).FindControl("lbSignIn"), LinkButton)
    pnlLogin.DefaultButton = lbSignIn.ID
    pnlLogin = Nothing
    lbSignIn = Nothing
End Sub

I’m sure I could have just hardcoded the lblSignIn ID to the pnlLogin, but no idea why I didn’t.

Play Ripped DVD’s on Windows Media Center

For Windows Vista:

Open Registry Editor (Start, Run, REGEDIT) and navigate to:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Media Center\Settings\DvdSettings

Double-click the key ShowGallery and change the value from “Play” to “Gallery”.

For Windows 7:

Don’t need it, it’s already built this way.

jQuery Plug-In Links I’ve collected

Here some links I’ve received from friends and have run across that have some cool jQuery plug-ins that I would like to use one day.

 

SilverLight Reference Controls

Reference a control that’s is outside your View, or on your MainPage if you’re using NavigationFrame or your “Parent” window.

Assumption: MainPage UserControl page is your starting page and has a NavigationFrame and a View is loaded in a content window.

Method 1: (Assuming “MainPage” is the name of your MainPage or the x:Class it uses, x:Class="<AppName>.MainPage" and the TextBlock named “lblStep1”)

Dim Main As MainPage = CType(<AppName>.App.Current.RootVisual, MainPage)
        CType(Main.FindName("lblStep1"), TextBlock).Text = "Hello Test123"

Or Method 2:

CType(CType(<AppName>.App.Current.RootVisual, MainPage).FindName("lblStep1"), TextBlock).Text = "Updated Text"
 

 

Reference a Control in a User Control that’s on the same view.

  1. CType(siTest.FindName("lblStep1"), TextBlock).Text = "Testing"

Test SMTP Server via Telnet

As a developer I always have to write code to send emails, here's a quick way as a developer to make sure the SMTP Server is working properly.

Telnet to Port 25 to Test SMTP Communication

1. Telnet into Exchange or SMTP Server using port 25.
Command is telnet <servername> 25

c:\>telnet 192.168.0.5 25
220 fredmastro.com Microsoft ESMTP MAIL Service, Version: 6.0.3790.1830 ready at Sun, 29 Nov 2009 10:22:22 -0400

2.Start by typing the following:
helo <your domain name><enter>                 
response should be as follows
250 OK

 

c:\>helo
250 fredmastro.com Hello [10.x.x.x]



3. Type the following command to tell the receiving SMTP server who the message is from:

mail from: <your Email Address><enter>
response should be as follows
250 OK - mail from <your Email address>

For example,

c:\>mail from: fredmastro@fredmastro.com
250 2.1.0 fredmastro@fredmastro.com....Sender OK



4.Type the following command to tell the receiving SMTP server whom the message is to. Use a valid recipient SMTP address in the domain that you are sending to.

For example, if you are sending to someguy@gmail.com, you must be certain that someguy@gmail.com exists in your domain. Otherwise, you will receive an NDR.

rcpt to: <recipient address><enter>
response should be as follows
250 OK - Recipient <recipient address>

For example, 
c:\>rcpt to: someguy@gmail.com
250 2.1.5 someguy@gmail.com

5.Type the following command to tell the SMTP server that you are ready to send data:

data<enter>
response should be as follows
354 Send data.  End with CRLF.CRLF

c:\>data
354 Start mail input; end with <CRLF>.<CRLF>
Test Message
.

250 2.6.0 <someguy@gmail.com>
Queued mail for delivery

6. Close the connection by typing the following command:
c:\>QUIT

response should be as follows:
221 closing connection

Another good reference: http://www.messagingtalk.org/content/470.html

C# - Singleton Pattern vs. Static Classes

Link sent to me from Justin.. as we’ve been discussing using Singleton’s in Win Services for the previous post I talked about. I’ll convert to VB later.

Original Article: http://dotnet.dzone.com/news/c-singleton-pattern-vs-static-

By Sam Allen

Problem: Store some common data in a singleton or static class about your program in an object array, which you store in a class. It saves state between usages and stores some caches, and must be initialized only once and shared in many code locations. Making a new object each time would be expensive.

Solution

This article covers the differences between the singleton design pattern and the static keyword on C# classes. Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.

Introducing the Singleton Pattern

Our ideal solution is called the singleton design pattern. Here is an implementation of a singleton that I will use. As you know, a singleton is a single-instance object. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference.

view source

print?

01./// <summary>

02./// Sample singleton object.

03./// </summary>

04.public sealed class SiteStructure

05.{

06. /// <summary>

07. /// Possible an expensive resource we need to only store in one place.

08. /// </summary>

09. object[] _data = new object[10];

10. /// <summary>

11. /// Allocate ourselves. We have a private constructor, so no one else can.

12. /// </summary>

13. static readonly SiteStructure _instance = new SiteStructure();

14. /// <summary>

15. /// Access SiteStructure.Instance to get the singleton object.

16. /// Then call methods on that instance.

17. /// </summary>

18. public static SiteStructure Instance

19. {

20. get { return _instance; }

21. }

22. /// <summary>

23. /// This is a private constructor, meaning no outsides have access.

24. /// </summary>

25. private SiteStructure()

26. {

27. // Initialize members, etc. here.

28. }

29.}

Static Class Example

In the following example, look carefully at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages, which I will elaborate on after this code block.

view source

print?

01./// <summary>

02./// Static class example. Pay heed to the static keywords.

03./// </summary>

04.static public class SiteStatic

05.{

06. /// <summary>

07. /// The data must be a static member in this example.

08. /// </summary>

09. static object[] _data = new object[10];

10. /// <summary>

11. /// C# doesn't define when this constructor is run, but it will

12. /// be run right before it is used most likely.

13. /// </summary>

14. static SiteStatic()

15. {

16. // Initialize all of our static members.

17. }

18.}

You can use static classes to store single-instance, global data. The class will be initialized at any time, but it is my experience that it is initialized lazily, meaning at the last possible moment. However, you lose control over the exact behavior of the class by using a static class.

Singleton Advantages

Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.

view source

print?

1.// We want to call a function with this structure as an object.

2.// Get a reference from the Instance property on the singleton.

3.{

4. SiteStructure site = SiteStructure.Instance;

5. OtherFunction(site); // Use singleton as parameter.

6.}

Interface Inheritance

In C#, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface. Usually, the requirements of the interface are a subset of the object in question. Here is how we can use a singleton with an interface, which in the example is called ISiteInterface.

view source

print?

01./// <summary>

02./// Stores signatures of various important methods related to the site.

03./// </summary>

04.public interface ISiteInterface

05.{

06.};

07./// <summary>

08./// Skeleton of the singleton that inherits the interface.

09./// </summary>

10.class SiteStructure : ISiteInterface

11.{

12. // Implements all ISiteInterface methods.

13. // [omitted]

14.}

15./// <summary>

16./// Here is an example class where we use a singleton with the interface.

17./// </summary>

18.class TestClass

19.{

20. /// <summary>

21. /// Sample.

22. /// </summary>

23. public TestClass()

24. {

25. // Send singleton object to any function that can take its interface.

26. SiteStructure site = SiteStructure.Instance;

27. CustomMethod((ISiteInterface)site);

28. }

29. /// <summary>

30. /// Receives a singleton that adheres to the ISiteInterface interface.

31. /// </summary>

32. private void CustomMethod(ISiteInterface interfaceObject)

33. {

34. // Use the singleton by its interface.

35. }

36.}

Now we can reuse our singleton for any of the implementations of interface-conforming objects. There may be 1, 2, or 10. We don't need to rewrite anything over and over again. We store state more conventionally, use objects by their interfaces, and can use traditional object-oriented programming best practices.

Conclusion

Here we can reuse code and control object state much easier. This allows you greatly improved code-sharing, and a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain. One good book about this topic is called C# Design Patterns and is written by Judith Bishop.

Expression Blend 3 – SketchFlow – Creating Prototypes

I’ve been dying to try and use SketchFlow with Expression Blend 3.  I do a lot of development design and ideas and screen layouts. It seems that Microsoft has developed a “tool” to allow for this. Though at first glance I’m lost and confused, maybe because I haven't applied anytime to learn it.  Found a good article from a friend on it so thought I’d post it here for my reference as well.

SketchFlow Official Site – See the screen shots to get an idea what what you can do.

SketchFlow How-to Videos – Scroll to bottom area.

Article, Using SketchFlow to Create Better Protoypes.  By Simon Guest.

http://www.infoq.com/articles/guest-simon-sketchflow

All good developers and designers that I’ve run into do some kind of prototyping. For me, prototyping is about creating a communication channel with customers, sharing ideas with stakeholders, and receiving feedback so that changes can be made early on in the development lifecycle.

RelatedVendorContent

As you’ve likely seen, prototypes can come in all kind of forms, ranging from something drawn on the back of a napkin, through to something that looks very close to the original, designed in a professional software package. Despite this variation we commonly see two different types of prototypes: Low fidelity and high fidelity. A low fidelity prototype is as raw depiction; often a whiteboard drawing or sketch that outlines a particular piece of user interface, an example of which can be seen in Figure 1.

Figure 1 - An example of a Low Fidelity Prototype showing a sign in screen

This is known as a low fidelity prototype because the primary purpose is to show a piece of functionality in its simplest form without any of the icons, colors, font selection and so forth.

The opposite is a high fidelity prototype. A high fidelity prototype, such as the one shown in Figure 2, is still a prototype in that the functionality underneath is not complete or wired up to logic, but the look and feel is closer to the finished product.

Figure 2 - An example of a High Fidelity Prototype

Both low fidelity and high fidelity prototypes have their places in the development lifecycle.

Low fidelity prototypes are typically very effective at getting user feedback as they express the raw functionality of the application without losing the user on the details. As the prototype is nothing more than a sketch, users tend to assume that it will be easy to incorporate feedback and as a result are much more open about giving feedback. With that said, there are situations where low fidelity prototypes don’t work as well. An example I’ve found is when updating the executive team at the next board meeting. Because of the rough format of the low fidelity prototype, I’ve been greeted with looks of confusion when walking into the board meeting with nothing more than a flipchart; the executives thinking “Don’t we pay you to write software?”

As you might expect, high fidelity prototypes suffer from the opposite problem. While they work well in board meetings to show what a finished product could look like, the polish that has been applied can often be too overwhelming for many users. I’ve seen examples where users have been frightened to ask for major changes in a high fidelity prototype due to the amount of work that they feel may have to be done to make a change. The user believes that because the prototype looks so close to the finished product, too much work has already gone into the application, and they often are held back in suggesting such changes. In addition, high fidelity prototypes tend to draw users into a conversation about the finer aspects of the design, such as “Shouldn’t that blue be the same shade as our company logo?” rather than focusing on the overall design of the layout.

Moreover, taking a user through any type of prototype can be very tricky, especially those users based in remote locations. Often, we’ll put together a PowerPoint deck of screenshots and send it to the user without having the ability to share the context or interactively take them through the design.

To help address some of the issues with prototyping, at MIX09 in March 2009, Microsoft announced a new technology called SketchFlow, which will ship as part of Microsoft Expression 3. As described by Group Program Manager, Christian Schormann on his blog, SketchFlow is a fun, informal, flexible, quick and powerful way to sketch and prototype rich, dynamic interactivity with Expression Blend.

In this article we’ll be exploring the functionality within SketchFlow, covering how it works in a soon-to-be-released preview edition, and looking at how such a tool could make your prototypes more usable and effective.

If you’ve heard of the Expression Blend family of products, you’ll likely know that the Expression Blend tool is marketed toward the designer community. While interaction designers will likely make up the majority of the users of Blend, I believe that the SketchFlow functionality also makes for an attractive proposition for many developers – many of whom have been prototyping for some time, using whiteboards through to creating mockups of screens in Visual Basic or other tools.

SketchFlow – Getting into the Details

Expression Blend 3 supports two different types of SketchFlow projects. One for WPF (Windows Presentation Foundation) client based applications, and one for Silverlight applications hosted within the Web browser. Both project types offer the same prototyping functionality, however the asset library offered depends on the platform chosen.

After creating a new project in Expression Blend 3, the first component that you’ll likely run across is the “Application Flow”. The Application Flow panel in Blend enables you to create a simple layout and flow for your application.

Figure 3 - A simple application flow for an online store

As shown in the above diagram, the Application Flow is used to compose a simple workflow for the navigable screens of your prototype. In the above application flow we have five boxes representing a simple online store; a storefront screen, a browse screen, a checkout screen, a sign in screen, and a shipping confirmation screen. The navigation screens are interconnected with one way or bidirectional connection lines to indicate the path that the user will take within the application.

Creating this application flow diagram automatically generates a series of blank XAML pages within Expression Blend.

Figure 4 - Creating the application flow generates a series of XAML files in the editor

With the application flow in place we can now start to add controls to each of our prototype screens.

If you’ve used any previous versions of Expression Blend you could probably guess that we could drag and drop items from the asset library to start creating the user interface.

Figure 5 - Standard controls from the asset library

You would be right, however as you can see in Figure 5, by doing this we are already heading down the path of creating a high fidelity prototype.

To help convey a more low fidelity feel, SketchFlow introduces a new XAML style called “WigglyStyles”. As you can guess from the name, this new style imitates the raw form that you may get from a whiteboard or napkin style of sketch. To add to the effect, SketchFlow also comes with two new fonts depicting a handwriting style and an architect’s sketch style. Applying controls from the WigglyStyles style to the same controls gives quite a different effect.

Figure 6 - Controls using the WigglyStyles XAML style

What’s important to note here is that these are all valid and working controls, not simply images. Edit boxes can accept text, buttons can be clicked, scrollbars can be moved, resulting in a very functional screen yet one that adheres to low fidelity visible characteristics.

Adding Navigation

Now that we have an understanding of the application flow and the styles, let’s start designing our prototype. In this article we are going to be creating a prototype for a new “InfoQ store” designed to sell a range of products branded with the infamous InfoQ logo.

Although we have defined the flow of the screens, we haven’t yet added navigation behavior. For example, when I click on the “checkout” button, I naturally want to navigate to the checkout page.

In previous versions of Expression Blend, and this equally applies to many other UI development environments, wiring up navigation often requires setting an action or event and then having to write some code to handle the navigation. While this isn’t complex for most developers, it’s not necessarily that intuitive to designers or those without a development background and in addition, adds unnecessary code that slows down the development of the prototype.

Expression Blend 3 however, treats prototype navigation somewhat differently. Rick clicking on any control brings up a new “Navigate to” context menu, as shown in Figure 7.

Figure 7 - The “Navigate to” context menu in Expression Blend

Selecting the “navigate to” screen generates an activation trigger on the control. In XAML this looks similar to the following:

<Button FontSize="20" Height="34" HorizontalAlignment="Right" Margin="0,0,8,19" Style="{StaticResource Wiggle_ButtonStyle}" VerticalAlignment="Bottom" Width="105" Content="Checkout">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<Microsoft_Expression_Prototyping_Behavior:NavigateToScreenAction TargetScreen="InfoQStoreScreens.Screen_1_1"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

The XAML responsible for the navigation is the interaction trigger and contains an “EventName” to act as the trigger and “NavigateToScreenAction” containing the desired target screen. All of the XAML is auto-generated by the right click of the context menu and no code is required to wire this up.

Adding Composition Screens

Another area of navigation in SketchFlow is the concept of composition screens. If you have experience in Web development, you’ve probably come up against the need to have common controls on each screen. This might be a common set of tabs or buttons displayed at the top of the web page, or a common look and feel that all pages inherit.

In SketchFlow this is known as a composition screen. A composition screen is a collection of XAML objects that can be displayed in a consistent way on any navigation page. To create a composition screen, we first define a common set of controls.

Figure 8 - A common set of controls that we want to replicate on each page

As Figure 8 shows, this includes four buttons – one for returning to the home page, one for displaying the products page, one for showing the account page and one to display the shopping cart. To take these controls and add them to each page, we select all of the controls, right click and select “Make Into Composition Screen…” as shown in Figure 9.

Figure 9 - Turning these controls into a composition screen

After naming the composition screen (I’m going to call this one “TopBanner”) the controls are taken into a separate XAML file, and the composition screen is shown in the Application Flow.

Figure 10 - The composition screen as part of the application flow

As you can see in Figure 10, the TopBanner composition screen is now displayed in the application flow. (The green color differentiates the composition screen from the blue navigation screens). To bind the composition screen to the other XAML pages, we can create a relationship between the composition screen and the navigation screens.

Figure 11 - Binding the composition screen to other navigation screens that should display the common controls

Figure 11 shows how the composition screen will now be used by the storefront, browse, and checkout navigation screens.

Getting Feedback from Users

We’ve added some more controls to the InfoQ store and now feel ready to share with our users in order to get some feedback:

Figure 12 - A completed form that we’d like to share with our user for feedback

As you might imagine, hitting F5 will build and launch the application, but not as you expect. The application does launch but within the context of the SketchFlow Player, a Silverlight based navigation frame that allows the user to drive the application and add feedback during the process.

Figure 13 - The application running in the context of the SketchFlow Player

As depicted in Figure 13, the user has three ways to navigate through the prototype. The “navigate” tab to the left of the player shows the available screens in the workflow, buttons that were configured to navigate to other pages also work, and in the bottom left the user can also investigate the flow of the application by clicking on the flow tab. This displays the same representation as the application flow in the designer, as shown in Figure 14.

Figure 14 - The flow tab in the SketchFlow Player showing the application flow

While navigating through the prototype, the SketchFlow player gives the user the ability to add comments and feedback about the design in two ways: by entering feedback text into the feedback window (for example, asking questions or providing textual feedback on the prototype) and by actually drawing on the screen with an ink or highlighter control. Both text and ink feedback are shown in Figure 15.

Figure 15 - Some user feedback on the search screen for our store application

This can be very useful for the user to share details on finer elements of the design such as placement of controls or windows. This feedback is saved as a “.feedback” file which can then be uploaded to a site or emailed to the original development team. When the development team receives this feedback, it can be imported back into Expression Blend 3 and used as an overlay within the project, allowing the team to have the exact user feedback and annotations as they relate to screens in the designer.

States and Transitions

We talked about screen navigation earlier, but how about if you want to display a message or another animation that didn’t warrant creating a new page? For example, in the InfoQ Store when the user clicks on the “add cart” button, we may want to display a message confirming that an item was successfully added to the shopping cart. This doesn’t necessitate a new screen, but we do need some action to handle the response in the prototype. In SketchFlow this is known as a change of state.

States are created using the States tab to create a group of elements on a page.

Figure 16 - Two states for showing and hiding the “added to cart” message for the user

In the above example, notice how I have created two states – ShowCartMessage and HideCartMessage. I can define what happens in each of these two states. For DialogBoxShow I create a simple dialog that contains a message to indicate that the item has been added and set the opacity of the dialog to 100%, similar to the one shown in Figure 17.

Figure 17 - A simple dialog to indicate the item has been added to the cart

Likewise, for the DialogBoxHide state I set the opacity of the dialog to 0% in order to give the effect that the dialog box has been removed.

Similar to how I wired up the navigation controls earlier, I can simply right click on each of the controls to bind them to a particular state. In this example, when the user clicks on the “add to cart” button, the ShowCartMessage state is activated and the dialog is shown.

Figure 18 - Binding a state to a button control

A similar action is added to the dialog so that when the user clicks anywhere on the window, the message disappears.

Similar to the form navigation, binding to the state adds a XAML code block for each control. The behavior controlling the state is the ActivateStateAction:

<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<Microsoft_Expression_Prototyping_Behavior:ActivateStateAction TargetScreen="InfoQStoreScreens.Screen_1" TargetState="ShowCartMessage"/>
</i:EventTrigger>
</i:Interaction.Triggers>

For added effect, states also support transitions and animations. For example, if our prototype mandated that the dialog box show fade or fly in then we could create a XAML storyboard that could accommodate this. As you’ve probably guessed, everything created by SketchFlow is correctly formed XAML – there are no proprietary switches or hidden options – this means that anything that can be done in XAML can also be reflected in the prototype, even if it’s not supported in the designer.

Adding Sample Data

Up to this point, we’ve covered adding controls and navigation, but a critical element to many prototypes is the need to pull in sample data – in our example this could be a list of products that we’ll be selling through the InfoQ store.

Previous versions of Expression Blend have supported connecting to external data sources through either a direct database connection or CLR object, but wiring this up can be time consuming especially in a prototype environment. It the prototype has a chance of being rejected, it can be cumbersome to create a database, schemas, and tables in a database to handle a few sample objects.

To help overcome this Expression Blend 3 supports the ability to create sample data directly within the designer. This is achieved by adding a new sample data source in the data tab:

Figure 19 - Sample data options within Expression Blend 3

Two options are supported in the current preview; defining a new set of sample data or importing sample data from XML. The second option can be especially useful if you have an XML data representation from an internal system, for example an export from a current line of business application or even a public RSS feed.

No XML data source exists for the prototype store, so I’ll choose to define some new sample data instead.

Figure 20 - Sample data collection for our store

For the sample demo store, a simple collection of types representing the products has been created. You’ll notice that the sample data collection supports multiple data types. SKU is represented here by a text field, but the image is actual a .PNG file from disk (a directory of images can be imported into the sample data collection).

Now that we have the data structure defined, we can define the sample data for the store:

Figure 21 - Editing sample data

Note that in addition to supporting fixed values entered into the sample value dialog box, Blend also supports “automatically generated” sample data for a number of types.

Figure 22 - Automatic sample data types

This option is especially useful if you are working on a prototype that has a need to display a list of fake telephone numbers, URLs, Email addresses, etc.

With the sample data complete, the next step is to drag and drop the data collection from the data panel to the object (in this case this is the search list box) to populate the item. When the application is run, all of the data imported is usable within the prototype.

Figure 23 - Dragging and dropping the data collection to the search list box to populate the items in the prototype

You can imagine creating a new state bound to the “Search” button in this form that populates the sample data.

Documentation

I’ve run into only a few people that actually find enjoyment when creating documentation for projects - yet documentation, especially for prototypes, can be critical as it provides a record for mapping out all of the elements assets, user feedback, and states for a prototype.

If you fall into the category of not liking documentation either, one of the features in Expression Blend 3 you’ll be pleased to see is the “Export to Microsoft Word” option from the file menu.

Figure 24 - The “Export to Microsoft Word…” option

Clicking on this option generates a new Word document based on all of the elements in your prototype file.

Figure 25 - Example output

This includes application flow, screen layouts, user feedback, transitions, and states, all wrapped up with a table of contents and list of applicable figures. All this information in Word format makes it easy to then apply a template and add your own comments before sending it to your user or client for review.

Moving from Prototype to Production

At the end of the day the success of a prototype can often be measured by the success of the resulting application, which raises the question, “How do I take these prototypes into production?” When working with customers I often see two approaches.

The first answer is to throw everything away, and with existing tools this is often the case today. Frequently, a designer will create a screen mockup of an application in a tool such as Adobe Photoshop, export the complete image to JPG files, and then rely on the developer to take those JPG files and create the real application. More often than not this can lead to different interpretations between the designer and developer, especially around some of the subtleties within the design.

The second answer is to keep as much of the prototype as possible in order to re-use the assets as you move into production. Using SketchFlow, a lot of the visual assets and controls can be kept, together with replacing the navigation and application flow with a more robust framework such as MVC, switching out the states into code, handling exceptions, and so forth. There is always a balance between how much of a prototype you keep into production and how much gets thrown away, but an interactive prototyping tool makes it much easier to make those kinds of tradeoffs.

Conclusion

I hope this article has been useful for walking through some of the early capabilities in SketchFlow. Microsoft is still very early on in the preview process for Expression Blend 3, so lots of things may well change before release, but I hope you’ll agree that this new set of tools has the opportunity to help designers and developers take prototyping to the next level.