Our team is hiring: http://jobs.sweux.com/

Waking up the computer at the office with your cell phone

January 29th, 2010 Pedro Pombeiro No comments
… And saving on utility bills while you’re at it! What I’m about to show you is a way to wake up your machine remotely with nothing more than a Twitter client and a small utility running on one of the machines at your office/campus.

 

Abridged version :-)

To get the utility that allows you to wake up a machine from a Twitter direct message, you need to go to the project’s home page at CodePlex. The source code is also available.

 

 

The problem…

Back in 2004, when it started becoming practical to use Remote Desktop to access my office machine, I started taking advantage of that to get more stuff done from home. Unfortunately, that required leaving the office machine turned on the whole time, 24/7, as I never knew when I might need to access it again. As you can imagine, this is terribly inefficient energetically (although arguably efficient in economic terms, as you could reason that the work done from home more than pays for the cost of the electricity bill).

Over the years, I have toyed with the idea of being able to remotely wake up my machine upon demand, leaving it in sleep mode or in hibernation mode during off-hours. I tried Wake-on-LAN, and although I could easily set it up within two machines in the office, our VPN box seemed to interfere with the communications required to wake up the machine. I needed a way to bypass the VPN…

 

My solution (and my first practical use for Twitter!)

Fast forward to 2010: with the advent of social networking platforms with open APIs, and the proliferation of free client software and libraries to access them, I now had all the tools I needed to quickly build a small mash up application that would sit on the server and react on Twitter direct messages. I started devising the requirements for such a tool:

  • Have low impact on the machine (no installation or 3rd party products to install);
  • Must be usable by everyone at the office, not just me;
  • Will take requests, and reply back once your machine is online. I immediately thought of Hanselman’s toy project, Tweet Sandwich. That was pretty much what I needed as far as the basic logic. However, instead of printing orders, my utility would run a piece of networking code that would take care of waking up a machine in the local network.

    How does it work?

    The simple answer is that you will be creating a file with an entry on each line for each machine you want to be able to wake up (normally one for each co-worker). Each line contains:

  • the Twitter screen name of the person;
  • the MAC address of the machine’s network card (you can type ipconfig /all at the Command Prompt to find out the address); and
  • the machine name or IP address.

When the utility app receives a special message from a given befriended Twitter account, it broadcasts a Magic Packet to the network, containing the MAC address of the specific machine, which will cause that machine to wake up. Twitter Buttler then checks whether the machine is now online and will fire back a Direct Message to the Twitter user letting him now that his machine is now turned on. At this point, the user can connect to his machine and carry on working.

Note: for you to be able to send direct messages to the utility app, the accounts listed in the config file need to follow the account used in Twitter Buttler, and vice-versa.

The are two commands you can currently send to Twitter Buttler: “wake up”, and “who’s online?”. They are pretty self-explanatory, so I won’t go into them here.

      Give it a try if you normally leave your office machine running for no good reason other than to be able to access it from home. Every little step counts in the quest to reduce our carbon footprint, and as the data suggests, there is quite a lot to be gained by just leaving our machines turned off.

     

     

    Shout it kick it on DotNetKicks.com

    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print

    Strange behavior of DropShadowEffect

    January 11th, 2010 Pedro Pombeiro 2 comments

    Yesterday, I spent the whole morning wrestling with WPF because an object I was re-implementing was appearing too blurry when compared to the existing native version. This was a basic label object, containing a picture and some text. Both the picture and the text were quite fuzzy, and don’t get me wrong, I am aware that WPF 3.5 SP1 still has issues with the text layout mechanism (the ideal layout compared to pixel-aligned layout). But this was much worse, as you can see in the screen grab:

    image

    You may notice that I am applying a drop shadow effect to the label, for some eye candy. And believe it or not, after a few hours of tweaking the XAML, and selectively disabling Visuals, I found the culprit to be the DropShadowEffect! As a designer, I would expect the DropShadowEffect to create a shadow behind my object, with the same shape as the object boundaries. Apparently this is not what the effect does, but rather overlays (or underlays?) a version of the source Visual, causing the blur effect. The solution to these types of problems is very simple: you just need to embed my Visual inside a Grid, so that you can add a Border with the same shape under my Visual. That Border will then have the effect applied to it, so basically I have moved any blurriness behind my label:

    Separate drop shadow compared to On-object drop shadow

    You can easily test this behavior in Kaxaml, by entering the following XAML, and removing the Effect from the Border element:

    <Border Background="Yellow" BorderBrush="Black" BorderThickness="1" Width="100" Height="26">
        <Border.Effect>
            <DropShadowEffect/>
        </Border.Effect>
        <TextBlock Text="Label"/>
    </Border>
    

    I would still like to understand the reason for this behavior of the DropShadowEffect, so if you have any explanation for it, do let me know.

    Shout it

    kick it on DotNetKicks.com

    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print
    Categories: Tips Tags:

    A Busy State Indicator attached behavior

    December 1st, 2009 Pedro Pombeiro No comments

    Today I decided to encapsulate the circular progress indicator I use in Scrum Sprint Monitor in a reusable behavior. This served as a learning experience as well, since I had not yet had the chance to play with attached behaviors. My requirements were the following:

    • Have a behavior that displays an animation during long running operations. It should dim out a defined region in the UI, optionally preventing input into that region. All state transitions must be animated.
    • Have minimal impact on the logical tree.
    • Allow configuration of parameters, such as dim brush, transition duration, etc.

    This problem turned out to be a perfect candidate to writing a behavior, and I needed only a few hours to crank it out. Here is a short video demoing it:

    This behavior makes use of the simple and great Circular Progress Bar control by Sasha Barber, up on CodeProject. You can easily replace the control used for the animation though, should you require a different one.

    Usage

    The behavior has a simple requirement, that it can only be attached to a Grid element (I believe that is a requirement that can easily be satisfied, in most projects). The only required property is the BusyState property, which tells the behavior when to do its work:

    <Grid DataContext="{Binding Path=ConfigurationViewModel, Source={StaticResource serviceLocator}}"
          Behaviors:BusyIndicatorBehavior.BusyState="{Binding IsBusy}"
          Behaviors:BusyIndicatorBehavior.TargetVisual="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}">

    The behavior works by adding a Visual Tree at runtime under the attached DependencyObject (the Grid). You connect your Busy state flag by providing a Binding to the BusyState attached property. There are a few other optional properties you can use, to customize things such as the dimming brush, the transition duration, margins, etc.

    The source code is available for download from the Microsoft Expression Community Gallery. Do leave some feedback if you have any suggestions, or if you just find it useful.

    If you want to take a look at source code that uses this behavior, head to the Scrum Sprint Monitor project at CodePlex, and search for Behaviors:BusyIndicatorBehavior.

    Shout it
    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print

    Red Bull Air Race in Gaia

    September 11th, 2009 Pedro Pombeiro No comments

    This weekend the Red Bull Air Race is visiting Porto, right beside our office building. That means about 650,000 spectators watching airplanes performing low altitude laps around a section of about 2 km of the Douro river. Apparently Porto is one of the venues with the most spectators for this event.

    I must admit I was caught by surprise last year by a maneuver called “Tumble” over the World Heritage downtown Porto:

    Shout it
    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print
    Categories: Uncategorized Tags:

    Animating the Visibility property

    August 30th, 2009 Pedro Pombeiro 2 comments

    This post is sort of a future reference for myself. I needed to animate the Visibility property as part of a larger Storyboard, and it wasn’t immediately apparent how to do it. It took a bit of effort to find the solution on Google, so I am posting the solution in hope that it will make someone else’s life easier as well.

    If you have something like the following, for an object that is usually hidden:

    <Setter Property="Visibility" Value="Visible" />
    

    and you want to fade in the object instead of suddenly showing it, you will need to convert the Setter into an Animation action in a Storyboard. You are probably aware of the DoubleAnimation and BooleanAnimationUsingKeyFrames classes already. To animate the Visibility property, however – which is an enum –, the solution is not immediately apparent: you need to use ObjectAnimationUsingKeyFrames:

    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
            <DiscreteObjectKeyFrame KeyTime="00:00:00">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Visible</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    
        <DoubleAnimation Duration="00:00:01" Storyboard.TargetProperty="Opacity" To="1" />
    </Storyboard>
    

    There you go. The animation will start by making the object visible, and then animating it to 100% opaque. Hope this helps you!

    Shout it

    kick it on DotNetKicks.com

    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print
    Categories: Tips Tags: ,

    Animating a data-bound color property

    August 17th, 2009 Pedro Pombeiro No comments

    As I was going through the UI of the Scrum Sprint Monitor to introduce animations to the larger UI elements, one type of property was proving difficult to animate: the dynamic background color of some elements which were bound to Brush (or Color) properties of the ViewModel.

    Picture this: you have a Color property that is currently Green. At some point it changes to Red. You would like the UI to update smothly, so you would not see the color jump from Green to Red. You are not able to do this in XAML with triggers and storyboards directly. The problem lies in the fact is that the Animation objects in XAML cannot be bound to dynamic values (see instances here and here), as they must be frozen for performance and thread safety reasons.

    <DataTemplate DataType="{x:Type ViewModels:BuildStatusBackgroundViewModel}">
        <Grid Background="{Binding Path=BuildStatusColor}" />
    </DataTemplate>
    

    Therefore there is no point in trying to introduce triggers (be it EventTriggers or DataTriggers) in this Grid element. What I ended up doing is deriving a class from Grid and spawning the animation from code behind.

    <DataTemplate DataType="{x:Type ViewModels:BuildStatusBackgroundViewModel}">
        <Controls:BuildStatusBorder />
    </DataTemplate>
    

    See the code-behind example here. I did encounter a pitfall while developing this approach. I ran into a “Cannot freeze this Storyboard timeline tree for use across threads” exception, when the animation was kicked off. I fixed this by cloning the existing property value, essentially removing any data binding from the property.

    Hope this helps someone who is running into the same problem of animating transitions between databound properties!

    Shout it

    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print

    Animated WPF Panels (animating collection views)

    August 14th, 2009 Pedro Pombeiro No comments

    UPDATE: The same functionality is now available out of the box using the Blend 3 SDK, through the FluidMoveBehavior. Just drag that behavior to your container panel, and set the Duration and AppliesTo properties! The only difference is that easing functions are not yet supported in WPF. We will need to wait until WPF 4 is released.

    Last evening I finally implemented a long awaited feature (by me!) in the Scrum Sprint Monitor: animated WPF panels. As the team members in the Sprint move up and down the list (an ObservableCollection<>), get added or removed, I always wished that change could be animated. My current knowledge of the WPF layout mechanism wasn’t sufficient to finish on that endeavor within a few hours, though.

    I finally found a blog post that set me on the right path, on Ed Foh’s blog. Ed in turn was inspired by Kevin Moore’s WPF Bag of Tricks, which also includes an Animating Tile Panel.

    Here is a video demonstrating the enhanced behavior of my AnimatedUniformGrid:

    An AnimatedUniformGrid in action

    Why those two solutions didn’t work for me

    Both of the aforementioned solutions contained hardwired positioning logic, though. I simply needed to add the animation behavior to StackPanel, WrapPanel and UniformGrid, not a completely custom panel. Ideally, the solution would be a behavior that could be added on top of those containers. That particular aspect wasn’t realized, and I ended up deriving classes for each of these panels, prefixing the new classes with “Animated”. It is still a pretty acceptable solution. UPDATE: I eventually found this was the same approach taken by at least one commercial offer.

    The following is the code required to instantiate the uniform grid (note how you simple need to prefix the panel class with Wpf:Animated):

    <ItemsControl ItemsSource="{Binding TeamMembersIncludingUnassigned}">
        <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
             <Wpf:AnimatedUniformGrid Duration="00:00:01" />
          </ItemsPanelTemplate>
       </ItemsControl.ItemsPanel>
    </ItemsControl>
    

     

    Adding animation to an existing panel control class

    The workflow for converting an existing Panel to an AnimatedPanel is pretty easy:

    1. derive a new class from the desired panel class (prefix it with Animated);
    2. override the ArrangeOverride method in the new class (don’t call the base class implementation);
    3. using .NET Reflector, extract the ArrangeOverride method contents from the base class implementation, and simply substitute the element.Arrange call that is performed for each child for a call to the AnimatedPanelHelper.ArrangeChild() static method.

    That is all you need to do!

    Acknowledgements

    Thanks to Ed Foh and Kevin Moore for their great work.

    Download the source code here.

    Shout it
     
    kick it on DotNetKicks.com
    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print

    Writable machine-level AppSettings

    August 12th, 2009 Pedro Pombeiro No comments

    The other day I needed to make an application (a screensaver to be more exact) run under lower privilege in Windows 7. The application worked fine in Windows 2003, but something must have changed in Windows 7, because the screensaver was no longer running under my user account. In the end, this meant I had to move the application settings from User level to App level. It should have been a straightforward operation: simply change the level of each setting to Application, in the Visual Studio 2008 project settings page. The problem is that if you do that, the settings will become read-only.

    A quick search through the web told me I would need to roll my own solution, using the ExeConfigurationFileMap class, and that is what I did at http://scrumsprintmonitor.codeplex.com/sourcecontrol/changeset/view/26836?projectName=scrumsprintmonitor#643147. Here are some observations about the implementation:

    • The settings file is hand-edited (no designer support, although the value of a designer here is negligible for a small app);
    • It has support for access in special scenarios, such as in a WPF designer;
    • It supports read-only scenarios, throwing an exception if you try to modify the settings.

    Feel free to use it in your own projects.

    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print

    Maintaining folder structure in ClickOnce deployments

    July 6th, 2009 Pedro Pombeiro No comments

    Recently, in developing the Scrum Sprint Monitor, I came across a situation that deviated my ClickOnce deployment from the standard. I needed to add an “AddIns” subfolder to the deployment folder, in order to isolate my MEF addins from my Prism modules (they seem not to play nice together, since my Prism setup will enumerate the deployment folder, loading all DLLs into memory, and on the other hand, MEF will not try to load imports from DLLs that are already loaded into memory).

    In any case, I had no choice but to isolate the DLLs in separate folders, and I didn’t really want to have to learn the nuts and bolts of ClickOnce just to solve this one problem.

    The problem

    I have two deployment scenarios: xcopy deployment and ClickOnce deployment. On the ClickOnce scenario, I deploy a fixed set of addins – non-configurable, for simplicity reasons. I wanted to start deploying a single known DLL (generated by a dependent project), into the AddIns\ServerAdapters folder. I initially had the app project set up to include a reference to the addin project, in order to have the addin DLL included in the deployment. Unfortunately, there is no way to choose the folder the DLL will end up in. It will just be deployed alongside the application, on the root folder. Moving the DLL elsewhere seemed to require me to start editing the manifest file, instead of relying on Visual Studio to maintain it for me – not something I was looking forward to at this point.

    After scouring the web for information, I gathered some bits and pieces that got me to a workable, and simple solution: if you add a file to your deployment project and mark it as “Build Action: Content”, Visual Studio 2008 will include that file in the Publish|Install Mode and Settings|Application Files dialog. While I have seen other people include a DLL in the project in order to have Visual Studio include it in the deployment, inserting a link seemed like a cleaner solution (and it actually worked!):

    1. Right-click on the folder you wish to add the DLL to;
      image
    2. Click Add|Existing Item…
      image
    3. Select the file in question and click in the drop-down arrow of the Add button:
      image
    4. Select “Add As Link”.
    5. Now you have the target DLL listed in your project:image
    6. Next, you’ll need to set the properties for the DLL, marking it as ”Build Action: Content”. This will make it a part of the deployment.
      image 

    After that I could see the DLL listed in Application Files:

    image

    I only had to take care not to accept TFS’ suggestion to add the DLL to source control (just Undo Pending Changes for that file). This solved my deployment problem, and I managed to avoid having to use a tool like mageui.exe or ManifestManagerUtility just to accomplish this seemingly simple task.

    Shout it kick it on DotNetKicks.com

    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print
    Categories: Tips Tags: ,

    Creating a dynamic UniformGrid with ItemsControl

    May 21st, 2009 Pedro Pombeiro No comments

    Recently I needed to replace a UniformGrid control where the number of columns was known at design time, with something equivalent that would be bound to a Prism region (update: if you are unfamiliar with Prism, the RegionName attached property will basically pull the items into the ItemsSource property). The goal was for each cell to hold a view, and to grow horizontally as more views were added. For some reason, at the time was under the impression that Grid and UniformGrid did not support ItemsControl, so I started with a StackPanel with horizontal Orientation, but of course, that doesn’t work well when you have a narrow display area. I then thought of a couple of approaches: either making my own RegionAdapter for ItemsControl, or deriving from ItemsControl. Those seemed more complex than required, so after looking long and hard on the web for a way to automatically set the Grid.Column attached property based on the number of views assigned, I realized that UniformGrid does support ItemsControl. All I had to do was bind the UniformGrid.Columns property to the ItemsControl.ItemsSource.Count property, and voilá! I got myself a dynamically sized UniformGrid:

    <ItemsControl cal:RegionManager.RegionName="{x:Static
        Extensibility:RegionNames.SprintOverviewChartsRegion}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="{Binding Path=ItemsSource.Count,
                    RelativeSource={RelativeSource FindAncestor,
                    AncestorType={x:Type ItemsControl}}}"
                    IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

     

    Shout it

     

    Technorati Tags:
    Share and Enjoy:
    • Digg
    • del.icio.us
    • DotNetKicks
    • DZone
    • Technorati
    • LinkedIn
    • Google Bookmarks
    • StumbleUpon
    • email
    • Print
    Categories: Tips Tags: