Monthly Archives: July 2009

Set Up “Push” Gmail on Your iPhone [Hack Attack]

Despite iPhone 3.0‘s push notifications and previously mentioned Google Sync's contacts and calendars syncing chops, push Gmail still hasn't come to the iPhone. But with the Prowl iPhone application, you can now push Gmail notifications—and then some—to your iPhone.

What Prowl Does

The $3 Prowl iPhone application [iTunes App Store Link] works in conjunction with Growl, the universal notification application for Macs, to push desktop notifications to your iPhone. (The current release of Growl for Windows doesn't yet work with Prowl, but the latest unreleased version supposedly already does—meaning Windows users should be able to do this once Growl for Windows updates.)

How It Works

The image associated with this post is best viewed using a browser.Whenever an application sends a notification to Growl, Growl sends that notification to Prowl's servers, which in turn sends a push notification to your iPhone. So, for example, if you've got Growl set up to display new Gmail notifications (details below), Prowl can push those same notifications to your iPhone. The cool part about Prowl is that it doesn't just work with Gmail—it works with anything that Growl does.

NOTE: What you’ll get after following these instructions isn’t true push email, but it’s a pretty solid approximation. In fact, in order for it to work consistently, you’ll need to have an always-on computer to push your Growl notifications to your iPhone. But until something better comes along, it’s a pretty strong alternative.

Set Up Prowl with Growl

If you haven’t already, go download and install Growl (it will install as a new preference pane in the System Preferences of your Mac).

Next, head over to the Prowl web site and register for an account (Prowl doesn’t even require an email address). Once registered, download the Prowl plug-in for Growl, unzip it, and double-click the Prowl.growlView file to install the Prowl plug-in to Growl.

Once you've done that, you're ready to set up Prowl on your computer. Fire up the Growl preference pane (System Preference -> Growl), then click on the Display Options tab. Select Prowl in the Display Styles list on the left, then enter the Prowl username and password you registered with and click Verify to make sure Growl can properly talk to Prowl's servers. (If everything's copacetic, you'll see a green checkmark next to the Password field.) If you want to use Prowl as the default for Growl (meaning you want the majority of your Growl notifications pushed to your iPhone), you can also set Prowl as the default from the Default Style drop-down.

When you set Prowl as your display notification type, you still get to choose what your Growl notifications will look like—you just do so through this Prowl display options menu. Make sure you've ticked the checkbox labeled Display notifications using style, then select the style you prefer (I'm a smoke person). You can also adjust what kind of Growl notifications Prowl will forward and when—for example, I've set Growl to only send notifications to Prowl when the priority is at least High, and I only send notifications when my computer has been idle for more than 5 minutes (presumably you don't need push notifications if you're already sitting at your computer).

If you’ve already downloaded Prowl to your iPhone (and choked on the $3 price tag—yeah, we're cheap) and logged into your Prowl account from your device, any new Growl notifications with Prowl set as the display type will push those notifications to your iPhone. Pretty cool, huh? That can potentially include anything from your IM client to your iTunes notifier and, yes, Gmail. Of course, Gmail requires a little more set up.

Set Up Gmail Notifier with Growl and Prowl

In order to get Gmail playing nice with Growl, you’ve got a few more steps to go. First, you need to download and install the Google Notifier for Mac—the official Gmail and Google Calendar notifier from Google. Next, download the Google+Growl plug-in for Google Notifier, unzip it, and install the Google+Growl Utility to your Applications folder. When you run it, this little utility keeps its eye on the Google Notifier and pushes any new email updates (and event alerts, if you wish) to Growl… which, if set up with Prowl, pushes the alert to your iPhone.

To make sure Google+Growl is set to work with Prowl, open up Growl one more time, click the Applications tab, and double-click on Google+Growl. Make sure Prowl is set as the default display style, then click the Notifications tab. On this tab, you’ll see a notifications drop-down with New Event and New Gmail selections. Make sure that both are set with Prowl as the display style. (If, like me, you’re setting Prowl only to push high priority Growl notifications, make sure you set the priority to High as well.

Keep in mind that you need to keep Google+Growl running in the background for the whole system to work, too. It all sounds fairly convoluted for something that should be so simple, but once you’ve got it set up, you shouldn’t have to do any fiddling after that


A year or so ago I was using a third-party background app (required jailbreak) called iMapIDLE that simulated push for Gmail, and while it looks like something similar is undergoing review for the App Store, the Prowl approach seems like another very solid one. It doesn’t require you to hand over any usernames or passwords to a third party, since the notifications are all coming from your computer, and it can work with all sorts of notifications that Growl already supports (imagine getting a notification that your BitTorrent client just finished downloading that movie while you’re picking up dinner, for example).

As I said above, Windows support for using Prowl in conjunction with Growl for Windows isn't quite there, but it should be very soon, making this a pretty solid solution for rolling notifications for just about anything from your desktop—and that, we like very much.

Got something clever you’d like to use Prowl for aside from Gmail push notifications? Have another, better method you’re already using? Let’s hear it in the comments.





Validating Properties in Silverlight Classes

Silverlight classes rely on the INotifyPropertyChanged interface and associated PropertyChanged event it contains to ensure that data binding stays up-to-date in an application.  It’s a great feature because you don’t have to worry about ensuring that changes to object properties are propagated back to controls….Silverlight handles refreshing control values for you automatically as long as the class that’s being data bound implements INotifyPropertyChanged and property set blocks raise the event.  I use a fairly standard pattern for defining my properties and raising property changed events (there are several options for doing this…see a nice list here).  Here’s an example of a property:

public Job CurrentJob
{
    get
    {
        return _CurrentJob;
    }
    set
    {
        if (value != _CurrentJob)
        {
            _CurrentJob = value;
            OnPropertyChanged("CurrentJob");
        }
    }
}

The problem is that I tend to change property names from time to time within an application and use the Visual Studio refactor feature to do it.  This works great for changing the property name or field name but doesn’t change the quoted value passed to OnPropertyChanged.  I’ve run into a few issues where I missed renaming the string value and decided that I needed to be more proactive with validating the value.  I ended up going with the following validation code after looking at a few options:

protected void OnPropertyChanged(string propertyName)
{
    CheckPropertyExists(propertyName);

    if (this.PropertyChanged != null)
    {
        this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

[Conditional("DEBUG")]
private void CheckPropertyExists(string propertyName)
{
    Type type = this.GetType();
    if (type.GetProperty(propertyName) == null)
    {
        string errorMessage = string.Format("Invalid property found: {0} in {1}", propertyName, type.FullName);
        Debug.Assert(false, errorMessage);
    }
}


Originally I used #if..#endif statements to conditionally add or take out the CheckPropertyExists method until I came across a nice post by Josh Smith where he used the Conditional attribute in a WPF application.  If you’re new to it, the compiler will leave CheckPropertyExists in the compiled code if you’re in debug mode.  If you switch to release mode it’ll take it out which is good since at that point you wouldn’t want to slow down the application with the reflection statements. 

With the CheckPropertyExists method in place I now have an easy way to know if I missed renaming a property value that’s passed to OnPropertyChanged which saves a few headaches.  I put the code in my ViewModelBase class so I only have to write it once and have it available for just about everything I do in Silverlight.  Here’s the message that I get if there’s a problem:

image

Update:  The same day I posted this I ran into a mis-named property.  The assert message popped up and I fixed it within a matter of seconds instead of searching through the code for minutes (or longer) to locate the problem. 

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

 

Improving jQuery’s JSON performance and security

When you’re working with JSON, performance and security are often opposing, yet equally important concerns. One of these areas of contention is handling the JSON strings returned by a server. Most JavaScript libraries do a great job of abstracting away the details, but the underlying process has long been a frustrating exercise in compromise.

On one hand, eval() is the fastest widely available method, but it is not safe.

On the other hand, textual JSON parsers written in JavaScript may be much safer, but are dramatically slower. In client-side situations, where milliseconds count, such a large performance overhead is typically too prohibitive to accept.

Recently, an exciting new alternative has emerged: browser-native JSON parsing. Integrating JSON parsing as part of the browser’s implementation of JavaScript allows for using the more secure parsing method, and even provides performance faster than eval() offers.

To take advantage of that, this post will show you how to detect whether or not a browser supports native JSON parsing, and how to force jQuery to use browser-native parsing in its $.ajax calls when it is available.

Native JSON parsing in the browser

Previously known as ECMAScript 3.1, ECMAScript “Fifth Edition” (the specification that JavaScript implements) formally codifies a native JSON parsing feature. The spec’s API exactly mirrors that of Crockford’s implementations of JSON.parse and JSON.stringify in json2.js, easing the transition to browser-native functionality.

This native JSON parsing brings marked improvements in terms of both security and performance. Not only does the native routine use textual parsing to avoid the risk of executing malicious code embedded within JSON, but it is also fast.

At the time of this writing, three major browsers already include support for native JSON parsing: IE8, Firefox 3.5, and Chrome 3.

Safari 4 does not currently support the standard, but its underlying engine (WebKit) has recently implemented it. Hopefully the feature will make its way to Safari soon.

Detecting native JSON support

Determining whether or not native JSON parsing is available within a given browser is the first problem we need to solve. To do this, we ultimately need to know if the JSON.parse function is defined.

We can’t test for JSON.parse directly because attempting to reference it will throw a JavaScript error if the underlying JSON object doesn’t exist. So, first we need to inspect the type of that underlying object itself:

if (typeof(JSON) === 'object') {
  // native JSON may be available.
}

If we find that the JSON object does exist, it’s likely that native JSON parsing is available. However, it’s a best to double check the JSON.parse function as well:

if (typeof(JSON.parse) === 'function') {
  // native JSON parsing is available.
}

Because JavaScript performs short-circuit evaluation, it’s safe to clean this up by combining both tests in a single conditional, as long as they’re in this order:

if (typeof(JSON) === 'object' &&
    typeof(JSON.parse) === 'function') {
  // Native JSON parsing is available.
}

Curious whether your browser supports native JSON parsing? Using the JavaScript above, I have determined that:

You appear to have JavaScript disabled or are reading this in an RSS reader. In order to view the status of your browser’s native JSON capability, please view this post in a browser with JavaScript enabled.

Extending jQuery to use native JSON parsing

In my previous post, I demonstrated how to use jQuery’s dataFilter to transform a JSON response before it is returned to the $.ajax() success handler. In the process, we also preempted jQuery’s default method for deserializing JSON data.

The focus at that time was implementing the same method for JSON parsing that jQuery uses by default, so eval() was still used. However, we can also use the same dataFilter mechanism to force browser-native JSON parsing instead.

Using our JSON parsing detection code and a dataFilter callback, upgrading jQuery to use browser-native parsing is simple:

$.ajax({
  // Your usual $.ajax() URL, data, dataType, etc.
  dataFilter: function(data) {
    if (typeof (JSON) !== 'undefined' &&
        typeof (JSON.parse) === 'function')
      return JSON.parse(data);
    else
      return eval('(' + data + ')');
  }
});

Because jQuery only attempts to deserialize JSON responses if their type is string, and because the dataFilter callback executes before jQuery would normally perform that deserialization, this technique preempts jQuery’s JSON evaluation completely. In the worst case, it will simply revert back to the same eval() method that jQuery internally uses by default anyway.

Note: It’s important to keep in mind that the dataFilter will run regardless of what type is actually returned from the server. You should only use this when you’re sure that you’re receiving a JSON string.

Conclusion

If you’ve been paying close attention to jQuery’s ongoing development, you may already know that jQuery 1.3.3 will provide functionality very similar to what I’ve shown you. I decided to go ahead and write this post anyway for a few reasons:

  • You can use this today, without waiting for jQuery 1.3.3.
  • You can use this in previous versions of jQuery, if upgrading isn’t feasible for you (as is often the case with plugins dependent on older versions).
  • If you use my technique for isolating your code from ASP.NET AJAX’s “.d”, you will still need a method for deserializing JSON in the dataFilter.

Speaking of that last point, if you’re using jQuery with ASP.NET AJAX services, be sure to watch out for the next post in this (accidental) series. There is at least one more productive step left in improving this workflow that I have been using in my projects and want to share with you soon.

###

Originally posted at Encosia. If you’re reading this elsewhere, come on over and see the original.

Improving jQuery’s JSON performance and security

Creating a ComboBox Style AutoCompleteBox Control in Silverlight

Silverlight’s AutoCompleteBox control provides a nice way to filter a list of items as the user types into a TextBox.  If you haven’t used it before you can see an example here.  In a previous post I showed how you could customize AutoCompleteBox to make it look and feel more like an editable ComboBox so that users can click a down arrow to see the list of items and also filter the items by typing into the TextBox. 

image

The solution I wrote about in the previous post relied upon a custom control template which works fine but you may want to encapsulate that functionality into a re-useable control so that you don’t have to worry about adding the template into each application project.  Fortunately, it’s not too hard to derive from AutoCompleteBox and create a custom control.  Here are the steps I went through to build a derived version of AutoCompleteBox that I call AutoCompleteComboBox.

Step 1: Create a Silverlight Class Library

Create a new Silverlight class library and add a class named AutoCompleteComboBox into it.  Derive the class from AutoCompleteBox:

public partial class AutoCompleteComboBox : AutoCompleteBox

Once the class is created add a folder into the project named Themes that contains a file named Generic.xaml in it.  Right-click on Generic.xaml, select Properties and ensure that the Build Action is set to Resource.

Step 2: Define the Control’s Template

Since AutoCompleteComboBox needs to look like a ComboBox I took a template available in one of the AutoCompleteBox toolkit samples that added the drop down arrow (normally seen on the ComboBox control) and tweaked it a little bit.  The template code needs to go in the Generic.xaml file that was created in the previous step.  Here’s what my Generic.xaml file looks like.  You’ll see that there’s a ComboToggleButton style which is referenced by the AutoCompleteComboBox style.

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:system="clr-namespace:System;assembly=mscorlib"
  xmlns:custom="clr-namespace:MyCustomControls">

    <!-- AutoCompleteBox Styles -->

    <!-- Custom toggle button template -->
    <Style x:Name="ComboToggleButton" TargetType="ToggleButton">
        <Setter Property="Foreground" Value="#FF333333"/>
        <Setter Property="IsTabStop" Value="False" />
        <Setter Property="Background" Value="#FF1F3B53"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ToggleButton">
                    <Grid>
                        <Rectangle Fill="Transparent" />
                        <ContentPresenter
                            x:Name="contentPresenter"
                            Content="{TemplateBinding Content}"
                            ContentTemplate="{TemplateBinding ContentTemplate}"
                            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                            Margin="{TemplateBinding Padding}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- Custom control template used for the IntelliSense sample -->
    <Style TargetType="custom:AutoCompleteComboBox">

        <!-- ComboBox should not perform text completion by default -->
        <Setter Property="IsTextCompletionEnabled" Value="False" />

        <!-- The minimum prefix length should be 0 for combo box scenarios -->
        <Setter Property="MinimumPrefixLength" Value="1" />

        <!-- Regular template values -->
        <Setter Property="Background" Value="#FF1F3B53"/>
        <Setter Property="IsTabStop" Value="False" />
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FFA3AEB9" Offset="0"/>
                    <GradientStop Color="#FF8399A9" Offset="0.375"/>
                    <GradientStop Color="#FF718597" Offset="0.375"/>
                    <GradientStop Color="#FF617584" Offset="1"/>
                </LinearGradientBrush>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="custom:AutoCompleteComboBox">
                    <Grid Margin="{TemplateBinding Padding}">
                        <TextBox IsTabStop="True" x:Name="Text" Style="{TemplateBinding TextBoxStyle}" Margin="0,0,0,2" />
                        <ToggleButton x:Name="ToggleButton"
                                HorizontalAlignment="Right"
                                VerticalAlignment="Center"
                                Style="{StaticResource ComboToggleButton}"
                                Margin="0" BorderBrush="Black" BorderThickness="1,0,0,0"
                                HorizontalContentAlignment="Center"
                                Background="LightGray"
                                Height="16" Width="16">
                            <ToggleButton.Content>
                                <Path x:Name="BtnArrow" Height="4" Width="8" Stretch="Uniform"
                                      Data="F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z "
                                          Margin="0,0,6,0" HorizontalAlignment="Right">
                                    <Path.Fill>
                                        <SolidColorBrush x:Name="BtnArrowColor" Color="#FF333333"/>
                                    </Path.Fill>
                                    <Path.RenderTransform>
                                        <ScaleTransform x:Name="ToggleButtonScale" />
                                    </Path.RenderTransform>
                                </Path>
                            </ToggleButton.Content>
                        </ToggleButton>
                        <Popup x:Name="Popup">
                            <Border x:Name="PopupBorder" HorizontalAlignment="Stretch" Opacity="1.0" BorderThickness="0">
                                <Border.RenderTransform>
                                    <TranslateTransform X="2" Y="-2" />
                                </Border.RenderTransform>
                                <Border.Background>
                                    <SolidColorBrush Color="#11000000" />
                                </Border.Background>
                                <ListBox x:Name="Selector" ScrollViewer.HorizontalScrollBarVisibility="Auto"
                                                 ScrollViewer.VerticalScrollBarVisibility="Auto"
                                                 ItemTemplate="{TemplateBinding ItemTemplate}" />
                            </Border>
                        </Popup>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="FocusStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="0:0:0.2" To="ToggleButtonOver" />
                                    <VisualTransition GeneratedDuration="0:0:0.2" To="ToggleButtonOut" />
                                </VisualStateGroup.Transitions>
                                <VisualState x:Name="ToggleButtonOver">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="ToggleButtonScale" Storyboard.TargetProperty="ScaleX" To="1.3" />
                                        <DoubleAnimation Storyboard.TargetName="ToggleButtonScale" Storyboard.TargetProperty="ScaleY" To="1.3" />
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="ToggleButtonOut">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="ToggleButtonScale" Storyboard.TargetProperty="ScaleX" To="1" />
                                        <DoubleAnimation Storyboard.TargetName="ToggleButtonScale" Storyboard.TargetProperty="ScaleY" To="1" />
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="PopupStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="0:0:0.4" To="PopupOpened" />
                                    <VisualTransition GeneratedDuration="0:0:0.2" To="PopupClosed" />
                                </VisualStateGroup.Transitions>
                                <VisualState x:Name="PopupOpened">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="PopupBorder" Storyboard.TargetProperty="Opacity" To="1.0" />
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="PopupClosed">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="PopupBorder" Storyboard.TargetProperty="Opacity" To="0.0" />
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="ValidationStates">
                                <VisualState x:Name="Valid" />
                                <VisualState x:Name="InvalidUnfocused">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Visible</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="InvalidFocused">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Visible</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsOpen">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <system:Boolean>True</system:Boolean>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Step 3: Add a TemplatePart Attribute

Go back to the AutoCompleteComboBox class created in Step 1 and add a TemplatePart attribute on it that references the ToggleButton control name (which will represent the drop down arrow) defined in the control template.  Template parts are used to be able to reference the different controls defined in the template.  Although TemplatePart’s Name property can be given a direct string value, I followed the convention seen in Silverlight controls and used a constant to define the name value.

[TemplatePart(Name = AutoCompleteComboBox.ElementToggleButton, Type = typeof(ToggleButton))]
public partial class AutoCompleteComboBox : AutoCompleteBox
{
    private const string ElementToggleButton = "ToggleButton";
}

Step 4: Add the ToggleButton Property

Add a ToggleButton property into the AutoCompleteComboBox class as shown next.  You can call it whatever you want but I like to keep things simple and call it what it really is….a ToggleButton.  The event handlers referenced in the code below are shown in Step 6.

#region Template Parts

ToggleButton _ToggleButton;

ToggleButton ToggleButton
{
    get { return _ToggleButton; }
    set
    {
        if (_ToggleButton != null)
        {
            _ToggleButton.Click -= new RoutedEventHandler(ToggleButton_Click);
            _ToggleButton.MouseEnter -= new MouseEventHandler(ToggleButton_MouseEnter);
            _ToggleButton.MouseLeave -= new MouseEventHandler(ToggleButton_MouseLeave);
        }

        _ToggleButton = value;

        if (_ToggleButton != null)
        {
            _ToggleButton.Click += new RoutedEventHandler(ToggleButton_Click);
            _ToggleButton.MouseEnter += new MouseEventHandler(ToggleButton_MouseEnter);
            _ToggleButton.MouseLeave += new MouseEventHandler(ToggleButton_MouseLeave);
        }
    }
}

#endregion

Step 5: Set the DefaultStyleKey for the AutoCompleteComboBox Control

Next you need to tell the AutoCompleteComboBox to use the Style you defined in Generic.xaml instead of the default style used by AutoCompleteBox.  Do this by adding the following constructor into the class (which also adds code to call the ApplyTemplate class shown in the next step):

public AutoCompleteComboBox()
{
    this.DefaultStyleKey = typeof(AutoCompleteComboBox);
    Loaded += (sender, e) => ApplyTemplate();
}

Step 6: Override ApplyTemplate and Handle Events

We’re almost there! The next thing that needs to be done is to override the control’s OnApplyTemplate method.  We need to do this so that the ToggleButton can be injected into the process so that we can handle the user clicking on it to show all of the items like a normal ComboBox would do.  Here’s the remaining code that needs to be added into the class. 

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    ToggleButton = GetTemplateChild(ElementToggleButton) as ToggleButton;
}

void ToggleButton_MouseEnter(object sender, MouseEventArgs e)
{
    VisualStateManager.GoToState(this, "ToggleButtonOver", true);
}

void ToggleButton_MouseLeave(object sender, MouseEventArgs e)
{
    VisualStateManager.GoToState(this, "ToggleButtonOut", true);
}

void ToggleButton_Click(object sender, RoutedEventArgs e)
{
    if (String.IsNullOrEmpty(this.SearchText))
    {
        this.Text = String.Empty;
    }
    this.IsDropDownOpen = !this.IsDropDownOpen;
}

This code accesses the ToggleButton control defined in the Generic.xaml template using the base class’s GetTemplateChild method.  Once the ToggleButton control is found it’s assigned to the ToggleButton property of our control which handles hooking up the Click, MouseEnter and MouseLeave events.  The ToggleButton_Click event handler does the magic of making the AutoCompleteComboBox control look and feel like a standard ComboBox.

Step 7: Use the AutoCompleteComboBox Control

Once the custom control is finished and you successfully build it you can use the control in a Silverlight application.  To do that, create a Silverlight application project and reference the control project created in Step 1 (or reference the dll that’s generated by the project).  Within the XAML for your Silverlight application add a reference to the control’s namespace and assembly:

<Usercontrol x:Class="SilverlightApplication1"
    xmlns:controls="clr-namespace:YourCustomControlNamespace;assembly=YourCustomControlAssemblyName">
</UserControl>

Once the assembly and namespace are referenced you can define the control and bind items to it using it’s ItemSource property:

<controls:AutoCompleteComboBox ItemsSource="{Binding Jobs}"
    Margin="5,0,5,10" Width="150"  HorizontalAlignment="Left"
    MinimumPopulateDelay="0" MinimumPrefixLength="0" />

If I had to pick out the key parts from these steps they’d be creating the Generic.xaml file, adding the TemplatePart attribute, setting the control’s DefaultStyleKey, overriding ApplyTemplate and calling GetTemplateChild to locate the ToggleButton control.  These changes allow the AutoCompleteComboBox to look like a regular ComboBox while still allowing the user to type into it to filter the items. 

Download Code

 

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Free OCR Converts Your Scanned Documents to Text [Documents]

Converting a scanned document to editable text is a handy trick that can save you hours of retyping documents. Free OCR converts your documents for free.

To use Free OCR you need to have your document in a PDF, JPG, GIF, TIFF or BMP format. You can upload documents up to 2MB in size which for most small document conversions will be sufficient. We tested the site with the same passage from the introduction of In Defense of Food by Michael Pollan. Submissions were made in both PDF format and a JPG screenshot of the PDF page we used. Free OCR seems to like PDF files better, the PDF file rendered with fewer errors.

The rate of errors and quirks in the conversion wasn’t much higher than commercial OCR software and just like using a commercial solution you’ll need to go through and double check to make sure what you see and what the machine sees are the same thing. If you know of other free OCR services, share the wealth in the comments below.





Make an Outlet-Mounted Charge Station from a Shampoo Bottle [DIY]

Giving your cell phone or iPod a semi-permanent, clever-looking home on your wall doesn’t have to cost more than $2. A used shampoo bottle and some basic tools are all that’s needed for MAKE’s outlet-mounted “charging pocket.”

If this specimen looks familiar, that's because it is—we previously pointed to a similar charge station for single gadgets, but that tutorial’s been taken down by the author “due to safety issues.” That might raise a few eyebrows, but DIY haven MAKE tends to see this project as fairly safe, at least for cell phone chargers with built-in transformers. Your mileage will vary, though, with how firm your sockets hold a plug, and you shouldn’t hang anything too heavy in the charger that might pull a plug loose. That said, commenters have suggested using a faceplate screw to better secure the pocket holder and reduce the tension on the plug, and pulling out the plug if you’re going for long periods between charges, as most any power “brick” draws phantom power, even when not in direct use.

The design is a bit different than our previous example (and its commercially purchased cousin), as the case hangs from holes drilled for the charger’s prongs instead of loosely hanging on top of them. As for cost and convenience, you can pick out any cheap shampoo with a nice look to its plastic bottle, or, if you’re already set up with one, pull out the razor and drill and get to work. The tutorial includes a handy printable drill guide for making neat prong holes.





WPF: How To Animate a Gradient Brush

 

In the previous blog item in this series, I created a simple Animation in Visual Basic Code. This used a DoubleAnimation to animate the thickness of the gradient border. That example doesn't even begin to scratch the surface of what you can achieve with WPF Animation and – as you have seen demonstrated in the previous items – how you can include these animations in Windows Forms.

In this part, we will look at a slightly more complex animation. Or at least one that seems complex at first, but a quick analysis reveals that it is really rather simple and easily created by writing the XAML by hand.

In order to see the animation effect, I recommend you download the project attached to this blog item and run it. When you click the Button if there is no text in the TextBox, two animations will run. The first is the resize border one that was covered in the previous blog. The second animation changes the position of each of the colors in the gradient to give the impression of movement.

If you are new to WPF, you perhaps won't be too comfortable with the idea of hand-writing the XAML. You can of course use a tool, such as Expression Blend, to create the XAML for you. A time-limited trial version of Expression Blend is available, so if you decide that the hand-written route isn't for you, then you can certainly use Blend instead. (That said, there is something of a learning curve involved in getting to grips with Blend too – especially if, like me, you have more of a Developer mindset than Designer).

One of the reasons I decided to add this part to the blog was that sometimes you need to start the animation running from some user action. In this case, the user action will be the clicking of a button on a totally unrelated UI – a Windows Form, as it happens (although of course the same approach works fine with an all-WPF application too.)

So, firstly, here is the XAML that goes in the WPF UserControl to create the moving gradient effect: 

(Note that there is a formatting problem with the blog editor.  The GradientStop isn't really a Devil's Head it is the numeral 6 in square square brackets – [ 6 ], but without the spaces.  )

    <Storyboard x:Key="MoveColors" >

 

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

         AutoReverse="True" 

         Storyboard.TargetName="GradBorder"

               Storyboard.TargetProperty="BorderBrush.GradientStopsDevil.Offset"

                BeginTime="0:0:0.6" />

 

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

                       AutoReverse="True"

              Storyboard.TargetName="GradBorder"

               Storyboard.TargetProperty="BorderBrush.GradientStops[5].Offset"

                BeginTime="0:0:0.6" />

 

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

                       AutoReverse="True"

             Storyboard.TargetName="GradBorder"

               Storyboard.TargetProperty="BorderBrush.GradientStops[4].Offset"

                BeginTime="0:0:0.6" />

 

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

                       AutoReverse="True"

         Storyboard.TargetName="GradBorder"

               Storyboard.TargetProperty="BorderBrush.GradientStops[3].Offset"

                BeginTime="0:0:0.6" />

 

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

                       AutoReverse="True"

             Storyboard.TargetName="GradBorder"

               Storyboard.TargetProperty="BorderBrush.GradientStops[2].Offset"

                BeginTime="0:0:0.6" />

 

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

                       AutoReverse="True"

            Storyboard.TargetName="GradBorder"

               Storyboard.TargetProperty="BorderBrush.GradientStops[1].Offset"

                BeginTime="0:0:0.6" />  

 

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

                       AutoReverse="True"

             Storyboard.TargetName="GradBorder"

               Storyboard.TargetProperty="BorderBrush.GradientStops[0].Offset"

                BeginTime="0:0:0.6" />

 

    </Storyboard> 

That may look like a lot of typing, but there's a whole lot of repetition in there, which means you can copy and paste the majority of it, then just make minor tweaks. 

 <Storyboard x:Key="MoveColors" > 

The first line shown above simply creates a new Storyboard instance and assigns it a name, or Key, that we can use to reference it.

The next block creates a DoubleAnimation.  

      <DoubleAnimation By="0.2" Duration="0:0:1.3"

         AutoReverse="True" 

         Storyboard.TargetName="GradBorder"

         Storyboard.TargetProperty="BorderBrush.GradientStopsDevil.Offset"

         BeginTime="0:0:0.6" /> 

Most of us tend not to think of Types such as Double numeric values when we are thinking about animation. In our mind's eye we are more likely to picture the physical result of such a change – the size of an element or its position, its shape or its color, perhaps. But it is perfectly possible to change the value of a Double Type, taking a set amount of time to make the change, and then having this change be visible to a user by assigning it to a property of an element that takes type Double.

That's exactly what we are doing here – changing the value of the Double that is being used to set the position of a GradientStop in a LinearGradientBrush. Here's a more detailed breakdown of what's going on:

By changes the Double value by the amount stated – in this case by 0.2. In our demonstration animation this moves one of the colors that make up the gradient 0.2 along the gradient's linear scale.

Duration sets the length of time taken to change the value from its starting value to the end of the By value. In this case it is 1.3 seconds.

AutoReverse set to True will ensure that the value returns to its starting value by the end of the Duration. In our gradient example this will cause the color to move 0.2 out and then return the same 0.2 distance back.

Storyboard.TargetName uses the WPF Attached Property syntax to identify which element is the target of the animation.

Storyboard.TargetProperty in a similar way identifies the property of the target element which is to be animated. See the further explanation below about the identification of the property.

BeginTime is an optional pause feature. The animation will only begin after an initial pause of (in this example) 0.6 seconds.

The TargetProperty in each of these DoubleAnimations is the Offset value of a GradientStop. If you look at the XAML which creates the BrightGradient LinearGradientBrush, you will see that it contains seven colors, each of which has its position in the gradient assigned by its Offset value. All we are doing in this animation is shunting each of the colors along by a value of 0.2 and this creates the effect of the color movement.

The particular block of XAML shown above animates the last GradientStop, which has an index of 6 – the index being zero based. When you look at the six DoubleAnimations which follow that one, the only difference is that the Index has changed so that the next GradientStop is targeted. So by copying and pasting the first DoubleAnimation, pasting it six times and then changing the value of the Index, this complex looking animation is shown to be very basic in reality.

All that remains now is to wire up this Storyboard in the code-behind.  

    Public Sub MoveColors()

        Dim SB As Storyboard = CType(FindResource("MoveColors"), Storyboard)

        If SB IsNot Nothing Then

            SB.Begin()

        Else

            MessageBox.Show("Can't find storyboard")

        End If

    End Sub 

The FindResource method is very useful in these kind of situations in WPF. I used it in the original example to change the LinearGradientBrush on the Border element and now we can employ it to find the animation. It allows you to dig into the XAML, find the markup you need for a particular task and use it. In this cas, the Resource we are looking for is the Storyboard that has a Key of 'MoveColors' – the one we have just dissected above.

Over in the Windows Forms Form1 code, the Button click has only one additional line from where we left it at the end of the previous blog. This calls the MoveColors procedure shown above, which in turn runs the animation. The additional line is: 

           MovingGradientTextBox1.MoveColors() 

You can see the remaining unchanged Button Click event code in the sample project attached.

Ron’s Curio Cabinet – Viewer Project

curio-1Ah the curio… it’s inspiration came out of shear need. A need to house all 150 of my wives shot glasses. The design is probably basic as curio cabinets go however the thought was something simple but yet elegant. Although it appears basic in nature it was constructed without plans and on the fly and was most likely the most expensive and most labor intensive project I have constructed to date at probably 100+ hours of labor and maybe $900 of course had I of prepared a better set of plans rather than a sketch and most likely would have went faster. curio-2The cabinet stands at about 5’8” high and about 18” wide. The curio was constructed from quarter sawn white oak and features one 15W halogen light in the top and in the bottom display areas. All the glass with the exception of the mirrors is beveled which along with the lighting helps bring out the sparkle of the glasses. The finish consisted of about 12 hours of fuming, a glazing process followed by multiple coats of Arm-R-Seal.

curio-3 curio-4

curio-6 curio-7 curio-8 curio-10

Open a New Command Prompt from Explorer with a Hotkey [Autohotkey]

Reader Kevin used his ubergeeky AutoHotkey scripting skills to create a hotkey that opens a command prompt window at the same location as the folder you are browsing in Windows Explorer.

To use the script, you simply hit the Ctrl+Alt+H shortcut key sequence while looking at a folder in Windows Explorer and a new command prompt window will open, already set to the same working directory. We’ve already covered how to open a command prompt window from the context menu, but this method is even simpler.

To create this hotkey for yourself, create a new AutoHotkey script or add the following to your existing script:

#IfWinActive ahk_class CabinetWClass ; for use in explorer.
^!h::
ClipSaved := ClipboardAll
Send !d
Sleep 10
Send ^c
Run, cmd /K "cd `"%clipboard%`""
Clipboard := ClipSaved
ClipSaved =
return
#IfWinActive

Once you’ve added, saved, and launched the script, you should be able to start using the hotkey immediately. Thanks, Kevin!

For more Windows shortcut goodness, check out how to make Win+E open the folder of your choice, learn how to use Caps Lock for hand-friendly navigation, and see how Taskbar Overlord tweaks the Windows 7 taskbar. Brand new to AutoHotKey and its time-saving ways? Peek at our beginner’s guide to learn how to add this script, or write your own.





Dougal Campbell: WordPress Themes Tutorial

If you aren’t already following along, I highly recommend checking out the How To Create A WordPress Theme tutorial series by Ian Stewart (ThemeShaper.com). This 12-part series (8 complete at the time of this writing) aims to take you from nothing to a fully functional, semantically rich, flexible WordPress theme in digestible chunks. Along the way, Ian describes the changes being made, and why you are making them. In this way, you can gain a basic understanding of the roles of the various theme template files, and the code contained within them.

The lesson is broken down thusly:

  1. Introduction
  2. Theme Development Tools
  3. Creating a Theme HTML Structure
  4. Template and Directory Structure
  5. The Header Template
  6. The Index Template
  7. The Single Post, Post Attachment, & 404 Templates
  8. The Comments Template
  9. The Search Template & The Page Template
  10. The Archive, Author, Category & Tags Template
  11. The Sidebar Template
  12. Reset-Rebuild Theme CSS & Define Your Layouts

If you’ve ever thought about creating your own theme, but felt like the task was too big to tackle, this series of articles is for you. It’s a great bit of instruction that will introduce you to the core pieces of WordPress theming without overwhelming you or trying to cram too much into a single article.

Props, Ian!

WP Like Button Plugin by Free WordPress Templates