Russell Myers’ Blog

Automatic Login Script In Ruby

by Russell Myers on Jun.25, 2009, under Ruby

One of the most common tasks in my day is to log in to the applications I help maintain. As you can imagine, this becomes quite a repetitive task as every time you might redeploy it or change some feature, you’re likely to have to go through this step again and again. I’d had some experience with WatiN, a browser automation framework API for .NET. I could very well have (and have in the past) created scripts that could automate this task for me, but frankly I think implementing the solution in Ruby has a bit of an advantage in this type of problem.

Simply put, there’s quite a bit less overhead to using Watir for this type of thing. Additionally you can use IRB to fiddle with potential task automation before spending the time to create a full-out solution. And frankly my Ruby experience is non-existent so it was a good chance to learn something new.

To get Watir working, you’ll have to use gems to update itself and also install Watir:

1
2
gem update --system 
gem install watir

Beyond that, the code to get you logging in is really quite simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env ruby
require "Watir"
 
login_location = ARGV[0]
username = ARGV[1]
password = ARGV[2]
 
if (login_location == nil)
    login_location = "http://localhost/login.aspx"
end
if (username == nil)
    username = "username"
end
if (password == nil)
    password = "password"
end
 
browser = Watir::IE.new_process
browser.goto login_location 
browser.text_field(:id, "LoginTextFieldId").set username
browser.text_field(:id, "PasswordTextFieldId").set password
browser.link(:id, "LoginLinkButtonId").click

What this will do is open a new Internet Explorer process (whatever version you’re currently running), go to the address that was passed via arguments and then log in using the credentials you provide. For your purposes, you’ll have to inspect your text fields and link (or button) and set the ID’s of those HTML elements appropriately. After that its as simple as executing your .rb file with the appropriate arguments:

1
ruby login.rb http://www.yourlocation.com/login.aspx username password

If you set the conditional statements to your most common login spot, you can also run the script without any arguments for ease. This can just as easily be adapted to open a Firefox, Safari or Chrome browser as well. Both the Watir and WatiN API’s now support most all major browsers.

Leave a Comment :, , more...

Editing Button Templates In Blend

by Russell Myers on May.21, 2009, under Silverlight

In Silverlight, most every control is customizable. Everything from a button to a grid can be made to look, and in many cases, behave to your specifications. In this case, we’ll edit a button to make it a circular button instead of the default. Start by creating a simple Silverlight project in blend called “ButtonTemplateEditing”.

After this we’ll want to create a simple button. This will be the basis and the result of the template we create. Simply drag it some place appealing on your page:

button011

After creating the button, we’ll select it and go to “Object” > “Edit Style” > “Edit a Copy…”

button02

This will open a dialog (below) where we can give our style a name and define exactly where we’d like to store it. If we intended to reuse this particular style throughout the application, we might store it at the Application level or even create a resource dictionary for it, but for the purposes of this exercise we’ll just stick to defining it in MainControl.xaml.button03

What’s produced through this set of steps is quite a bit of XAML which is placed within our UserControl. This XAML represents the default style for a typical button in Silverlight and is what we’ll be editing in general to produce our variation. Its also worth mentioning that our button has also been bound to this new style copy so we don’t have to go back and tie it together:

<Button Height="122" 
    HorizontalAlignment="Left" 
    Margin="97,54,0,0" 
    VerticalAlignment="Top" 
    Width="121" 
    Content="Button" 
    Style="{StaticResource RoundedButtonStyle}" />

From this point we could just easily dig through documentation and change various aspects of our button in the code directly, but why bother? That’s what Blend is for — editing and stylizing your application. We can at this point right click on our button > “Edit Control Parts (Template)” > “Edit Template”.

button04This will drill into the template itself where we can finally edit portions of it to give it the feel we’re looking for.  First we’ll want to make sure the background is translucent. All of our template items can now be found in the Objects and Timeline window.

button05

At this point we can replace the existing Template setter with one of our own creation. We replace the node’s value with:

 
<Setter Property="Template">
  <Setter.Value>
    <ControlTemplate TargetType="Button">
      <Grid>
        <Grid Margin="1" Background="#00009F21">
          <Ellipse x:Name="BackgroundGradient" 
              Fill="{TemplateBinding Background}" />
        </Grid>
        <ContentPresenter x:Name="contentPresenter" 
            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
            Margin="{TemplateBinding Padding}" 
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
            Content="{TemplateBinding Content}" 
            ContentTemplate="{TemplateBinding ContentTemplate}"/>
      </Grid>
    </ControlTemplate>
  </Setter.Value>
</Setter>

We’ll also replace the setter for the Background with

<Setter Property="Background">
  <Setter.Value>
    <RadialGradientBrush>
      <GradientStop Color="#FF636363"/>
      <GradientStop Color="#FF000000" Offset="1"/>
    </RadialGradientBrush>
  </Setter.Value>
</Setter>

Finally, we’ll want to set the Foreground color to something useful as a default setting. Set it to “#FFFFFFFF”.

There you have it! A working circular button! If we wanted, we could now go back and work with some of the transition effects and such. Additionally, this can be done with code behind as well.

button06

Download ButtonTemplateEditing Project

Leave a Comment :, , more...

Turn Over Dialog Transition In Silverlight 3

by Russell Myers on May.14, 2009, under Silverlight

Often times it is useful and nice to put simple transitions between different logical groups of information either displayed or extracted from the user. In this case, we explore creating a transition that gives the visual appearance of the dialog flipping over on its diagonal axis.

After a creating a Silverlight project with the name “AnimationProject” in Blend 3 we can begin by editing the default template MainControl.xaml:

<UserControl
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	x:Class="AnimationProject.MainControl"
	Width="480" Height="150" Background="Black" mc:Ignorable="d">
 
 
 
	<Grid x:Name="LayoutRoot" Background="Black">
	<Canvas x:Name="FirstCanvas" d:IsHidden="True">
        	<TextBlock x:Name="FirstNameDescription" Height="29" 
			Width="159" Canvas.Top="8" FontSize="18" 
			Foreground="#FFFFFFFF" Text="First Name" 
			TextAlignment="Right" TextWrapping="Wrap"/>
        	<TextBlock x:Name="LastNameDescription" Height="29" 
			Width="159" Canvas.Top="43" FontSize="18" 
			Foreground="#FFFFFFFF" Text="Last Name" 
			TextAlignment="Right" TextWrapping="Wrap"/>
        	<TextBox x:Name="FirstName" Height="28" Width="300" 
			Canvas.Left="172" Canvas.Top="8" Text="" 
			TextWrapping="Wrap"/>
        	<TextBox x:Name="LastName" Height="28" 
			Canvas.Left="172" Width="300" Canvas.Top="43"
			Text="" TextWrapping="Wrap"/>
        	<Button x:Name="NextButton" Height="30" Width="112" 
			Canvas.Left="360" Canvas.Top="112" 
			Content="Next"/>
	</Canvas>
        <Canvas x:Name="SecondCanvas">
        	<TextBlock x:Name="AllDone" Height="65" Width="410" 
			Canvas.Left="33" Canvas.Top="17" 
			Text="All Done!" TextWrapping="Wrap" 
			Foreground="#FFFF0000" FontSize="48" 
			FontFamily="Verdana" TextAlignment="Center"/>
        	<Button x:Name="FinishButton" Height="30" Width="112" 
			Canvas.Left="360" Canvas.Top="112" Content="Finish"/>
        </Canvas>
	</Grid>
</UserControl>

What we’ve created here is two individual canvas elements that exist within the root layout of the control. Imagine these as the two logical groups that may have different groups of data you wish to represent. One has input in this case and the other a delightful success message.

After this creation, we can now create two separate storyboard timelines. We’ll create two storyboard resources

sl01

And give the names “FlipInAnimation” and “FlipOutAnimation”:

sl02

After creating these, use the drop down in the Objects and Timeline window to select FlipInAnimation. This will be first half of the transition that flips the control up on its side. When done the timeline will look like

sl03

As you can see, what we’re modifying is the layout root itself. This will give the effect of the entire control transitioning, including child elements below it. As we’ve got a solid starting case for our transition, we can define the end point for our transition by selecting the .5 second location on the timeline and once done select the layout root (also displayed in the above graphic) and alter its properties. The properties of this object we’re concerned with are the Transform properties:

sl04

Please note that by default the second half of this set of options isn’t visible. Clicking the button indicated by the green circle reveals this hidden set of gems. As also indicated in the shot, we’ll want to be editing the X and Z properties and setting them to 90. Thinking in degrees, this will tilt the entire object 90 degrees on both axis.

For the second transition, the timeline will be the the exact reverse. At time 0, we’ll set the X and Z properties to 90 and at time .5 we’ll set them back to 0. After this, both segments of the transition should be apparent in your XAML:

<UserControl.Resources>
	<Storyboard x:Name="FlipInAnimation">
		<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" 
			Storyboard.TargetName="LayoutRoot" 
			Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationX)">
			<EasingDoubleKeyFrame KeyTime="00:00:00.5000000" 
				Value="90"/>
		</DoubleAnimationUsingKeyFrames>
		<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" 
			Storyboard.TargetName="LayoutRoot" 
			Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationZ)">
			<EasingDoubleKeyFrame KeyTime="00:00:00.5000000" 
			Value="90"/>
		</DoubleAnimationUsingKeyFrames>
	</Storyboard>
	<Storyboard x:Name="FlipOutAnimation">
		<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" 
			Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationX)">
			<EasingDoubleKeyFrame KeyTime="00:00:00" 
				Value="90"/>
			<EasingDoubleKeyFrame KeyTime="00:00:00.5000000" 
				Value="0"/>
		</DoubleAnimationUsingKeyFrames>
		<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" 
			Storyboard.TargetName="LayoutRoot" 
			Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationZ)">
			<EasingDoubleKeyFrame KeyTime="00:00:00" 
				Value="90"/>
			<EasingDoubleKeyFrame KeyTime="00:00:00.5000000" 
				Value="0"/>
		</DoubleAnimationUsingKeyFrames>
	</Storyboard>
</UserControl.Resources>

From here we can delve into Visual Studio 2008. Once in, we’ll open the MainControl.xaml.cs file and be presented with the standard code template. We’ll change it to the following:

using System;
using System.Windows;
 
namespace AnimationProject
{
    public partial class MainControl
    {
        public MainControl()
        {
            // Required to initialize variables
            InitializeComponent();
            FirstCanvas.Visibility = Visibility.Visible;
            SecondCanvas.Visibility = Visibility.Collapsed;
            NextButton.Click += NextButtonClicked;
        }
 
        private void NextButtonClicked(object sender, RoutedEventArgs e)
        {
            FlipInAnimation.Completed += FlipInCompleted;
            FlipInAnimation.Begin();
        }
 
        private void FlipInCompleted(object sender, EventArgs e)
        {
            NextButton.Click -= NextButtonClicked;
            FinishButton.Click += FinishButtonClicked;
            FirstCanvas.Visibility = Visibility.Collapsed;
            SecondCanvas.Visibility = Visibility.Visible;
            FlipOutAnimation.Begin();
        }
 
        private void FinishButtonClicked(object sender, RoutedEventArgs e)
        {
            FlipInAnimation.Begin();
        }
    }
}

We’re done! As we see, the resources can be triggered and events placed on their completion like any other control. Run it and enjoy!

Source: AnimationProject.zip

Leave a Comment :, , , more...

Setting Up Silverlight Unit Testing

by Russell Myers on May.11, 2009, under Silverlight

When first attempting to unit test your Silverlight functionality, you might decide to use NUnit as your testing framework. From that you would write something similar to

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using NUnit.Framework;
using TwitterFeed;
 
namespace FailingClassLibrary
{
    [TestFixture]
    public class SilverlightTestFixture
    {
        [Test]
        public void TestingASilverlightClass()
        {
            // A Silverlight UserControl
            TweetView view = new TweetView();
            Assert.AreEqual(view.SomeProperty, "A value of interest.");
        }
    }
}

After potentially dealing with the lack of System.Windows not being referenced (if you’re using ReSharper, this is the recommended solution), you’ll attempt to run your new test and will get

System.TypeLoadException: Method ’Create’ in type ‘System.Net.Browser.BrowserHttpWebRequestCreator’ from assembly ‘System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e’
does not have an implementation.

Why is this an issue? Didn’t we fix the System.Windows requirement? The answer isn’t exactly obvious if you’ve taken this approach. The heart of the matter stems from the fact that you’re using an entirely different version of the CLR when creating a Silverlight application. Essentially what you’ve referenced is an entirely different subset of implementation.

So how can we test? You have two viable options at your disposal: The Microsoft Silverlight Unit Testing Framework by Jeff Wilcox and the Silverlight NUnit Project by Jamie Cansdale. Currently I’ve played exclusively with the Silverlight Unit Testing Framework. What has been an immediate disadvantage for me with it has been that it doesn’t work with the currently released versions of NUnit. For those, like me, with a strong background in this framework its a tiny bit disheartening to have to switch to the Visual Studio testing framework. The required binaries, should you not have them, are also provided here.

Despite this, there is still Rhino Mocks support as a Silverlight-specific version is available for download. Additionally, there are several terrific blog postings about how to get the framework set up correctly. I don’t mean to rehash them as both Justin Angel and Jeff Wilcox provide excellent posts on how to get this up and running. Furthermore, using add in called Odin these tests can be played directly from the ReSharper Unit Test Sessions window.

Leave a Comment :, , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

    Archives

    All entries, chronologically...