Wednesday, November 24, 2010

Phone: Transfer Your Google Voice Number to a Google Apps Account

I have a Google Apps account and a regular ‘ol gMail account, but now that Google Apps offers Google’s full line of product offerings, I’m trying to phase out and move my old data.  Part of this is moving my Google Voice number to my Google Apps account.  Turns out you can move it by filling out this form.  Took them about a week to complete the move.

Friday, November 12, 2010

Code: Silverlight Media Element Relative Urls

The best way I’ve found to use relative urls for media items in Silverlight is to place the media files (mp3, wmv, mp4, etc) in the ClientBin folder of the website (same directly as the .xap file) 


Ensure that the Build Action is set to Content and Copy To Ouput Directory is set to Copy if Newer:


Then you can reference the files with a single forward slash then the file name:

<MediaElement x:Name="DangerZoneTune" Source="/DangerZoneTune.mp3"></MediaElement>

Monday, October 11, 2010

Code: jQuery AJAX and Templates

The jQuery Templating plugin Microsoft’s web team has been working on has been accepted by the jQuery team check out the code below for usage with an AJAX web service.

1.  Reference jQuery 1.4.2 or later, and the template .js file (Templates will be an included part of jQuery 1.5)

    <script type="text/javascript" src=""></script>
script type="text/javascript" src="/Scripts/jquery.tmpl.js"></script>

2.  create the template that will be applied to each item in your result set, notice the ${} syntax

<script id="clientTemplate" type="text/html">
<li><a href="Detail.aspx?q=${Id}" target="_blank">${Description}</a></li>

3.  Give the DOM element that will house the template an ID

ul id="MatchingQuestions">

4.  Create the AJAX Call to your web service.  Notice that it is binding to the “d” element of the resulting msg object.

function SearchQuestions(text) {
type: "POST",
url: "/NotifierWS.asmx/SearchQuestions",
data: "{'searchText': '" + text + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
error: function (xhr, ajaxOptions, thrownError) {

5. Create a web service method (the service class will also need to have the ScriptService attribute)

public QuestionItem[] SearchQuestions(string searchText)
List<QuestionItem> result = new List<QuestionItem>();
foreach (Business.Question q in Business.Question.SearchQuestions(searchText, 5))
result.Add(new QuestionItem(){ Id = q.Id, Description = q.Title});
return result.ToArray();

public class QuestionItem
public long Id { get; set; }
public string Description { get; set; }

Tuesday, September 7, 2010

Code: No source control? Use DropBox

Recently I was working on a small development project that was only semi-work related.  I didn't want to use my work's source control since it was non-work and I didn't need versioning, just backup.  I created the project in my Dropbox folder and it worked really well to backup and keep the project synced across machines.

Wednesday, August 25, 2010

Code: FullText Search in SQL Server 2008 Express

In order to do full text search in SQL Server 2008 Express (Original or R2) you have to install the "Advanced Services". You can find the download for original here or R2 here.

After upgrading your current instance (or installing the new instance) you also need to make sure the Full Text service is enabled

You can then follow this guide to add a full text catalog and index.

If you are using SSMS and want the full text index scripts to be generated when you generate the create script for a table, you'll need to modify a setting.  Go to  Tools | Options - Scripting page and then scroll down to table options and select "Script full-text indexes". This will script the full-text indexes with the table definition.

If you are using the scripts then in a Visual Studio Database project, don't forget to set the Build Action property of the file to "Build", otherwise it will drop the indexes when it deploys

Tuesday, August 17, 2010

Code: Silverlight Navigation from a UserControl

For some reason Silverlight does not provide the ability to access a page's NavigationService from a user control, so in order to navigate correctly you have to manually walk the control tree. See the method below to use as a helper class.

public static class NavigationHelper
        public static void Navigate(Uri url, UserControl control)
            Page pg = GetDependencyObjectFromVisualTree(control, typeof(Page)) as Page;

        private static DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
            //Walk the visual tree to get the parent(ItemsControl)
            //of this control
            DependencyObject parent = startObject;
            while (parent != null)
                if (type.IsInstanceOfType(parent))
                    parent = VisualTreeHelper.GetParent(parent);
            return parent;

Monday, August 2, 2010

Code: Create Thumbnail from Video using VLC command line

If you want to create a thumbnail from a video, you can use VLC and its command line arguments as seen below. This was tested using VLC 1.1.2

C:\Users\amiller.NG>"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" --video-filter scene -V dummy --scene-width=80 --scene-format=jpeg --scene-replace --scene-ratio 24 --start-time=6 --stop-time=7 --scene-path=D:\ --scene-prefix=thumb D:\1.mp4 vlc://quit

--scene-path is the output directory
--scene-prefix is the output filename
--scene-format can be jpeg, jpg, or png
--start-time is the location in the video (in seconds) to grab the image from
--stop-time tells the vlc to stop playing the video at that point
--scene-width specifies the output width of the thumbnail in pixels, you can optionally include --scene-height, but the image will be stretched to fit that dimension.

Thursday, June 24, 2010

Code: WPF Binding a TreeView to an Array of Complex Objects

I’m taking my first stab at WPF as a learning exercise and figured out how to bind an array of objects (with sub-objects) to a TreeView control. 

First, here is the resulting output:



This TreeView binds to an Array of type ClientWithAssets, which contains an array of Asset and a Client as properties. 


Step 1: make sure your sub-objects are public properties and not members! (I was stuck for an hour because of this).

Step 2: Drop a TreeView control on your window and define the hierarchy:

        <TreeView HorizontalAlignment="Stretch" Margin="12,41,12,12" Name="treeView1" VerticalAlignment="Stretch" ItemsSource="{Binding}" >
HierarchicalDataTemplate ItemsSource="{Binding Assets}">
TextBlock Text="{Binding ClientItem.ClientName}"/>
TextBlock Text="{Binding Name}"/>

Step 3: Bind on window load:

private void Window_Loaded(object sender, RoutedEventArgs e)
treeView1.ItemsSource = ClientWithAssets.FindAll();

There are many, many ways to perform this same functionality, but this is what made most sense to me.

Thursday, June 17, 2010

Code: Create Properties for ASP.Net Web Form Pages

When developing web form pages I like to create properties to interact with user input controls that are more complex than simple strings (Enums, DateTime, etc).  This allows me to keep more of my page strongly typed.

using System;

namespace WebFormsSamples
public partial class PageProperties : System.Web.UI.Page
public enum PrimaryColors

public PrimaryColors SelectedColor
PrimaryColors result;
Enum.TryParse<PrimaryColors>(ColorInput.SelectedValue, out result);
return result;
ColorInput.SelectedValue = value.ToString();

public DateTime SelectedDate
DateTime result = DateTime.MinValue;
DateTime.TryParse(DateInput.Text, out result);
return result;
DateInput.Text = value.ToShortDateString();

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
SelectedColor = PrimaryColors.Yellow;
SelectedDate = DateTime.Today;

/// <summary>
Notice the strong types here!
/// </summary>
protected void SaveInput_Click(object sender, EventArgs e)
SaveItem(SelectedColor, SelectedDate);

private void BindControls()
ColorInput.DataSource = Enum.GetNames(typeof(PrimaryColors));

private void SaveItem(PrimaryColors color, DateTime date)
lblResult.Text = SelectedColor.ToString() + " " + date.ToLongDateString();

Tuesday, June 8, 2010

Code: Encoding Videos using Expression Encoder

I wrote an article for MSDN magazine about Expression Encoder, check it out at This is my first article pretty exciting!

Wednesday, June 2, 2010

Code: C# Optional Parameters

One of the new features of C# in .Net 4.0 is optional parameters.  VB has had this language feature for a while, and its nice to see it make its way to C#.  If you don’t like optional parameters you can still use method overloading, but it will definitely be useful in some situations.  To make a parameter optional, you just need to specify what the default value for the parameter is:

public int Add(int firstNumber, int secondNumber = 0, bool isAbsolute = false)
int result = firstNumber + secondNumber;

if (isAbsolute)
result = Math.Abs(result);

return result;


Wednesday, April 28, 2010

Code: Handling Back, Forward, and Middle Mouse Button Clicks

I’m currently studying to become a MCPD in Windows Forms development.  I don’t do very much development in windows forms, so some of what I’m learning is pretty new.  I learned today that .Net Windows Forms can easily handle mouse clicks that come from the back and forward buttons as well as the middle mouse button.  To do this you just need to handle the MouseClick event of a control as shown in the code below.

private void Form1_MouseClick(object sender, MouseEventArgs e)
switch (e.Button)
case System.Windows.Forms.MouseButtons.XButton1:                   
case System.Windows.Forms.MouseButtons.XButton2:
case  System.Windows.Forms.MouseButtons.Middle:

Friday, March 26, 2010

Code: C# Simple Multithreading Example using ThreadPool

Below you will find a simple, complete code sample for multithreading in C# using the ThreadPool class.  This sample uses a simple counter to track the number of threads that are active to prevent the application from closing before all threads have completed.  Although there are other ways to force a method to wait for all threads to complete before exiting, using a static counter allows you to create a separate method to determine when the application is allowed to exit.  This is useful for handling OnStop events on windows services.  Within the StopProcessing() method you could also set a flag that would prevent your application from creating new threads.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  7. namespace MultiThreadedApp
  8. {
  9.     class Program
  10.     {
  11.         static int _threadCounter = 0;
  13.         static void Main(string[] args)
  14.         {
  15.             for (int i = 0; i < 10; i++)
  16.             {
  17.                 CreateThread(i);
  18.             }
  20.             StopProcessing();
  22.             Console.WriteLine("Finished");
  23.         }
  25.         private static void CreateThread(int threadId)
  26.         {
  27.             Console.WriteLine("Creating Thread {0}", threadId);
  28.             MethodParameters newParameter = new MethodParameters();
  29.             newParameter.ThreadId = threadId;
  30.             newParameter.ThreadCreated = DateTime.Now;
  31.             Interlocked.Increment(ref _threadCounter);
  32.             ThreadPool.QueueUserWorkItem(new WaitCallback(LongRunningProcess), (object)newParameter);
  33.         }
  35.         private static void LongRunningProcess(object input)
  36.         {
  37.             MethodParameters inputParams = (MethodParameters)input;
  38.             Random random = new Random(((MethodParameters)input).ThreadId);
  39.             Thread.Sleep(random.Next(500, 5000));
  40.             Console.WriteLine("Thread {0} complete in {1} seconds", inputParams.ThreadId,
  41.                 (DateTime.Now - inputParams.ThreadCreated).TotalSeconds);
  43.             Interlocked.Decrement(ref _threadCounter);
  44.         }
  46.         private static void StopProcessing()
  47.         {
  48.             Console.WriteLine("Waiting for {0} threads to complete", _threadCounter);
  49.             while (_threadCounter > 0)
  50.                 Thread.Sleep(500);
  51.         }
  53.         private class MethodParameters
  54.         {
  55.             public DateTime ThreadCreated { get; set; }
  56.             public int ThreadId { get; set; }
  57.         }
  58.     }
  59. }

Monday, March 15, 2010

Code: C# Best Practices

I found a nice C# coding best practices doc from DotNetSpider today:

Great to use as a starting point for your own standards.

A couple things I’d change:

1.  There should only be 1 exit point in a method.  The word return should only appear once, and it should be the last line in the method.

2.  The Public regions should appear before Private regions in a class.  When navigating to a business method from a UI class it seems more natural to jump into the top of a file and work your way down.

Friday, March 12, 2010

Code: How To Run a .Net Windows Service as a Console Application

Attempting to debug a windows service can be a nightmare, especially if you are trying to debug the OnStart event by attaching to a local process.  To get around this you can configure the windows service to launch as a console application.  To do this go to the property pages of your service and select the Application tab.  Change the output type to Console Application:


Next modify the program.cs file by adding an args input parameter to the Main method and surrounding the logic in the method with an if statement like so:

Code Snippet
  1. static void Main(string[] args)
  2. {
  3.     if (args.Length == 0)
  4.     {
  5.         ServiceBase[] ServicesToRun;
  6.         ServicesToRun = new ServiceBase[]
  7.         {
  8.         new Service1()
  9.         };
  10.         ServiceBase.Run(ServicesToRun);
  11.     }
  12.     else
  13.     {
  14.         //DoWork();
  15.     }
  16. }

Now modify your service1.cs file to call the same worker method on start:

Code Snippet
  1. public partial class Service1 : ServiceBase
  2. {
  3.     public Service1()
  4.     {
  5.         InitializeComponent();
  6.     }
  8.     protected override void OnStart(string[] args)
  9.     {
  10.         //DoWork();
  11.     }
  13.     protected override void OnStop()
  14.     {
  15.     }
  16. }

Finally go to the Debug tab on the property pages and add a word to the Command line arguments text box:


Now just start debugging and your breakpoint will be hit!


Wednesday, March 3, 2010

Code: An attempt was made to load a program with an incorrect format.

I received the following error message today when setting up a website in IIS 7 (on Windows 7):

Could not load file or assembly X or one of its dependencies. An attempt was made to load a program with an incorrect format.

This error was due to a 32 bit website on a 64 bit system.  To fix this you need to go to the Advanced Settings on the Application pool and set “Enable 32-Bit Applications” to True.


Monday, February 22, 2010

Code: The type 'int' must be a reference type in order to use it as parameter

I received a new error message developing and ASP.Net MVC page today:

The type 'int' must be a reference type in order to use it as parameter 'TModel' in the generic type or method 'System.Web.Mvc.ViewPage<TModel>'. 

Apparently MVC requires a reference type to use the constructor that accepts a type as a parameter.  I was trying to pass an int as the Model type.  The workaround was pretty simple, I just used ViewData and a generic MVC page (Inherits="System.Web.Mvc.ViewPage").

Tuesday, January 19, 2010

Code: Serializing and Deserializing Objects (Converting Objects to a String and Back)

Object serialization in .Net is pretty easy, once you have the right code.  It took me a few minutes to figure out the right code so I thought I’d post it here.  The code below is a working C# console app.

Code Snippet
  1. using System;
  2. using System.IO;
  3. using System.Xml.Serialization;
  5. namespace TestApp
  6. {
  7.     public class Program
  8.     {
  9.         static string serializedObject;
  11.         static void Main(string[] args)
  12.         {
  13.             Serialize();
  14.             Deserialize();
  15.         }
  17.         static void Serialize()
  18.         {
  19.             Person p = new Person() { Age = 20, Name = "Bob" };
  20.             XmlSerializer serializer = new XmlSerializer(p.GetType());
  21.             using (StringWriter sw = new StringWriter())
  22.             {
  23.                 serializer.Serialize(sw, p);
  24.                 serializedObject = sw.GetStringBuilder().ToString();
  25.             }
  26.         }
  28.         static void Deserialize()
  29.         {
  30.             XmlSerializer serializer = new XmlSerializer(typeof(Person));
  31.             Person p = (Person)serializer.Deserialize(new StringReader(serializedObject));
  32.             Console.WriteLine("Name:" + p.Name + " Age:" + p.Age);
  33.             Console.ReadLine();
  34.         }
  36.         public class Person
  37.         {
  38.             public int Age { get; set; }
  39.             public string Name { get; set; }
  40.         }
  41.     }
  42. }

Friday, January 15, 2010

Code: Multiple Startup Projects in Visual Studio

Visual Studio has the capability to have multiple projects listed as startup projects.  This will allow you to launch and attach debugging to multiple applications at once.  This is very handy when debugging the encoding system locally.
To do this right click on the Solution icon in Visual Studio and select Properties.
Check the "Multiple Startup Projects" radio button
in the list of projects below the radio button change the Action to "Start" for the projects you want to launch.


Thursday, January 14, 2010

Code: Launch a Console Application in a New Window

I ran into a tricky situation today, How do I use a batch file to launch other batch files or console applications in a new console window?  The key to this is the START keyword.  So if you open up a new command prompt window and enter


You will effectively transfer control of your current window to the test.bat file.  However, if you change your command to

start test.bat

The batch file will be launched in a new window allowing your first window to continue operation to perform other commands or launch more programs.

Wednesday, January 6, 2010

Code: Build an Adaptive Bitrate SMIL File Using XmlDocument

Code Snippet
  1. /// <summary>
  2. /// Builds a smil file based on .mp4 files found in a given directory
  3. /// Assumes files are named XXX_bitrate.mp4 (movie_300.mp4)
  4. /// </summary>
  5. public static XmlDocument BuildSmilFile(DirectoryInfo sourceDirectory)
  6. {
  7.     List<FileInfo> files = new List<FileInfo>();
  8.     files.AddRange(sourceDirectory.GetFiles("*.mp4"));
  10.     //biggest file (highest bitrate) first.
  11.     files.Sort(delegate(FileInfo p1, FileInfo p2)
  12.     {
  13.         return p2.Length.CompareTo(p1.Length);
  14.     });
  16.     XmlDocument result = new XmlDocument();
  18.     //create element nodes
  19.     XmlNode smilNode = result.CreateElement("smil");
  20.     XmlNode headNode = result.CreateElement("head");
  21.     XmlNode bodyNode = result.CreateElement("body");
  22.     XmlNode switchNode = result.CreateElement("switch");
  24.     //add video nodes for each file
  25.     foreach (FileInfo mp4File in files)
  26.     {
  27.         XmlNode videoNode = result.CreateElement("video");
  29.         //Create and add attributes
  30.         XmlAttribute srcAttr = result.CreateAttribute("src");
  31.         srcAttr.Value = mp4File.Name;
  32.         XmlAttribute bitrateAttr = result.CreateAttribute("system-bitrate");
  33.         bitrateAttr.Value = Path.GetFileNameWithoutExtension(mp4File.Name).Substring(mp4File.Name.LastIndexOf("_") + 1) + "000";
  34.         videoNode.Attributes.Append(srcAttr);
  35.         videoNode.Attributes.Append(bitrateAttr);
  37.         //add video node to switch
  38.         switchNode.AppendChild(videoNode);
  39.     }
  41.     //append nodes to parent elements
  42.     bodyNode.AppendChild(switchNode);
  43.     smilNode.AppendChild(headNode);
  44.     smilNode.AppendChild(bodyNode);
  45.     result.AppendChild(smilNode);
  47.     return result;
  48. }