Code Challenge – Win a Gyroball

12 08 2010

UPDATE: The Contest is now closed – entries are being reviewed and will be announced in about a week

Can you solve our .NET code challenge?

If so, you might be eligible to win a gyroball.

How it works

  1. Solve the code problem at www.thycotic.com/codetest.txt
  2. Send your solution to tdd_me_now@thycotic.com (all solutions due by 8/31)
  3. One winner will be randomly selected from the pool of correct solutions
  4. The names of everyone that submitted a correct solution will be posted, along with the solution

Eligibility

  • Everyone is welcome to submit their solution, only those in the continental U.S. are eligible to win the gyroball.

Are you the Chuck Norris of coding?

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 http://www.thycoticsolutions.com/careers.html If you feel you have what it takes to work at Thycotic – submit a cover letter, resume, and solution to this problem to tddjobs@thycotic.com





Has Catch Phrase Loyalty Compromised your Software Development Process

29 07 2010

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

22 07 2010

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





Agile and Scrum Always Require the Retrospective

14 07 2010

July 14th 2010 | Jimmy Bosse

Agile, Scrum: Always Require the Retrospective

If you’re thinking about bringing Agile, Scrum, etc. into your development organization, I have one important piece of advice: always require, and never stop doing retrospectives.

I don’t care if your team is made up of brilliant developers who resist a new process, or project managers loathe to try something new. In my opinion, the retrospective is the single most important element of the Agile process. Implement it early, and keep it even if you scrap everything else.

The power of the retrospective to a development team is immediate and relevant change. The practice of developing software is littered with beleaguered development teams, exhausted from consistently delivering the impossible and getting very little recognition in return. When they express a desire to change things that effect their daily life but don’t provide immediate business value, their requests fall on deaf ears.

In Agile development, the team is paramount and their concerns are of great importance. The retrospective is the vehicle for improvement for both the team and the software it produces. When you provide a team with a forum to express their concerns, and commit to implementing their recommendations, the result is a motivated, productive team. As a developer,  I always get an opportunity to engage in a dialog with my team to decide if my concerns are valid. Not every request or suggestion will be granted, but knowing  my opinion is being seriously considered makes this easier to accept.

Without the retrospective, my recommendations and those of my team become a morale sinkhole, demoralizing the team and compromising the quality of the software we deliver. Issues and bugs become a game of CYA and everyone points fingers at everyone else. But in an open, collaborative environment the team as a whole takes responsibility for issues and bugs, responds to them quickly, and  has an opportunity to discuss how to keep them from happening in the future.

The retrospective is a time for the team to discuss what is working and what is broken; decide what incremental change is most important; and commit to fixing that one thing. At the next retrospective the team evaluates whether that change made things better or worse. Surprisingly, sometimes an item that was considered an improvement a few month earlier might now be identified as broken. It doesn’t matter if it worked well before—if the team decides it’s not working, they scrap it and keep on moving. Who knows, it might just be back again in another three months, but I am content in the knowledge that every two weeks (or whatever your iteration cycle might be) I will get the chance to make things better.

That makes me a happy developer, and happy developers make better software.

If you have any questions about this series of posts or about DevConnections, feel free to send me an email (jimmy.bosseATthycotic.com) or message me on Twitter @jimmybosse.

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





We’re Hiring: dotNet Developers

9 07 2010

Kevin:Tidbits of .NET

If you can solve the problem below, you may just have what it takes.

www.thycotic.com/codetest.txt

Please submit your solution with your resume and cover letter in an email to TDDjobs@thycotic.com

At Thycotic you’ll join a highly capable team of .NET developers who work on consulting projects for clients, and interesting products. Improve your agile development skills while working with a team of skilled, passionate developers. We’re hiring, and we’d love to hear from you!

Required:

  • You have the permanent legal right to work in the United States
  • You have excellent written and spoken English
  • You live, breathe, sleep, eat and drink C#
  • You have a strong understanding of Object Oriented principles, the .NET Framework, ASP.NET, relational databases and web application development
  • You are able to communicate effectively with co-workers and clients/customers
  • You are willing to work in the Washington DC Metro Area
  • You want to develop using Test Driven Development
  • You want to develop using Pair Programming

Why work at Thycotic:

  • Your ideas and opinions will be valued
  • You will continuously learn about new development techniques and technologies
  • We are a seasoned Agile .NET shop – not many of those around!
  • We are a Microsoft Gold Certified Partner
  • Follow a technical career path
  • Excellent benefits package
  • You will be working in the heart of Washington, DC

Learn more about Thycotic





Tidbits in dotNET Framework 4

30 06 2010

Kevin:Tidbits of .NET

June 30th | 2010

.NET Tidbits

Every now and then while exploring the .NET Framework 4 I come across something small, but very useful. In no particular order, here is a list of the top 10 new small changes to the framework that may help.

1. Environment.Is64BitOperatingSystem

This is a huge timesaver. Doing this previously required Platform Invoke to do properly (IntPtr.Size doesn’t work if your assembly is compiled for x86 only). Likewise, it has an additional helper Environment.Is64BitProcess. They aren’t something that will get used on a daily basis, but it’s great to have them when you need them.

2. System.Numerics

This is a namespace in a new assembly called System.Numerics. It contains two very useful types: BigInteger and Complex. BigInteger, like it sounds, is big. Unlike the primitives that already existed, such as Int32, Int64, etc; this has absolutely no limit to how big the number can be.Possible applications are calculators and cryptography when dealing with large prime numbers. Complex is a complex number that is used to represent number with an imaginary component, such as the square root of -1. The ToString implementation of this is disappointing. I would expect it to be “a + bi” notation, but rather uses “(a, b)”.

3. System.Lazy<>

This is class to better support lazy initialization of objects. A typical pattern would be a service locator that may or may not get all of its services used. Rather than the service locator setting everything up on startup, you can use the Lazy class internally to create the service when it is needed. It even has a constructor overload for thread safety. Here is a snippet:

public class ServiceLocator
{
    private readonly Lazy<IMyService> _lazyMyService
        = new Lazy<IMyService>(() => new MyService(), true);
    public IMyService MyService
    {
        get
        {
            return _lazyMyService.Value;
        }
    }
}

4. IEnumerable.Zip extension

A new extension method that is a part of LINQ is Zip. This allows you to merge two sequences together based on a predicate. It’s quite simple and was something that many considered an oversight in the original release of LINQ. Oversight or not, here it is!

5. Enum.TryParse

Ever been given an enumeration value in the form of a string, and needed to parse it in a safe way? Well now you can with the introduction of Enum.TryParse. It will not throw an exception like Parse will, and follows the same semantics as Int32.TryParse by returning a Boolean to indicate if it was successful or not, and using an “out” parameter to actually return the value.

6. System.Tuple

Many developers have been asking for Tuple support. A Tuple is an immutable structure that can contain two or more elements. Simple as that. They are created using Tuple.Create(), and support up to eight items. More dynamic languages, including the new F# language, make heavier use to tuples and are created using their own syntax.

7. System.Collections.StructualComparisons

Ever want to compare two arrays to see if they were the same? Sounds simple up front, but usually requires some sort of loop or LINQ operation. Now it’s possible to compare two arrays to see if their contents are the same, not if they are the exact same array. Here is snippet to illustrate the use:

var strings1 = new[] {"Hello", "World!"};
var strings2 = new[] {"Hello", "World!"};
int compared = StructuralComparisons.StructuralComparer.Compare(strings1, strings2);

In this case, the comparer returns 0 because there is no difference between the two arrays.

8. System.IO.File.ReadLines

ReadLines is a helpful method that allows you to lazily enumerate over the lines of a text file, rather than using ReadAllLines which isn’t efficient for large text files.

foreach(var line in File.ReadLines(".\\myfile.txt"))
{
    //parse the line and move on to the next one
}

9. MemoryMappedFile

This class is part of the System.IO.MemoryMappedFiles namespace. Its purpose is to provide a managed implementation of a memory mapped file. This is often desirable when working with extremely large files and remaining efficient. To do the same in previous versions of the .NET Framework, you would have to relied on platform invoke.

10. System.Net.Mail.SmtpClient.Dispose

This is more of a “gotcha” than a feature, but it also cleans up a known issue in the .NET Framework. The SmtpClient now implements IDisposable. This gives you control over when the SmtpClient sends a QUIT message to the SMTP server. If this isn’t called after you complete sending emails, it will leave the connection open and may result in unexpected behavior.

Kevin Jones 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 Kevin





Code Contracts in dot NET

24 06 2010

Kevin Code Contracts

June 24th | 2010

Code Contracts in dot NET

It is often desirable for a developer, particularly those who make public APIs, to communicate to 3rd party developers what their code expects. For example, say I have a product that allows plugins to be written for it. A plugin can call an API I provided, “Print”. Print takes a single string, however, the string should never be null.
Nonetheless, we can’t guarantee a developer will never pass in null; there may be a bug in their application. To prevent serious errors from occurring, we need to ensure our parameter is never null. We can do this with an exception.

public void Print(string data)
{
    if (data == null)
        throw new ArgumentNullException("data",
"This parameter must not be null.");
    //Implementation omitted
}

This is a very typical pattern but it leaves us wanting more. The developer won’t know he is giving the API a string that cannot be used until he attempts to run the application. Nothing is stopping the compiler from compiling.
Statically checking if our code is violating a contract is a powerful feature. An experimental language called Spec# currently supports this but unfortunately, being experimental, it makes it difficult to use in real-world scenarios.
Enter Code Contracts. Now built into the .NET Framework 4, all you need to do is download an add-on for Visual Studio 2008 or 2010. In the .NET Framework 4, the magic happens in the System.Diagnostics.Contracts namespace. You can download the add-on from here:

http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx

Once installed, you will see a new tab on your project’s properties called “Code Contracts”.

I’ve configured a few key options here. I’ve set the “Perform Runtime Contract Checking” to Full, and checked the “Perform Static Contract Checking”, “Check in Background”, and “Show squigglies”. Next, we need to define the contracts. We can use the Contract class to indicate these contracts. Our method now looks like this:

public static void Print(string data)
{
    Contract.Requires<ArgumentNullException>(data != null);
    //Implementation omitted
}

This will have the same behavior as before: If data is null, then an ArgumentNullException is thrown. However, in addition to the runtime failure, we will also see a warning when we compile and squigglies under the code.

And of course, if we set “r” to something not null, the contract is happy! However, what happens if r is getting data from somewhere else?

static void Main(string[] args)
{
    string r = SomeMethodThatWillNeverReturnNull();
    Print(r);
}

private static string SomeMethodThatWillNeverReturnNull()
{
    return "notnullstring";
}

The contract analyzer isn’t small enough to check and see what the method actually does. However, the method could potentially return null. We know better than that, so we can tell the Code Contract analyzer that the return value is never null. This is done with a post condition using Contract.Ensure. A post condition is a contract that ensures a condition is met when the method is exiting. In our case, we want a post condition that says “SomeMethodThatWillNeverReturnNull” won’t return null.

private static string SomeMethodThatWillNeverReturnNull()
{
    Contract.Ensures(Contract.Result<string>() != null);
    return "notnullstring";
}

This tells us that the result of the method will never return null. The call to Print is now satisfied knowing that its source of data cannot return null. If SomeMethodThatWillNeverReturnNull could return null, then the post condition will fail.
Let’s go over what we are seeing. The Contract.Requires indicates that the Print method requires its data parameter as not null, before the method is actually executed. If the condition fails, an exception is raised at runtime, and a warning is generated at compile time.
Contract.Ensures is a post condition. It indicates that before the method exits, that condition must be met. Though it is a post condition, it’s still recommended that the constraint be placed at the top of the method. Let’s say we need our code to meet this contract:

  1. Print must never accept a null string.
  2. Print must never accept a string that is greater than 1000 characters.
  3. When print is called, we must set dataWasPrinted to true.

Here is what our contract looks like:

class Program
{
    private static bool dataWasPrinted = false;

    static void Main(string[] args)
    {
        string data = GetData();
        Print(data);
    }

    private static string GetData()
    {
        Contract.Ensures(Contract.Result<string>() != null);
        Contract.Ensures(Contract.Result<string>().Length <= 1000);
        return "data from file";
    }

    public static void Print(string data)
    {
        Contract.Requires<ArgumentNullException>(data != null);
        Contract.Requires<ArgumentNullException>(data.Length <= 1000);
        Contract.Ensures(dataWasPrinted == true);
        try
        {
            //Implementation omitted
        }
        finally
        {
            dataWasPrinted = true;
        }
    }
}

This is a powerful concept and can be extremely useful. I wouldn’t recommend putting contract validation on all of your code, rather just public methods that will be exposed to others. I might also recommend using it in critical cases where a specific contract must be met. It isn’t a replacement for unit tests or mock testing, rather another tool in the belt that makes a software developer’s life easy.

Kevin Jones 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 Kevin





Observable Collections in .NET Framework 4

30 04 2010

Observable Collections in .NET Framework 4

April 30th | 2010

Observable Collections in .NET Framework 4

The observable pattern in software development has been something of interest to many. A former co-worker of mine called it “Hollywood programming: Don’t call us, we’ll call you”. It’s a feature that many Aspect Oriented Programming (AOP) models give, and many have hand-rolled their own.

An observable collection simply allows an object to know when the collection has changed, possibly through an event. This puts the responsibility on the collection to notify all of its listeners for changes, rather than the listeners checking periodically if the collection has changed. If you were to hand-roll your own, you might implement IList<T> on your own, and have your implementation raise an event on itself when Add is called.

Starting in the .NET Framework 4, these have been provided to you in a fairly straight-forward fashion. A new class called ObservableCollection<T> in the namespace System.Collections.ObjectModel does the heavy lifting for you. It contains an event called CollectionChanged that is raised when something changes on your collection. Its delegate contains two items. First is “sender”, which is the collection itself. The second is the “args”, which has a lot of interest to us. It is of type NotifyCollectionChangedEventArgs. The args parameter tells us what happened: how it changed, and what exactly changed. Let’s take a peek at some code to see it.

static void Main(string[] args)
        {
            var collection = new ObservableCollection<string>();
            collection.CollectionChanged += collection_CollectionChanged;
            collection.Add("Hello World!");
            collection.Add("Goodbye World!");
            collection.Remove("Goodbye World!");
        }

        static void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    Console.WriteLine("\"{0}\" was added.", e.NewItems[0]);
                    break;
                case NotifyCollectionChangedAction.Remove:
                    Console.WriteLine("\"{0}\" was removed.", e.OldItems[0]);
                    break;
            }
        }

The Action on the NotifyCollectionChangedEventArgs tells us if something was removed, added, or moved. NewItems is an array of items that were added, and OldItems contains items that were removed. In the ObservableCollection class, the event will be raised once per-item and the NewItems and OldItems will contain a single item. Other classes that implement the observable pattern in the framework (or possibly your own) may in raise the event once for several items, possibly for both an Add and Remove. One occurrence of this is the observable pattern that is in the AJAX 4.0 Framework when making web service callbacks.

Observable collections are useful when a collection is handed to several actors on the collection, and a single place must know what is occurring on the collection, for example: displaying feedback to the user on a GUI.

Kevin Jones 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 Kevin





Digging into the Parallel Framework

22 04 2010

Digging into the Parallel Framework

April 22nd | 2010

Digging into the Parallel Framework

A new feature I really like in the .NET Framework 4 is the parallel framework. Virtually every home computer has at least two physical cores, but client applications don’t utilize multiple cores as effectively as they could; probably because parallel programming is difficult.

As I’ve never been required to make heavy use of parallel programming, I haven’t invested time in existing frameworks. Typically, I’ve used a messy combination of a semaphore and threads. This lead to some complex design patterns and the occasional bug. Nor was this method as effective as the parallel framework.

To get started, most of the parallel related APIs exist in the System.Threading.Tasks.Parallel namespace. The class we will discuss here is fittingly named Parallel.

Example task, and how to solve it.

Take 20 popular websites, download their HTML and save it to disk.

We’ll use Alexa as our source for the websites, and keep it simple by hard-coding the URLs for now.

Using no parallel tasks at all, the code looks like this:

Sub Main()
    Dim topUrls() As Uri = {
        New Uri("http://www.google.com")
    } 'Remainder ommited for clarity
    Dim watch As Stopwatch = Stopwatch.StartNew()
    For Each url As Uri In topUrls
        Dim wc As New WebClient()
        Dim data() As Byte = wc.DownloadData(url)
        File.WriteAllBytes(".\" &
            url.GetComponents(UriComponents.SchemeAndServer Xor
            UriComponents.Scheme, UriFormat.SafeUnescaped) &
            ".html", data
        )
    Next
    watch.Stop()
    Console.WriteLine("Elapsed Time: " & watch.Elapsed.ToString())
    Console.ReadKey(True)
End Sub

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: Consolas, “Courier New”, Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Given that network performance is subjective, our mileage will vary. There was negligible latency except for sina.com.cn. All in all, the resulting performance is 00:01:11.068 over an average of 10 runs. The performance of sina.com.cn was pretty bad, but that’s expected given that it’s Chinese based – and their site is a whopping 466kb at the time of writing.

This kind of work is perfect for parallel programming. Even though it’s not CPU intensive, it’s also not utilizing my network as well as it could. The Parallel class can help us, and it isn’t a big leap to get the basics going. There’s a static method on the Parallel class called ForEach, and it will act as our iterator rather than an actual ForEach loop. We then pass a lambda specifying what the work is. This is the simplest use of the Parallel class.

Here is the code I wrote using Parallel.

Sub Main()
    Dim topUrls() As Uri = {
        New Uri("http://www.google.com")
    } 'Remainder omitted for clarity
    Dim watch As Stopwatch = Stopwatch.StartNew()
    Parallel.ForEach(topUrls, Sub(url)
                Dim wc As New WebClient()
                Dim data() As Byte = wc.DownloadData(url)
                File.WriteAllBytes(".\" &
                url.GetComponents(UriComponents.SchemeAndServer Xor
                UriComponents.Scheme, UriFormat.SafeUnescaped) &
                ".html", data
                )
            End Sub
        )
    watch.Stop()
    Console.WriteLine("Elapsed Time: " & watch.Elapsed.ToString())
    Console.ReadKey(True)
End Sub

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: Consolas, “Courier New”, Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

It doesn’t look too much different, does it? Behind the scenes, there is a lot going on. It’s a complex bit of multithreading and distribution. It’s dependent on your environment as well. The number of threads used depends on how many cores you have, and many other factors.

As a result, using the Parallel worker shaved an average of 10 seconds off every run.

Parallel.For is very similar in behavior, but rather than using a collection it will use a start integer and end integer.

Now let’s say we need to accumulate results. For example, let’s extract the title from the HTML. Again, the single threaded example looks like this:

Sub Main()
    Dim topUrls() As Uri = {
        New Uri("http://www.google.com")
    } 'Remainder omitted for clarity
    Dim watch As Stopwatch = Stopwatch.StartNew()
    Dim pageTitles = New List(Of String)()
    For Each url As Uri In topUrls
        Dim wc As New WebClient()
        Dim data As String = wc.DownloadString(url)
        Dim title As String = Regex.Match(data,
    "<title[^>]*>(?<title>[\W\w\r\n]*)</title>").Groups("title").Valu
        title = Regex.Replace(title, "[/\\:\?\*""<>|.\r\n\W]", "")
        pageTitles.Add(title)
        File.WriteAllText(".\" & title & ".html", data)
    Next
    watch.Stop()
    Console.WriteLine("Elapsed Time: " & watch.Elapsed.ToString())
    For Each title As String In pageTitles
        Console.WriteLine(title)
    Next
    Console.ReadKey(True)
End Sub

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: Consolas, “Courier New”, Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

My regular expression handiwork isn’t the best, but it gets the job done. To put this in Parallel, we might be tempted to wrap the whole thing with a Parallel.ForEach again, but we can be more efficient than that.

The Parallel framework does not execute one item per-thread and ditch the thread. That would be inefficient. What we can do is specify local storage for each thread, then an additional lambda containing the accumulated data from the thread will be invoked. In addition to our body, we will now have an initializer that returns an initial state of an object that we define. This gets passed into the body, and the body will accumulate to that thread’s local storage. And finally, when the thread is finished, we’ll merge it into a master collection.

It sounds complex, but really, it isn’t. Let’s look at the code:

Sub Main()
    Dim topUrls() As Uri = {
        New Uri("http://www.google.com")
    } 'Remainder omitted for clarity
    Dim watch As Stopwatch = Stopwatch.StartNew()
    'Use a thread safe collection!
    Dim pageTitles = New ConcurrentBag(Of String)()
    Parallel.ForEach(topUrls, Function() New List(Of String)(),
      Function(url, loopState, threadData)
          Dim wc As New WebClient()
          Dim data As String = wc.DownloadString(url)
          Dim title As String = Regex.Match(data,
    "<title[^>]*>(?<title>[\W\w\r\n]*)</title>").Groups("title").Value
          title = Regex.Replace(title, "[/\\:\?\*""<>|.\r\n\W]", "")
          threadData.Add(title)
          File.WriteAllText(".\" & title & ".html", data)
          Return threadData
      End Function,
     Sub(threadData)
         For Each title In threadData
             pageTitles.Add(title)
         Next
     End Sub)
    watch.Stop()
    Console.WriteLine("Elapsed Time: " & watch.Elapsed.ToString())
    For Each title As String In pageTitles
        Console.WriteLine(title)
    Next
    Console.ReadKey(True)
End Sub

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: Consolas, “Courier New”, Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This isn’t entirely different from the previous result, there’s just a little extra. Looking at the call to ForEach, we are still handing in the topUrls as before, but now we have an init function before the body. This is run once before each thread starts, and it is unique to that thread. In this case, it’s a plain list. Since the list is unique to each thread, we don’t have to use a ConcurrentBag or worry about thread safety.

Next: the body. Previously it was a Sub/Void that took in each URL as the collection iterated. Now it includes the loopState, which can provide information about your current loop. We aren’t going to use that as of now. It also has the object that we initialized in the beginning. We will add our title to this collection, and return the collection. Lastly, we have the finally piece. Throughout the body we were adding the titles to different Lists, which now won’t do us any good. The finally is a lambda that says, OK. This thread is done. Here is all the data this thread accumulated. Do with it as you see fit. In this case, we copy it to a ConcurrencyBag back on our main thread. Note that whatever you call in the finally piece must be thread safe.

That’s the basics of the Parallel task. And there’s still a lot to explore in the in the Parallel Framework including Tasks, Cancelling, and Progress updates.

Kevin Jones 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 Kevin





Retrospective Speculation

1 04 2010

April 1st | 2010

Retrospective Speculation

I recently read a book by Esther Derby and Diana Larsen titled Agile Retrospectives. When I first started skimming through the book I was rather skeptical (an activity titled Mad, Sad, or Glad? Right…) However, when I actually sat down and read through it I realized that the authors had a lot of good information to present. They also understood the disinclination of engineers to engage in activities that seem silly.

Agile Retrospectives focuses on iteration or release retrospectives, which primarily involve the development team. As such, there are a few goals that the various steps and activities presented in the book are designed to satisfy.

  1. Collect the viewpoints of everyone on the team, not just the most vocal members.
  2. Group the collected information to see what the team as a whole thinks.
  3. Come up with clear goals to improve based on the information collected.

This deceptively simple list of tasks includes what I believe to be the most challenging element of any retrospective meeting; keeping all team members engaged. If a few vocal members dominate the discussion, there is no guarantee that their stated issues or suggestions are identical with what the rest of the team thinks. This can result in decisions based on a vocal minority, never a good thing in a team environment.

Agile Retrospectives defines five stages within the retrospective .

  1. Set the Stage
  2. Gather Data
  3. Generate Insights
  4. Decide What to Do
  5. Close the Retrospectives

Each stage has a number of possible activities listed that are intended to keep all team members engaged and balance the results from each member against the team as a whole.

Our retrospectives occur about every two weeks, and are relatively informal in format. Process hiccups or any significant roadblocks are discussed and incremental suggestions made for the next iteration. We try to keep any changes small in order to reduce the cost of adjusting processes and reduce risk.

I’m interested in hearing about how other teams handle retrospectives or project post-mortems. Have you developed your own activities? How useful do you feel the activities or retrospectives in general are? How do you keep everyone engaged?

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.