Working with JSON Values that are C# Reserve Words.

February 17, 2011 Leave a comment

February 17th 2010 | Jimmy Bosse

Working with JSON Values that are C# Reserve Words

While playing around with GitHub’s API for Gists, I discovered I couldn’t simply deserialize into an object because the API used the C# reserve word “public” as a property name. Luckily, the DataMember attribute has a “Name” property that allows to you explicitly map a JSON property to your object’s property of a different name:

   1:  namespace MyGistClient
   2:  {
   3:      [DataContract]
   4:      public class GistsResult
   5:      {
   6:          ...
   8:          [DataMember(Name = "public")]
   9:          public bool IsPublic { get; set; }
  11:          ...
  12:      }
  13:  }

While C# will let me make a property named “Public”, I decided to use “IsPublic” instead so I don’t have any issues if my object gets consumed by another .NET language that isn’t case sensitive.

Jimmy Bosse is a Senior .NET developer and Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

Categories: C#, JSON Tags: , ,

Quick Tip: Control.Find(string id) Extension Method

December 27, 2010 Leave a comment

December 27th 2010 | Jimmy Bosse

Quick Tip: Control.Find(string id) Extension Method

For my current project, I am constantly using FindControl to dynamically locate a child control within a parent control. Instead of constantly typing this:

1: DropDownList dropDownList = employeeListView.FindControl(“regionDropDownList”) as DropDownList;

I created an extention method to prettify my code:

   1: public static class ControlExtensions
   2: {
   3:     public static T Find<T>(this Control control, string id) where T : Control
   4:     {
   5:         return (T) control.FindControl(id);
   6:     }
   7: }

So now I can type this:

1: employeeListView.Find(“regionDropDownList”);


Jimmy Bosse is a Senior .NET developer and Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

QuickTip Fix your IE7 Select Lists

December 8, 2010 2 comments

December 7th 2010 | Jimmy Bosse

Fixing the Display of Variable Width Select Lists in IE7

I recently helped a client with an ASP.NET website that targeted the IE7 browser. We weren’t doing anything specific that required IE7, but we knew that 99% of the users would be using IE7 as this was the standard installation for the internal users who would be given access to the system.

Several of the pages had select lists in the header of tables that would act as column filters. Unfortunately, IE7 has an incredibly annoying method of rendering select lists. It will shrink the input so that it is contained with its parent element, but when you click the pull-down to expand the selection list, the list does not expand to the width of the select list item. In our case, with narrow columns this resulted in some select lists where the user could only see the first few letters of each option, which is obviously useless.

Searching the internet I found a solution and a commenter to that solution that used a jQuery script to modify the css to force the inout to expand and contract as needed when you interact with the control. The script posted had a few kinks that had to be ironed out but I managed to get it working perfectly for IE7 and IE8. Once I got it working, I decided to turn the script into a jQuery plugin, and got that working as well.

Now we have a nice plugin that we can easily use in any page that has a select list that needs to be fixed.

In order to fix your select lists you need to only perform two steps:

1. Include jQuery, and the plugin:

<script type="text/javascript" src="<your=path-here>/jquery-1.4.3.min.js"></script>

<script type="text/javascript" src="<your=path-here>/fixieselects.js"></script>

2. Add call to the plugin with the relevant select lists on jquery ready event:

$(document).ready(function () {

$(".mycssclass select").fixieselects();



jQuery 1.4.3 can be downloaded here.

My fix script sample can be downloaded from here.

Jimmy Bosse is a Senior .NET developer and Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

How to build a Google Finance client app with Windows Phone 7

October 21, 2010 10 comments

October 21st 2010 | Ben Yoder

<< Update: the zip file of this application is now available for download

How to build a Google Finance client app with Windows Phone 7

1. Getting Started

Google Finance enables users to view and manage stock portfolios. Google provides an HTTP API that allows clients to interface with the application. With the release of the new Windows Phone 7 operating system, creating a portfolio viewer application is a great way to learn a new set of tools.
Download the Windows Phone development tools—they integrate nicely into an already installed version of Visual Studio 2010. Alternatively you can use an Express Edition of 2010.
Once you’re up and running open VS 2010 and select File->New Project, then select a new Windows Phone List Application:

You should see a split screen designer for MainPage.xaml. This is the opening list page of the application. On the side with the XAML code, update the TitlePanel section to give your application a new name.

Hit F5 to run your application. Your emulator should come up and look something like this:

2. Authentication
Now that you’ve seen your application run in the emulator you must authenticate to the Google Finance API. I used HttpWebRequest to handle all the calls. Using the WebClient class could also work and might be simpler, but I prefer the control that HttpWebRequest provides.
The following code illustrates sending a HTTP POST to the Google client login service and reading the response. For simplicity, I put all my code in the MainViewModel.cs file.

        public void LoadItems()
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            request.BeginGetRequestStream(new AsyncCallback(GetRequest), request);

        private void GetRequest(IAsyncResult asyncResult)

            string postData = "accountType=HOSTED_OR_GOOGLE";
            postData += "&";
            postData += "&Passwd=yourpassword";
            postData += "&service=finance";
            postData += "&source=test-test-.01";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            Stream newStream = request.EndGetRequestStream(asyncResult);
            newStream.Write(byteArray, 0, byteArray.Length);

            request.BeginGetResponse(new AsyncCallback(GetResponse), request);

        private void GetResponse(IAsyncResult asyncResult)
            string responseFromServer = ReadResponse(asyncResult);

        private string ReadResponse(IAsyncResult result)
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            WebResponse response = request.EndGetResponse(result);
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            return responseFromServer;

To see what the response is, paste this code into your project and call the LoadItems method from the OnNavigatedTo event in MainPage.xaml.cs.

            // Set the data context of the listbox control to the sample data
            if (DataContext == null)
                DataContext = App.ViewModel;

The Auth section is the only one we care about, so I parsed it out and assigned it to a private variable. All subsequent requests for portfolio and stock data will require it.

        private void GetResponse(IAsyncResult asyncResult)
            string responseFromServer = ReadResponse(asyncResult);
            AuthenticationToken = responseFromServer.Substring(responseFromServer.IndexOf("Auth=") + 5);

3. Getting Data
Now that we can authenticate to the Google Finance service, we can start retrieving stock information. First, set up your Google Finance account with some test portfolios if none currently exist. The call to retrieve your portfolio feed is significantly simpler than the authentication call—it’s a simple GET request with the Authorization header set to the previously returned Authentication Token.

        private void GetPortfolios()
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");
            request.Method = "GET";
            request.Headers["Authorization"] = "GoogleLogin auth=" + AuthenticationToken;
            request.BeginGetResponse(new AsyncCallback(GetPortfolioResponse), request);

private void GetPortfolioResponse(IAsyncResult asyncResult)

The resulting response is an XML doc detailing your portfolio feed. Now, let’s bind it to the list displayed in the MainPage. LINQ to XML provides a simple way to parse the response and create the list of items to bind to.

        private void GetPortfolioResponse(IAsyncResult asyncResult)
                string response = ReadResponse(asyncResult);
                XElement portfolio = XElement.Parse(response);

                XName qualifiedName = XName.Get("entry", "");
                XName qualifiedTitle = XName.Get("title", "");
                XName portfolioData = XName.Get("portfolioData", "");

                var portfolios = from p in portfolio.Descendants(qualifiedName)
                                 select new ItemViewModel
                                        LineOne = p.Element(qualifiedTitle).Value,
                                        LineTwo = "1 Week Return: " + p.Element(portfolioData).Attribute("return1w").Value

                foreach (var d in portfolios)


The ItemViewModel class is a default for the solution. Change it, or its property names, if you want them to be more descriptive. Update the GetResponse method to call GetPortfolios:

        private void GetResponse(IAsyncResult asyncResult)
            string responseFromServer = ReadResponse(asyncResult);
            AuthenticationToken = responseFromServer.Substring(responseFromServer.IndexOf("Auth=") + 5);

Then run the solution again. At this point you should get a security exception. This is because the HttpWebRequest kicks off a series of asynchronous calls which use separate threads. The NotifyPropertyChanged() call then tries to update the UI via event handlers, which isn’t allowed in Silverlight. To force the thread context, wrap the body of GetPortfolioResponse with:

            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>

This invokes the update on the UI thread which does not throw System.UnauthorizedAccessException: Invalid cross-thread access error.
An additional gotcha about parsing the response from Google is that the XML has a specified namespace, so doing something like portfolio.Descendents(“entry”) won’t work. You have to use the fully qualified name which you can do by using XName.Get with the elements specified namespace.
The solution should be runnable at this point. Hit F5 to debug. Your emulator should now look something like this (depending on your Google Finance portfolios):

If you click on an item you will automatically navigate to a detail page which will just display the portfolio name right now. In future posts, I’ll detail binding this page with specific stocks and making the app look great. If you have any questions or interesting alternative solutions please post them in the comments below.



Ben Yoder is a Senior .NET developer at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

Working with XML Namespaces and LINQ

October 11, 2010 3 comments

Ben XML Namespaces

October 11th 2010 | Ben Yoder

Working with XML Namespaces and LINQ

While working on a project using LINQ to XML to parse a web response, I ran into an issue whereby my calls to get an entity’s Descendants or Elements were returning no results. It turned out that the specified response included a namespace. In this case you can’t use the common element name—you must get the fully qualified XName.

For example, given the following XML and LINQ Query:

    string xml = @"<Employees>

        XElement employee = XElement.Parse(xml);

    var employees = from e in employee.Descendants("Employee")
                        select new
                            Id = e.Element("Id").Value,
                            FirstName = e.Element("FirstName").Value,
                            LastName = e.Element("LastName").Value

The query works and the employees object contains John Smith. However if the XML changes, the query returns nothing:

    <h:Employees xmlns:h="">

After browsing through some MSDN documentation, I learned that I have to include the namespace in the query. I got the full name using XName.Get()

    XName root = XName.Get("Employee", "");
    XName firstName = XName.Get("FirstName", "");
    XName lastName = XName.Get("LastName", "");
    XName id = XName.Get("Id", "");

Replace the names in the LINQ query and it returns the correct results. Of course, there are other ways to accomplish this. You could create an XNamespace object based on the namespace string and prepend it to each element name in the query. Creating an individual XName object for each query parameter gets kind of verbose, so for more complex LINQ this is probably not the preferred way.

Ben Yoder is a Senior .NET developer at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

Code Challenge Results

September 16, 2010 4 comments

Thank you to all to those that submitted code solutions. We will be running another code contest in a few weeks. Check back soon to enter our next contest. Congratulations to our contest winner: Rob Howarth

See the bottom of this page for an example solution

Others who submitted correct solutions

  • Rob Howarth
  • Scott Monnig
  • Eric Haddan
  • Thomas Eyde
  • Imran Baloch
  • Marc Chu
  • Cesar Neves
  • Jaider Ariza
  • Kenneth Hall
  • Teymur Mammadov
  • Cam Luc
  • Peter Burrell
  • Anthony Clayton
  • Mark Lindell
  • Steve Smith
  • Chris McKenzie
  • Amit Parikh
  • David White
  • Ron Warholic
  • Josh Clark
  • James Baker
  • Richard Deeming
  • Erik Jõgi
  • Scott Holodak
  • James Curran
  • Marius Ene
  • Matt Crouse
  • Michel Grootjans
  • Daniel Griffie
  • Xiu
  • Mordechai Sandhaus
  • Stuart Cam
  • Raj Rao
  • Rafik Ramtoolah
  • Ali Derman
  • Eric King

Sample Solution

        public class Converter
                public string Convert(int number)
                        StringBuilder buffer = new StringBuilder();
                        int quotient = number;
                        int remainder = -1;
                        while (quotient != 0)
                                remainder = quotient % BaseNumber;
                                quotient = quotient / BaseNumber;
                                buffer.Insert(0, ConvertSingleBaseNumber(remainder));
                        return buffer.ToString();

                protected virtual string ValidCharacters
                        get { return "0123456789xyz"; }
                private string ConvertSingleBaseNumber(int remainder)
                        return ValidCharacters[remainder].ToString();
                private int BaseNumber
                                return ValidCharacters.Length;

        public class BinaryConverter : Converter
                protected override string ValidCharacters
                                return "01";

        public class OctalConverter : Converter
                protected override string ValidCharacters
                                return "01234567";

        public class HexConverter : Converter
                protected override string ValidCharacters
                                return "0123456789abcdef";

Did you like this challenge? Maybe you found it easy? Were always looking for talented people to join our growing team. Take a look at what we do at If you feel you have what it takes to work at Thycotic – submit a cover letter, resume, and solution to this problem to

Lexing and Parsing with F# – Part I

September 10, 2010 3 comments

September 10th 2010 | David Cooksey

Lexing and Parsing with F# – Part 1

FsLex and FsYacc are F# implementations of Ocaml’s Lex and Yacc. They are part of the F# Powerpack released for Visual Studio 2010. Used together, they take an input string and create a parse tree of typed objects. Once you have the parse tree, you can do anything with it—generate code for another language, interpret it directly, etc. If you’d like to jump right into the code, scroll to the bottom of the post. Note that the code includes a small test project using FsUnit.

FsLex is the lexer part of the lexer-parser pair
. It converts an input string or stream into a series of tokens. A token is simply a string labeled so that the parser knows how to handle it. For example, ‘92’ might be within a token labeled DIGIT. Simply put, the lexer’s job is to take a meaningless string, label the parts of it relevant to the language, and hand the labeled parts, in order, to the parser.

FsYacc is the parser component.
The parser’s job is to impose syntactical rules onto the stream of typed tokens generated by the lexer. In an analogy to spoken languages, the tokenizer recognizes words and the parser recognizes correct sentence structures.
Let’s start with a very simple syntax that requires a valid program to be a single assignment of an integer or string to a variable. Working with Lex and Yacc primarily requires altering three files. Lexer.fsl defines the allowed tokens (the lexer component) and Parser.fsy defines the allowed syntax (the parsing component). The third file (which we will call Statements.cs) defines the types that we will use to generate the parse tree.

In it we define allowed types for Stmt and expr.  Stmt can be only a single type, called Assign, which is a tuple consisting of a string and an expr.  Its dependent type, expr, can be a string (typed as Val) or an Int32 typed as Int.

Note that this single file gives a very concise picture of what kind of language we are parsing. Assignments of strings and integers are allowed, nothing else.

Next comes the lexer.

Take note of a few things here.  The ‘open Parser’ statement on line 5 indicates that the lexer is dependent on the parser.  This is because the tokens (ID, INT, EQUAL, etc.) used on lines 18-23 are defined in the Parser file.  The syntax used for matching tokens is similar to regular expressions.  Line 18 ignores whitespace characters (defined above as space, tab, carriage return, and newline) by calling tokenize on the next character in the buffer.  The ID and INT tokens can contain multiple characters.  Token patterns can be defined above (like digit, equal, semicolon, …) or directly within the parse rules (such as the allowed pattern for ID).  Any character in the input stream that does not match one of these patterns will generate an error.

Last, the parser.

Here, it all comes together.  Lines 7 and 8 indicate that the program starts with start: which is of type Stmt as defined in the Statements file.  Line 16 declares the program must consist of a single StmtExp, which expands according to the remainder of the rules.   Rules are defined as an allowed pattern of tokens (defined above using %token ) and the types that they generate.  The $1, $2, $3 references inside the types indicate the 1-based index position within the tokens to the left.  For example, the $2 on line 19 refers to the contents of the ID token.  Let’s expand the syntax above for a specific example.

StmtExp -> ID EQUAL Expr SEMICOLON -> ID EQUAL INT SEMICOLON -> varname = 5;

Which becomes Assign(“varname”, Int(5))

StmtExp -> ID EQUAL Expr SEMICOLON -> ID EQUAL QUOTE ID QUOTE SEMICOLON -> varname = “string”;

Which becomes Assign(“varname”, Val(“string”))

We’ll see more complicated expansions, along with a bit more of the theory, in part 2.

One interesting expansion of the lexer/parser would be to adjust it to handle typed variable definitions.

Setting up FsLex and FsYacc within a project requires a few manual changes.  See this blog by Don Syme for details on setting up your project manually (or use the project file included here).


Fslex and FsYacc Info:

F# Powepack:


David Cooksey is a Senior .NET developer at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

Categories: F# Tags: , ,