Archive

Archive for the ‘programming’ Category

Back To Basics - Container.DataItem

June 16th, 2008

Since asp.net 2.0 was in beta, I pretty much bailed on .NET 1.1 and Visual Studio 2003 and I’ve been pretty happy that way.

One of my favorite features in asp.net 2.0 (it’s a long list after working in 1.1) was the shortened syntax for declarative databinding to objects using Eval(”propertyname”) where “propertyname” is, well, a property in the object being bound to the control. This works when binding to a collection of objects where the values you want to use are stored in properties of the object. What about simple types such as integers or strings?

It’s pretty easy to bind a databound control to a collection of simple types such as a List<string> or a string array but since I don’t do it very often, I have to stop and remember (or look up) how to do it. So for my own reference and anybody else that may find this useful, here is a simple code example:

<ul>
  <asp:Repeater ID="rptSampleStrings" runat="server">
    <ItemTemplate>
      <li>
        <asp:Label runat="server" ID="lblStringDisplay"
          Text='<%#Container.DataItem %>' />
      </li>
    </ItemTemplate>
  </asp:Repeater>
</ul>

Here I have a repeater that will render a bulleted list of items from my List<string>. Notice the use of Container.DataItem for the text property… this is the point of this post. This is the syntax I always have to think about.

This is just to illustrate a point, I know I could use a ListView or the BulletedList control to do this. Anyway, here is the code-behind that creates the List<string> and binds it to the repeater (this code is in the Page_Load event handler):

var sampleStrings = new List<string>();
sampleStrings.Add("Test One");
sampleStrings.Add("Test Two");
sampleStrings.Add("Test Three");
sampleStrings.Add("Test Four");
sampleStrings.Add("Test Five");

//Set repeater datasource
rptSampleStrings.DataSource = sampleStrings;
rptSampleStrings.DataBind();

So, as you can see, it’s very simple to bind control properties to a list of strings, integers, etc. as long as you can remember the syntax.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

.NET, ASP.NET, Back to Basics, programming , , ,

CSI NY and Visual Basic

May 14th, 2008

“I’ll create a GUI interface with Visual Basic…”

This is a partial quote from a character on CSI NY. To set the scene a bit, there is a blogger being held hostage by a serial killer and being forced to blog while in captivity. The blog is being updated periodically while they are looking for the killer, and the “GUI interface” is intended to track down the location of the blogger (and killer) by IP Address.

Seriously? You need to find a killer who is currently holding a living hostage and a crime scene investigator is going to go just whip up a quick VB app to solve the case?

No wonder people think software development is easy!

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Thoughts, programming

MyBlogPost

April 23rd, 2008

A few years back, I was working on an ASP.NET project and in order to help me meet the tight deadline, my boss brought in a consultant. We’ll call him John. John had done some work with the company before I had started and was available at the time, so the decision was made and he came in and started working. I went over the requirements and the design for the app. I assigned him a portion of the app to start working on and went about my work. A couple days into the project, I asked how he was doing and as I was talking to him I glanced over his shoulder at his monitor and I couldn’t believe what I was looking at. There was a variable in his code-behind file called “MyDataSet”!!

I think my head almost exploded! I asked him about it and did an informal code review, at which point I asked him to update his variable names and to make them more meaningful. I was going to be responsible for all of the code once it launched and I had no interest in trying to interpret the variable and control names. A week later, there were still instances of “MyDataSet” and “MyTextBox” all over the code. Needless to say, he didn’t last long on that project, and I spent a couple of late nights “fixing” the code so I would be able to understand it.

So where did the “my” prefix come from? In his case, it came from books and the msdn site. I saw it just today in a demo, hosted by Microsoft and produced by a Microsoft employee…

When Microsoft and the authors of technical books put together demos, there is typically a contrived scenario that they are supplying code for. Why can’t they look at the code and the scenario and come up with some meaningful variable names? Why does it make sense to name a texbox intended to accept a username, “myTextBox”? Why wouldn’t you call it “UsernameTextbox” or “txtUsername” or just “Username”?

In simple examples, this can be annoying, in larger ones, it can be thoroughly confusing. When taken seriously by a new developer, it can have more severe consequences.

What happened to the naming standards and best practices? What about self-documenting code?

I’ve probably been guilty of this once or twice, in my early years of teaching .NET, but I probably caught it from a book.

It doesn’t take much effort to use more meaningful names and the development community leaders, especially those working for Microsoft, should be held to a higher standard. I propose a ban on using “my<Object Name>” as variable names.

Who’s with me?

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

.NET, C#, programming , , ,

Unit Testing as a Method to Enforce Requirements

April 10th, 2008

I have recently started putting a lot of stock in automated unit testing. Not that I didn’t think unit testing was important in the past, I just didn’t know how to write them properly. A little instruction from a co-worker has corrected that situation and I am now writing proper unit tests. I like the test first approach, though I don’t know that I’ll be doing the full “TDD, no code without a test” thing just yet, but at the moment, I am writing tests first. Only time will tell if I can keep it up throughout the life of my project.

I recently ran into a situation that made me see some additional value in my tests. Beyond making sure everything works properly and lives through changes to the application, I am starting to see how my tests keep me in check and make sure I don’t stray from the requirements.

As an example we’ll assume we are testing classes from an application’s business layer. Each class in this layer will inherit from an abstract base class called “ServiceBase”. In this case, the ServiceBase is a generic class with some abstract members, but it also contains implementation code for a Save method.

The Save method accepts a business entity as an argument and decides whether to call Insert or Update in the underlying data access class. If the value passed in is null, the method throws an exception. This behavior is pretty standard, but some classes that inherit from it may have a need to perform some additional steps when saving. To account for this, I have also made the Save method virtual so any implementation that needs to can override the Save method.

Now we will create a couple of subclasses for ServiceBase. Let’s call them ProductService, CustomerService and OrderService. To start we create the ProductService class and make it inherit from the ServiceBase class. Now in order to make sure we have a complete set of unit tests, we create a test that expects an exception if a null item is passed to the save method. As long as the ServiceBase class throws the exception, it will pass for our test against the ProductService class. Now if we repeat the process (including the test) each class (ProductService, CustomerService, and OrderService), they will all have the ability to save an item, and each test that expects the exception should pass.

Now, let’s say the ProductService class has a need to write to a log when its Save method is called. This is easy, all we have to do is create an override for the Save method in our ProductService class. We add our logging code and all is good. We run our test and it fails.

Why did it fail? Because in my contrived story, we forgot to add the code that throws an exception if a null value is passed in. This is an honest mistake, but it’s ok because our test has saved us. This type of requirement cannot be enforced by the compiler through an interface or abstract base class. As far as the compiler is concerned, this code is completely valid. The unit test however, has alerted us to the fact that we did not implement the code according to our requirements (which was the basis for writing the test in the first place).

While this may be a no-brainer for those of you who have been practicing test driven development or just writing solid unit tests for a while, but for those of us who are just starting down this road this is an added benefit that may not seem obvious at first.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

.NET, C#, TDD, Unit Testing, programming , ,

Forcing an “open, save” prompt for known file types

March 31st, 2008

This was originally posted on vanslaars.com in December of 2006. It seemed pretty popular so I wanted to make sure it made it up on the new one.

Ever want to provide a link for a document that the user should download even though it will want to open directly in the user’s browser? Well, this isn’t as hard as you might think. Basically, all you need is a way to get some indirection between the clicking of the link and the transmission of the file to the user in order to tweak the response headers a bit. Using an HttpHandler makes this a breeze.

For this example, we will use a “.ashx” file, rather than creating a seperate HttpHandler assembly and registering it in the web.config, this way you can just drop the code in a file and see it work. I would highly recommend the Class Library approach for a handler that will be useful in multiple projects.

The basic project setup for this includes a directory in the root of my application called “PDF”, which holds a sample PDF document, the standard Default.aspx page and a “.ashx” handler file called “PdfHandler.ashx”. The code that will perform the file retrieval and force the dialog to appear is all in the “.ashx” file and the Default.aspx file will simply hold the following link code for testing purposes:

<a href="PdfHandler.ashx?fileName=css_cheat_sheet">Download CSS Cheatsheet</a>

As you can tell from the link, we will be calling the .ashx file from our link with a parameter called filename. The path and file extension for the file are not included since we want to limit the amount of information that is available in our querystring for the link.

In the Handler file (”PdfHandler.ashx”) we will add the following code to the “ProcessRequest” method:

string fileName = context.Request.QueryString[?FileName?];
if (!string.IsNullOrEmpty(fileName))
{
string filePath = context.Server.MapPath(string.Format(?~/PDF/{0}.pdf?,fileName));
context.Response.ContentType = ?application/pdf?;
context.Response.AddHeader(?Content-disposition?,
string.Format(?attachment;filename={0}.pdf?,fileName));
context.Response.WriteFile(filePath);
}

This code simply grabs the filename from the querystring, uses it to get the full path to the file through the MapPath method and then uses Response.WriteFile to send the file back to the user. This is not what I would call “production ready” code, but this is not the point of this example. The point here is the Header that is being added to the Response. The line that uses the AddHeader method is where the dialog comes in… setting the content-disposition to attachement and specifying a default filename will cause the browser to prompt the user to save the file. Without this, the PDF would be opened in Acrobat.

This is pretty simple to do, you just need to remember the proper syntax for the header since there is no strongly-typed way to set this through the Response object.

The first time I had to do this was in .NET 1.1 with a text file a few years back and it took quite some time to find the information, so hopefully this has made your life a little bit easier.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

.NET, ASP.NET, C#, programming , ,

A Bit Rusty, But It Could Be Worse

February 5th, 2008

I’m just wrapping up with work for the day. I am just into my second week on the job and I am already knee-deep in a project.

My last position had me working in .NET 1.1 (though I did some .NET 2.0/Visual Studio SDK Stuff towards the end). I worked on a product that had been written years before and there was very little need to think about what I was doing. It seems I experienced a bit of brain rot in my 6 months there and I’m feeling it now.

Today I am working with C# 3.0, LINQ to SQL, SQL Server 2005(sometimes) and Visual Studio 2008. My coding skills have gotten a bit rusty… ok, very rusty! It’s coming back to me and after re-writing the same 5 lines of code about 20 times today (I may be exagerating a little), I started seeing code that I was happy with. I’ll get back to normal soon enough and the rusty-ness will be a distant memory.

While having a tough time getting back into the swing of things kind of sucks, It could be worse. I was reading Rob Conery’s latest post, and it reminded me of stuff I wrote 5 years ago. Scary stuff! It wasn’t all bad, but I’m sure if I had the opportunity to comment on that code now, it wouldn’t all be nice.

At least I can feel a little better knowing that the code I wasn’t happy with today was better than stuff I wrote years ago.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

programming , ,