Brendan Enrick

Daily Software Development

Converting an Array of Integers int[] to an Array of Strings string[]

I was working on a code snippet I plan to put into a blog post, and while writing it I needed to convert and array of integers to an array of strings. I try to think of a quick easy way to do this and none comes to mind. Well, I of course know that I could just loop through them and convert them from ints to strings, but that is really lame especially when I want the code to be small so I can put it in a blog post.

So there are a few options that present themselves when you are looking for a method to help you out.

  • Write your own method to solve the problem. (I try to only do this as a last resort. I try to use existing code when possible.)
  • Ask Google (or any other search engine) for answers posted on forums, blogs, articles, documentation, etc.
  • Go ask/search on a forum or a Question and Answer site.
  • Use intellisense and check some related classes which may hold the answer.

In this instance I used the last one. I checked out some classes using intellisense to see what methods were available. I was working with arrays, so the one I checked is the Array class. Array.ConvertAll is what I needed.

var intArray = new[] {1, 2, 3, 4, 5};
string[] stringArray = Array.ConvertAll(intArray, i => i.ToString());

That is roughly how I am using it in my code. Notice the nice lambda way of handling the individual object conversion. You can also solve the problem using a full-fledged method call. I just chose this to keep things more compact.

Here is an example using a method to hide the lambda and do the conversion.

static void Main()
{
    var intArray = new[] {1, 2, 3, 4, 5};
    string[] stringArray = Array.ConvertAll(intArray, IntToStringConverter());
}

private static Converter<int, string> IntToStringConverter()
{
    return i => i.ToString();
}

As usual there are still many other ways to do this, but I'll show you one that just has way too much unnecessary code.

I don't recommend using this example since it really just specifies way more than it needs to. I am just including this to illustrate the many ways to have solved this problem using this same method.

static void Main()
{
    var intArray = new[] {1, 2, 3, 4, 5};
    string[] stringArray = Array.ConvertAll<int, string>(intArray, 
        new Converter<int, string>(IntToStringConverter));
}

private static string IntToStringConverter(int n)
{
    return n.ToString();
}

Why don't I really like that one? Well to be honest I intentionally made it bad. The "new Converter<int, string>()" part is completely useless. You can remove it completely and the code still works, because we specified already that we are doing int to string. We alternatively could have removed the first <int,string>.

Although if I were using an older version of C# I would be forced to use the last one, or I could also use a combination of the second and third one.

Well, we're out of time here today. I hope you've enjoyed this edition of Finding Stuff Using Intellisense. This is your host, Brendan Enrick. We've been glad to have you with us today. Join us next time when we....  Find Stuff Using Intellisense. {queue the ending theme music}

Parameter Order Should Be Consistent

I was looking at a piece of code recently and noticed that someone was checking for a null parameter and throwing an ArgumentException, so I figured since ArgumentNullException inherits from ArgumentException I would just replace it with the more specific exception. Little did I know that Microsoft has a wee little bit of a problem with consistency on these.

With ArgumentExceptions it is important to have a message as well as specify which parameter is causing the trouble, so there are 2 string parameters in the ArgumentException constructor. What you might not know if you haven't switched one to the other is that they changed the order of those parameters. What I mean is that you call them like this.

throw new ArgumentException("The Message", "paramName");
throw new ArgumentNullException("paramName", "The Message");
throw new ArgumentOutOfRangeException("paramName", "The Message");

How can they possibly switch those?!?! If I am not mistaken the lower two exceptions actually inherit from the first one, so it is quite surprising that the ordering was not maintained in the second two. I need to keep an eye out for other such inconsistencies while I am working. They obviously can't easily fix it now, because too much code depends on the current ordering. I try to maintain consistence parameter ordering, but I am also not working on a framework.

ASP.NET Supports Valid HTML Attributes in its Tags

While reading an article, I came across a misconception that seems all too common with people using ASP.NET, and they need to stop trusting intellisense!!! I love intellisense, but you can't trust in it entirely. It doesn't know everything, so as a rule, I will state that if html supports something... SO DOES ASP.NET!

So now that I am done ranting I first want to say I am not intending to bash the author or the publisher site. Both have some great content and are valuable to the .NET community. I simply want to step in and provide some clarity by providing some explanation and an alternative solution to the problem. The article is about adding a tooltip to individual items in a dropdown list. There are plenty of reasons to do this, including the one the author states which is that the list might have a fixed width and will display badly in IE. Below is an example of a DropDownList with this problem.

SmallDropDown

That is a terrible UI problem right there. I personally prefer the way Firefox handles this situation, but aside from that we might want to use a tooltip anyway.

GoFirefox

The thing that seems to throw everyone off is that some ASP.NET controls don't seem to have many properties when you look at intellisense. A lot of them don't include style, title, or some other commonly used attributes. THEY ARE STILL THERE!! Underneath the hood ASP.NET is basically just the HTML you know and love. So when you go in and try to add the title attribute to a ListItem, you will not see it in the intellisense box.

TitleNotInList

The article suggested doing a foreach loop over the Items in the DropDownList and edit their title property. Well, you can actually just set the title property. ASP.NET will give you a warning about it because it isn't an ASP.NET attribute, but it will work.

ValidationMessage

I would also like to mention that this also works with the style attribute. I've heard plenty of people complain that some controls don't support the style attribute in ASP.NET. If their underlying HTML control supports a tag it supports a tag. For this example since the option tag supports the title attribute it means that the ListItem of a DropDownList also supports the attribute.

DropDownWithToolTip

In his article he does one great thing showing people that it is very easy to make changes to the html by simply using the Attributes collection of any control in the code behind an ASP.NET page. Using this allows us to alter any attribute we wish. One thing  you need to be careful of is the ease through which we are able to add duplicate attributes or cause other problems by this.

In his article he uses the following line of code to add in the title attribute.

_listItem.Attributes.Add("title", _listItem.Text); 

If the above code were to somehow run twice it literally would add two separate title tags into the HTML which is not always the best way of handling things. Just figured I would throw this out there so people have a better understanding how the connection between ASP.NET and HTML. Some people try to separate ASP.NET as some new thing when at the end of the day it is really just creating HTML. Don't let ASP.NET be mystical, it is relatively easy to understand if you just read articles and blogs. Be curious and questioning of everything. Yes, I mean for you to question what I tell you also. Plenty of things I write over a long period of time will be questionable and some will just be outright wrong. Everyone will do it. Yes, even people writing documentation.

Party with Palermo

If you've ever gone to a conference and not known what to do on the first night, you should check out Party with Palermo. Hosted by Jeffrey Palermo, these parties are a good time. Free finger food, free swag, and free drink. The next one is for Alt.Net and the MVP Summit. On the first day of March 2009 from 7:00 PM until 10:00 PM the party will be at Jillian's 731 Westlake Ave N, Seattle, WA 98109.

The event is fun and easy to attend. Palermo wants people to RSVP on his site. Even if you don't respond, you can still show up. The price of admission is one business card. It is easy and will give you a fun event to attend.

If you are not going to be there at that time, don't worry there will be other parties with Palermo later.

Party with Palermo

Validating Entity objects

While working with an entity object I wanted to validate, I took some time to do some Googling. I was planning on creating an IValidator<T> interface so I could keep the validation separate from my classes, and I was going to implement this interface for every entity that needed it. Since validation is pretty common I figured I would take a look around first to see if there were some good ways of performing validation which differed slightly from how I had done things previously or offered any insight on a good solution similar to what I mention above. I found a link to a blog post that had exactly what I was looking for. It turns out that Jimmy Bogard already had a great post on this topic. His post, Entity validation with visitors and extension methods, demonstrates a very cool IValidator implementation.

He combines a couple of cool interfaces to get this working. He uses an IValidator<T> interface like I mentioned I wanted to use. His implementation of this is pretty nice. (I made a slight adjustment to it here, because his example code had a bug.)

public class OrderPersistenceValidator : IValidator<Order>
{
    public bool IsValid(Order entity)
    {
        return BrokenRules(entity).Count() == 0;
    }

    public IEnumerable<string> BrokenRules(Order entity)
    {
        if (entity.Id < 0)
            yield return "Id cannot be less than 0.";

        if (string.IsNullOrEmpty(entity.Customer))
            yield return "Must include a customer.";

        yield break;
    }
}

 

I look at this an see a fairly nice and elegant solution to the validation problem. He also has an IValidatable<T> interface he uses, which is nice because it sets up a method to pass in the IValidator to use.

public class Order : IValidatable<Order>
{
    public int Id { get; set; }
    public string Customer { get; set; }

    public bool Validate(IValidator<Order> validator, out IEnumerable<string> brokenRules)
    {
        brokenRules = validator.BrokenRules(this);
        return validator.IsValid(this);
    }
}

So I think this code is pretty cool, but the only thing that was still irking me about this code is that now I would have to pass the IValidator object in to the Validate method of the entity. I really don't want to have to pass those in, so I start thinking about how to get around that problem. Well then I just read a little further in his article. He has a very nice solution to this problem using an extension method on a Validator class. (I adjusted this snippet slightly also, because it too had a bug.)

public static class Validator
{
    private static Dictionary<Type, object> _validators = new Dictionary<Type, object>();

    public static void RegisterValidatorFor<T>(T entity, IValidator<T> validator)
        where T : IValidatable<T>
    {
        _validators.Add(entity.GetType(), validator);
    }

    public static IValidator<T> GetValidatorFor<T>(T entity)
        where T : IValidatable<T>
    {
        return _validators[entity.GetType()] as IValidator<T>;
    }

    public static bool Validate<T>(this T entity, out IEnumerable<string> brokenRules)
        where T : IValidatable<T>
    {
        IValidator<T> validator = Validator.GetValidatorFor(entity);

        return entity.Validate(validator, out brokenRules);
    }
}

 

This Validator class reminds me a lot of IOC stuff. You register a validator with the entity type it validates. This lets you set up which validators each class needs so you don't have to specify on use. It also provides a nice extension method which allows you to call the validate method without having to pass in the correct validator. It will use the one it has registered for that entity type.

Great solution in my opinion. Now I am going to add his blog to the blogs I read. I hope some of you do also.

My Article is Popular

As last year was coming to an end I wrote an article on ASP Alliance. Well now to my surprise, my article explaining very simply what the MVC pattern is and why it is useful, has become relatively popular. I wrote the article, because I talked to a bunch of people and they didn't really seem to understand the MVC pattern, what it did for them, or why they should use it. Setting out my goal was to write an article to help people understand exactly that. I am sure there are plenty of ways in which it could have been improved, but I think it turned out pretty well.

How do I know the article is popular? It is currently listed as one of the popular articles on the ASP Alliance home page. As of writing this blog post, that article has had 3964 views in the past 10 days. Not too shabby I'd say since the article is not new. I have noticed that posts usually get more traffic right after they're written. I believe this is because search engines find them and list them higher for a while because they are newer.

So I took a quick screen shot of the list of popular articles, so my readers could see the fame I've reached....

PopularArticleList

Just to show my enthusiasm about this feat, I've taken the same screen shots and added some Batman-style onomatopoeias. This will let everyone know that my blog posts are knocking out other ones to get to the top... or save Gotham... or something like that. Enjoy!

PopularArticleListBatmanStyle

Have a great day. I hope everyone enjoyed reminiscing about their childhood batman-watching days.

Tune in for the exciting conclusion on a different blog time on the same blog site. (yes, I mean here later)

Write a Test Before Fixing a Bug

As I've said in previous posts, it is important to write tests for your code. A lot of the time I am talking about when refactoring code or when writing new code. Now I agree that bug fixing could be considered refactoring, but people seem to treat it differently. When fixing bugs they want to go in and quickly make the bug go away. That is a dangerous way to solve things, because it doesn't prevent the bug from returning.

If a bug exists in your system then there are test cases missing from the system. When you fix a bug, even if you do write a test case to handle the bug how do you know you've tested the right thing? If your test is not right it will not prevent the bug from returning. I know of only one way to be fairly confident that a bug is tested well. The test needs to be written before the fix. If it isn't written first you will not know. If you follow the TDD practice of Red, Green, Refactor, the Red lets you know that you've found the bug. Then when you make it green you can have confidence that you've fixed the bug.

RedGreenRefactor

If you had not tested first you don't even know that your test is accurate. How do you know you actually found what is causing the bug? You can't really be sure with any confidence, because all you saw were green tests. Your test couldn't fail. Either the test didn't actually test the bug or because you fixed it. You hope the latter, but it could be the former.

GreenGreenRefactor

This will not work. For other things I can agree with you that you can write code and then test it, but not for bugs. With bugs the test needs to be written first, so there is some confidence that the bug is being tested. Since code already exists the test needs to be in place first. This same practice should be adhered to when doing refactorings of working code as well. The point in that case is also to prevent software regressions caused by the refactoring. Tests help you hold existing functionality, and in the case of bug fixing they help to ensure that the bug has truly been fixed and tested to prevent a return.

Software bugs are like bad musicians. If you don't actively prevent them, they will make a comeback.

Example

As an example of this. We can assume that we have two classes. One of them is called Student and the other is called Course. To represent this example we are going to have some badly written code which is going to cause us to have a few nasty bugs (Badly written code makes for easier examples). From our knowledge  of the domain, we know that students take a few courses at a time, so there is a collection of courses associated with a student.

Say our student has a property called Courses and that property holds the collection.

public class Student
{
    public int ID { get; set; }
    public List<Course> Courses { get; set; }
}

Now we say that somewhere we are caching the Student objects based on their IDs. We want to make sure that if the student object is changed that we expire the cache, so we will cache it with a SqlCacheDependency on the database table for the Student object.

Assume we have a "View my courses" page for the student to get information about the courses. For ease, it will obviously grab the student object out of cache and use its collection of courses to display the information if the information is already there.

What bug have we created here?

Well we've now made it so that if any of the courses change this change will not be reflected on the courses page of any student currently in the cache. There are literally probably a dozen ways of fixing this bug. Plenty of ways we could have prevented it, but then we wouldn't have this nice example now would we?

All I am saying is that some unit tests and integration tests be written for these before we fix the problem. This lets us be sure that we've fixed the problem correctly.

The first test I would write is one that loads a student object (making sure that is gets cached) and then separately loads one of the courses the student is in and alters that course. I would then make sure that the change to the course succeeded and then I would get the student again, (it would come out of cache this time) and I would verify that it had the change I made to the course. I would expect that the first time I run it that the test will fail. If it doesn't fail, or fails for a reason other than what I expected, I need to fix it so it fails the way I expect.

Once it is failing correctly I can adjust the code to make it work correctly. I would call this an issue violating the single responsibility principle, because the Student object in my opinion shouldn't be holding a local copy of the Courses. If it doesn't have that then it will not be able to cache it. I think that property should just be a getter calling through to some Course-related class which can cache it if it wants to. Even though these are obviously domain objects, we should try to keep them separated a little bit better, because keeping them too close can cause some annoying bugs.

As always, have a great day, and keep testing your code.

Handling msbuild File Paths in Visual Studio Project Files

Yesterday, a co-worker of mine and I were working on a task which required that we work in the xml of a Visual Studio project file. We were setting up a target with an exec statement, and ran into a little annoyance. The file we were trying to execute was in a folder with a space in the name.

If we were typing this into a command prompt window it would be easy. We would simply wrap the statement in quotes. Working in the project file our brains sort of stopped working. We tried to find a way to escape the spaces in the file path. Instead of doing this in the end we used the xml encoding for a quote. We used &quot; to wrap the path in quotes. Yipee everything worked!

Today we were doing some similar work, and ran into another problem in these files. We want our msbuild stuff to work with both 32-bit and 64-bit machines. The code we are calling is always 32-bit, so we need to use a different file path depending on which type of machine we are using. We found this post on stack overflow from a person who found a way to specify the 32bit directory for program files in msbuild. The post on there is asking for a better solution, so I will also ask people to provide a better solution.

This is how Wimmel solved the problem.

<PropertyGroup>
  <ProgramFiles32 
    Condition="Exists('$(PROGRAMFILES) (x86)')">$(PROGRAMFILES) (x86)</ProgramFiles32>
  <ProgramFiles32 
    Condition="$(ProgramFiles32) == ''">$(PROGRAMFILES)</ProgramFiles32>
</PropertyGroup>

<Exec WorkingDirectory="src\app1" 
  Command='"$(ProgramFiles32)\doxygen\bin\doxygen" Doxyfile' />

All he did is create a variable called ProgramFiles32 which would contain one of two file paths depending on whether the (x86) program files exists. He then uses that variable in his file path. It works reasonably well, and since I am not concerned with running this in any language other than English I am not too concerned with any problems which might arise from this. If this bites me down the road please point me back to this blog post.

Change Local SQL Server Used By Visual Studio

A while back I ran into a problem when setting up SQL Server on a computer and using it along with a database project in Visual Studio. It isn’t really a big deal, but I needed to change which locally installed instance of SQL Server I was using by default with Visual Studio. Since I blogged about this previously it is a very nice reference for where to find that setting should the need to change it arise again.

Today I just sat down at a computer which had Visual Studio pointing to a SQL Express instance. Yesterday I installed SQL Server on the computer, so I went to change to the new SQL Server instance. What was my first step? I Googled for my blog post I’d previously written, because I knew it had nice screen shots to show me exactly what I was looking for.

I simply searched for, “change database Brendan Enrick”. The top hit on Google was my previous post explaining how to change the SQL Server Instance for a Visual Studio Database Project. As I mention in that post, I expected the setting to be DB Project specific not VS specific. Now I know better, and I just use the blog post for a quick solution.

Step one is to go to the Tools menu in Visual Studio and choose Options…

Change SQL Server Instance Menu Selection

Now that the Options windows is open in the left side navigation tree select Database Tools and then Design-time Validation Database. Once that screen is visible there is a text box to change the SQL Server Instance Name. Set that to the name of your desired SQL Server Instance. In my case the default one, so I erased the existing value.

Change SQL ServerInstance Options Change

 

 

 

This is one of the big reasons why I am a strong believer in blogging. It is a quick easy way to get this information out for others to use. Posts like this often get a few comments of thanks from people they helped. If helping others in the development community is not enough of a reason, you also always have a record to help you if you run into the same problem again.

Earned My First MVP Award

A couple of days ago I received an email informing me that I received the 2009 Microsoft® MVP Award.

Thanks Microsoft. I am very honored.

Thank you everyone who reads the articles and blog posts I write as well as the other things I am involved in.

I hope everyone has a happy new year. Everyone at my office should not worry, because I am not really going to uphold the random resolution I mentioned in my previous post.

The year 2009 is turning out well. I hope everyone has enjoyed their first couple of days of the new year.