sábado, octubre 25, 2008

Reflector Add-In's Save the Day

Recently my brother had a problem with an old winforms application we developed to help him upload images and product information. The issue was really simple, once I had a chance to run and debug the application the issue was evident. The app was using FTP to upload pictures to the website and the credentials were invalid.

image

Easy I thought, go to the config file and change it, it'll probably be encrypted and might give me a hard time to hack. I opened it and didn't find anything. Let's open reflector and see what's happening I have a Stack Trace to start with, but that wasn't the best place. I remembered the name of the user, so the Reflector Add-in Code Search quickly pointed me to the right place:

image

From there a double click sent me to the method

image

Great. Someone thought it was safer to hard code it instead of using the web.config.

Then the question remains, how can we change it? The proper solution would be to open Visual Studio, connect to TFS, get the sources, edit recompile and sent back the new version. However I don't think the latest version is stable, so I would need to search for a label to get the latest deployed version. I'm running on a really slow connection now and that would probably take a while, beside it's sunday and I'm ready to go surfing (or at least try to).

Option 2. In that same screen just open Reflexil (another Reflector-Addin) locate the IL line that sets the password (this is not as hard as it sounds) and edit the string.

image

Then we simply save the assembly. This was probably the hardest part, this was the first time I used Reflexil and I was expecting the Save As option to be right next to the place where I do the edit, in the Tools menu or a toolbar, I finally found the option when clicking file in Reflector.

image

After that, just save the file e-mail it and ready to go, but then I had the brilliant idea of write this post and it took me more time than the fix.

You can find this an other reflector add-ins in http://www.codeplex.com/reflectoraddins

lunes, octubre 06, 2008

Learning with Tests (MessageBroker in NInject)

A great way to learn a few coding practices is to get an open source project (one good, don't get the first thing you see en codeplex) and trying to understand the code, how they apply patterns, use certain classes or reuse code through the project. The best way to start (with most of the good projects) is with the tests.

I have been playing lately with Ninject, a Dependency Injection Framework,  it's well designed, auto-documented and documented (probably too much documentation at the code level), the downside is that the wiki, the blog posts and tutorials barely cover the basics. However, the tests do a good job to describe the project at a higher level. As an example an example we can see one of the tests for the MessageBrokerModule.

        [Test]
public void OnePublisherOneSubscriber()
{
using (var kernel = new StandardKernel(new MessageBrokerModule()))
{
PublisherMock pub = kernel.Get<PublisherMock>();
Assert.That(pub, Is.Not.Null);

SubscriberMock sub = kernel.Get<SubscriberMock>();
Assert.That(sub, Is.Not.Null);

Assert.That(pub.HasListeners);
Assert.That(sub.LastMessage, Is.Null);

pub.SendMessage("Hello, world!");

Assert.That(sub.LastMessage, Is.EqualTo("Hello, world!"));
}
}


The code is really easy to follow, first he asserts that the kernel can create instances of the publisher and subscriber, then the publisher should have a listener, the subscriber doesn't have any message and finally he sends a message than the subscriber should receive. The other tests like OnePublisherTwoSubscribers and ManyPubsManySubscribiers are similar.

sábado, octubre 04, 2008

Task Board for Scrum for Team System

 

I have been using Scrum for Team System since beta 1 and I quickly fell in love with that template. It reflects the way we were working, however, there was a big gap in the process, specially when planning for a sprint, we usually did all the prioritizations, sizing, assigning and breakdown of Product Backlog Items using other tools like Mindmanager, Excel or sticky notes.

Recently the guys from Conchango, creators of the template, released a beta of a tool that will help use fill that gap. It's a cool WPF tool that will interact with TFS and allow us to create and edit sprint backlog items.

I don't think the tool will replace Mindmanager and the whiteboard still will be an indispensable resource, but I don't think I would like to go back to Excel to edit my items (well lets see how it goes after a couple of sprints of working with it).

When I was looking at the tool I was thinking, mmm yes, you can move a task from In Progress to Done, that's cool, but excel can do much more specially with pivot tables and reports, but then I saw the rest of the features, like changing to Planning Mode to start adding Product Backlog Items, automatically doing the binding between product backlogs and sprint backlog items, searching, filtering and reporting and I have to say, this tool is something worth to try. So in two weeks I'll let you know more about this.

I'm still not sure about the pricing scheme and I'm a bit concern. At the moment is beta, and you can simply request a license, but it doesn't seem something that will remain free. I will need to consider if this is a tool that every developer on the team will be able to use.

Crispin Parker from Conchango published some useful webcasts and a post with more info on the product.

By the way, it would be great to get a surface to use this tool.

lunes, septiembre 15, 2008

Sydney ALT.NET Group

The newest user group in Sydney will have it's first meeting on September 30 at the Thoughtworks offices. Richard Banks published the agenda and details in the group's blog, but what exactly is an ALT.NET Group? Why do we need another one if we have generic groups like Sydeny's DNUG and RDN or technology specific groups like OzTFS and OzSilverlight? 

ALT for Alternative has caused a lot of controversy that lead to misunderstanding, so let's better start for what it's NOT, it's not the anti-microsoft group, its not the open source community tired of Java wanting to use something better (altough some of them might be part of the group), its not a group that loves NHibernate and hates Entity Framework.

Simply is a group of developers that like to look for better ways to do their work, keeping a "get things done" approach and commonly identified with agile practices, continuous improvement and the pragmatic thinking, people who "use what works while keeping an eye out for a better way".

If you feel identified with these ideas, come and join us or if you're not in Sydney, find an ALT.NET User Group or create a new one.

In our first meeting we will have talks about Ruby and Mocking.

Recommending reading/listening:

martes, septiembre 09, 2008

C# and more dynamic features (C# 4.0?)

static void Main(string[] args)
{
    dynamic
    {
        object myDynamicObject = GetDynamicObject();
        myDynamicObject.SomeMethod();         // call a method   
        myDynamicObject.someString = "value"; // Set a field
        myDynamicObject[0] = 25;              // Access an indexer
    }
}

How cool is it? I don’t know, probably will be something dangerous if not used with care, C# depend a lot of compile time checking.

To see more about this see Charlie Calvert’s Blog

martes, agosto 19, 2008

Cool Site with great controls, components and skins - www.wpfstyles.com

Logo If you haven't you gotta check www.wpfstyles.com by Andrew den Hertog. The just released site oriented to the dev community, is quickly becoming a great resources for controls, components and skins sharing for WPF and Silverlight. Go give it a try and if you have something, share it and if you need something, probably you will find it here. If you don't check it back later, the site is new and people is starting to publish content, so don't freak out if you don't see 1,000 controls yet.

Personal Note/Public Apology: There has been a while without a post, because I have been traveling a lot and didn't have Internet connection in several of those places. I just moved to another country and I'm still getting installed, but you can expect frequent posts again.

martes, agosto 05, 2008

Using the ASP.NET Providers from Silverlight - Membership, Roles and Profile

Brad Abrams wrote an excellent post about how to set everything in the server and client to consume this services. He covers for areas:

1. Login\Logout
2. Save personalization settings
3. Enable custom UI based on a user's role (for example, manager or employee)
4. A custom log-in control to make the UI a bit cleaner

These Services are simple wrappers to the actual providers and only provider the most common functions (i.e. Membership has login/logout, but not CreateUser), but would be pretty straightforward to extend them. If your application is not 100% SL and you have parts already build in ASP.NET you can easily combine them, for example, use the Login controls to Authenticate users, but use the Role Services to restrict certain functions depending on who is who.

sábado, agosto 02, 2008

Value Converters - More Simple Samples

This is the third of several posts related to Value Converters. Reading the posts in order can be useful, but not necessary. The first post, Databinding 101, served as an intro to the problem and the second, DefaultValueConverter, introduced the basics about ValueConverters. Now we're ready to present several examples to give you more ideas of where ValueConverters can be used.

 

ImageSourceConverter

The Image control doesn't update its Source property automatically, so setting it to a path will work only the first time, but if the path in your datasource changes it won't be reflected, well the ImageSourceConverter will help you. This is really a bug that will be corrected in SL RTM, but meanwhile this is another place to use ValueConverters.

public class ImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string path = (string)value;
return new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute));
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}


VisibilityConverter



You might want to change the visibility of a control based on a boolean property of your objects, this is simple with the VisibiltyConverter:



public class VisibilityConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((bool)value)
return Visibility.Visible;
return Visibility.Collapsed;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}


StringFormatConverter



This is one of my favorites. ASP.NET and Winforms use a StringFormat that let you display properly numeric or date objects (use these cheat sheet as reference). With this converter for example you can simply pass the ConverterParameter of C to format a numeric value as currency and will work similar to the way it does in the mentioned platforms. This is another convertar that I feel should be part of the Binding object.



public class StringFormatConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string formatString = parameter.ToString();
return String.Format("{0:" + formatString + "}", value);
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new InvalidOperationException("This Convert supports only OneWay binding");
}
}


StringFixedLengthConverter



For some controls you might want to specify a fixedlength for the text. You can do it with the StringFixedLengthConverter setting its ConverterParameter. This is rarely useful...



public class StringFixedLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return GetFixedLengthText((string)value, int.Parse((string)parameter));
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}

private string GetFixedLengthText(string originalString, int maxChars)
{
int textLength = originalString.Length;
if (textLength > maxChars)
return originalString.Substring(0, maxChars - 3) + "...";
int padding = (int)Math.Round((maxChars - textLength) / 2d);
string paddingChars = "";
for (int i = 0; i < padding; i++)
paddingChars += " ";
return paddingChars + originalString + paddingChars;
}
}


IfNullChangeColorConverter



This is not common, but we had run into cases where we need to change the color of a control in case a property is null. This could be combined with the DefaultValueConverter presented yesterday. Imagine you will display a DefaultValue of 'Not Available' if the person doesn't have a phone number, but you also want to greyout the text to emphasize the lack of data. To create this effect, specify the desired color in the ConverterParameter (if no value is specify grey will be used).



public class IfNullChangeColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return new SolidColorBrush(GetColor(parameter));
return new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
}

public Color GetColor(object parameter)
{
byte[] argbColor = new byte[4];
if (parameter != null)
{
string[] argbColorStrings = parameter.ToString().Split(',');
for (int i = 0; i < 4; i++)
{
argbColor[i] = byte.Parse(argbColorStrings[i]);
}
}
else
{
//#FFC0C0C0
argbColor[0] = 255;
argbColor[1] = 192;
argbColor[2] = 192;
argbColor[3] = 192;
}
return Color.FromArgb(argbColor[0], argbColor[1], argbColor[2], argbColor[3]);
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}


Creating ValueConverters is really easy and these examples are meant to show that, rather than to try to cover every scenario. However, ValueConverters have many drawbacks. You can't combine them (e.g. use StringFormat and DefaultValue for the same property because the binding object only allows one) and won't scale easily (you will end up with lots of classes for super simple scenarios). Tomorrow I will talk about a pattern that can overcome these drawbacks.



You can download the attached code here with the last examples and the classes presented here.


I format my code using Manoli's website


Don't forget to vote for your favorite topics for this column.

viernes, agosto 01, 2008

Professional Visual Studio 2008 for Sale Now.

As I mentioned before I was invited to write the chapters of Team System in the book Professional Visual Studio 2008, well the book is finally out now and you can get it in Amazon, Barnes & Noble or your favorite bookstore. This is the Table of Contents:

Table of Contents

Part I: Integrated Development Environment

Chapter 1: A Quick Tour
Chapter 2: The Solution Explorer, Toolbox, and Properties
Chapter 3: Options and Customizations
Chapter 4: Workspace Control
Chapter 5: Find and Replace, and Help

Part II: Getting Started

Chapter 6: Solutions, Projects, and Items
Chapter 7: Source Control
Chapter 8: Forms and Controls
Chapter 9: Documentation Using Comments and Sandcastle
Chapter 10: Project and Item Templates

Part III: Languages

Chapter 11: Generics, Nullable Types, Partial Types, and Methods
Chapter 12: Anonymous Types, Extension Methods, and Lambda Expressions
Chapter 13: Language-Specific Features
Chapter 14: The My Namespace
Chapter 15: The Languages Ecosystem

Part IV: Coding

Chapter 16: IntelliSense and Bookmarks
Chapter 17: Code Snippets and Refactoring
Chapter 18: Modeling with the Class Designer
Chapter 19: Server Explorer
Chapter 20: Unit Testing

Part V: Data

Chapter 21: DataSets and Data Binding
Chapter 22: Visual Database Tools
Chapter 23: Language Integrated Queries (LINQ)
Chapter 24: LINQ to XML
Chapter 25: LINQ to SQL and Entities
Chapter 26: Synchronization Services

Part VI: Security

Chapter 27: Security in the .NET Framework
Chapter 28: Cryptography
Chapter 29: Obfuscation
Chapter 30: Client Application Services
Chapter 31: Device Security Manager

Part VII: Platforms

Chapter 32: ASP.NET Web Applications
Chapter 33: Office Applications
Chapter 34: Mobile Applications
Chapter 35: WPF Applications
Chapter 36: WCF and WF Applications
Chapter 37: Next Generation Web: Silverlight and ASP.NET MVC

Part VIII: Configuration and Internationalization

Chapter 38: Configuration Files
Chapter 39: Connection Strings
Chapter 40: Resource Files

Part IX: Debugging

Chapter 41: Using the Debugging Windows
Chapter 42: Debugging with Breakpoints
Chapter 43: Creating Debug Proxies and Visualizers
Chapter 44: Debugging Web Applications
Chapter 45: Advanced Debugging Techniques

Part X: Build and Deployment

Chapter 46: Upgrading with Visual Studio 2008
Chapter 47: Build Customization
Chapter 48: Assembly Versioning and Signing
Chapter 49: ClickOnce and MSI Deployment
Chapter 50: Web and Mobile Application Deployment

Part XI: Automation

Chapter 51: The Automation Model
Chapter 52: Add-Ins
Chapter 53: Macros

Part XII: Visual Studio Team System

Chapter 54: VSTS: Architect Edition
Chapter 55: VSTS: Developer Edition
Chapter 56: VSTS: Tester Edition
Chapter 57: VSTS: Database Edition
Chapter 58: Team Foundation Server

I also had a chance to review a couple of chapters. Writing a book was a great experience and I hope you will enjoy the results.

As Dave Gardner mentioned there are books available for instructors from the publisher and other's through the books's page. Nick Randolph mentioned later than they will have books to give away in TechEd Australia and TechEd New Zealand.

Value Converters - Default Value Converter

This is the second of several posts related to Value Converters. Reading the posts in order can be useful, but not necessary. As we saw yesterday sometimes we need to specify a DefaultValue for cases where there's no value specified by our datasource. This is a look of the application with data, then without a phone number and the third pic shows how would it look with the DefaultValueConverter.

With data:

Without data:
image
Wit DefaultValueConverter:
image
The change in XAML is really simple, this is the original line:
<TextBlock Text='{Binding Mode=OneWay, Path=PhoneNumber}'/>
 
This is the modified line:

<TextBlock Text='{Binding Mode=OneWay, Path=PhoneNumber, ConverterParameter="[Not Available]", Converter={StaticResource DefaultValueConverter}}'/>

We also need to add a Resource that holds the reference to our DefaultValueConverter

<UserControl.Resources>
<SilverlightApplication14:DefaultValueConverter x:Key="DefaultValueConverter"/>
</UserControl.Resources>

We added two attributes to the Binding object, a ConverterParameter and a resource that will hold an instance of our ValueConverter. A ValueConverter is simply a class that implements IValueConverter and consists of two methods Convert and ConvertBack. ConvertBack is used with TwoWay BindingMode, but we won't use it here. The Convert method simply checks if the value is null and if it is, it returns the parameter which will hold the object specified in the ConverterParameter.

public class DefaultValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return parameter;
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

In WPF the Binding object has a DefaultValue property, so there's no need to create a ValueConverter there.


You can download the attached code here
I format my code using Manoli's website
Don't forget to vote for your favorite topics for this column.

miércoles, julio 30, 2008

Value Converters - Databinding 101

This is the first of several posts related to Value Converts. Trying to minimize the length of the posts I break it in 4 deliveries, but the first one will have to be an intro to databinding before I can get into Value Converters tomorrow.

Databinding is great and probably one of the best features in WPF and SL (I know I have said that before for others), well, it's great, but somehow inflexible as we will see tomorrow and Value Converters will add a bit of flexibility.

As with winforms or ASP.NET to do databinding we will need a DataSource. We will define our person class.

public class Person
{
public string Name { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
}



In our Codebehind we will add this to the DataContext property of the control

public partial class Page : UserControl
{

public Page()
{
InitializeComponent();
DataContext = new Person {Name = "Miguel", LastName = "Madero", PhoneNumber = "+52 (871) 123-4567"};
}
}

Obviously in a real example we won't hard code the values and instead get our data from a Service. Then in XAML we will define the controls that will be bound to our object. In this case we're using only textboxes inside inside a StackPanel.

<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding LastName}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding PhoneNumber}" TextWrapping="Wrap"/>
</StackPanel>

That's it, super simple. There are obviously more complex examples, but I probably won't go there since other people have already have done a great job covering them, for example binding to a List Box (read Scott's post) or a DataGrid (all Scott Morris blog), or a step by step tutorial by Jesse Liberty who explains Binding objects, change notifications implenting INotifyPropertyChanged, Binding Modes (OneTime, OneWay, TwoWay). This is not an intro to databinding, rather an intro to Value Converters and why is it needed.


After a couple of modifications (see attached code) the page will look like this:


image

Everything looks as expected, so why would we need value converters. Imagines some people won't have phone numbers, we would be displaying a blank space, that might not be the desired experience. What if we want to show a default value like "Not available". Tomorrow we will see how to show default values using ValueConverters.


You can download the attached code here
I format my code using Manoli's website
Don't forget to vote for your favorite topics.

No More Need to Change Your URIs

It's a pain having to remember to edit your ServiceReferences.ClientConfig (the file with the service proxies configuration) or editing your code to point to another path when changing between developing, testing and production environments. Well, it's time to stop the pain:

   1:              Uri uri = HtmlPage.Document.DocumentUri;
2: return String.Format("{0}://{1}:{2}/", uri.Scheme, uri.Host, uri.Port);

It would be better to encapsulate this in a class:

   1:  public static class UriHelper
2: {
3: public static string GetHost()
4: {
5: if(!HtmlPage.IsEnabled) // Get design time URI
6: return http://localhost:1650/;
7: Uri uri = HtmlPage.Document.DocumentUri;
8: return String.Format("{0}://{1}:{2}/", uri.Scheme, uri.Host, uri.Port);
9: }
10: }

I suggest you to update your proxies, so instead of using the URL defined in your ServiceReferences file it will use the URI provided by your method:


   1:  public AuthenticationServiceClient()
2: : base("BasicHttpBinding_AuthenticationService", UriHelper.GetHost() + "B2B2/Cotizador/AuthenticationService.svc"){}


It will be useful for pictures too:

   1:              string uri = String.Format("{0}/Images/{1}.jpg", UriHelper.GetHost(), productId);
2: image.ImageSource = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));

Hope this helps.
Don't forget to vote for your favorite topics.
I format my code using Manoli's website

martes, julio 29, 2008

Silverlight Tip of The Day - Vote for The Future Posts

Before I started writing this column, I began writing ideas for future posts and the list seems to grow faster than the daily frequency my posts have. So this is a list of posts in the queue, you can vote for them either by e-mail of leaving a comment.

Because of time constraints I have not been able to post some of the interesting topics.

  • Debugging Tips
  • Deploying
  • Cross Domain Calls
  • Problems Debugging
  • Recommendation of cool tools (for Dependency Injection, AOP, extensions, etc)
  • Model-View-ViewModel Pattern
  • Handling Image Paths
  • Using ASP.NET Providers (Membership, Roles, Profile)
  • Styles and Templates
    • Basics
    • Controls
    • Create a Clean Style for ListBox or ItemsControl
    • Change ListItemStyle
    • Blend and Styles
    • Blend and Templates
    • Visual State Manager
    • Visual State Manager and Blend
  • Blogs I read and cool links
  • Patterns for code reuse between Silverlight and .NET or .NET Compact Framework
  • Patterns for XAML code reuse between Silverlight and WPF
  • Silverlight Unit Testing
  • Test Code reuse
  • Refactoring your ASP.NET code to Silverligtht
  • Changing patterns from ASP.NET to Silverlight
  • Dummy Data and Better Design Experience (See controls with data in Blend)
  • Services and Security
  • Interoperability (JavaScript-.NET)
  • Caching and ClientSide Persistence
  • Silverlight Disconnected Client - Designing for Occasionally Disconnected Systems

Vote for your favorite topics, but remember, they might take a while to appear, If you want to learn a topic for today's project, probably this is not the place and you would be better off in the SL Forum, another blog or reading a book that gets you from a to z, but this can be an useful resource to learn SL a step a day or find some hidden tricks.

The idea of this column is it to be something simple and a quick daily read. Something won't take you more than 5 minutes (and that probably won't take me that much time to write either). When needed I will point you to other places to get deeper info, so open your favorite RSS reader and subscribe now and remember to vote through e-mail or leave a message for the topics you would like to read soon here.

lunes, julio 28, 2008

How to Update a TextBox Binding OnPropertyChanged

When using TwoWay Binding, most properties get updated after the control's property changes, but the Text in a TextBlock is a different case, it gets updated after the TextBox lost focus. It makes sense, since the value might be incomplete and validations and other logic triggered at the Business Object level unnecessarily, but sometimes this is not the desired behavior.

WPF has an UpdateSourceTrigger as part of the Binding object and you could say something like:

      <TextBox Text={Binding Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}>

This is not available in Silverlight, but there's a quick workaround provided by Yi-Lun Luo in this thread.

        private void cantidadTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            otherControl.Focus();
            cantidadTextBox.Focus();
        }

It's really ugly, but works.

 

viernes, julio 25, 2008

Style Inspector

Go check it out, it's a cool tool from the Delay, the name is self explanatory and the tool is really easy to use so this post is one line long. Well an a screenshot.

SilverlightDefaultStyleBrowser sample image 

jueves, julio 24, 2008

Sniffers and Silverlight

It's very useful to know what Silverlight is doing behind the scenes, what is requesting, from which URI, what it sends and what was received. My preferred sniffer is Web Development Helper by Nikhil Kothari. The important part of this tools, related to SL is that you can see exactly what is happening at the network stack, but go try it out. It's probably not a tool you will use daily, but add it to your toolbox and keep it close to your hand.

The bar integrates nicely into IE, here we can see that it got my TestPage, the XAP Package, called a Service and then get several pictures and finally called another Service. This information is important, we can determine the order in which things are hapenning, if a Service is being called to much or if we probably misspelled some address (more on this tomorrow).

image

The filter option is really useful, we might not care about images and only want to look for URLs with a svc extension.

image

We can go deeper and see the exact content of each request/response. In the following image we see the Request Headers and the XML of the Response.

image

Today I only presented the Silverlight related features, but the Web Development Helper does a lot more stuff than just a simple HTTP Logger.

Tomorrow I will talk about how to get different URIs based on the original request's address. I am running out of topics. Please suggest and I will write.

miércoles, julio 23, 2008

Visual State Manager

The Visual State Manager allows us to define different states for our controls. Most controls in Silverlight already use this technology and we can change them editing their template. The best example is the button, the next picture shows its different VisualStateGroups and its VisualStates in Blend.

image

VSM its a big topic and I will get to it in better detail in another topic, but for now consider it as the way to decouple behavior and design. The creator of the control would typically define the states and its transitions in response to certain events, for example, when the mouse is over the programmer will change the state to MouseOver. The designer can use blend to change the look of each state and define transitions (animations) between them. To start with, you would typically change the defined states of some other people's controls, once you start doing your own controls you might want to expose States, to change between them in response to events, simply use the following method:

VisualStateManager.GoToState(myControl, "myNewState", true);

It's not available for WPF yet, but it will in a next update (probably in SP1).

For a complete tutorial go to http://www.nibblestutorials.net/ and look for the new Blend 2.5 tutorials or check this webpage for an example on how to change a button style for the MouseOver state.

viernes, julio 18, 2008

Silverlight's DropDownList

SL doesn't have a DropDownList. It will in a next release, but while this happen we had to write one ourselves. I tried different options from here and here. The first is a really simple control we used as a basis, the second one is a dll with a lot of control, I only tried the ddl and have to say it had a couple of bugs, didn't worked as expected, specially with databinding.

Get the source code and tests. This is not a complete, fully functional, tested, component, it's simply an easy to use, composite control. The test suite only met what we needed and there might be a lot of uncovered scenarios. Anyway, you can either use it as it is, improve it to meet your need or simply as a rough example on how to do composite controls.

This control has a TextBlock and a Listbox. The listbox is collapsed and it contains the items of the ddl, when the TextBlock is clicked the listbox becomes visible and when the mouse leaves the listBox it's collapsed again. To use it, you can bind something to the control's DataContext and you're done. This will work for the default scenario where you just need to display text for each item and update the text in the TextBlock. The control doesnt support templates, and this is an enhancement you could easily made, simply exposing the listbox templates so you could change, for example, how each item is displayed and databound.

I left my post about the Visual State Manager for tomorrow since I have been asked for the ddl sample in this thread and by e-mail.

 

Professional Visual Studio 2008 is almost

 

In March of this year, Nick Randolph invited me as a guest author of Professional Visual Studio 2008 from Wrox. I wrote only 5 chapters, all about Team System (Server, Dev, Tester, Architect and DB Pro), it was tough, but was a great experience. I thought writing a few pages of topics I know would be easier, but being the first time I write something formal and amongst other projects, courses and all the VISA paperwork for Australia it was hard to get the time. Writing at 2:00 am was fun, more than correcting the mistakes the next morning. I'm really glad Nick invited me.

We are getting closer to its release date (July 28th). You can preorder it now on Amazon, read the table of contents or read more about this on a post from Dave Gardner or visit the book's webpage. I hope you like it. 

Use VisualTreeHelper to Navigate Through Objects Hierarchy - Part 2

Yesterday I wrote about the VisualTreeHelper class, today, I will present a class with extension methods useful to search for objects in a more convenient way. You can download the code here.

It's a static class with extension methods like GetChild, GetChildrenCount and GetParent, similar to the VisualTreeHelper methods, but cleaner to use. Compare:

VisualTreeHelper.GetChild(myControl, 0);

myControl.GetChild(0);

Ok, it's cleaner, but really doesn't add much value, but what about getting an Item by name instead of only by index (as provided by the VisualTreeHelper method):

myControl.GetChild("childrenName");

Or better yet doing recursive searches through all the object hierarchy:

myControl.GetChild("childrenName", true);

Methods like that would make scenarios like the one presented yesterday really easy to solve, for example to get an Item of a ListBox using VisualTreeHelper you would have to do something like this:

DependencyObject grid = VisualTreeHelper.GetChild(listBox, 0);
DependencyObject stack = VisualTreeHelper.GetChild(grid,0);
DependencyObject scrollViewer= VisualTreeHelper.GetChild(stack, 0);
DependencyObject scrollPresenter = VisualTreeHelper.GetChild(scrollViewer,0);
DependencyObject border= VisualTreeHelper.GetChild(scrollPresenter ,0);
DependencyObject grid2 = VisualTreeHelper.GetChild(border,0);
DependencyObject etc = VisualTreeHelper.GetChild(grid2, 0);
DependencyObject itemIReallyCareAbout = VisualTreeHelper.GetChild(etc,1);

Using extension methods you could nest calls and made it a bit simpler in one line of code, but not necessarily simpler.

//       Grid,          Stack,       ScrollViewer,ScrollPresenter,Border,Grid,etc,etc, MyItem
listBox.GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(1);

Not only that looks horrible, but the worst part is than if the designer decides to change the ItesmPanel or the ListBox Template, you would probably have to change your code, with recursive searches you would simply do something like:

listBox.GetChild("innerControlName", true);

Another useful method is GetChildren wich return an IEnumerable<DependencyObject>.

Tomorrow I will talk about the Visual State Manager.