Archive

Archive for the ‘General Software Development’ Category

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”);

Enjoy!

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();

}

Requirements:

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("https://www.google.com/accounts/ClientLogin");
            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 += "&Email=yourusername@gmail.com";
            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);
            newStream.Close();

            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);
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
            response.Close();
            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)
                App.ViewModel.LoadItems();
                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("http://finance.google.com/finance/feeds/default/portfolios");
            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", "http://www.w3.org/2005/Atom");
                XName qualifiedTitle = XName.Get("title", "http://www.w3.org/2005/Atom");
                XName portfolioData = XName.Get("portfolioData", "http://schemas.google.com/finance/2007");

                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)
                {
                    Items.Add(d);
                }

                NotifyPropertyChanged("Items");
        }

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);
            GetPortfolios();
        }

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.

Has Catch Phrase Loyalty Compromised your Software Development Process

July 29, 2010 Leave a comment

July 29th 2010 | Jimmy Bosse

Has Catch Phrase Loyalty Compromised your Software Development Process?

The software development landscape is full of buzz words and catchy names.

‘Competing process’ and ‘best practices’ abound. Then we have Waterfall, Agile, Scrum, Lean, Scrum, Kanban (both with big K and little k), and Alt.Net. Each of these groups has its fanatics. You know them. Their ears go bright red when you mention a successful project using another methodology. I used to be one of them. Sometimes I still am.
But since reading the book “Sofware Craftmanship” by Pete McBreen, and an old blog post “Composition over Inheritance and other Pithy Catch Phrases” by Phil Haack it dawned on me: we all want to write great software, and we all want to enjoy doing it.

The thing I love most about my current development project is that our client listens to the team, and the team is striving to make things better. This is the nature of the Agile environment. But while we identify ourselves as an Agile development company, there’s more to what makes us tick than the adoption of a label. We want to deliver great software to our clients, and Agile helps us do that.

The right tool for the right job.

In his book “Sofware Craftmanship”, Pete McBreen is selling the idea of adopting the craftsman model of software development. It is a response to the heavy weight of the Software Engineering paradigm that has reigned since the late 60s. What is most striking about his argument is not what he argues, but rather how he argues. He does not come out guns blazing, trying to convince us that we’ve had it wrong the whole time. Instead he explains what Software Engineering does really well and why it’s great for implementing the sort of projects for which it was created. He then shows us how many of today’s software development projects are quite different, and how those differences make Software Engineering the wrong tool for those projects. He then proposes a new one to take its place.

Think for yourself and strive to improve.

In his post “Composition over Inheritance and other Pithy Catch Phrases”, Phil Haack raises a discussion he was having about a design pattern and the manner in which the other person was arguing his point. What I took away from Phil’s post is that he is asking developers not to blindly adopt one practice or another, but rather consider all of them as they pertain to the problem at hand. Your job as a developer is to write good software—and the right solution might be under someone else’s catch phrase.

Don’t be a slave to your catch-phrase.

By not taking sides with any particular camp, I suggest we open ourselves up to learning about the merits of each camp, and bring to our projects an open mind that is willing to use a method or process that works, even if it’s from a different camp.

Jimmy Bosse is a 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. On Twitter? Follow Jimmy

Warm Turkey

July 22, 2010 3 comments

July 22th 2010 | Jimmy Bosse

Warm Turkey

In a recent post, “Cold Turkey”, my colleague Kevin Jones challenged developers to “try writing code for a day, even an hour, using notepad. Not Notepad2 or notepad++. Though you can cheat and use MSBuild to compile your solution. It might just change your idea of what good code is.”

I say poppycock!

Imagine being a patient about to go into surgery when your doctor explains that he will be removing your appendix without anesthesia or a scalpel. Instead, he’ll be getting back to his roots and will be using a knife and some leeches to demonstrate what good surgery is. Utter nonsense.

Tools like IntelliSense do not write good or bad code—they are used by good or bad developers. Should I be aware of the methods of the System.IO.File class? Absolutely. Should I be able to recall each of its 56 methods on demand? Absolutely not. Can I tell you the parameter types of each of the three overloaded signatures for its Open method? Nope again. Knowing this information by rote does not make me a better developer. It’s also a waste of my time, and to our clients (if you are a consultant like many of us developers) time is money.

Tools like IntelliSense are about efficiency, and to argue that it rots the brain is to argue that we should launch the space shuttle on the minds of brilliant engineers who insist on using the abacus.

Tools help good programmers deliver good software faster. I couldn’t write a post about essential tools without discussing ReSharper. I have on more than one occasion stated that, “I will never use Visual Studio again without ReSharper, ever.” I stand by that statement. I even saw a recent tweet by someone stating that they could do more coding with one hand and ReSharper than with two hands without it.

True, if you’re a bad developer, the tools are going to make you better—at writing bad code. There’s not much I can do about that.

Jimmy Bosse is a 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. On Twitter? Follow Jimmy

Build Your Solutions from the Context Menu

November 9, 2009 Leave a comment

Quickly look up table information in SQL Server Management Studio

Sept 2nd 2009 | Jimmy Bosse

Build Your Solutions from the Context Menu

Many times you want to quickly refresh your solution from the repository and quickly build it without having to open Visual Studio. Follow these simple steps to add a Registry Key that will add a context menu for you solution files.

Launch RegEdit: Start > Run > type regedit > click OK.

Navigate to HKEY_CLASSES_ROOT > SystemFileAssociations.

If there is no “.sln” key, add a key for “.sln”.

If there is no key for “shell” in “.sln” then add a key for “shell”.

Add a “Build Solution” key in “shell”.

Add a “command” key to “Build Solution”.

Set the default value for command to:

cmd.exe /k “call “%%VS90COMNTOOLS%%\vsvars32.bat” x86&&msbuild “”%1″” /p:Configuration=Debug /t:Rebuild /l:FileLogger,Microsoft.Build.Engine;logfile=MSBuildDebug.log&&pause&&exit”

Reboot, and now you can build your solution file from the context menu.

Tada!

Note that this specific entry will only build debug builds for 2008 solutions. You can modify the VS90COMNTOOLS and Configuration=Debug to add entries for other versions of Visual Studio and other build configurations.

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

The Dangers of Single Responsibility in Programming

November 9, 2009 3 comments

The Danger of Single Responsibility in Programming

October 16th 2009 | David Cooksey

The Dangers of Single Responsibility in Programming

The principle of single responsibility is an important and well-known object-oriented guideline. Systems designed without any consideration for this principle often result in the God-object anti-pattern, with predictably unfortunate results. However, taking single responsibility too far also results in code that is difficult to read and maintain.

Let’s take a look at a possible system built for a company that sells a wide variety of products. This system was originally built around a Product object, and over the years the product object has continued to grow and acquire responsibility as new features were added to the system. The IProduct interface now looks like this:

  public interface IProduct
  {
    int Id { get; set; }
    string Name { get; set; }
    int TypeId { get; set; }
    DateTime AddedDate { get; set; }
    decimal Cost { get; set; }
    decimal BasePrice { get; set; }
    decimal SalesPrice();
    decimal Price(int customerId);
    decimal Discount(int customerId);
    decimal GetShippingCharge(int customerId, string stateCode);
    int GetMinQuantity(int customerId);
    DateTime GetNumAvailable(int customerId);
  }

This company has built its business model on special services for frequent customers, including special discounts, shipping rates, lower base prices, etc. Some customers receive lower prices on specific products in return for promises to order at least a certain quantity each time. The net result is that the full cost depends on who and where the customer is as much as it depends on the product itself.

Now imagine that a developer on this project has read about the fascinating new concept of single responsibility and decides that IProduct is responsible for too much. In fact, it’s responsible for everything. So he creates a PriceProvider that contains a GetPrice method as shown below, moving the logic of the method directly from the Product class to the PriceProvider.

    public decimal GetPrice(IProduct product, int customerId)
    {
      decimal price = product.BasePrice;
      ICustomer customer = GetCustomer(customerId);
      if (customer.GoldLevelCustomer)
      {
        price = price * (1 - GetGoldLevelDiscount());
      }
      if (ProductIsOnSale() && !FixedDiscountAgreementExists(customer, product))
      {
        decimal salePrice = product.SalesPrice();
        if (salePrice < price)
        {
          price = salePrice;
        }
      }

      return price;
    }

So far, so good. The logic is adequately complex and involves enough dependencies that it should probably exist in its own class. Initially, our developer is happy. However, as he continues to look at this method, he decides that it is doing a lot more than it should. After all, any number of business logic changes could make this class change, and a class should have only one reason to change, right? So he rolls up his sleeves and gets to work, eventually producing the following:

    public decimal GetPrice(IProduct product, int customerId)
    {
      decimal price = product.BasePrice;
      ICustomer customer = GetCustomer(customerId);
      if (goldLevelDeterminator.IsGoldLevelCustomer(customer))
      {
        price = price * (1 - goldLevelDiscountProvider(product));
      }
      if (saleProvider.IsOnSale(product) && !fixedDiscountAgreementProvider.AgreementExists(customer, product))
      {
        decimal salePrice = product.SalesPrice();
        if (useSalesPriceInsteadOfPriceDeterminator.UseSalesPrice(price, salePrice))
        {
          price = salePrice;
        }
      }
      return price;
    }

The goldLevelDiscountProvider, saleProvider, and fixedDiscountAgreementProvider probably refer to their own tables, given the code structure shown, so it makes sense to split them out. However, the goldLevelDeterminator is literally calling the GoldLevelCustomer property on customer and returning it, and the useSalesPriceInsteadOfPriceDeterminator is simply comparing the sales price to the price.

These latter two changes are examples of implementing the principle of single responsibility at a level of granularity below that of the business requirements. It is possible that the company’s needs will change in such a way that these classes will become necessary, but they do not need their own class unless and until their complexity warrants it. The creation of two determinator classes here implies that significant logic is involved in determining whether a customer is a gold level customer, or whether the sales price should be used.

Unnecessary classes like the two mentioned above cause a number of problems. Firstly, they increase the complexity of the code. A developer reading through this class for the first time will need to open both determinators up and mentally piece their contents back into the main function instead of simply reading them. Secondly, their existence as independent entities implies that they are reusable. However, their creation was solely based on a desire to separate method calls into their own class, not a thorough investigation of how the class meshes with the rest of the classes in the project.. Quite often, classes like these are not reused and in fact their functionality is duplicated in other tiny classes used in other places.

In short, when you’re designing or refactoring systems, plan your class structure around business needs, not logical decision points. A method with two if statements should not automatically be considered as having two reasons to change. After all, those two if statements may represent a single business concept.

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