Archive

Archive for the ‘Fun’ Category

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
  • MORRIS CRISTOPHER
  • 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
                {
                        get
                        {
                                return ValidCharacters.Length;
                        }      
                }
        }

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

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

        public class HexConverter : Converter
        {
                protected override string ValidCharacters
                {
                        get
                        {
                                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 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

Fun with Anonymous Types and LINQ

March 24, 2009 Leave a comment

Ben Yoder: LINQ

March 24th 2009 | Ben Yoder

Fun with Anonymous Types and LINQ

A new feature introduced in C# 3.0—anonymous types and their proper usage—has sparked some debate.  While some may feel that they distract from code clarity, they can be used for standard object initialization, such as:

—————–
var f = new FakeClass()
—————–

or primitive types

—————–
var i = 1;
—————–
In these cases, anonymous types add little to code readability.  In the case of initializing primitive data types, they really don’t save much typing or make a programmers life any easier.  Although anonymous types may not add much to standard object and type initialization, they are extremely handy for defining tuples and collections with LINQ.  For example, instead of having to define a struct or class of read-only properties, you could initialize the type like this:

—————–
var person = new {FirstName=”James”, LastName=”Ingram”};
var persons = new {first = new {FirstName = “James”, LastName = “Ingram”}
,second = new {FirstName=”Kenny”, LastName = “Loggins”}};
—————–

And even better, once a composite type is initialized, intellisense picks up on the properties making them easy to reference:

—————–
Console.WriteLine(person.FirstName);
—————–

We can also do fun things with delegates and functions with composite objects.  By specifying two different delegate functions and setting the “Join” property of the person object we can specify how each person should join their names.

—————–
Func<string, string, string> ReverseJoin =
(first, last) => last + “, ” + first;
Func<string, string, string> NormalJoin =
(first, last) => first + “, ” + last;

var persons = new {first = new {FirstName = “James”, LastName = “Ingram”, Join = ReverseJoin}
,second = new {FirstName=”Kenny”, LastName=”Loggins”, Join = NormalJoin}};
—————–

This behavior can be nicely leveraged in LINQ queries.  Since the compiler infers a type for the left hand side at build time (Check out the IL after compiling some code with anonymous types to see for yourself) there is no need for casting or conversions.  With anonymous types and LINQ we can write something like:

—————–
Func<string, string, string> ReverseJoin =
(first, last) => last + “, ” + first;
Func<string, string, string> NormalJoin =
(first, last) => first + “, ” + last;

var persons = new[]{
new {FirstName = “James”, LastName = “Ingram”, Join = ReverseJoin},
new {FirstName=”Kenny”, LastName=”Loggins”, Join = NormalJoin}
};

foreach (var person in from p in persons where p.LastName == “Ingram” select p)
{
Console.WriteLine(person.Join(person.FirstName, person.LastName));
}
Console.ReadLine();
—————–

Anonymous types aren’t really meant for replacing that standard class or initialization, its much more advantageous to use it with the set based operations of LINQ.  The example above may be somewhat contrived, but it’s handy that due to the inferred creation of the anonymously typed objects there was no need to create any classes.  Sure we could have created a Person class that specified properties for First and Last names, and methods to join them, and then looped through each item in the collection to check the LastName field.  That would have been a valid way of getting the same result, but with the combination of Anonymous types and LINQ we can write the same functionality in a more concise manner.


Ben Yoder is a Senior .NET developer at Thycotic Software Ltd. Thycotic is recognized for providing Agile TDD Training and Agile .NET Consulting Services, and its flagship password management software Secret Server.

A sign that you are no longer a startup.

April 11, 2008 1 comment

100_0455

Ok, so it is a really bad pun.  It is tough writing blog post titles sometimes. 🙂

Anyway, we finally got a beautiful metallic official sign for our office after inhabiting our office space for almost two years.  (Now if we could just do something about that door!). 

 

 

In our first office suite in Vienna (VA) we had a good excuse for not having a sign since it was shared space and we weren’t allowed sign-age.

In our current space, we actually lasted almost two years with this paper sign.  Not exactly glamorous but it did the job.

100_0453

This got me thinking … when is the moment that you are no longer a startup? 

A few facts about Thycotic’s beginnings:

  • We were profitable from day one.
  • Our software development consulting business has always been a stable, profitable area.
  • On the product side, Secret Server is self funded, started small and has slowly built a solid customer base.
  • The company was officially formed in 1996 but only hired its first employee other than me in 2004.

So how do we identify a change from startup to mature company?
(if it is has even really happened to us yet)

Could it be?

  • The day you finally turn off the email that tells you when someone bought your product.
  • The day the founder can take more than one consecutive week of vacation.
  • The day you don’t know how many employees are in the company (this has already happened but that is just because I have a hard time figuring it out on the fly).
  • The day that the company hires someone the founder didn’t hire or even meet.
  • The day you walk by someone in the hall you have seen often but have no idea who they are.
  • The day you are bought out by some monster corporation. (assuming you want to be bought out … which we don’t)

What would you define as the tipping point?  In the meantime, we are going to continue admiring our new sign. 🙂

 

Jonathan Cogley is the CEO and founder of Thycotic Software, a .NET consulting company and ISV in Washington DC.  Our product, Secret Server is a enterprise password manager system for teams to secure their passwords.  Is your team still storing passwords in Excel?

Can you find the bug in this code? (THE FIX)

March 26, 2008 2 comments

Thanks to everyone for contributing!  It was really neat to read everyone’s ideas and see the discussion and review (talking about code is always fun!).  Here is a summary of responses and the “fixed” code. 

If you are interested in the original problem, go here.

 

@drakiula: The idea with the Response.Redirect is that it will stop processing so the else is not needed on line 23.

@JV: Yes, this code could definitely be refactored! 🙂
And your suggestion would squish the bug.

@rajbk: Nice. Yes, the ThreadAbortException is definitely part of the bug but I don’t think the Redirect(url, false) is the best way to go.

@Basgun: Changing line 17-23 as you suggest would make it cleaner but wouldn’t fix the bug.

@cibrax,Lee:  Nice. Yes, the ThreadAbortException will cause the catch to fire everytime and redirect the user to the same page.

@Thomas Eyde: Nice. Yes, the refactoring into separate responsibilities would make it much cleaner and also would somewhat inadvertently fix the bug since the redirect would happen outside the catch.

@Zack Jones:  Nice suggestions.  Thanks!

@Hosam Kamel: Yes, good point – there are several ways those method calls could fail (lots of encryption and authentication done within them) so the catch is there as a simple default “then send them here”.

Summary:

If you call Response.Redirect(string) or Response.Redirect(string, true), it will throw a ThreadAbortException.  So if you do the redirect inside a generic try/catch then your catch will fail everytime.  As pointed out by several people above, the code could be refactored so the responsibilities are separated out – this means that the Redirect should probably only be done in one place which would mitigate the issue.

I was surprised to see that Response.Redirect throws this exception especially since this exception is not thrown up the Application_Error event so some “magic” must happen within ASP.NET to issue the HTTP location header but not allow the exception to continue as a real exception.  This seems like a misuse of exceptions since a Response.Redirect is hardly an “exceptional” case and in many applications happens somewhere on every page!
That said, it is reasonable to see how Microsoft uses this mechanism to prevent further execution in the page.

Either way, it is a good gotcha to remember!

Here is the “fixed” code:  (although this could still be seriously refactored)

01: private void Page_Load(object sender, EventArgs e)
02: {
03: string redirectUrl = null;
04: try

05: {

06:     AuthenticationInfo authenticationInfo = GetAuthenticationInfo(Request.QueryString[“t”]);

07:     Authenticator authenticator = new Authenticator(new LoginProvider());

08:     AuthenticationStatus authenticationStatus = authenticator.Authenticate(authenticationInfo);

09:     if (authenticationStatus.Authenticated)

10:     {

11:         IUser user =

12:             BLUser.Load(authenticationInfo.UserName, authenticationInfo.OrganizationCode, aut
henticationInfo.DomainId);

13:         user.SetNewSessionId();

14:         AuthenticationTokenParser authenticationTokenParser = new AuthenticationTokenParser();

15:         string authenticationToken = authenticationTokenParser.Create(user.UserName, user.OrganizationId,

user.DomainId);

16:         FormsAuthentication.SetAuthCookie(authenticationToken, true);

04:         redirectUrl = FormsAuthentication.GetRedirectUrl(authenticationToken, true);

04:     }

16: }

17: catch

18: {

19:     // If anything goes wrong (encryption error, etc) then just let it fall through to the redirect.

20: }

21: if (redirectUrl == null || redirectUrl.Trim().Length == 0)

22: {

23:     redirectUrl = “~/Home.aspx”;

24: }

25: // NOTE: If you do the Redirect inside the try/catch it will get a ThreadAbortException!

26: Response.Redirect(redirectUrl, true);

27: }

 

We are hiring!  Do you want to write beautiful code in a Test Driven, Refactored, Agile .NET software company in the heart of Washington DC and work on cool products
Take the code test and send your resume along with why you want to join Thycotic to
tddjobs@thycotic.com.

For once, not blogging wasn't my fault

March 25, 2008 Leave a comment

For the last couple of days, the weblogs.asp.net website has been unable to accept posts from Windows Live Writer.  For the first time in the history of this blog, I can blame someone else for not posting.  In fact, I even started queueing up draft blog posts! 🙂

Kudos to the weblogs.asp.net team for fixing the issue quickly.

 

We are hiring!  Do you want to write beautiful code in a Test Driven, Refactored, Agile .NET software company in the heart of Washington DC and work on cool products
Take the code test and send your resume along with why you want to join Thycotic to
tddjobs@thycotic.com.

Categories: Blogging, Fun

Can you find the bug in this code?

March 25, 2008 14 comments

This is a real bug that I came across yesterday in some code I had written about a week before.  I was a little surprised at the mechanics but it makes sense once you understand what is happening …

   1:  private void Foo()
   2:  {
   3:      try
   4:      {
   5:          AuthenticationInfo authenticationInfo = GetAuthenticationInfo(Request.QueryString["t"]);
   6:          Authenticator authenticator = new Authenticator(new LoginProvider());
   7:          AuthenticationStatus authenticationStatus = authenticator.Authenticate(authenticationInfo);
   8:          if (authenticationStatus.Authenticated)
   9:          {
  10:              IUser user =
  11:                  BLUser.Load(authenticationInfo.UserName, authenticationInfo.OrganizationCode, authenticationInfo.DomainId);
  12:              user.SetNewSessionId();
  13:              AuthenticationTokenParser authenticationTokenParser = new AuthenticationTokenParser();
  14:              string authenticationToken = authenticationTokenParser.Create(user.UserName, user.OrganizationId, user.DomainId);
  15:              FormsAuthentication.SetAuthCookie(authenticationToken, true);
  16:              string redirectUrl = FormsAuthentication.GetRedirectUrl(authenticationToken, true);
  17:              if (redirectUrl == null || redirectUrl.Trim().Length == 0)
  18:              {
  19:                  redirectUrl = "~/Home.aspx";
  20:              }
  21:              Response.Redirect(redirectUrl, true);
  22:          }
  23:          Response.Redirect("~/Home.aspx");
  24:      }
  25:      catch
  26:      {
  27:          Response.Redirect("~/Home.aspx");
  28:      }
  29:  }

.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; }

 

I will post the answer soon if no-one gets it. 🙂

 

Jonathan Cogley is the CEO and founder of Thycotic Software, a .NET consulting company and ISV in Washington DC.  Our product, Secret Server is a enterprise password manager system for teams to secure their passwords.  Is your team still storing passwords in a text file?

Don't surprise the user

January 29, 2008 1 comment

copier

You are probably getting ready to hear about some error dialog or weird setting in an application but not this time – it was a photocopier!  I was copying some printouts for a meeting and discovered midway through the job that the paper tray had fancy paper in it that I shouldn’t be using.  Not a problem, right?  Just hit the “Cancel Job” button …

Are you sure that you want to cancel this job?

CONTINUE      EXIT

I was stumped.  Does that mean “continue” to cancel the job or should I “exit” the job?  After ten seconds careful thought, I pressed “continue” and my print job continued printing! Not exactly what I expected. 🙂

 

Jonathan Cogley is the CEO and founder of Thycotic Software, a .NET consulting company and ISV in Washington DC.  Our product, Secret Server is a enterprise password manager system for teams to secure their passwords.  Is your team still storing passwords in Excel?