What Does it Mean to be “Lookless”?

One of the powerful features of Silverlight is the ability to have fine grain control over how your application looks. This power is given to use through “Lookless” controls or more commonly known as Templated Controls.  What this means is that the functionality of the control is contained in a class file and the look and feel is implemented in XAML.  All of the out of the box controls are created this way.  You can test this out in Expression Blend by adding a button to your canvas. Right click on the button select ‘Edit Template’ and see what is generated for you.

In this article I will work through how to create your own templated control.  Even if you never create a real control of your own, it is a good exercise to understand how templating works in Silverlight.  I will be creating a simple control that contains a text box and a button:

image

There is nothing fancy with the control I have created and I probably would not create a control like this.  I did something simple to demonstrate the power of templated controls.

The first thing you need to do is create the control. You can create this control in the current project or in a class library project.  Visual Studio helps in create templated controls by providing a template.  Go to File –> Add and select ‘New Item’.  From the ‘Add New Item’ dialog select ‘Silverlight Templated Control’. I am creating a control called TextWithButton (I know real original).

 

image

This is going to create a class file, a directory called ‘Themes’ (a hold over from WPF) and a XAML file called Generic.  The class file is for your implementation code. The Generic.xaml file is for your default template. Now we have to wire up the template to the implementation.  When you added the control the implementation class inherits from Control.  Control has a property called DefaultStyleKey that we can set in the constructor of our control.

this.DefaultStyleKey = typeof(TextWithButton);

Your control is going to go out to the Generic.xmal and find a style with this key.

Templated controls assume that there are parts (Framework Elements that make up your interface). Inside the Generic.xaml file you create the parts of your control ensuring to set the x:name property.  This will be used to get a reference to the parts from the class file.   You will also want to implement any Visual States that you will be working with.  Here are the visual states for my control:

<VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="GroupCommon">
                                <VisualState x:Name="Unfocused"/>                                
                                <VisualState x:Name="Focused">
                                	<Storyboard>
                                		<ColorAnimationUsingKeyFrames BeginTime="00:00:00" 
                                                                      Duration="00:00:00.0010000" 
                                                                      Storyboard.TargetName="InputText" 
                                                                      Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)">
                                			<EasingColorKeyFrame KeyTime="00:00:00" Value="#FFFAFAFA"/>
                                		</ColorAnimationUsingKeyFrames>
                                		<ColorAnimationUsingKeyFrames BeginTime="00:00:00"
                                                                      Duration="00:00:00.0010000" 
                                                                      Storyboard.TargetName="border" 
                                                                      Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
                                			<EasingColorKeyFrame KeyTime="00:00:00" Value="#FFCE4646"/>
                                		</ColorAnimationUsingKeyFrames>
                                	</Storyboard>                                
                                </VisualState>                    
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>

Now you want to override the OnApplyTemplate method. Here is my override:

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _inputTxt = GetTemplateChild(ElementTextBox) as TextBox;
            if (_inputTxt != null)
            {
                LoadText();
            }

            _inputButton = GetTemplateChild(ElementButton) as Button;
            if (_inputButton != null)
            {
                ConfigureButton();
            }
        }

Here I am using GetTemplateChild method, passing in the name of the part, and setting an internal variable casting the results as parts type. It also gives you a chance to call some methods to do some initialization work for you. When working with templated controls it is important to code defensively in order to ensure that a user hasn’t delete a control part you were expecting.

Now we have to tell our implementation which parts to expect.  We do that by setting the TemplatePart attribute on the class:

    [TemplatePart(Name = TextWithButton.ElementTextBox, Type = typeof(TextBox))]
    [TemplatePart(Name = TextWithButton.ElementButton, Type = typeof(Button))]

Here you tell the attribute what is the name of the part and the type.  You also need to specify and VisualStates you are expecting again by setting an attribute on the class:

    [TemplateVisualState(Name = VisualStates.StateFocused, GroupName = VisualStates.GroupFocus)]
    [TemplateVisualState(Name = VisualStates.StateUnfocused, GroupName = VisualStates.GroupFocus)]

I am doing something simple to implement state changes. In the constructor I am subscribing to focus events:

      this.GotFocus += new RoutedEventHandler(TextWithButton_GotFocus);
      this.LostFocus += new RoutedEventHandler(TextWithButton_LostFocus);

Here are the handlers for those events:

        void TextWithButton_LostFocus(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, VisualStates.StateUnfocused, true);
        }

        void TextWithButton_GotFocus(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, VisualStates.StateFocused, true);
        }

At this point you have a templated control that you can add to a page and it will render.  What we haven’t done yet is create any functionality. We are going to want to have the ability to bind to the text property of the text box part and to the command property of the button part.  There are other things that you can do like expose events but I am not going to cover those in this article.  In order to be able to bind to properties on your control you have to create Dependency Properties. 

Here is the property that I created to handled the text:

        public string ControlText
        {
            get { return (string)GetValue(ControlTextProperty); }
            set { SetValue(ControlTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ControlText. 
        //This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ControlTextProperty =
            DependencyProperty.Register("ControlText",
            typeof(string), typeof(TextWithButton),
            new PropertyMetadata(ControlTextChanged));

Dependency properties allow you to handle when the value is changed. Here is the implementation of the change event handler:

        private static void ControlTextChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs args)
        {
            TextWithButton view = d as TextWithButton;

            if (view != null)
            {
                view.LoadText();
            }
        }

Here I cast the DependencyObject as the control type and call a method on it.  Notice that is the same method I am calling when the template is applied. I can now create a two way binding that will handle text from a view model through to the inner textbox.  Here is the LoadText implementation:

        private void LoadText()
        {
            if (!string.IsNullOrWhiteSpace(ControlText) && _inputTxt != null)
            {
                Binding binding = new Binding();
                binding.Source = this;
                binding.Path = new PropertyPath("ControlText");
                binding.Mode = BindingMode.TwoWay;
                _inputTxt.SetBinding(TextBox.TextProperty, binding);
            }
        }

Note the defensive coding. I do something similar for the button command (see code for implementation). 

I now bind to my ControlText property in my view from my view model:

            <cc:TextWithButton ControlText="{Binding SomeText, Mode=TwoWay}"
                               ButtonCommand="{Binding ButtonClickCMD}"
                               Margin="10"
                               Width="500" />

So let’s recap what we have done we have created a control with encapsulated functionality that can be templated by users without breaking that functionality.  We could have two different instances of this control on the same page that have two different styles:

            <cc:TextWithButton ControlText="{Binding SomeText, Mode=TwoWay}"
                               Margin="10"
                               Width="500" />
            <cc:TextWithButton ControlText="{Binding SomeText, Mode=TwoWay}"
                               ButtonCommand="{Binding ButtonClickCMD}"
                               Margin="10"
                               Width="500"
                               Style="{StaticResource TextWithButtonStyle1}" />

In the static recourse I change the layout and back ground of one of the controls so it looks something like this

image

 

These two controls share the same functionality but as you can see I get the ability to change how they look.

You may not need to create a templated control unless you are building your own control library.  By creating my I own, I now feel more confident when it comes to altering the templates of the native Silverlight controls.  Another good exercise is to look at the source control of the Silverlight Toolkit. Here you will see a similar approach done by the Silverlight Team.

Source Code

Posted in Uncategorized | Leave a comment

I can write my application in classic ASP but do I really want to?

I can write my application in classic ASP and satisfy all my requirements but do I really want to. There has been a lot of hype around Silverlight vs. HTML5. I started into the conversations with “The Future of Silverlight”  from the Silverlight Team Blog and continued on to “Is Silverlight becoming a niche technology?”.  There are some great arguments that for each technology but the piece of the argument that is missing is choosing the correct technology for the situation.  It all boils down to the business requirements, technical infrastructure restrictions, the audience, and the comfort level of the development team.

The Business Requirements

If my requirements call for an application that needs a web component, a desktop component, a mobile component and offline capabilities. I am going to want to minimize the code that I write. In this situation I would probably go with Silverlight. If all I need is a web component then I can HTML (HTML, JS, CSS) and be done with it. You should approach each situation with the mindset that I am going to choose the best tool for the job.

Technical Infrastructure Restrictions

First and foremost if an organization won’t allow the Silverlight plug in to be installed the obviously you can’t use Silverlight.  The niche article points out that there are great JavaScript frameworks that make developing HTML (HTMl5) applications easier.  The problem with that is most of them are open source.  I worked for an organization that did not allow the use of any open source (business reasons not technical) in their product.  Who wants to re-implement JQuery, with all of the different browser nuances,  in their spare time. 

The article from the Silverlight Team brings up a good point around HTML5. When is the standard going to be finalized and published? How long will it take browser manufacturers to implement the standard and how standard will it actually be across the different browsers (here is a hint how standard is it now)?  Finally how long will it take to get users to download the new browser (my Mom would still be on IE6 if it wasn’t for my last visit a year ago)?

Developer Comfort Level

My final point centers on the comfort level of the development team.  If your team is not use to writing JavaScript and you can use those nice frameworks that abstract out the complexity (see above for reason) why would you want to extend your project timeline learning JavaScript or even worse using the cut and paste Google snippit editor.  On the flip side if you are a PHP developer you are not going to drop everything to run to Silverlight.  There was a commenter on in the niche article that stated:

“Silverlight share the same problem as any of .net technology…it is not reusable…if you put your time and energy, to learn some .net technology, for example asp.net, you can hardly reuse when learning some other web technology, for example php”

Really?  When I use .NET technologies I separate my concerns, try not to repeat myself and all the other buzz words used to describe a great developer.  My point is that if you follow good coding practices switching to another language/framework mean learning the syntax and capabilities of those frameworks.  One of the main jobs of a developer learning the capabilities of frameworks and applying those capabilities to the problem at hand.  Anyone can write code, it takes practice and skill to write an application!

Conclusion

It is great that these debates are ongoing.  They help bring facts to the surface that we might not have otherwise known but we can’t loose site of the fact that the situation should dictate the technology.

Posted in .NET, C#, Computer Science, HTML5, Silverlight, Software Architecture | Leave a comment

Silverlight Child Window With MEF and MVVM Light

UPDATED: I created another post that updates my approach for working with Silverlight Child Windows.

So it has been a long time since I did a pure technical post.  In fact I  have completely blown my goals for the year.  I am going to keep working towards them.  My life has been hectic since the beginning of the year and I am about to embark on a second Master’s degree.  This does not bode to well for reaching the goals I have set.  I jump on  any opportunity to play.  This is one such time.

Windows Phone 7 is due out later this year.  Microsoft was smart and decided to leverage the technical abilities of all the Silverlight developers.  So to effectively fulfill Ray Ozzie’s vision of three screens and a cloud developers are going to have to reuse as much code as possible.  One of the ways they can do that is by separating out the ViewModel into a separate project.  I have written post that demonstrated this.  One of the challenges is how to launch a child window from the view model.

In this post I will demonstrate how I have addressed the problem using MEF and MVVM Light.  I will even pass values back and forth.  I am not say that this solution will work for anyone.  In fact it may offend the MVVM purist.  I launch the child window from the parent view.  Say it ain’t so!!!  Scandalous!!!!  Before you jump all over me it works without over complicating things and I am ok with the fact that this little bit of code won’t be covered by unit tests.

The Main Page

Here is the meat of the solution:

 public partial class MainPage : UserControl   
 {       
      [Import("MainPageViewModel")]       
      public object ViewModel       
      {           
            set {DataContext = value;}
      }

              public MainPage()       
             {
                           InitializeComponent();

                           if (!ViewModelBase.IsInDesignModeStatic)           
                          {   
                                        // Use MEF To load the View Model               
                                       CompositionInitializer.SatisfyImports(this);           
                           }

                          Messenger.Default.Register<string>(this, “FromMain”,              
                                      a => { LaunchWindow(a);  });
            }

             private void LaunchWindow(string a)       
             { 
                     MyChildWindow window = new MyChildWindow(a);           
                     window.Show();       
              }   
}

As you can see I am using MEF to set my DataContext and I am using MVVM Light to listen for an event that will cause the childe window to launch. In my sample application I am passing a message from the main screen to the child window.  I will show in a bit where this little bit of magic originates.  I pass the message to the constructor of the child window.

The Child Window

Here is the code behind of the child window:

    public partial class MyChildWindow : ChildWindow   
    {       
          [Import("MyChildWindowViewModel")]       
          public object ViewModel       
          {           
                set { DataContext = value; }       
          }

                        public MyChildWindow(string message)       
                       {           
                                    InitializeComponent();

                                    if (!ViewModelBase.IsInDesignModeStatic)           
                                     {               
                                                         // Use MEF To load the View Model               
                                                         CompositionInitializer.SatisfyImports(this);          
                                      }

                                      Messenger.Default.Send<string>(message, “ChildLoad”);           
                                      Messenger.Default.Register<string>(this, “DialogResult”,              
                                                       a => { HandleDialogResults(a); });       
                          }

                          private void HandleDialogResults(string a)      
                         {            this.DialogResult = true;        }

                          private void CancelButton_Click(object sender,   
                                       RoutedEventArgs e)       
                          {            this.DialogResult = false;        }    }

Here  I am taking the text from the main page and sending it out as a message where the child window’s view model will pick it up.  I was thinking I could have exposed the text in the ViewModel with MEF.  I am not offended either way.  You can also see that we are subscribing to an event that closes the dialog.

The Child Window ViewModel

Here is the Child Window ViewModel:

    [Export("MyChildWindowViewModel")]   
    public class MyChildWindowViewModel : ViewModelBase   
    {       
          private string _childMessage;
          public string ChildMessage       
          {
               get { return _childMessage; }           
               set { _childMessage = value; }       
          }

          private RelayCommand<string> _okClicked;       
          public RelayCommand<string> OkClicked       
          {           
                get { return _okClicked; }       
          }

          public MyChildWindowViewModel()       
          {           
                _okClicked = new RelayCommand<string>(               
                         a => Messenger.Default.Send<string>                   
                         (a, "DialogResult"));

                Messenger.Default.Register<string>(this,                
                                        "ChildLoad",              
                                        a =>{ HandleMessage(a); });       
      }

       private void HandleMessage(string a)       
       {           
              ChildMessage = a;       
       }           
}

The first thing to note is the message coming through MVVM Light and getting assigned to the ChildMessage property.  You have now seen a message that was typed in a TextBox on the main page make it all the way to the child window. Now it is time to pass a message back to the main page.  So the next thing to notice is the RelayCommand.

MVVM Light provides a RelayCommand that can be bound to a button. 

<Button Content="OK"                 Width="75"                 Height="23"                 HorizontalAlignment="Right"                Margin="0,12,79,0"                Grid.Row="1" >            <i:Interaction.Triggers>                <i:EventTrigger EventName="Click">                    <ml:EventToCommand Command="{Binding OkClicked}"                                       		     CommandParameter="{Binding Text, ElementName=_dialogText}"/>                </i:EventTrigger>            </i:Interaction.Triggers> </Button>

In the initiation of the command I am creating a new message that will pass the value typed into the child window to any one how is interested.   You have already seen on subscriber to this even (think dialog close).  The beauty of the MVVM Light Messenger is that it can have multiple subscribers across multiple dlls.

The Main Page View Model

We have now come full circle.  Here is the main page’s view model:

[Export("MainPageViewModel")]   
public class MainPageViewModel: ViewModelBase   
{       
         private string _message;       
         public string Message       
         {           
                 get { return _message; }           
                 set            
                 {               
                        _message = value;               
                        RaisePropertyChanged("Message");           
                 }       
         }

        private RelayCommand<string> _launchWindow;       
        public RelayCommand<string> LaunchWindow       
        {
               get { return _launchWindow; }       
        }

        public MainPageViewModel()       
        {
             _launchWindow = new RelayCommand<string>(               
                      a=> Messenger.Default.Send<string>(a, "FromMain"));           
             Messenger.Default.Register<string>(this, "DialogResult",               
                              a => { LoadDialogResults(a); });       
        }

        private void LoadDialogResults(string a)       
        { Message = a; }   
}

Here we can see that we are getting the message from the child window (spanning dlls). So why are there two subscribers to the “DialogResult” message?  If the ChildWindowView did not handle this message then the dialog would not close. In the main page view model I am creating a RelayCommand that responds to the Launch button being clicked.  Again I am creating a message that the view handles.

My Thoughts

The circle is now complete.  We have launched a child dialog window, passing an argument.  We work in the child window and then pass information back to the main page.  There are many improvements that can be done, get rid of the magic strings, for one. I have used this and it has worked for me.  If you have other ideas I would be happy to try them.

Get the code here

P.S.  I am really digging the HTML Clipboard in the Productivity Power Tools

Posted in .NET, 2010 Goals, C#, MEF, MVVM, MVVMLight, Silverlight | 8 Comments

Day 1 of New England Give Camp Done!

So today (or yesterday as it is past midnight) was the first day of New England Give Camp.  We met all the charities and the developers that are making their projects a reality. 

My team is building an application to deliver messages to the children at the hospital.  These messages will appear as balloons that float up on the screen.   The powers that be decided that we should use Silverlight.  Since I am the project lead I decided it was a good opportunity to use some of the following technologies:

  • Silverlight 4
  • MVVM
  • MEF
  • MVVMLight
  • WCF RIA Services
  • Entity Framework

Most of the people on my team have very little Silverlight experience but that should not be a problem.   The project is not that complex and is an excellent one to learn on.

Tonight we got the project structure organized and worked on getting the pieces in order.  We have gotten our project up on CodePlex (will be making it public later) and the developers have all the code.  We went through some initial brainstorming.  Our designer is working on the screen shots.  In the morning we should be ready to get rolling.

It should be fun!

Posted in .NET, Give Camp, MEF, MVVM, MVVMLight, Silverlight, WCF RIA Services | 1 Comment

Giving Back

So I haven’t done a good job blogging lately, in face I have pretty much blown my goals out of the water.  I am hoping that will change in the near future (more on that in a later post). This weekend is the New England Give Camp and I decided to blog about my experience.  It is a weekend long event where developers can use their skill to benefit local non-profit organizations by working on small projects.

This event is being hosted in the Microsoft NERD center in Cambridge.  I am the team lead of a team that will be developing Messaging Social Networking application for The Children’s Hospital at Dartmouth.  This application will allow messages for the kids to be displayed on a screen as balloons floating in the sky (sort of a moral booster).

I am hoping to write a post each day with what happened and with pictures.  I think that it is a good opportunity to give back to the community.  I am looking forward to it.

Stay tuned!

Posted in .NET, Give Camp, MVVM, Silverlight | 1 Comment

Predicting The Future!

So it has been a while since I have posted and I am not doing so hot on my goals for the year.  Work has kept me pretty busy an I have not had time to play but when I heard about Windows Phone 7 Series from Microsoft I had to make time to talk about a bunch of small observations that add up to something that is potentially big.

I am going to make a prediction about what is going to be announced at Mix 10: “The Window Phone 7 Series SDK is Silverlight!”   There it is my prediction and I am not just talking about browser support.  It is pretty obvious that Microsoft is going to include Silverlight in the phone’s browser, if they don’t then it is a big fail.  What I am saying is that applications developed for the phone will use Silverlight (think out of browser apps) as the platform.  Here are some of my observations:

1) Ray Ozzie got up at PDC 2009 and stated that the vision of Microsoft is “Three Screens and a Cloud”.  During his address he kept going back to this premise. During that address I could have sworn I saw a slide that had the Silverlight Icon on all three screens (I will have to go back and take a look).  It makes sense to have a common development platform for all devices.

2)  During Scott Guthrie’s keynote at PDC a Silverlight Client for Facebook was demo’ed and subsequently released to the public.  If you take a look at the UI it looks very similar to the functionality seen in the Phone Demos.  Was this a Proof of concept for the Phone?

3) My next observation is the install base of the Silverlight Plug-in is continually increasing.  This is due in part to events like the Olympics on NBC and other high profile applications using Silverlight to deliver content.  This helps push developer to develop Silverlight content.  If the 7 Series uses Silverlight as it’s SDK then there is already a developer community that can start creating applications that work both on the PC as well as the Phone and it is not a big stretch to move that app to the Big Screen (Think Three Screens and a Cloud).  That is one of the reasons Apple made the iPad use the iPhone operations system; over 100,000 applications ready to use once the iPad is released.

4) At PDC 2009 Silverlight 4 was introduced to the world and as such there were many sessions centered around Silverlight 4.  The one thing I noticed was that there were not too many session on WPF.  The out of browser functionality of SL4 moves it closer to replacing WPF as a platform for Windows based systems.  Plus SL4 works nicely with the Cloud (Here again that Three Screens and a Cloud is popping up).

5) The last point flows nicely in to my next point the Silverlight 4 Feature Set.  If you look at the features that are coming they play nicely with a phone:

  • Hardware Access (camera, microphone, etc.)
  • Out of Browser (The base OS is a form of Windows)
  • COM Interop (Integrate with Outlook on the Phone?)
  • Rich Text (foreign character recognition, think text apps)
  • Multi Touch Support (hardware requirement)
  • Sensor Awareness (could this be coming)?

6) My final point is the lack of Silverlight 4 support in Visual Studio 2010 RC.  It has been noted that the next public release of SL4 will work with the RC.  My guess is that release will happen at Mix 2010.  What better way to announce that SL4 will be the SDK than at Mix 2010.  Microsoft has already said that they will be making announcements at MIX around the SDK.  Is there anything new in the SL4 release that can be tied to the Phone (see sensor awareness prediction above)?  Is that why there was not a public release at the same time as the RC release?

I may be way off as I have no affiliation with Microsoft. I am not privy to any ongoing development there or at any of their partners.  My prediction is based upon my observations that I noted here.  But if I am right, then I think that exciting things are in store for the future.  Makes me wish I was going to Mix!

Posted in .NET, Mix 2010, PDC09, Silverlight, Windows Phone Series 7 | Leave a comment

My 2010 Goals

Happy New Year all!  I meant to write this blog last week but was too busy to do it.  It has been a snowy start to the new year.  Shoveling has taken the time I wanted to spend writing this post.  I am already behind in my goals, not a good way to start the year.  I will have to work hard to catch up.  That should not be too much of a problem now that the rush of the holidays are over.  I hope that everyone had a great time over the holidays.

Public Gardens 007

So, what are my goals for the new year. I won’t call them resolutions because I want to work on them all year long.  Resolutions seem to fall by the way side after January. 

Goal #1

Become a better developer.  I am continually striving to learn the trades of my craft. 

Steps to reach goal:

  • - Keep up reading technical books: I like to keep one technical book going at all times. My goal is 12 books.
  • - Attend local user groups: There are many user groups in the area.  I will try to regularly attend some of them.
  • - Attend Conferences:  I plan on attending local conference like the MSDN Northeast Road Show and others.  I also hope to convince my boss to send me to TechEd 2010.  I made some good friends and learned a lot at PDC 2009 and want to continue this momentum.
  • - Actively blog:  I plan on posting 12 substantial coding blogs this year.  I was able to reach my goal that I set towards the end of last year.  I figure one a month is a good start to blogging.  In the past my blogging has fallen to the wayside, not this year.
  • - Improve Technical Design skills:  I want to work on my technical documentation writing skills.  I hope to learn how to develop UML diagrams in MS Visio and incorporating them into my documents
  • - Contribute to an Open Source project:  I have committed to help on Jesse Liberty’s Hyper Video Project.  This will help improve my Silverlight skills.  This step flows into my next goal.
Goal #2

Get move involved in the local developer community.  This will help me with my first goal.  There is an active community in the Boston area.  I need to take advantage of the networking and comradery that this community offers.

Steps to reach goal:

  • - Present at local user group:  I have committed to present at a local user group in the coming months.  I want to do four presentations this year.
  • - Become active in community forums:  I want to become more active by responding to posts in community forums (i.e. StackOverflow, Silverlight Forum).  My goal is to respond to 24 messages.  This is a small start and if I find I have reached this goal early in the year I may adjust (up only) the number.
  • - Produce a demo video:  I have always wanted to do this.  I think that it will be fun.  I am going to try and do 1 video this year.  If this works out then maybe more for next year.
  • - Be more vocal on social network sites:  I should be more vocal with my thoughts and opinions in sites like Twitter.  I am not going to commit to a specific number of tweets but I should tweet everyday!
Goal #3

Increase my ‘soft’ skills. All to often developers concentrate on their technical skills and forget to sharpen the ‘soft’ skills.  These days developers are taking on more and more responsibilities. With these responsibilities comes the need to tap into more of these skills. 

Steps to reach goal:

  • - Better time management:   I am pretty good about managing my time but there are areas where I can definitely improve.  One of those areas is task time estimation.  I need to tighten my estimates on how long I think something is going to take.
  • - Better interaction with stakeholders:  I recently took over a Tech Lead position in my organization which puts me in more contact with non-technical stakeholders.  I need to improve my communication skills when it comes to conveying technical concepts to not techies. 
  • - Take more an active role in project management:  I have a MS in Management with a specialization in Project Management.  I need to keep those skills up  to date and provide more feed back into the process
Goal #4

My personal goals.  To remain well rounded I need to have some personal goals to strive for.  The key here is family, health, and happiness.

Steps to reach goal:

  • – Increase work/life balance:  My daughter is now 15 months old and boy did those months fly by.  I want to make sure that I take the time to enjoy her formative years.  I want to be there for all the ‘firsts’.  I need to strive to ensure that I balance my work time, my personal development time, and my family time.  My goal is to spend more time with my wife and daughter.
  • - Shed the weight:  Since I have left the military I have put on a few pounds.  I have also stop being as active.  Now is the time to get back into shape and to shed the excess weight.  So the goal is to loose (and keep off) 40lbs.  I think that is a reasonable goal for the year.
  • - All work and no play blah blah blah:  When I am not spending time working, professionally developing, and enjoying family, I need to take some time and enjoy life.  I enjoy going to Fenway Park to watch the Red Sox.  I hope to make it to 3 games this year.

So there here it is written in 1’s & 0’s for all the world to see.  I will post updates, periodically, tracking the progress I am making towards my goals.  Stay tuned!

Posted in 2010 Goals, Blogging | Leave a comment

MEF, MVVMLight and Silverlight…Oh My!

Well, it is the last day of 2009 and I am posting my last coding post of the year.  Nothing like waiting until the last day of the year to complete my goal of three substantial coding post before the end of the year.  In the coming days I will be putting a post together with my goals for 2010.  Stay tuned!

After reading posts by Glen Block and Shawn Wildermuth I have decided to try and build an application in Silverlight 4 using MEF and MVVMLight with a little bit of RIA Services thrown in for good measure.  I liked the way that Shawn structured his projects so I am going to follow that structure.  This application is not going to be ground breaking, it is more to get me comfortable using MEF and take MVVMLight for a spin.  These are technologies I hope to use in an upcoming project at work so I needed to get up to speed fast.  I believe that this project has succeeded in getting me the knowledge needed to complete my project at work.

Here is a list of the technologies I used:

As I stated before my goal was not to build a groundbreaking application but to test drive some frameworks so see if they were going to satisfy my needs.  Here is a list of some of those needs:

  • Common Controls/Layout Across Apps
  • Rapid Development
  • Separation Of Concerns
  • Maintainability
Common Controls and Layout

My company is developing an application this divided into modules.  Each module contains separate Silverlight applications.  The goal is to have a common layout and to utilize set of common controls.  This is where MEF comes in.  The layout consists of a menu area, a content area, a toolbar area and an information panel.  In my demo application I was able to create a common project to be shared across applications using MEF to provide the content.

   1: public partial class LayoutFrame : UserControl

   2:     {

   3:         [ImportMany]

   4:         public IContentList[] ContentLists { get; set; }

   5:  

   6:         [ImportMany]

   7:         public IDetailedList[] DetailLists { get; set; }

I facilitate this by creating interfaces in a common project that corresponds with areas in the layout.  Right now there is nothing to implement in these interfaces but I could see some in the future. 

Now all I have to do is have my view implement that interface and Export it….

   1: [Export(typeof(IDetailedList))]

   2: public partial class AlbumListView : UserControl, IDetailedList

   3: {

   4: ...

   5: }

Add the Layout control to the MainPage.Xaml…

   1: <cc:LayoutFrame />

Through the power of MEF my Views are laid out the way I want them even though the Layout control is in one dll and he Views are in another.  I can see my common controls living in that same common dll as the layout and getting the content from a ViewModel in my application.  I came up with this pattern from Glen’s demo.  I am not going (at this time) as far a having separate packages like Glen did but the concepts are the same.

Rapid Development

The ability to reuse these common controls and layouts will allow me to build out multiple modules more quickly.  All I have to do is build out the views and view models, wire them up to be picked up by the parts, and build out the back end using WCF RIA Services. Each application (module) will have its own RIA Services and  model (minimal overlap between modules).   There are business services already in place servicing the current UI implementation that I will reuse to increase the productivity of the Silverlight UI.  I will wrap those service with a custom RIA Sevice Context.  This will allow me to spend most of my time developing the views and view models.

Separation Of Concerns

One of the goals of my project is to keep the code clean by separating the concerns (the UI from the business logic).  To do this I decided to use MVVM.  This seems to be the pattern that community is embracing to develop Silverlight applications.  It satisfies my goal of keeping the code pretty clean.  One of the challenges of MVVM is cross View communications.  How do you get one part to talk to another part with out tightly coupling them.  That is where a framework like MVVMLight comes in (Thanks Shawn for the demo).

I used MVVMLight’s Message object to broadcast events…

   1: _artistSelected = new RelayCommand<Artist>(a => Messenger.Default.Send<Artist>(a, "AlbumListViewModel"));

Parts that are interested in events can subscribe…

   1: Messenger.Default.Register<Artist>(this, "AlbumListViewModel",

   2:    a =>

   3:    {

   4:        GetAlbumByArtist(a.Name);

   5:    });

   6:    }

I still have a little more research to do with the MVVMLight framework but my initial playing around has helped. 

Maintainability

MEF and MVVM will go along way to making my applications maintainable and also extendible.  The separation of concerns will allow me to change and add functionality without having to change my common layout, localizing changes to their respective modules.  The  flipside is also true, if I want to change the layout behavior I can do it in one place.  As long as I don’t mess with the MEF tags things should still work

Conclusion

In this post I touched on only a few things that I will need for my application at work.  In my demo code I did not address the Blendibility of my application.  In fact I did not address an UI candy.  I hope to build on this demo in future post to continue building it out.  I would like to thanks Glen Block for giving me the inspiration (and the framework) to compartmentalize my application.  I would also like to thank Shawn Wildermuth for giving me my initial project structure and pointing me to MVVMLight. 

Hope everyone has a safe and Happy New Year!  Talk to you next year.

You can get the code here.

Posted in .NET, C#, MEF, MVVM, MVVMLight, Silverlight, WCF RIA Services | 1 Comment

Silverlight 4 Data Binding: String Format

This is the second substantial coding post to reach my goal of three by the end of the year. In this post I will demonstrate the new string formatting functionality in Silverlight 4 data binding. There have been a lot of new functionality in data binding. The string formatting functionality will help save time and reduce code. These enhancements help make business applications quicker and easier to program in Silverlight.

The first thing I noticed in Silverlight 4 is that you now have Intellisense support for binding.

Prior to Silverlight 4 you had to manually type binding statements. This was prone to “fat finger” errors, mistyping a key word or forgetting to close brackets. True, there were GUI means of binding (through Expression Blend) that could help prevent these errors but now there is support right in the XMAL editor. This should help increase productivity and reduce errors.

Now to the main task at hand, formatting strings. Many business objects have properties that represent dates, currencies and the like. In Silverlight 3 you had two options when it came to controlling the format of these properties when data binding. First you could add a property to your view model that returned the properly formatted string. This is not ideal because to have maintain extra properties that would hand conversion to and from the desired format.

The second choice you had was to create a value converter. This method off loaded the conversion code to a different class keeping your view model clean. This also allows you to reuse the code. For instance if all dates need to be displayed in specific format they could use the same value converter.

To create a value converter you first create a class that implements the IValueConverter interface:

   1: public class CurrenceyValueConverter : IValueConverter

This interface requires the implementation of two methods: Convert and ConvertBack. These methods contains the code to convert to and back from the desired format.

Here is and example of the Convert method for converting double values to currency:

   1: public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   2: {

   3:    string retVal = string.Empty;

   4:

   5:    double? cost = value as double?;

   6:

   7:    if (cost != null)

   8:    {

   9:        retVal = cost.Value.ToString("C", 

culture);

  10:    }

  11:

  12:        return retVal;

  13:    }

Now in XAML you add a resource for your value converter:

   1: <Grid.Resources>

   2:     <local:CurrenceyValueConverter x:Key="CostConverter" />

   3: </Grid.Resources>

Finally, you reference the resource in the binding:

   1: <TextBlock Text="{Binding Path=Cost, Converter={StaticResource 

CostConverter}}" Margin="10" />

This seems like a lot of work just, not to mention and class file to get a dollar sign in front of a double value. Silverlight 4 makes this process a whole lot easier.  In Visual Studio 2010 all you have to do is select the control you are binding to, select the property and launch the binding window. Under the options tab you now have the ability to control the format for the text.

When you select a format the following code gets generated:

   1: <TextBlock  Margin="10" Text="{Binding Path=Cost, StringFormat=\{0:c\}}" />

Combine this functionality with the Intellisense and you should be able to increase your productivity, produce cleaner code, and build business applications faster.  Does this mean that you will no longer need to write value converters, no they are still useful. For instance if you actually need to convert the cost to a specific currency (Dollars to Euros), you will need a converter. It does mean that you no longer need to write converters to format text. There are a many other new data binding features introduced in Silverlight 4. I hope to address some of them in future posts.

Posted in .NET, C#, Silverlight | 2 Comments

Bing Maps SilverLight Control

Yesterday I attended a lunchtime session on the new Bing Maps Silverlight Control. I went to this session for fun. It was pretty cool, even if I won’t get a chance to use it anytime soon. There is a lot of functionality out of the box. The biggest piece of functionality is the Deep Zoom. This provides smooth zooming and panning of maps.

One of the nicest features is that you don’t have to host this control in a Silverlight Application. With one line of HTML you can have a Silverlight Map on the page. There are a few attributes that allow you some customization. Using the control in this manner does not require a key to access the map servers. If you want access to the full functionality, you have to host the control within a Silverlight application.

The first thing that you have to do is go out an get an access key. It is free to use the service for development, non-profit, and educational purposes. There is a pricing model based upon bandwidth used. Bing has made it easy to get and manage keys from its website. Pass this key to the map control and you have access to the full functionality of the mapping service.

Now that you have a key you can develop rich mapping applications. Here is a list of functionality:

  • Push Pins (standards look and custom looks)
  • Polygon plotting
  • Control map type (Arial, Road and others)
  • Geodata (access to search)
  • Map Layering
  • and others

You can access this functionality both in XAML and in the code behind.

There are a lot of cool possibilities with this If you applications requires mapping I would highly recommend using Bing. BTW they also have an AJAX control if you don’t to create a Silverlight application.

Posted in Bing Maps, PDC09, Silverlight | Leave a comment