Archive

I’ve been familiar with WPF since December 2006 and the release of C# 3.0, and I’ve had Expression Suite installed for almost a year. While I’ve toyed with it here and there, I have never devoted the time and effort necessary to really begin to become proficient.

However, since last week’s Silverlight 2.0 release, I have been burying myself again in learning new technologies. I finally decided to take the plunge, so I installed Silverlight 2.0, the Visual Studio updates, and upgraded to Expression Suite 2 SP1. I spent a couple of days going through ScottGu’s tutorials and some others on Silverlight.net. I followed along and built the samples, some in Visual Studio and some in Blend.

Most of these have been around for a while, so I’m not claiming any kind of leading edge stuff here. What I wanted to do was to share some of the insights I’ve had in attempting this project.

What’s the big deal

XAML marks a sea change in how user interfaces are developed. The end result of XAML is still .NET objects, and as such they can be created and managed programmaticaly, but the ability to simply describe what you want is very attractive. For a long time, I did not like XAML itself, and one of my reasons for putting off learning WPF was that I wanted to wait until something like Blend made all XAML interaction obsolete. After diving in for a few days, I no longer feel that way, but I’ll share more about that later.

What really makes all this so attractive is the ability to do basically whatever I can imagine for an interface. More importantly, I can do it without a ton of hand coded control drawing, something I never liked doing in the first place. The behavior of a control truly is separate from its presentation, and the presentation can be altered or replaced in any number of ways. In other words, you can achieve some pretty cool effects with a reasonably small effort.

Visual Studio or Blend?

I’ve been having an ongoing discussion with a friend of mine at RVNUG about the usefulness of writing WPF applications within Visual Studio. Having seen some demos and had some training on Blend, I was staunchly in the Blend corner on this one. While you can drag and drop controls in Visual Studio, it takes a lot of hands on XAML coding to get anything more than a rudimentary window up and running. As I mentioned previously, after seeing some XAML presentations I really wanted to avoid that as much as possible, which is what makes Blend so intriguing.

But, having gone through ScottGu’s Silverlight tutorial and building an application in Visual Studio, I have a better appreciation for it now. One thing I do like about using Visual Studio is that it is keyboard centric. As a classic Midrange developer I have always shied away from using the mouse as much as possible, so it appeals to my keyboard-philia. And of course, Intellisense is still the killer feature and makes it much more palatable. Also, as a seasoned and grizzled web developer who still likes the occasional dip into VI and Notepad, it only took a little time with XAML to feel comfortable with what was going on. Anyone familiar with XHTML and CSS should find XAML completely doable. It is, of course, a lot more complex, with numerous options and quirks, but it is still familiar territory.

Now, all that being said, I still prefer Blend 5 to 1 over Visual Studio for Visual XAML development. I have only run into a few things that I couldn’t accomplish easily through Blend, and I’m new enough to it that I still chalk it up to just not knowing the tool well enough. Applying and developing styles is still one of these areas: I so far have not figured out how to do them in Blend, so I revert to XAML editing.

Which brings me to my question of the day: “Should I use Visual Studio or Blend?” The answer is a resounding “both!” OK, I’m sure you saw that one coming, but let me explain my position. If you are a developer, there is no question that you are going to use Visual Studio. After all, it is our bread and butter, and all the real code will still be developed in our beloved IDE. But designing serious WPF solutions in Visual Studio would be far too painful, even with great Intellisense support. There are simply too many options to have to code them by hand.

It reminds me of my first Windows application: a Java Swing application that I wrote in Wordpad. Believe me, the pain of that experience made me instantly recognize the value of Visual Studio and is largely responsible for my shift to Microsoft technologies. On the same order, as soon as I saw Blend I knew that this was the tool I needed to design good WPF applications. So, for layout and Visual Tree management, use Blend. When you find a problem that you think you must solve using XAML editing, switch over to Visual Studio and take advantage of Intellisense, which Blend does not have.

Quirks

A couple of things so far have jumped out at me. While Blend and Visual Studio do a pretty good job of keeping each other in synch, there are a couple of irregularities.

The first real problem I had was in adding existing projects to my solution in Visual Studio. I started my solution in Visual Studio and then opened it up in Blend to work on the design. Later in the same session, I went back to Visual Studio and added several projects. Now that I had some CLR objects to work with, I wanted to try Data Binding, so I followed one of the online tutorials but no joy. No matter what I did, I could not get Blend to find the objects. Every time I tried, I received a slew of “file could not be located” errors. Finally, I restarted Blend and when I opened my solution, there the missing objects were.

Second, there have been several times when I’m not sure that I am being properly prompted to reload. I could be imagining it, but I feel pretty strongly that I have made changes in one without being prompted by the other to reload them. Perhaps this is just a matter of timing Saves.

Conclusion

Well, I don’t really have any as of yet. I do think that a lot of developers are going to struggle against the designer learning curve, yours truly included. But I think in the long run we will be much better off. So far, I am pleased with my efforts. I like the combination of resources the two applications provide me, and I amd getting more comfortable in deciding which to use for certain scenarios.

I’m not quite ready for a tutorial series, but I will try to share some of my learning with you all as I go. In the meantime, give it a try yourself and let us know what you think. Happy Coding!

Today I am in Roanoke, VA at the MSDN Mid-Atlantic Roadshow. This Microsoft event highlights Web development and .NET 3.5.

Web Development Basics – 9am

Presented by Andrew Duthie, Microsoft Technology Evangelist. Andrew presents a nice history and overview of web development, from HTML/XHTML, Classic ASP, and up to ASP.NET. It definitely confirms my opinion that I am glad I never was a Classic ASP developer!

He discussed Postback and ViewState, (my least favorite features of ASP.NET and hence my appreciation of ASP.NET MVC.) I know this is not a popular ASP.NET view point, but it makes it difficult for traditional web developers like myself to step into an ASP.NET role. One thing he mentioned was that you can disable ViewState for particular controls, for performance reasons. You would only do this if the element was for display only.

He also discussed one of my favorite features, Master Pages. I have long used this same concept in PHP development and I immediately recognized it in ASP.NET.

Note to self: learn about Membership Profiles. I’ve been developing my own because I am connecting to a non-standard data source (IBM iSeries DB2). Andrew said you can write your own custom backend but still use the built in Profile features.

DataBinding Demo: he showed a typical GridView Control bound to a SqlDataSource. “Declarative Data Binding” – there is no executable code that drives the GridView, it is all expressed in the ASPX. It is fast and easy to develop, but you still have the option to develop your own binding for more control.

Web Services: ASMX and WCF Services both supported. ASMX is simpler, and hosted on IIS, but harder to make cross platform capable. WCF is more complex to configure and can be hosted by any .NET process. ADO.NET Data Services uses WCF. WCF can be used to communicate between servers and applications. “ABC”s of WCF: Address, Binding, Contract. I think it’s time I learned about WCF…

What’s New in the .NET 3.5 Framework for Web Developers and Intro to ASP.NET MVC – 10:40am

Entity Framework is a set of services that allow you to consume EDM from within your applications. It includes Object Services, Entity Client, EntitySQL, and Linq-to-Entities.

Visual Studio Support is supposed to make the development seamless and simple.

DataSets are raw data store connections. Linq To SQL provides an ADO.NET connection to SqlServer. Entity Framework is going to allow ORM connections to most any database.

DEMO: Z wrote live a WPF application that consumes EDM. Create a WPF solution. Add a DLL project and add a new ADO.NET Entity Model item to the project. Select the data connection and store it in the Web.config file. The database is diagrammed in Visual Studio, complete with relationships. It also creates a Mapping Details window, which he did not demonstrate, but it looks like that is where you change the mapping. The EDMX file contains the XML definition of the SSDL and CSDL. Copy the App.Config file from the EDM project to the WPF project – this links the WPF to the correct Data Store. Add an xxxEntities model object to instantiate the connection. Very fast development, very impressive results in less than 5 minutes!

ASP.NET Dynamic Data

Data driven web application scaffolding. If you are unfamiliar, scaffolding, popularized by Ruby on Rails, provides default pages for Insert, Update, Delete, etc. DD is based on an object model with full controls, metadata, validation, etc. This is expressed in two new ASP.NET project types: Entity Data Model and Linq To SQL.

DEMO: Z added a Dynamic Data Web Application to the above demo so that he could tie in to the same EDM code he already produced. Set the connection stream in the Web.config file to connect the site to the EDM data store. Apparently DD is set up assuming Linq, so Z had to make changes to the Page Templates to use the EDM instead. He had to change LinqDataSource to EntityDataSource. Then he had to register the EDM assembly within the individual pages. (Couldn’t you do this once in Web.config?)

The default scaffolding is very nice and has all the features you would expect. I saw a Routing mechanism, but he did not really discuss how it is used. He demonstrated custom validation. It uses System.ComponentModel.DataAnnotations and implements events for validation.

Overall it looks interesting, but I’m not sure yet how it would be used in a real world setting.

ADO.NET Data Services

Formerly “Astoria”, this technology exposes data in a secure fashion over the web or network. It is a combination of patterns and libraries that enable the creation and consumption of data services for the web as “feeds”. This does not have to be a database: it can be any data source.

Implemented as ATOM – tables = feeds, rows = entities. Includes CRUD, is RESTful, and a URI points to a resource.

Uses common URL syntax

Capable of exposing any object model that contains IQueryable<T>, such as Linq to SQL and EDM.

Locked down by default and supports Operation Batching

Supports optimistic concurrency

DEMO: Z added a ADO.NET Data Service item to the above Web project. You have to update the service code to indicate what the model is and set some rules. It was a lot of copy and paste and went by too quickly to document. At this point he basically lost me. He hard coded the port the service executed on. He generated a file using DataServiceUTIL.exe (but never executed the app that I saw) and then copied the file into the WPF solution. He added a reference in the XAML to the service and a pointer to the service in App.config. He did finally get it working, and it is interesting, but again I’m not sure how I would use it.

ASP.NET Routing

Routing maps an application URL to specific handlers. I have been using this in ASP.NET MVC for a while, and they have always said that this was not limited to MVC. His example used DynamicDataRoute() instances. At this point his time was running short, so he didn’t really go into a lot of details.

ASP.NET MVC

As we know, MVC has been in my sights for a while now, and I have been very pleased with the implementation. To be fair to Z, he was really rushing to get through this because of time. Unfortunately, I think he skipped a lot of important basics, but he did at least demo the default and the Task List projects. He really skimmed over the project types, and in the long run I think he just confused anyone who was not already familiar with MVC. Last but not least, he only mentioned that you could use Unit Testing, but did not demo it at all.

AJAX Development and Troubleshooting – 1pm

Andrew Duthie presenting. AJAX is a system of lightweight calls to the server without having to repost the entire web page. I have used AJAX extensively in ASP.NET MVC using jQuery.

ASP.NET AJAX

Simple Development Framework

Represented as additional libraries to ASP.NET

Two Models:

UpdatePanel Control (zero code implementation)

ScriptManager Control (provides a rich framework of JavaScript libraries)

Included with .NET 3.5. AJAX Control Toolkit is a separate project available from CodePlex. The AJAX libraries work on Windows, Mac OS, and Linux in IE, Firefox, Opera, Safari, and others.

DEMO: Andrew created an AutoComplete textbox sample. Create a Web Form and add an AJAX Form to it, which automatically set up the ScriptManager. Add a reference to the AjaxControlToolkit. Now all the Extenders are available in the toolbox. Drag an AutoCompleteExtender to the page and set up a few attributes to hook into a data source. Viola! Good demo.

AJAX updates in .NET 3.5 SP1:

Browser History – allows an Ajax page to be bookmarked for future return (including page data)

Script Combining – batches a set of Scripts to be treated as a single download

ANNOUNCEMENT: jQuery will be included in all future versions of Visual Studio! It is to be treated as a first class citizen, complete with jQuery support. Microsoft will even have full PSS support. ASP.NET MVC will be the first ship of this feature.

AJAX Troublesooting

While it is a great tool, Visual Studio is not enough. You also need tools for CSS, DOM, and Scripting analysis.

The IE Developer Toolbar allows you to drill down into your code and is especially good for IE 6 and IE7. IE8 has built in developer tools including JavaScript debugging, dynamic CSS changes, and more.

Andrew then spent the rest of the session showing some cool AJAX and JavaScript components.

Microsoft Silverlight 2.0

Ashish Jaiman, ISV Architect Evangelist

Silverlight is a cross browser, cross platform .NET plugin for delivering Rich Experiences in a browser. Silverlight runs in the browser sandbox and executes .NET code. Can be hosted in any container element in HTML. HTML can be overlaid on top of Silverlight elements, and you can have many Silverlight components on a single page.

Silverlight 1.0 was only HTML and JavaScript. Silverlight 2.0, on the other hand, includes a mini CLR, WPF controls, LINQ, collections, media, layout controls, and more. Silverlight 2.0 has local storage, FileOpen capabilities, sockets, and cross domain HTTP requests.

Silverlight Pros:

Video/Audio

Enhanced UX to increase stickiness

Decrease the learning curve

High resolution imagery

Data Visualization

Leverage .NET Skills for cross browser/cross platform solutions

Silverlight Cons:

Requires a browser plugin

There is still a learning curve

Need for designers to take full advantage

Designer and Developer Collaboration

This brings up one of the main problems with WPF and Silverlight. Microsoft’s belief is that developers should focus on developing data, communications, business rules, etc. Designers should be the ones designing our user experiences. As a one man shop, I can tell you that this isn’t going to happen, but I understand Microsoft’s point.

In order to really maximize the XAML abstraction concept, it will truly take a designer’s touch wrapped around a developer’s logic. XAML is simply a description of a user interface in XML and contains no code. A designer can then use tools like Expression Blend (2.5 for Silverlight 2.0) to design the interface, which will then export the design as XAML. Visual Studio then can read the XAML and allow the developer to add any necessary application logic. In fact, Blend and Visual Studio can be opened and used simultaneously against the same code, which is more realistic for someone in my shoes.

ASP.NET includes Silverlight support via the <asp:xaml> and <asp:media> tags, Silverlight has web-service support, and it can utilize the Membership, Profile, and Application Service integration. IIS 7.0 also includes specific support for Silverlight.

Here is a pretty cool Silverlight demo. (Go to the “Patient Journey Demonstrator”)

Styling and skinning are completely customizable, which is one of the main points of WPF technologies: however you can imagine visualizing your data or application, then you should be able to make it a reality in WPF/Silverlight.

Local Storage

“Cookies on steroids”, local storage provides 1MB of application specific local information. Can be expanded if the user allows it. Exposed through Microsoft Isolated Storage.

DOM Integration

Silverlight is still a browser application, so it can interact with and create HTML elements and scripts through .NET code.

Open File Dialog

You can use this to open a local file on the client.

LINQ

Silverlight 2.0 has LINQ support as part of its CLR. Currently only on IEnumerable<T>, but XLINQ and DLINQ are in development.

Back in February I posted the beginnings of a project to wrap Authorize.Net credit card transactions in C# .NET code. I have been working on this project off and on, in conjunction with a new website we are developing, and have been meaning to post the production version for some time.

Today, I am publishing the current version of the code, DevelopingForDotNet.AuthorizeNet, along with a few supporting updates. I’d like to thank everyone who posted comments on that entry and the First Foray into Unit Testing entry. Most of those suggestions made it into the final version and I learned a lot about Unit Testing along the way.

This version is slightly different than the original post. Here are the major differences:

Validity Checking

This version incorporates validity checking on the following TransactionRequest class properties:

EMail

Zip

SecurityCode

CardNumber

ExpDate

EMail, CardNumber, and ExpDate validation have been completely rewritten.

Right now, all the failures throw an ArgumentException, which is very heavy handed but I haven’t had a need to improve it yet.

INotifyPropertyChanged

Each of the three classes implements INotifyPropertyChanged so you can use them for data binding if you wish. If you have never implemented this interface before, it is very easy. Add a reference to System.ComponentModel to your code. Then add the inheritance statement to your class:

public class TransactionRequestInfo : INotifyPropertyChanged
{
...
}

Then implement the PropertyChangedEventHandler and add a method to fire the event:

Transaction is a static class with ProcessPayment as its single static method. In reviewing the project, I realized that this was a perfect case for an Extension Method, so I added this before the first keyword, and now calling the method is even nicer than before:

I really got my feet wet with Unit Testing on this project. I followed the advice I got from FreekShow and implemented the testing of Exceptions in a much cleaner fashion. The whole experience got me thinking about why Unit Testing is so beneficial, and as I began rewriting the code I started by writing tests that fail first and then coding my way into success. Just for grins, the testing project for this solution is included in the download.

Last night I attended the monthly RVNUG (Roanoke Valley .NET User’s Group) meeting. Kevin Hazzard gave a good presentation on Silverlight 2.0, which I have been eager to try. After what I saw last night, and now that I have a little experience with WPF, I am even more eager to give it a shot. What I am not eager to do is what I saw last night, and that is Silverlight development in Visual Studio. More specifically, I have no desire to hand code XAML, which is why I like Blend so much.

Today I’ll be downloading and installing the Silverlight 2.0 Beta 1 Tools, and I may install Blend 2.5 Preview (which I hear is far from rady for prime time). I’ll be putting together a couple Silverlight samples in the next week or so. If I come up with anything interesting, I’ll be sure to share it.

In this example, our task is to build a portion of an SQL update string that contains only the fields within a class that have been changed. The class stores original values and current values, so finding the changed fields is a simple matter of comparison. We are going to use a StringBuilder to construct the string. The problem comes in properly appending a comma between each name-value pair string. You cannot always add one after adding a new string since it may be the last, so the solution is to check the length of the StringBuilder before appending the string: if it is greater than 0, then we append a comma first.

The task is simple enough, but what we end up with is a lot of redundant code:

As you can see, this repeatedly defines the same behavior. It is especially aggravating when dealing with some of our legacy database tables that have hundreds of fields. While it may not be likely in this example, if we had to change this behavior it would be very tedious and some changes could easily be missed. This action is only relevant within the context of our Update method, so I really don’t want to outsource this to a private class method. Instead I will use a Generic Delegate to create a Local Method.

Since I am updating a local variable, I really don’t need to pass it: I’m going to take advantage of local variable access to reduce the parameter list and simplify the method signature. I do not need a return value, so I am going to use Action<T> to define a method that accepts a string and appends it to the StringBuilder and handles the commas as necessary. To ensure I can access the desired StringBuilder variable, I need to define it before defining my Local Method:

And this code could probably be simplified a little more, but I think this is adequate to the task. Hopefully, you’ll agree that this technique has merit. It’s very clean and easy to implement. I really like this, so much so that I am going to need to be careful to take my own advice and not go crazy with this approach.

I’m sure that most of us have created many private methods to outsource code from one method to another. There are times we do this even when the method is only called from a single location. I’m going to use a simple example, but I think you’ll get the point:

Console.WriteLine(“{0} {1} was probably born in {2}.”,
person.FirstName,
person.LastName,
age);}

Kind of a silly example, but fairly straight forward stuff, right? Well, what if we had two loops or other calculations in the same method that needed to know the Year born? Since we believe in code reuse, we would typically throw this into its own private method:

This should be code we can all relate to, and is a fine practice because it accomplishes two very important things. First, it promotes code reuse. Second, it simplifies and cleans up our logic. What unfortunately happens quite frequently is that the outsourced method is only called from one other method, even if it is multiple times. In this scenario, what we really need is a Local Method.

Local Methods

I don’t know if anyone else has coined this phrase before in this context, but it seems appropriate. A quick google search turned up several references to Java and some statistical analysis looking items. Adding the “C#” to the search terms found a couple of references where the term is misapplied to mean a private class method. To be clear, though, what I mean by Local Method is a method defined completely within a non-class parent scope. If you think about it, that’s what Anonymous Delegates are, but unlike an anonymous delegate, we need to be able to assign our method a name. The Func<> Generic Delegate can be used to accomplish this goal.

This approach is going to give us the best of both worlds. First, it is going to allow us to reuse code. Second, it is going to clean up our execution logic by replacing some of it (or maybe even all of it) with a method call. Finally, it is going to help reduce “Class clutter” by eliminating private methods that are only called from one location.

Creating and Using the Local Method

In order to use the local method, we first need to define it as a local variable. This local variable is of type Func<>, which has several different signatures. We are going to use Func<Person, int> to create a method that accepts a Person object as a parameter and returns an int:

I think you’ll agree that this is pretty cool and could be very useful. And of course, since this is based on a Generic Delegate, we can use Lambda Expressions to write our code. So even though this is a fairly silly example, let’s go ahead and clean it up a bit:

I really like this approach, but it naturally does not suit every purpose, so rule one, to paraphrase Sean Connery in The Untouchables, “don’t bring a knife to a gun fight.” In other words, don’t go crazy and use this just because you can. Use it to minimize repeated code within a specific method or to simplify complex code blocks.

There are a couple of additional things you should know. First, you must define the delegate and method details before using them, otherwise the compiler will complain. Second, since this is a local method it has complete access to the other local method variables: this should help reduce the number of parameters you must send in order to accomplish your task. Finally, since the local method is actually a local variable itself, you should be able to change the address dynamically to other delegates. I don’t think I would recommend this last item, but it could prove to be interesting experimentation fodder.