Saturday, August 4, 2007

Playing Favorites

Can a man favor one piece of code over another? Will the neglected code lead a life of misery because it did not know it's father's love? No, unless you're on the verge of writing some AI that needs to be reviewed before you go any further...

Over the years, I have written lots of T-SQL and .NET code. I'm always on the lookout for development language enhancements that make it easier to accomplish the same tasks with fewer lines of code. Among my favorite enhancements are sorting and filtering with C# 2.0 Generics.

Let's start with a simple Employee object:

public class Employee
{
string _firstName, _lastName;
decimal _salary;
public Employee(string firstName, string lastName, decimal salary) { _firstName = firstName; _lastName = lastName; _salary = salary; }
public string FirstName
{
get { return _firstName; }
}
public string LastName
{
get { return _lastName; }
}
public decimal Salary
{
get { return _salary; }
}
}


Let's create a Generic list of Employees:

List<employee> employeeList = new List<employee>();
employeeList.Add(new Employee("John", "Walker", 35000M));
employeeList.Add(new Employee("April", "Aagard", 45000M));
employeeList.Add(new Employee("Joann", "Wilten", 50000M));


List<T>.ForEach returns all of the items in the list:

Console.WriteLine("List all employees");
employeeList.ForEach(delegate(Employee em) {
Console.WriteLine(
string.Format("Name: {0} {1}, Salary: {2}",
em.FirstName, em.LastName, em.Salary.ToString()));});
Console.WriteLine();


List<T>.FindAll filters the list:

Console.WriteLine("Filtered by salary (where salary > 40000)");
List<employee> wellCompensatedList = employeeList.FindAll(delegate(Employee em) { return em.Salary > 40000M; });
wellCompensatedList.ForEach(delegate(Employee em)
{
Console.WriteLine(
string.Format("Name: {0} {1}, Salary: {2}",
em.FirstName, em.LastName, em.Salary.ToString()));
});
Console.WriteLine();


List<T>.Sort reorders the list:

Console.WriteLine("Sorted by last name ascending");
employeeList.Sort(delegate(Employee em1, Employee em2) { return em1.LastName.CompareTo(em2.LastName); });
employeeList.ForEach(delegate(Employee em)
{
Console.WriteLine(
string.Format("Name: {0} {1}, Salary: {2}",
em.FirstName, em.LastName, em.Salary.ToString()));
});
Console.ReadLine();


As you can see, the Generic list methods FindAll, ForEach and Sort, when combined with anonymous methods, allow you to easily manipulate your lists. Clean and simple code. No wonder it's my favorite. What code is your favorite?

Monday, July 30, 2007

Old School Keyboard Shortcuts in Microsoft SQL Server Management Studio

Want to use Query Analyzer keyboard shortcuts, like Ctrl-Shift C (comment the highlighted lines) and Ctrl-Shift R (uncomment the highlighted lines) in Microsoft SQL Server Management Studio (SSMS)? Easy. Open SSMS's Options (Tools -> Options), go to Environment -> Keyboard and change the Keyboard scheme to SQL Server 2000 and click OK.

Thursday, July 19, 2007

.NET Setup Project Custom Actions

Ever created a .NET windows service in Visual Studio, added a setup project, set all of the properties to install and display the correct information during installation, only to have the service not show up in Windows' Services Microsoft Management Console (mmc)? You probably forgot to add the custom actions.

To add custom actions to your setup project:
1) Click the setup project in Solution Explorer
2) Click the Custom Actions Editor button at the top of Solution Explorer
3) Right-click on the Custom Actions node
4) Click Add Custom Action
5) In the Select Item in Project dialog box, select Application Folder from the dropdown
6) Click OK

That's it. Right-click the setup project, and click Install. Your service should now appear in the Services mmc. Just remember to close the Services mmc before you uninstall, or undesired consequences may result. Good luck!

Wednesday, July 18, 2007

Microsoft Certified Professional Developer (MCPD) certification

Two years. It's been two years since I received my Microsoft Certified Application Developer (MCAD) certification for Microsoft .NET 1.0 and 1.1. Now, I'm studying for the MCPD certification for .NET 2.0. The practice tests are similar to the tests leading up to the MCAD, so I'm not worried about failing the test because of formatting changes. In fact, I've been programming in .NET 2.0 for nearly a year, and most of the practice questions are familiar.

Because I already have my MCAD, upgrading to the MCPD requires that I pass only one test. I have chosen the Windows developer MCPD path (test 70-552), because most of the .NET 2.0 applications that I write at work are windows applications.

The reason that I want to complete Microsoft certifications is that my employer pays for the study materials and tests, it looks good to potential employers, and hey, this is a good substitute for going back to school (who would hire me if I had a Ph.D., anyway?).

I plan on taking test 70-552 mid-late August, depending on how much time I can spend studying between now and then.

Do you have any of the Microsoft .NET certifications? Have they helped you in your career? Please post in the comments below. Thanks.

Friday, June 29, 2007

Include Column Headers When Copying the Results

In Microsoft SQL Server Management Studio, there is now an option to include column headers with the rows that you copy from the results pane. For example, when I copy the following records from SQL Server Management Studio and pasting into Excel, I now know the names of the columns:

ID First Name Last Name
1 Robert Doe


To enable this feature in Management Studio, click Tools -> Options -> Query Results -> SQL Server -> Results to Grid and check 'Include column headers when copying or saving the results' and click OK. Click on the screenshot below for a screenshot.

Monday, June 4, 2007

Secret Question Authentication Schemes

Ok, this post isn't directly related to coding, but it is related to website design. This morning I visited a credit reporting website (who shall remain nameless) to obtain my credit score. It asked for the basic info, including name, address, SSN, and b-day. Once the website had my info, the next page told me that I already had an account. Great. The website asked for my username and password. I tried a couple of usernames and passwords that I have used in the past, but no luck. Did you forget your password, the website asked? Yes, I guess so. Ok. Take me to the forgotten password page. Now it's asking for my favorite TV show as my only option for my "Secret Question." What? I hardly ever watch TV. I tried a couple of shows that I used to watch. No luck. Sorry, if you can't remember your favorite show that you never watched, I won't let you in, the website blares.

I'd say don't get me going about these subjective authentication schemes, but it's too late.
What I dislike is that the example above was based on an opinion that I had about a TV show from years ago. If a website must use a question-based authentication scheme, a better solution
would be to base the questions on facts, such as the year I graduated from high school, the mascot of my high school, my mother's mother's maiden name, and so on and so forth.

In summary, if you must use secret question authentication schemes, make sure the questions are based on facts, not favorites.

Friday, June 1, 2007

Search Only Microsoft.NET Websites

I find it annoying when I go to Google.com, search for a .NET class or error, and get a page full of websites that have the same copy of a newsgroup post. Well, for you .NET developers, there is a solution: DotNet Developers Search (http://www.searchdotnet.com). Developers Search is a custom Google search that only searches relevant websites and newsgroups.

To make it even easier, you can add DotNet Developers Search to the search bar of Mozilla Firefox and Internet Explorer.

To add Developers Search to the Firefox search bar, 1) click on the dropdown button next to the search icon. 2) Click "Add SearchDotNet".

To add Developers Search to the Internet Explorer 7 search bar, 1) click on the dropdown button next to the magnifying glass. 2) Click "SearchDotNet".

Wednesday, May 30, 2007

Get Midnight DateTime in SQL

Here's a quick and easy way to get the midnight timestamp for the current day:

SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)

For more tricks on calculating SQL DateTimes, see http://www.databasejournal.com/features/mssql/article.php/3076421

Thursday, May 24, 2007

Prevent page caching in ASP.NET

Having problems with the client caching pages in ASP.NET? Put the following three lines in the Page_Load event handler in your forms:

Response.Expires = 0
Response.Cache.SetNoStore()
Response.AppendHeader("Pragma", "no-cache")

Thursday, May 17, 2007

Branching in Visual Studio 2005

Ok, so I'm new to branching code. Lucky for me, I'm using Visual Studio Team Foundation Server at work. Here's what I have found so far:

There's a great but lengthy article named 'Team Foundation Server Branching Guidance' at http://www.codeplex.com/BranchingGuidance. I'm going to summarize the article here, to help myself and others quickly get up to speed on branching in TFS.

Definition of branching: a branch is a self-contained snapshot of the code that has access to all of the required sources, tools, dependencies, and process automation. Branching is synonymous with isolation. Two branches are created when branching: the parent and the child. The parent is the original source code, while the child is the copy of the source code. After changes have been made, the source code copy (child branch) can be merged or integrated back into the parent branch.

There are multiple levels of isolation in TFS:

  1. Isolation on an individual level


    1. Implemented in Visual Studio 2005 using source control workspaces

    2. Workspaces are mapped to and managed by TFS

    3. Allows the developer to shelve their code


  2. Isolation for collaboration


    1. Managed on the server

    2. Allows teams of developers to work on a child branch of source code



Branching occurs in a TFS "path space", which is like copying a folder in Windows Explorer. The benefit that TFS provides, though, is it maintains the history of the child branch to the parent branch. This allows TFS to merge changes that are made in both branches.

New branches appear in the Source Control Explorer just like other source code. When you need to work on another branch, just get that folder in the Source Control Explorer.


Creating a Branch


  1. Open the Source Control Explorer in VS 2005

  2. Right-click the folder you would like to branch in the folders treeview

  3. Click Branch...

  4. Type a name for the branch in the Target textbox

  5. Choose to branch by date, label, or the latest server version

  6. Click OK to create the branch



More info on branching: http://msdn2.microsoft.com/en-us/library/ms181423(VS.80).aspx


Merging

Merging combines the source code of the child and parent branches. In files where changes were made to only the child or to only the parent, TFS will combine the changes automatically. When source code is modified in the same files, a version conflict will be filed, and the changes will need to be merged by the developer using TFS's merge tool.

To Merge:

  1. Open the Source Control Explorer in VS 2005

  2. Right-click the folder you would like to branch in the folders treeview

  3. Click Merge...

  4. Browse to a Source branch

  5. Choose 'All changes up to a specific version' or 'Selected changesets'

  6. Choose an item in the Target branch dropdown

  7. Click Next for more options or Finish to begin the merge process



Branching Scenarios

  1. Release Isolation


    1. Allows the developers to work on multiple releases in parallel


  2. Feature Isolation


    1. Used when new functionality may introduce risk

    2. Allows developers working on new functionality to collaborate without exposing the rest of the application to instability


  3. Team Isolation


    1. Used to shield one team from being subjected to another team's breaking changes


  4. Integration Isolation


    1. A new "integration branch" is created that serves as a staging area for merges

    2. The "integration branch" is not used for development

    3. Changes from other branches can be merged into the integration branch and then stabilized

    4. Once the integration branch is stable, the changes can be merged back into other branches




What is your experience with branching in TFS? Please post in the comments below.

Update (6/15/2007):
I have now successfully branched my first piece of code. We have a project at work that has a production release (version 2.4.9.1) that has been in use for a while on the floor. Since version 2.4.9.1 was released to production, we have added a large number of features, and the testing version is up to version 2.4.15.1. We found a major bug in version 2.4.9.1, and, instead of attempting to fix the bug in version 2.4.15.1 and releasing an untested version with a couple of month's worth of code changes, we branched 2.4.9.1 and created 2.4.9.2. The branched version quickly passed tests by the quality assurance department, and was released to production. A few days later, we talked to the business users, and they reported no issues with version 2.4.9.2.

Introduction

Welcome to Bug My Code. This blog will focus on the following topics: MS SQL Server, C#, MS Visual Studio, and whatever other tools and languages I am using in my software development.