David Sandor

Build succeeded.

Caliburn.Micro how to set the MinHeight and MinWidth of the Root View / Window ( WPF )

clock July 17, 2013 18:11 by author dsandor

This is pretty easy.  Basically you can send any property values to the Window object that is being created to hold your root view.  Simply create a Dictionary<string, object> with the property name as the key.  Pass that dictionary to the DisplayRootViewFor<>() method and viola!

protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
    Dictionary<string, object> settings = new Dictionary<string, object>();
    settings.Add("MinHeight", 480);
    settings.Add("MinWidth", 640);


Using Caliburn Micro with WPF Frame for navigation.

clock July 17, 2013 18:06 by author dsandor

I have an application that uses the WPF frame for navigation.  The frame markup looks like this:

<Frame x:Name="ActiveItem"
            Source="{Binding FrameSource}" MinHeight="400" MinWidth="600"
            VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" 
            HorizontalAlignment="Stretch" Background="White"

This Frame tag is located in my ShellView.xaml file and this takes the place of a ContentPlaceholder.  In order to navigate to another page I simply call ActivateItem( viewModelInstance ) from my ShellViewModel.  Because the ShellViewModel orchestrates the page loads I created a simple ChangeViewMessage class to throw via the EventAggregator.  My ShellViewModel handles this message and passes the viewModel instance to the ActivateItem method.  Caliburn Micro takes care of everything else.

Here is an example of the ShellViewModel loading my initial page/view in the constructor.

class ShellViewModel : Conductor<object>, IHandle<ChangeViewMessage>, IHandle<OpenWindowMessage>
        IEventAggregator EventAggregator;
        IWindowManager WindowManager;

        public ShellViewModel(IEventAggregator eventAggregator, SimpleContainer container, 
IWindowManager windowManager) { this.StepNumber = 1; this.EventAggregator = eventAggregator; this.WindowManager = windowManager; var selectServersViewModel = (SelectServersViewModel)container.GetInstance(
typeof(IViewModel), "SelectServersViewModel"); ActivateItem(selectServersViewModel); this.DisplayName = "Simple SQL Compare"; this.EventAggregator.Subscribe(this); }

You can see that my first view (SelectServersView via the ViewModel) is loaded there.

In order to make Caliburn Micro work you have to patch one method to be 'Frame Aware'.

In the View.cs class of the Caliburn Micro source in the Caliburn.Micro.WPF project change the SetContentPropertyCore method to look like the one below.  This allows you to use a Frame.

static void SetContentPropertyCore(object targetLocation, object view) {
    try {
        var type = targetLocation.GetType();
        var contentProperty = type.GetAttributes<ContentPropertyAttribute>(true)
                                  .FirstOrDefault() ?? DefaultContentProperty;

        if (contentProperty.Name == null && type == typeof(Frame))
            type.GetMethod("Navigate", new Type[] { typeof(object) })
.Invoke(targetLocation, new object[] { view }); } else { type.GetProperty(contentProperty.Name) .SetValue(targetLocation, view, null); } } catch(Exception e) { Log.Error(e); } }




Git provider for Visual Studio integrates seamlessly into Visual Studio 2012 and allows GitHub access.

clock June 29, 2013 05:42 by author dsandor

There are a few Git providers floating around and I found the one here to be the best.  The reason is that it uses the familiar Team System UI elements to control source which is very nice.



Web Api Client for Xamarin MonoTouch / iTouch / iPhone / iPad / iOS

clock June 14, 2013 19:45 by author dsandor

Just posted the code that I am using for an iOS project of mine that handles all the Web Api calls.  


Example of use:

WebApiClient.Post<ServiceResponse<User>>(string.Format ("{0}Auth/Login?emailAddress={1}&password={2}"
  , AppDelegate.Current.ApiBase, email.Value, password.Value), "", "")
.ContinueWith ( (t) =>

            this.InvokeOnMainThread(() => { loadingView.Hide (); });
            var result = t.Result;
            if (result != null && result.IsSuccess && result.Payload != null)
               this.InvokeOnMainThread(() => 
                  AppDelegate.Current.UserInfo = result.Payload;
                this.InvokeOnMainThread(() => {
                    new UIAlertView("Invalid login", "Invalid username or password.", null, "OK").Show();

Simple class for consuming WebApi via Windows Phone 8

clock May 5, 2013 08:43 by author dsandor

I wrote a simple generic method for making POST calls to MVC4 WebApi for use on Windows Phone 8 (But you can use it elsewhere).  The idea is simple: Create one set of generic methods that will take a generic TResultType, an Api Uri, and optionally some data to post and return back a strongly typed response object.

Usage is simple:

var result = await client.Post<ServiceResponse<User>>
("http://localhost:8080/api/Auth?emailAddress=test@test.com&password=pass", "token", "");

This allows you to simply use await to make your MVC4 WebApi calls and get back strongly typed objects.  The Post code uses Newtonsoft Json library to deserialize the response string as an object.

I will package this up as a simple GIT project when I have time and create a nuget package so that everyone can use this simply.

public async Task<TReturnType> Post<TReturnType>
(string apiUrl, Dictionary<string,string> headers, string data)
    var webClient = new WebClient();
    var uri       = new Uri(apiUrl);

    if (headers != null)
        foreach (var key in headers.Keys)
            webClient.Headers[key] = headers[key];

    return await Post<TReturnType>(webClient, uri, data);

private Task<TReturnType> Post<TReturnType>(WebClient webClient, Uri uri, string data)
    TReturnType returnObject = default(TReturnType);

    var taskCompletionSource = new TaskCompletionSource<TReturnType>();

    webClient.Headers["Content-Type"] = "application/json";

    webClient.UploadStringCompleted += (s, e) =>
        var result = e.Result;

            returnObject = JsonConvert.DeserializeObject<TReturnType>(result);

        catch (Exception ex)
            var newEx = new Exception(
              string.Format("Failed to deserialize server response: {0}", result), ex);

    webClient.UploadStringAsync(uri, data);

    return taskCompletionSource.Task;

DelegateCommand class for Windows Phone 7 and 8

clock May 4, 2013 10:27 by author dsandor

First off, I did not author this from scratch.  Instead, I added some functionality to this class that WindowsPhoneGeek published. I wanted to add CanExecute() and Execute() methods that take no parameter.   Most of the commands I use in my MVVM apps tend to be based on the state of the ViewModel anyway and thus I do not need the parameters.

Here is the DelegateCommand.cs class and the cmds snippet that lets you quickly add a command to any ViewModel.


Command code would look like the following:

public MainPageViewModel()
    LoginCommand = new DelegateCommand(OnLoginCommand, CanExecuteLoginCommand);

public ICommand LoginCommand { get; set; }

private void OnLoginCommand()


private bool CanExecuteLoginCommand()
    return false;

The code for the DelegateCommand.cs looks like this:

public class DelegateCommand : ICommand
    Func<object, bool> canExecute;
    Action<object> executeAction;
    Func<bool> canExecuteSimple;
    Action executeActionSimple;
    public DelegateCommand(Action<object> executeAction)
        : this(executeAction, null)
    public DelegateCommand(Action executeAction)
        : this(executeAction, null)
    public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
        if (executeAction == null)
            throw new ArgumentNullException("executeAction");
        this.executeAction = executeAction;
        this.canExecute = canExecute;
    public DelegateCommand(Action executeAction, Func<bool> canExecute)
        if (executeAction == null)
            throw new ArgumentNullException("executeAction");
        this.executeActionSimple = executeAction;
        this.canExecuteSimple = canExecute;
    public bool CanExecute(object parameter)
        bool result = true;
        Func<object, bool> canExecuteHandler = this.canExecute;
        if (canExecuteHandler != null)
            result = canExecuteHandler(parameter);
            return result;
        Func<bool> canExecuteHandlerSimple = this.canExecuteSimple;
        if (canExecuteHandlerSimple != null)
            result = canExecuteHandlerSimple();
        return result;
    public bool CanExecute()
        bool result = true;
        Func<bool> canExecuteHandler = this.canExecuteSimple;
        if (canExecuteHandler != null)
            result = canExecuteHandler();
        return result;
    public event EventHandler CanExecuteChanged;
    public void RaiseCanExecuteChanged()
        EventHandler handler = this.CanExecuteChanged;
        if (handler != null)
            handler(this, new EventArgs());
    public void Execute(object parameter)
        // Default to action that takes parameter.
        if (this.executeAction != null)
        // Fallback to parameterless delegate.
        if (this.executeActionSimple != null)
    public void Execute()

Arduino based water dispenser. (Flow Meter, Solenoid Valve)

clock March 10, 2013 08:33 by author dsandor

I started this project so that I could easily dispense a preset amount of water into my brew kettle when brewing beer.  My local brew club has a brew house and currently has hoses attached to the water filtration system.  Instead of waiting to fill up jugs of water this device will allow me to set 6.5 gallons, turn on the water and it will automatically shut off at the preset volume of water.  This lets me get started on other things while the water is dispensing and assures an accurate water level.

Parts include:

Arduino Uno $25 but will be replaced with a $3 ATMega Chip Later
YF-S201 Water Flow Meter $11
LCD Display Panel $5
ECHOTech Solenoid Valve $9


The flow meter is hooked up to the Arduino and there is a basic program uploaded that displays the flow rate and total volume of water that has passed through the flow meter.

Below is a video of the flow meter working.  I had to tweak the program to take measurements every 1/8th of a second.

The flow meter in action.

TODO: Wait for solenoid to arrive.
TODO: Code the reset button, Volume Up and Volume Down buttons.
TODO: Hardwire circuit to breadboard for compact mounting.
TODO: Mount in project box (waterproof).

Version two of the Serial LCD circuit.

clock February 3, 2013 14:28 by author dsandor

This version of the board looks a little better.  Wired the ground and +5v on the back (and one data line) to reduce the number of line crossings.  There are still two but far better than the first layout.  It follows the same schematic from the original post.  I also added a 470 Ohm variable resistor between the backlight (Pin 15 of the 16 pin header) and the +5v.  (My Dremel skills need reevaluation.)



3 Wire Serial LCD Backpack for Arduino with a 595 Shift Register, a Capacitor, and 2 pin headers.

clock February 2, 2013 13:58 by author dsandor

Here is a video link of the backpack operating.

The completed project with a glimpse at the breadboard prototype version.

This is not the first serial backpack for Arduino and it wont be the last.  I wanted to build one of these because I did not want to pay $16.95 plus shipping for something that could be built for $1.11.

Here is the parts list:

1 x Small Stripboard $0.66
1 x 74HC595 8 bit shift register $0.20
1 x 10pf Ceramic Disc Capacitor $0.01
1 X 40 Pin Pin Header $0.24

The finished product looks like this.  I did a pretty bad job of laying out the wires so there is some overlap.









Here is my feeble attempt at drawing out a schematic.  I used visio so I did not have the luxury of rerouting tools like Eagle has.  Maybe I will try that next.


I used the LiquidCrystal_SR3W.h from here: https://bitbucket.org/fmalpartida/new-liquidcrystal/src/bebe49d613c15933d3c2f41721f707526adc32dc/LiquidCrystal_SR3W.h?at=default

I wound up with this Arduino sketch to do a simple hello world app that outputs the current millisecond and animates an X across the second row of the LCD.  It's pretty basic but I can now use this in my projects that need to provide the user with a display.

#include <Wire.h>
#include <LiquidCrystal_SR3W.h>

LiquidCrystal_SR3W lcd(7,8,9);

void setup(){

  lcd.begin(16,2);               // initialize the lcd
  lcd.home ();                   // go home

int p = 0;

void loop(){
  lcd.home ();                   // go home
  lcd.print("Millis: ");
  lcd.print(millis(), DEC);
  if (p == 0)
    lcd.setCursor( 15, 2);
    lcd.setCursor( p-1, 2);
  lcd.print(" ");
  lcd.setCursor( p, 2 );
  if (p == 16) p = 0;

I got the schematic from this link: http://www.electronics-lab.com/projects/mcu/015/index.html

SkyDrive API Helper for Windows Phone 8

clock January 21, 2013 07:27 by author dsandor

While building a small application for viewing passwords (basically pwsafe for Windows Phone 8) I realized that because of the restrictions of WP8 with regard to the file system I needed a way to pull password files from a remote storage.  As it turns out, the SkyDrive API is comprehensive but did not have a concise Windows Phone 8 API so I started building one.


The code is very basic at this point but I do intend on improving it.

With the API helper you can:

public async Task<LiveUserInfo> GetLiveUserInfo()

public async Task<List<DirectoryEntry>> GetDirectoryEntries(string path)

public async Task<DirectoryEntry> GetDirectoryEntry(string id)

public async Task<Stream> DownloadFile(string id)

public async void DownloadFile(string id, string fileLocation)

These commands will allow you to do the majority of what you need (except upload).

To use it, simply place a SignInButton found in the Microsoft.Live.Controls assembly for Windows Phone 8.  On the OnSessionChanged event simply pass the Session to the helper and it is ready to go.

There is a very simple sample application included in the source tree that will let you get the directories from the skydrive and download a file.


SOLVED: Windows Phone 8, WP8 - The 'await' operator can only be used within an async method.

clock December 3, 2012 08:16 by author dsandor

This is a pretty rookie mistake with .NET 4.5 and the new async / await operators.  While searching for the answer I found a lot of noise and no valuable answers so I thought I would notate the solution on my blog.

The short answer is that any method that uses await must itself be marked with async.

Take this code for example:

private void OnUnlockCommand(object parameter)
   StorageFile file = await Windows.Storage.ApplicationData.
   Current.TemporaryFolder.CreateFileAsync("filename", CreationCollisionOption.ReplaceExisting);
The code above will fail with the error message:

Error    2    The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. 

To solve this you must add async to the method declaration like below:
private async void OnUnlockCommand(object parameter) 
StorageFile file = await Windows.Storage.ApplicationData.
Current.TemporaryFolder.CreateFileAsync("filename", CreationCollisionOption.ReplaceExisting);

SOLVED: Trouble with WebGet and JSON with .NET 4.0 WCF Services

clock July 21, 2012 15:27 by author dsandor

This problem has been solved and answered many different ways but none of the answers seem to propose a complete basic or step by step solution.  This article is my attempt to consolidate the answer into one concise how to article.

Executive Summary

For those of you that want the answers quickly, here are the steps necessary to properly use WebGet methods in a WCF Service:

  1. Use the WebGet attribute and specify a UriTemplate.
  2. Use the webBinding binding type in your web.config.
  3. Create an endpoint behavior that specifies webHttp in your web.config.
  4. Reference the endpoint behavior in the service endpoint configuration section.
  5. Set the binding in the service endpoint configuration to webHttpBinding (or to the name of the binding configuration that specifies webHttpBinding).

How-To / Step by Step

In this section we will go through the process of creating a simple service with Visual Studio 2010 that performs a simple WebGet operation.

Create a new WCF Service Application project.


I am going to leave the default Service1 class and interface names intact for simplicity.

Open the IService1.cs code file and change it so that it looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WebGetTest
    public interface IService1
        string AddNumbers(string a, string b);

Note the WebGet attribute in the interface definition.  Now we are going to modify the Service1.cs file to implement the AddNumbers method.

public class Service1 : IService1
    public string AddNumbers(string a, string b)
        int firstInt, secondInt;

        int.TryParse(a, out firstInt);
        int.TryParse(b, out secondInt);

        return string.Format("{0} + {1} = {2}", 
            firstInt, secondInt, firstInt + secondInt);

This implements the method.

Compile the project and make sure it builds. Next we are going to update the web.config file so this actually works.

In Visual Studio click Tools | WCF Service Configuration Editor, Load the web.config file for this new project.


You will see the WCF Config Editor.

Now we are going to create a Service Endpoint and an Endpoint Behavior.

Click the Services configuration node and click Create a New Service.

Click Browse to find the service type.  You are going to navigate to the DLL that implements your WCF service (hint, it should be in your /bin folder).


After clicking Open you will be allowed to choose the class that implements your service.  Click it and then click Open.


After clicking Open you will click Next.  This will bring you to the service contract screen.  This screen is asking you what the interface is that describes your service.  Typically this will be automatically detected and filled out for you.


Click Next.


Choose HTTP and click Next.


Choose Basic Web Services interoperability and click Next.

For the Endpoint Address enter / and click Next then on the summary page click Finish.


You will now have a service configured in your Web.config file.


Now we will create an endpoint behavior.  Expand Advanced, Right Click on Endpoint Behaviors and choose New Endpoint Behavior.


Click Add, Choose webHttp and click Add.


The new behavior configuration screen will now look like this:


Change the Binding to webHttpBinding and select the NewBehavior0 behavior configuration.


Click Save and exit from the WCF Service Configuration tool.

Now you should be able to start your WCP project and navigate to the web method in your browser and see a result like below.


Note that the URL contains your .svc file and then the UriTemplate property of the WebGet attribute kicks in. 

Source code for this project: WebGetTest.zip

WPF TextBox with smart options.

clock July 18, 2012 20:05 by author dsandor

I am building a 'smart TextBox' that allows additional data to be presented along with the actual data in the textbox.  I will detail the creation of this new TextBox in this blog entry. 

I started with a TextBox, a 'smart indicator', and a panel that will slide out of the textbox when the mouse enters the smart indicator area.  I used the following XAML to accomplish this.

<Window x:Class="ExpandoTextbox.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <Storyboard x:Key="SBSlideOut">
Storyboard.TargetName="rectangle"> <EasingThicknessKeyFrame KeyTime="0" Value="0"/> <EasingThicknessKeyFrame KeyTime="0:0:0.3" Value="0,36,0,0"/> </ThicknessAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="SBSlideIn"> <ThicknessAnimationUsingKeyFrames
Storyboard.TargetName="rectangle"> <EasingThicknessKeyFrame KeyTime="0" Value="0,36,0,0"/> <EasingThicknessKeyFrame KeyTime="0:0:0.3" Value="0"/> </ThicknessAnimationUsingKeyFrames> </Storyboard> </Window.Resources> <Window.Triggers> <EventTrigger RoutedEvent="FrameworkElement.Loaded"> <BeginStoryboard Storyboard="{StaticResource SBSlideOut}"/> <BeginStoryboard Storyboard="{StaticResource SBSlideIn}"/> </EventTrigger> </Window.Triggers> <Grid> <Ellipse x:Name="LeftAction" HorizontalAlignment="Left" Height="7" Margin="213,164,0,0"
VerticalAlignment="Top" Width="7"> <Ellipse.Fill> <RadialGradientBrush> <GradientStop Color="White" Offset="0"/> <GradientStop Color="#FF5555FF" Offset="1"/> <GradientStop Color="#FF5555FF" Offset="0.709"/> </RadialGradientBrush> </Ellipse.Fill> <Ellipse.Triggers> <EventTrigger SourceName="LeftAction" RoutedEvent="UIElement.MouseEnter"> <BeginStoryboard Storyboard="{StaticResource SBSlideOut}" /> </EventTrigger> </Ellipse.Triggers> </Ellipse> <Rectangle x:Name="rectangle" Width="80" Height="24" Fill="#FF5555FF"> <Rectangle.Triggers> <EventTrigger SourceName="rectangle" RoutedEvent="UIElement.MouseLeave"> <BeginStoryboard Storyboard="{StaticResource SBSlideIn}" /> </EventTrigger> </Rectangle.Triggers> </Rectangle> <TextBox Width="100" Height="24" /> </Grid> </Window>

The following movie clip shows the action.


  • Make into user control.

  • Make configurable (1 - ?) possible smart indicators each with it's own panel.

  • Make panel have a content panel so it can be XAML'ized.

  • Make it look pretty.

  • Provide example of use.

How a developer wins in the end, Visual Studio 2012 and the ALL CAPS.

clock July 18, 2012 19:33 by author dsandor

Dear Visual Studio 2012 developer that put in the registry entry to remove the ALL CAPS metro menu item 'feature'.  I owe you a frosty cold beer.


Here is the fictional transcript of the SCRUM meeting at the Visual Studio team:

Program Manager: Guys, marketing wants the IDE to represent the metro look and feel.

Developers: OMG are you kidding?  The development community is going to roast us for having the UI yell at them all day.

Program Manager: Well we need to eat our own dog food.

Developers: Fine, if we have to. (Thinks to himself: I am making this configurable.  I just know this is not going to fly in the real world.)

Hence: http://www.richard-banks.org/2012/06/how-to-prevent-visual-studio-2012-all.html

Visual Studio 2012 Look and Feel

clock June 15, 2012 19:49 by author dsandor

My first impression so far has been "Oh my Metro".  I am not sure if I like it yet.


The menus are in all CAPS.  WHY IS THE IDE YELLING AT ME?


The color scheme is a bit washed out.  I am still trying to get used to this but it does telegraph to the code and designer as they are where your eyes go.  I could get in to this high contrast look if it were to splash color at the portion of the UI I were currently using.

WPF Control / Element selection works well and very fast.


The UI is very responsive.  If you remember Visual Studio 2008 (Ugh I still have to work in VS2008) clicking on a UI element in the designer renders properties in about a minute if you are lucky (and have ReSharper disabled).  Visual Studio 2012's new IDE is very responsive.  Thank you!


Visual Studio 2012 adds List as an option for your DataSources if you are a drag and drop binding kinda guy.


The XAML Designer has some Blend functionality built right in now.  From the left: Zoom Level, Toggle Effects, Show Snap Grid,  Snap to Grid Lines, Snap to Snaplines, Show Annotations.

Toggle Effects

This allows you to turn off the special effects bound to controls.  This helps speed up the designer a great deal.


Allows you to view annotations about your WPF application (presumably from a sketchflow annotation).


The Solution Explorer looks Metrofied and adds a really useful Collapse All command and a Pending Changes filter command.

Finished the 4x4x4 LED Cube

clock May 1, 2012 19:10 by author dsandor

My previous post has a description and laundry list of parts I used.  I wanted to learn how to use the 74HCT595 shift register chips.  These chips are really cool because you can daisy chain them together and then simply shift bits of data into the DS serial input.  The data will write out across all the chips in the chain and you only need three digital IO ports for any number of 595's in the chain.  You just write out 8 bits of data for each chip.  So if there are 4 595's chained together you write out 32 bits of data. 

The 595's operate 8 active low output ports which means they are LOW when there is a (0) bit shifted in to the corresponding pin's register and HIGH (Vcc) when there is a (1).  So 2 chips let me turn on the positive columns of the cube.

The MC74HC138A I used let me turn on and off the connectivity to the negative voltage.  I only needed 4 of the 8 pins because I only have 4 horizontal rows of cathodes to switch.

The code attached to this only runs a test pattern that appears to turn on all the LED's in a layer and cycles to the next layer.  I did this to catch some solder points that came undone.  Next I am going to work on building some animations for the cube like rain, sinking letters, bouncing ball...etc.

Here is my parts list with prices:

2 X 74HC595 Shift Registers @ $0.20 each
64 X Blue 5mm LED's @ $0.038 each
16 X 470 Ohm resisters @ $0.01 each
1 X MC74HC138A @ $0.29

So that was $0.88 in parts if you don't count the $29 Arduino.

Previous post:

Arduino Code

int STPin = 2;
int SHPin = 3;
int DSPin = 4;
int A0Pin = 8;
int A1Pin = 9;
int A2Pin = 10;
int layers[4][3] = 
  { LOW, LOW, LOW },
  { HIGH, LOW, LOW },
  { LOW, HIGH, LOW },
void setup()
   pinMode(STPin, OUTPUT);
   pinMode(SHPin, OUTPUT);
   pinMode(DSPin, OUTPUT);
   pinMode(A0Pin, OUTPUT);
   pinMode(A1Pin, OUTPUT);
   pinMode(A2Pin, OUTPUT);
void loop()
  for(int cathodeLayer =0; cathodeLayer < 4; cathodeLayer++)
    for(int i=0; i< 50; i++)
void setCathode(int bits[])
  digitalWrite(A0Pin, bits[0]);
  digitalWrite(A1Pin, bits[1]);
  digitalWrite(A2Pin, bits[2]);  
void pulseEachAnode()
  for(int led=0; led < 16; led++)
    // Tell chip we are sending data.
    digitalWrite(SHPin, LOW);
    digitalWrite(STPin, LOW);
    for(int i=0; i < 16; i++)
       if (led == i)
         digitalWrite(DSPin, HIGH);
         digitalWrite(DSPin, LOW); 
       // Tell chip we are through sending bits.
       digitalWrite(SHPin, HIGH);
       digitalWrite(SHPin, LOW);
    // Latch.  Tell chip to move the data from the shift register stages (internal QnS) 
// to the storage register and parallel output stages
    digitalWrite(STPin, HIGH);

Notes on 4x4x4 Arduino LED Cube

clock April 29, 2012 11:30 by author dsandor

Designing my own 4x4x4 LED Cube.  These are my working notes as I only spend an hour or so each day working on this.

Using the following:

2 x SN74HC595N shift registers daisy chained to give me 16 output ports from 4 digital ports on the Arduino.
1 x MC74HC138AN Decoder / Demultiplexer to switch the cathodes on the LEDs.

Info on the 595's in serial can be found here: http://www.protostack.com/blog/2010/05/introduction-to-74hc595-shift-register-controlling-16-leds/

LED Layout

4 layers tall.  Each layer has all LED Cathodes (-) connected to each other but not connected to any other layer.  Each cathode layer will connect to it's own pin on the MC74HC138AN.  So 4 pins will be used on that IC in order to switch on or off a cathode layer.  This allows us to selectively connect / switch on the negative to any one of the 4 independent layers.

16 vertical Anode columns.   Each column of LED Anodes are connected vertically to the one below it.  These vertical columns are independent of each other so we have sixteen vertical anode columns.  Each column is connected to one output pin of the SN74HC595N ICs.  Each IC has 8 outputs so we are connecting one anode column to each discreet output.



So by turning on one of the cathode layers and then turning on one of the positive anode columns we can light one of the 64 LEDs.

Datasheet on themc74hc138an

Datasheet on themc74hc138an

Resize Images in a batch in C#/WPF with an MVVM application.

clock January 21, 2012 19:11 by author dsandor

I am working on a project where I need to resize a bunch of raster images from miscellaneous sizes to fit within a certain frame.  More specifically, I need a bunch of icons for an iPhone application and I need them to fit within a 64px by 64px frame.  I found a bunch of Photo Shop scripts, some console apps, and a few spamware solutions.  I figured half an hour and I would have one that works well.  I was right.


So here is how the app works:

Drag and drop the graphics files you wish to resize into the application.  The files will show in the list view area.  Next, enter the Max Height and Max Width values and then click the Resize button.

The application will write the resized file next to your original with _MaxHeightxMaxWidth appended to the filename.  Original files are not modified in any way during this process. 

So if you found this blog post in hopes that you would find a quick and simple image resizer for free, here is the link to the binaries: 

A little about the application source code.  The application is a .NET 4.0 WPF application that follows the M-V-VM (MVVM) design pattern.  Since there is drag and drop support in the application there is a little code behind to support this.  The rest of the application follow the MVVM pattern.

There is a tiny image resizer class in the project that you are free to use.  This is located in the DevSQL.Imaging assembly. 

The source code can be found below.

Align your code in Visual Studio 2010

clock January 21, 2012 16:47 by author dsandor

I love this Visual Studio Extension.  Wanted to keep it in the blog so I do not forget.  Chris also wrote a notepad++ plug-in for the same thing.  Kudos.


Align by... (Dialog) Ctrl + Shift + =
Align by position... (Dialog) Ctrl + =, Ctrl + backspace
Align by Equals Ctrl + =, Ctrl + =
Align by m_ Ctrl + =, Ctrl + m
Align by " Ctrl + =, Ctrl + '
Align by . Ctrl + =, Ctrl + .
Align by Space Ctrl + =, Ctrl + Space

Netduino: Day 2 - uBlox LEA-5H-0-009 GS407 GPS Receiver

clock August 5, 2011 16:38 by author dsandor

So I decided to jump in to serial communication.  Why not?  I have a ublox LEA-5H-0-009 GPS Receiver and a GS407 break out board from sparkfun.com. I connected the red (3.3v) and the black (gnd) from the GPS to the netduino.  There is a TXO and RXI pin and a GPIO pin on the GPS break out board (BOB).  I admit, I had to google a lot.. I mean a LOT to figure this one out.  Eventually I found a great article from blog.bobcravens.com with 99.9999% of the solution.

2011-08-05 15.35.28

I learned a lot about serial communication from reading Bob’s article.  In summary, what I learned is that I can use D0 and D1 on my netduino as a serial port COM1.  D0 is COM1 IN or RX and D1 is COM1 OUT or TX.  The last piece of the puzzle was the GPIO pin on the GPS.  Clueless me had no idea what to do with the GPIO pin.  After reading his blog, it seems that is used to turn on and off the power.

Here are a few better views of the connections.  Ignore the IC chip and the three axis sensor on the project board.

2011-08-05 15.35.38

2011-08-05 15.35.28

When I first connected the device I was getting nothing from it because the TX and RX were flipped.  Then, I started getting bytes from the serial port but they were poorly formatted and I could not convert them to UTF.  This caused errors when using the System.Text.UTF8Encoding.UTF8.GetChars(buffer); code.  As it turns out the baud rate needed to be 9600 and I had it at 4800.  After that fix I was set and I was getting NEMA messages.


It does not look like it is picking up a signal yet but that is my next step.  Get the messages decoded and get the device to lock on a few satellites.

Here is the code I used which I got from Bob’s post and tweaked a bit as I was running into issues decoding the bytes because of the baud rate issue.

        public static void Main()
         SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
         // pin D2 off = gps module turned on
         OutputPort powerPin = new OutputPort(Pins.GPIO_PIN_D2, false);
         char[] str = null;
         while (true)
             int bytesToRead = serialPort.BytesToRead;
             if (bytesToRead > 0)
                 // get the waiting data
                 byte[] buffer = new byte[bytesToRead];
                 serialPort.Read(buffer, 0, buffer.Length);
                 // print out our received data
                     str = System.Text.UTF8Encoding.UTF8.GetChars(buffer);
                 catch { }
                 if ( str != null )
                    Debug.Print(new String(str));
             Thread.Sleep(100); // wait a bit so we get a few bytes at a time...

About the author

David Sandor is a Software Architect working in Chicago, IL.  My development focuses around the Microsoft Stack including Azure, AppFabric, Silverlight, WPF, .NET Framework, and various mobile devices including iOS (iPhone/iTouch), Android, Windows Mobile and Windows Phone 7.

Month List

Sign in