Using the WPF Visualizer in Visual Studio 2010

Visual Studio 2010 now has a cool little feature I want to show you. When you’re debugging WPF applications, you sometimes need to see the controls and their hierarchy. Now with VS2010 this is easy. Simply use the magnifying class (the visualizer feature) and select the WPF Tree Visualizer:   This will show you all the controls with their properties like this:   In the left pane you get the tree view of controls with a rendering of the selected control, at the right side you get all properties of the control.

WCF and large messages

This week I’ve been training a couple of people on how to use .NET, WCF4, Entity Framework 4 and other technologies to build an Enterprise Application. One of the things we did was return all rows from a table, and this table contains about 2500 rows. We’re using the Entity Framework 4 self-tracking entities which also serialize all changes made it the objects. And I kept getting this error: The underlying connection was closed: The connection was closed unexpectedly. Server stack trace:    at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)    at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)    at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)    at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) At first I thought it was something to do with the maximum message size, another kind of error you get when sending large messages. The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element. Server stack trace:    at System.ServiceModel.Channels.HttpInput.ThrowMaxReceivedMessageSizeExceeded()    at System.ServiceModel.Channels.HttpInput.GetMessageBuffer()    at System.ServiceModel.Channels.HttpInput.ReadBufferedMessage(Stream inputStream) This one is easy to fix (although a little confusing because you have to configure the binding of the receiving side of the message, which is most of the time the client: But doing this didn’t help. So what was it? I knew the size of the message couldn’t be the problem, because I’d sent way bigger messages before. Maybe there was something in the contents that made the DataContractSerializer crash? Checking this is easy, I wrote a little code that would make the serializer write everything to a stream and see what happens. Works fine. Hmmm. What could it be? So I went over the list of properties of the DataContractSerializer. I has a MaxItemsInObjectGraph property. Maybe that was it, but how can I change this number? Looking at the behaviors I found it. What you need to do when you send a large number of objects is you have to increate this number, which is easy. At the server side you use the DataContractSerializer service behavior and set its value to a large enough number:   At the clients side you use the DataContractSerializer endpoint behavior. That fixed my problem.

Using the Visual Studio 2010 Historical Debugger to save and reproduce bugs

Visual Studio 2010 Ultimate now has IntelliTrace, which is a historical debugging feature. IntelliTrace will keep track of everything your code has been doing and then, when a bug arrives, you can back-track to the possible cause of the bug. You might think this is nothing new, but don’t forget it also tracks the value of any variable at that moment in time. With the usual debugger you will see the latest value, not the value at that moment. You can enable (and it is enabled by default) by going into Options->IntelliTrace->General If you want to try this, build a simple windows forms application with a Button and CheckBox. Then add code as follows: 1: Public Class Form1 2:  3: Private message As String 4: Private flag As Boolean 5:  6: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 7: flag = FlagCheckBox.Checked 8: Doh() 9: End Sub 10:  11: Private Sub Doh() 12: If flag = True Then 13: message = "This should work" 14: Else 15: message = Nothing 16: End If 17: flag = True 18: ShowMessage(message) 19: End Sub 20:  21: Private Sub ShowMessage(ByVal message As String) 22:  23:  24: ' Throw exception if message is empty 25: Dim len As Integer = message.Length 26:  27: End Sub 28: End Class Run it with the checkbox unchecked. This should cause the application to stop in the debugger: Your code should look like this: See those special arraws in the gutter (the gutter is the section where you click to add/remove breakpoints)? These will allow you to backtrack. You should also have a IntelliTrace window looking like this (two views are available): With these you can jump directly to one of your code’s stackframe. Let’s try stepping back to see what happened. Press the back arrow, or better yet, use the keyboard shortcut (on my machine that is Ctrl+Shift+F11): You should now be able to step back in time, for example look how my IDE looks like when stopped at the ShowMessage method: IntelliTrace keeps track of the values of the arguments and such, at each point in time. For example, a little higher in the code I changed the flag variable to true, while the bug is caused because it was false before. IntelliTrace will show me this. 1: Private Sub Doh() 2: If flag = True Then 3: message = "This should work" 4: Else 5: message = Nothing 6: End If 7: flag = True 8: ShowMessage(message) 9: End Sub IntelliTrace will save all of this information in a file (now with an extension called iTrace, notice the naming convention <GRIN>), and because you can open this file afterwards, all kinds of scenario’s can now be implemented. You can send the file to a colleague so he/she can help you debug the problem. So where is this file? Go back to Tools->Options->Advanced and copy the directory for later: Open this directory in file explorer and copy the file to where you like. You will have to stop debugging, otherwise Visual Studio keeps a lock on the file. Don’t stop Visual Studio, because VS throws away the log file when it quits. When you open the file again, Visual Studio will show the log’s summary: Open the Thread Lists and look for the thread you want to see (probably the main thread): Double click it and with a little patience the debugger will open (make sure Visual Studio can find the sources). Or better even, the Visual Studio Test and Lab Manager 2010 can do this for you. So even if you have a non-technical user who is testing some application, and finds a bug, the IntelliTrace file will be attached automatically!

Building an Enterprise Application with Entity Framework 4

Entity Framework 3 was a bit of a disappointment when it came to supporting enterprise applications. For me the major reason was the fact that entities used by EF required deriving from a class which is part of EF, thus coding the EF requirement into your Business Logic Layer (BLL) and presentation layer. EF 4 is still under development, but already they’re making a lot of compensation for this with their support for POCO (Plain Old Clr Object) and self tracking objects. POCO vs. Self Tracking A self tracking object is an object that has state where you can check what has happened to the object (unmodified, new, modified, deleted). The advantage of this kind of object is simplicity for the user, because the object does all the tracking. Of course this means more work building the object itself, but this can be solved using T4 templates. A POCO is really nothing more than a data carrier object, without any tracking support. Simplicity means maximum portability, especially if you use DataContracts. For the rest of this post I’ll be using self tracking objects, generated through EF 4. I’ll also be using the EF feature CTP 2. Using EF 4 to generate the self tracking objects Start by creating a new WinForms project (of WPF, Silverlight, whatever). Add another library project for your data access layer (DAL) and another one for your entities: Normally I would also add a business logic layer (BLL) but for simplicity I’ll leave it out for now. Now add a new Entity Data Model to your DAL project. Select the Northwind database, then select the Categories and Products tables: This way you end up with this model: Please note that my tables/entities each have an extra column, the Version column. This is a TimeStamp column used to detect concurrent updates. To tell EF to use this column for concurrency, set its Concurrency Mode property to Fixed. This is typically the best way to handle concurrent updates. Right-click your entity model’s background, then select the Add Code Generation Item… menu choice: This alternative code generation will add two T4 templates to the DAL project (using the .tt extension) The ProductsModel.Context.tt is an EF dependent template, so leave it in the DAL project, but the ProductsModel.Types.tt contains the EF independent types which actually are self-tracking entities. Move this template to the Entities project: Watch out, your project will not build until you set following references (diagram made with Visual Studio’s new UML Component Diagram) : This diagram also includes the BLL layer, our solution doesn’t, but if you want, feel free! If you’re using VB.NET, you should also add the Product.Entities namespace to your list of imports of the DAL project: Now you’re ready to implement the DAL layer, so add a ProductsDAL class as follows: 1: Public Class ProductsDAL 2:  3: Public Function GetListOfCategories() As List(Of Category) 4: Using db As New NorthwindEntities 5: Return db.Categories.ToList() 6: End Using 7: End Function 8:  9: Public Sub UpdateCategory(ByVal cat As Category) 10: Using db As New NorthwindEntities 11: db.Categories.ApplyChanges(cat) 12: db.SaveChanges() 13: End Using 14: End Sub 15:  16: End Class Now let’s add some controls and data bind them with Window Forms. For this I use the Data Sources window. Open it and add another data source. Select an object data source: Then select your Category of Product entity, which you should find in the Products.Entities project: Your data source window should now display your entities: Right-click category and select Customize… from the drop-down list. Now you can select Listbox as the control to use. Drag the Category entity to your form to create a listbox and bindingSource: Add two buttons, the Load and Save button. Implement the first button to retrieve the list of categories from the DAL: 1: Dim dal As New ProductsDAL 2: CategoryBindingSource.DataSource = dal.GetListOfCategories() And implement the save button as follows: 1: Dim dal As New ProductsDAL 2: Dim cat As Category = TryCast(CategoryBindingSource.Current, Category) 3: dal.UpdateCategory(cat) Run the solution and click on load. The listbox should fill with categories and the window should look like this (you might first want to copy the connectionstring in the DAL’s project .config to the form’s config): Note the “Change Tracking Enabled”. Check the checkbox if you want to update an object, this will enable the self tracking. Make a change, then click Save. This should update the database. Open two instances of this application. Load in both, then change the same record in both (with tracking enabled). Save both. The second Save should fail because of concurrency checking. Done!

Project Management: Planning an iteration with Team System 2010

In my previous post I talked about planning a whole project. Now I want to blog about planning a single iteration using the new Team System 2010 iteration with Excel and Project. After creating the user stories, the next step is to break each user story into detailed tasks. To facilitate this, the MSF agile template has a special Excel sheet under Documents->Shared Documents->Iteration <X>: Double-click to open it. Before you edit, click the Edit Workbook button beneath the ribbon: To split up a user story into (linked) tasks, you want to create child work items beneath your user story. Do this using the “Add Child” button on the ribbon: Pressing the Add Child will add another row to the sheet, and also adds another Title column. This is used to detect/indicate the parent/child relation between two work items. So here I’ve added a couple of child tasks to the user story. Now we can start planning the iteration. First you will want to fill in the “Assigned To”, “"Remaining Work”, “Area” and “Iteration” columns with some data. Choose a team member for the Assigned To column, and choose your iteration for the Iteration column. Here’s an example: Next you want to plan the iteration, so go to the Settings tab. In this tab you set the iteration start and end date. The Excel sheet will use this together with the interruptions sheet to determine the amount of work that can be done in this iteration. Once you fill out this sheet you can go to the Capacity sheet, where you can balance the work load for each team member. Start by providing the hours/day and number of days in the iteration for each team member. Now you can see the workload for each team member. April has way too much work (and Abu too little) so go back to the backlog sheet and move some work to Abu. Go back to the capacity sheet and see the now work load: Imagine Doris being called over to help with another project. How will this affect capacity? Start by filling in the interruptions tab: And go back to capacity. Whew. Not a problem!

Project Management: Hierarchical Work Items with Visual Studio and Project in Team System 2010

In my previous posts I talked about high level project management, and detailed iteration planning. Both created work items, mainly user stories with child task work items. How does this work in Visual Studio? And what about MS Project? Visual Studio and hierarchical work items Let’s start with Visual Studio. Open your team project and expand the Team Queries, then Workbook Queries: You’ll notice that for each iteration VSTS creates an iteration backlog query, showing you the work items for the iteration. Pay attention to the icon: this means that this is a hierarchical query which will use indentation to show the parent child relation. Execute one of the iteration backlog queries. You should get a list user stories: Notice the + sign before the user story title: with this you can expand the the child tasks. In the toolbar you can also see an + and – icon. These will expand/contract all user stories with their children: Should you see a task assigned to the wrong user story, you can simple drag it to the correct one, and Visual Studio will automatically move it, and indicate your changes using bold. Here I’ve moved tasks #48 to user story #11: You can also use the green arrows in the toolbar to change the level of a work item, for example to make it a child work item. Be careful: this only works if your work items is below a user story. Otherwise drag it to the parent like before. You can also directly create a child work item by right-clicking on a work item and adding a New Linked Work Item. Linking to other work items has been greatly extended. You can now choose from a variety of links: Note the predecessor link. We will revisit this when we look at MS Project and TFS. Scheduling tasks with MS Project When using MS Project with TFS 2008, dependencies added with MS Project would not be saved back to TFS. With TFS 2010 you can now easily plan tasks in project using Gantt charts, add dependencies and publish back to TFS without losing these dependencies. Start MS Project using the “Open in Microsoft XXX” feature in Visual Studio: Let’s say you have two tasks: Now you want to indicate that the first task assigned to April must be done before April can start the second task. Do to this Alt-drag the first task to the second task to create a predecessor relation. Your Gantt chart should now look like this: Note the Predecessors column which contains the row number of the first task. This is not the work item id, it is the number of the row in Project. Now you can publish this back to TFS. After that, go back to Visual Studio and open the first work item. Go to the links tab. You should now see a successor link to the next task:

Project Management: Planning a project with Team System 2010

Project management has changed. Changed towards SCRUM based project management where you start by building a list of User Stories, also known as the backlog... This list of user stories allows you to plan the project by selecting the highest priority user stories, adding them to an iteration, planning the iteration and implementing it. User stories are assigned story points which is an abstract unit for measuring the amount of work. Let’ start by creating a new Team Project. Nothing has changed in the “New Team Project” wizard except that the team project templates have been modified (to better support SCRUM like project management). Again you can choose between an agile template and the CMMI template. The CMMI (Capability Maturity Model Integration) template is more formal; in this post I’ll be using the agile template. Creating user stories A newly created team project will now be empty of work items; the intent is that you start by creating User Stories. These user stories describe the user’s needs. Then you prioritize the user stories and assign story points to them to estimate the work required. A user story is a very slim and high-level user requirement. For example: “The delegate can pay by credit card to confirm reserving the course” (Personally I see user stories as short-hand versions of use cases). To create a new user story with Team System you can choose between Visual Studio, Excel or Team Web Access. Using Excel To create user stories you’ll probably want to use Excel. Previously I found the workbook that came with team foundation 2008 a little lacking, but now you get all you need to perform high level planning. So let’s set out and try this. Open Team Project explorer, and drill down to Documents->Shared Documents. Double click on Project Backlog.xlsm to open Microsoft Excel. Ignore the security warnings if you get some... The Product Backlog is a new workbook that enables you to manage your product backlog of work items from within Microsoft Excel. Start by refreshing from the server by clicking the Refresh button. This will synchronize your workbook with changes made to the server. From Excel you can also edit your areas and iterations, access Team Web Access, and create reports. But also take notice to the sheets in this workbook: First one is for editing the backlog, second one is for high-level iteration planning and the third one is for planning interruptions. The workbook takes very good care of synchronizing changes from one sheet in the other. Let’s start with the first one: the product backlog. The workbook is open in read-only mode by default, so start by clicking on the “Edit workbook“ button: Then you can start adding user stories: Prioritize your user stories by assigning a rank. Prioritizing user stories can be done in many ways, for example Karl Wiegers Kano model. You also need to assign story points as an estimate for the amount of work required (story points don’t generally use precise estimates, like hours or something). Using Visual Studio You can also use Visual Studio to add a new user story; then you’ll get this window inside VS: Please note the format of the title. This makes it a lot easier to think about user stories. Using VS for a single user story works like a charm, but for lists of users stories you’ll want to use Excel. Using Team Web Access Another option, which I think is quite realistic for project managers (and even end users), is to use a web site for editing work items. That is why Team System comes with Team Web Access. You can find the site from your team project portal. Then you can add any work item directly like this: Select User Story from the drop down and you get this: Again, you can add all necessary information directly. Planning Iterations Once you have a good idea about your user stories, you can start iteration planning. In this phase you will assign user stories to iterations. Each iteration will have room for a number of story points (this number is called project velocity, which is the average number of story points your team can do in a single iteration). Iteration planning is done with the Iteration planning worksheet. Note the help above. Once you’re familiar with this sheet you can hide the help. In here you plan your iterations. First you enter start and end date. The sheet will calculate the number of days for the iteration, taking into consideration any planned interruptions you entered into the interruptions sheet. Next you can start to assign user stories to iterations. The sheet will update again with a simple bar chart, making it easier to load balance your work over iterations: The interruptions sheet is just that, simply fill out any dates when no work can be done on the project because of holidays, special events, etc… The Planned Iterations sheet will automatically update nr of days with it. So for example, if we plan a team building meeting in Hawai on the 01/13/2010, the iteration will have 4 days: That’s it for now. In my next post I’ll discuss detailed iteration planning with Visual Studio 2010. Trying this yourself If you want to try this yourself, I recommend you download the virtual machine from Microsoft (comes with sample data and all, and a bunch of labs). The one using Virtual PC 2007 The one for Windows 7 Virtual PC The one for Hyper-V Windows Server 2008

Generate sequence diagrams with Visual studio 2010

Cool! I’ve just discovered this new feature in Visual Studio 2010 (Beta 2) where you can generate a sequence diagram from your code. This should take the hard bit out of generating documentation from your code :) Here’s a screen shot: The only thing you need to to is to point to the method you want to see a sequence diagram for, right-click and choose Generate Sequence Diagram… Then Visual Studio will ask you how deep you want to go, which classes/methods to include in the sequence diagram: And then you can start making changes to the diagram: Nice!