Web.Config Basics pt 1

by percent20 2/6/2008 11:59:00 AM

One things that has always been utterly confusing in ASP.NET is the dang Web.Config file.  For the beginner to ASP.NET it makes next to no sense and Visual Studio adds a whole bunch of stuff to it that I have no idea what it does.  It is also so odd and confusing if I want to do basic config stuff in my application I have no idea how in the world to go about it. 

Partly out of necessity and partly to rid myself of not knowing how the web.config works I have been spending time learning about it.  I am first starting out with the basics.  Getting something to work.

Getting Started

With most things I want to learn I completely bypass the "how" at first and get something basic to work, which is usually a "Hello World".  That is what we are going to work on in this post.  Lets just see something work.  So these are the two objectives:

1) Set a configuration option we can use in our code
2) Allow for debugging our ASP.NET application

Now, we don't "need" a web.config to run basic .aspx pages, but if you want to anything more advanced than a one page site then you will need one.

Web.Config

Here is our web.config that we are going to look at today.

CropperCapture[45]

This is really all we need to set a configuration option to access in code and to allow for debugging our application.  Please notice that everything is wrapped in:

<configuration>
</configuration>

That is important to note because all your config information should be under the root configuration node.

Custom Application Configuration

Next we have where we will set configuration options.

<appSettings>
     <add key="Hello" value="World" />
</appSettings>

In the appSettings is where you will put configuration options that are like global variables to your WHOLE asp.net application.  So in this case you will access the Hello key and it will return the world as its value.  So the code you would use to access the config options is:

CropperCapture[48]

You will use ConfigurationManager object which access all the information in your web.config file.  Since the Hello key is in the <appSettings> node then you would use AppSettings collection to access what key value pair you need.  In this case accessing hello and it returns world.

Why would you ever need to use this? Well one things comes to mind.  You might have a membership system that you want to turn on and off so you could have in the web.config:

<appSettings>
    <add key="Membership" value="false" />
</appSettings>

In your code you might have it check to see if it is true or false if true then it displays login stuff for people to register and login if false it doesn't display it. It might look something like:

If(ConfigurationManager.AppSettings["Membership"] == "true")
    //display login control

This is just a possibility of something you might want to do.

Debug

<system.web>
    <compilation debug="false" />
</system.web>

Here we set whether we want to debug our application or not.  I usually set this to yes as I have yet to write a bunch of code with out a bug.  All you need to do is to change false to true and you will enable debugging in your asp.net application.

Conclusion

The web.config file is actually a little more simple than it appears once you understand more of what is going on with it.  If you take learning it slowly and one little step at a time it is quite possible.  I hope to cover a little bit at a time of the web.config as I learn more and more since it is quite important to learn.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | ASP.NET

Eval in DataList, DataGrid, and Repeater

by percent20 1/24/2008 2:09:00 PM

Yesterday in the "Coolness of SubSonic" post I had a bit of asp.net markup (as I call it) that would display data in a data list from the data source.  It specifically used.

<%# Eval("Name") %>

For a long time I have wondered how that worked I could never seem to figure it out until yesterday.  Basically, you have an object that you bind to the data control like a datalist.  In the case yesterday it was a Product class Object:

Well in the asp.net markup that we have below:

Notice in the Eval part it uses Name also notice from the product class above there is a name property.  What ever property the object has you can use that in the Eval and it will display the data in there that comes from our collection of objects.  In this case the Name property of our collection of Product Objects.

I know this wasn't a "cool" post, but it is something I was excited to finally understand so I thought I would post on it to help others understand hopefully.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

.NET | ASP.NET

Coolness of SubSonic

by percent20 1/23/2008 5:17:00 PM

From my last post SQL Parameters in C# I mentioned that I wanted to learn an ORM package.  Well I took a quick glance at NHibernate and got overwhelmed and decided to take a look at SubSonic as I have heard a lot of good things about it.  Well I am happy to say I doubt I will EVER do database access by hand ever again if I can help it.  As such I figured I would make a code post on some SubSonic code.  I am not really going to explain it just want to show you how easy, cool and simple it is.  I'll show the code starting with my .aspx main aspx page code, the code behind then the data access layer code.

.aspx Code

Code Behind

DataAccess Class

Product Class

I am also including the project I used too.  Be sure you have Northwind database.

I suggest you download, install, and start using SubSonic.  It is a great framework to help generate and create your DAL.  Once you have it I suggest you watch the screencast on the using the Query Tool.  If you would like me to explain this code i'd be more than happy to just let me know and I'll make another post.

SubSonicTest.zip (188.54 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | Sql Server

SQL Parameters in C#

by percent20 1/21/2008 7:03:00 AM

Until I figure out how to use an ORM package, which might be soon, I will continue to do direct database CRUD code.  One thing I have heard which helps make code more secure is using SQL Parameters.  Well this was a good idea until I tried to figure it out.  Over the last couple of years I have just tried to find the code to get it to work.  With a project I just started yesterday it I decided to figure out what was going on and now I want others to know as some stuff on the web, tutorial wise, can be quite confusing.

 

Getting Started 

I am only going to show you them method that was used to do the database stuff and for the sake of this blog post I am going to assume you know how to use the data reader.  If you don't please let me know and I will make a post on it specifically.  There are basically 3 lines I want to cover with you and explain what they are doing to help you understand what is going on and how to use parameters in your SQL Queries.  First though the code.

 


Now that you have had a chance to review the code a bit lets take a look out our query.

 string query = "SELECT * FROM TestTable WHERE ID = @id";

This is a normal select statement but notice the WHERE ID = @id this the @id signifies it is a parameter to be used and what ever is passed to it will be like normal query without it.  Think of it as a variable that you would use.

 SqlCommand command = new SqlCommand(query, conn);

This is an object we use that will help us build up our query and execute it against the database.

 command.Parameters.Add("id", SqlDbType.Int).Value = id;

This here is the main part of what we are after.  First, we are using the SqlCommand object and in the object it has a Parameters collection that holds all the parameters a query might have.  Since it is a collection we can just call the Add method and the first parameter that metho takes tells the object the parameter name is id for the @id in our query string.  The second parameter the method takes is they datatype which it uses a Struct called SqlDbType to help you fill that it so it is fairly easy to do.  Next we can give the sql parameter a value in this case the id we passed to the method.

Please take a moment to really compare and look at what is going on by understanding what it is doing you can better know how to use it so you don't need to look it up everytime.

Wrap-Up 

This was meant to be quick so you can get an idea of what is going on.  I am including a sample project with the post please feel free to download it.  I have included sql scripts to create the database, create the table and add data to the table.  Please just run those scripts then edit the connString variable with the write server name for you sql server.  Just to note I did this in .NET 3.5.

DatabaseParameter.zip (7.41 kb)

Currently rated 2.0 by 1 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | Sql Server

Hello World of Rhino Mocks

by percent20 1/16/2008 1:19:00 PM

Mock Objects are something that I hear more and more and more and more about as I continue my path into the TDD world, and even from some not in the TDD world.  They are a wonderful tool for helping you to create code for tests that hasn't been implemented yet. Or to help test your data access code without having to run to the database every time you run a test.  Before we go much further lets get a more "formal" definition of Mock Objects.  For that lets visit Wikipedia:

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to test the behavior of a car during an accident.

To use Rhino Mocks first you need to download Rhino Mocks then unzip it somewhere on your hard drive.  Then in your projects just go to add references in the solution explorer then the browse tab then find the assembly where you unzipped it and tada you are read to start.

So let me introduce you to basically what the application is I wrote to mess with mock objects.

Getting Started

First, let me tell you I don't completely understand what is going on with Rhino Mocks and "how" it works.  At this point I know just enough to start "using" mock objects and that is what I want to pass on to you today.  I assembled this code together from around 20 different tutorials so please do not look at this as best practices.  So in typical TDD fashion lets start with test. (I am including the top portion of the file so you can see what I have above the actual test)

Test

HelloWorld Test

Firstly, don't forget to add references to NUnit and your Rhino Mocks assemblies.  You will also need to setup all the appropriate attributes for your tests.  If you do not know how to do this please visit my Part 2 of TDD for Beginners.

MockRepository mock = new MockRepository();

This is the object you create initially that will store all of your mock objects that you are going to be using. (That is what I gather from what it does and the name)

IWorld world = mock.CreateMock<IWorld>();

As best I understand this code we are creating an instance of IWorld object as if it was an object that inherited from IWorld.

using (mock.Record())

From my understanding this basically will run and in this block of code is where we load our mock object with what the objects will do.  Like we are going to basically say what the world object is going to do.

Expect.Call(world.GetWorld()).Return("World");

With this we just told our mock object that it can expect us to call the GetWorld method that is in the world object and it will return the string "World".  So now when we use this object later it will have a method implemented that will return a string.

using (mock.Playback())

In this section of code is where we start USING our mock objects to write our test.

Person p = new Person()
string saying = p.SayHello(world);

Here we create an instance of our person class that is going to call its method SayHello and pass it that mock world object we create above as if it a real and fully created world object.

Assert.AreEqual("Hello World", saying);

This is just a normal assertion that we do for our test.

Making the test Compile

At this point if you were to try and compile it wouldn't so we will implement the code to make it compile.  Lets start with the IWorld interface.

IWorld

That is all you need for the IWorld interface.  And that is all you will need TOTAL for the whole example for IWorld.  Next is the Person Class.

Person Class 

The thing to notice about this piece of code is that for our parameter we are using IWorld as the type and not World since we don't have a world object yet, but we know that we are going to implement it later.  Later the world object will inherit from the IWorld interface so the method will know what to do.

So now it should compile and the test should fail. This is good.

Making the test Pass

All that we need to do to make the test pass is to add change line of code now.

SayHello Method

With this code it takes the object that it was passed and uses it as if it where a regular a real object, but it was created as a mock object in our test.  The great thing is that since we created the mock object and gave it its mock functionality we can implement code to USE that functionality even though it really doesn't exist YET.

To drive home the point on my own and test further I went ahead and created a test using a real world object and a world object.  It worked like a charm.  Those are below.

World Object:

CropperCapture[31]

Real Object Test

World Object Test

Wrap-Up

I hoped that this helped to give you an understanding of mock objects and how to use Rhino Mocks to use mock objects.  I am starting to like mock objects the more I read about them mostly because I can not worry about the database code itself until last, as I don't enjoy it, and can start to work on the application itself and create a layer that is calling mock objects to retrieve data.  Then later turn those mock objects into a real data access layer and I am set to go.

Please feel free to leave any comments or criticisms the more the merrier.

RhinoMocks_1.zip (7.42 kb)

kick it on DotNetKicks.com

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | TDD | Tutorials

TDD for Beginners pt4 - Unit Tests

by percent20 1/14/2008 4:34:00 PM

Part 1: TDD Test Driven Development for Beginners pt1
Part 2: TDD for Beginners pt2 - Pig Latin
Part 3: TDD for Beginners pt3 - The Application
Part 4: TDD for Beginners pt4 - Unit Tests

Recap

I just want to remind everyone of the goals of this series.  It is not to be ALL TDD all the time, but a series on what is TDD and how to start using it on an existing project. Part  1, 2, and 3 are all lead ups to doing this.  Part 1 described what TDD is.  Part 2 described how to do TDD.  Finally, Part 3 setup an existing application that we are going to have as our "Existing" project.  Again, since a lot of people want to start using TDD right away they don't always get the option to start a new project so they need to be able to integrate TDD into an existing application.  My purpose is to give a taste of that with this series while describing some of the basics of TDD and over all concepts and goals of TDD.  This is not an all inclusive how to do TDD and would be irresponsible of me if I said it was as I am still learning TDD myself.

Getting Started

Unfortunately, we can't start doing TDD from the very beginning of a project all the time, would be nice.  We often times come into a project and have to put up with existing code that is usually not easily testable which is pretty unfortunate and can leave you with an icky feeling at times.  This part is going to be about how to implement tests on existing code.

What are we going to test?

I am glad that you asked that question.  Since there are many ways to test things we are only going to test our Business Logic Layer we presented in the Part 3 "TDD for Beginners pt 3 - The Application". If you have not read it I highly recommend you do.  We are going to leave the testing of our Data Access Layer to our final part in the series.

So, right now we want to get our code tested at least a little bit before we start adding features so lets write some tests for our 4 methods. 

  • RetrieveContacts()
  • AddContact()
  • UpdateContact()
  • DeleteContact()

Our Solution

There are many ways to set up your projects to do testing.  In this project I simply made a sub folder called tests and am throwing my tests in there, and they will be built into the application.

Solution Explorer 

Lets take a moment and do some planning based on what this code is doing.

First, we are going to be testing the BusinessLogicLayer Class so that means that we want to use the BLL in ever method that we are going to write our test with.  Since the BLL only does data manipulation in a static way we don't really "need" to create an instance of it in each method.  NUnit provides a SetUp attribute that allows you to do "stuff" before any of the tests are ran such as create instances of objects or populate variables to be used in the tests across your current test fixture.

 

SetUp Attribute

At the top of this code we see our class declaration and the class is going to be a test fixture that will have tests in it (explained in Part 2).

BusinessLogicLayer bl;

Here we are setting up the object that will be used by the tests to access and do stuff with our data.

[SetUp]
public void SetUp()

This is a declaration that the SetUp method is going to be called first because of the SetUp attribute.  How, I look at it is the SetUp method with the SetUp attribute is the constructor of the test fixture it is called first before anything. (the method can be named anything it just makes sense to me to name it setup)

bl = new BusinessLogicLayer("Contacts.xml");

This is just creating an instance of BusinessLogicLayer object and adding that instance reference to the bl object.  Pretty straight forward. Like assigning a variable a value.

Before we move on I want to point out that up until this time the code that we had written in the past with no tests had not been implemented while writing the code so basically it lead to having to try and write all the code at once implement it in some way and hope it all works.  By writing tests we can write a test write a bit of code and then test and tweak until the code works.  At least to me this makes me feel safer about my code actually working because I know, pretty much, as I am writing the code it works. So now lets move on.

Lets talk strategy of testing our data interaction.  One way to test is to try and do stuff on existing data, but that can be dangerous because what if we shouldn't touch the data that exists? We still need to test right? This leads us to the option of what about adding our own data that we know everything about and testing against it then removing it (I did not think of this on my own it came from the book Test Driven Development in Microsoft .NET).  Doing it that way makes sense because then that limits me from accidentally deleting something I shouldn't delete.

Now, with that strategy in mind you should realize now that we are going to be adding data in every test.  So something easy we can do is to create a Contact object in the setup since that is the data we are going to be passing around anyway.

SetUp Method

If you notice the only thing we did was to create a new Contact object and populate it.  Pretty straight forward stuff.  So now lets move onto some the tests.  I want to say here that I may switch back and forth between explaining lines of code and/or chunks of code.  So just be prepared for that as you go along.

RetrieveContacts()

Code:

CropperCapture[13] 

Test:

RetrieveContacts Test

I am not going to explain the naming convention of the test that is done in Part 2 of this series needless to say you kind of get the idea of what the purpose of the test is by the name of it.  Again this part assumes you have read at least part 2 and 3.

List<Contact> l = bll.RetrieveContacts();

This line is fairly simple it is getting a list of all contacts that are in the xml file.

Assert.IsNotEmpty(l);

I like this assertion it you can check to make sure if the method was successful with out having to do much at all just make sure the collection isn't empty.

AddContact()

Code:

CropperCapture[14]

Test:

AddContact Test

bll.AddContact(contact);
List<Contact> l = bll.RetrieveContacts();

Right of the bat we are adding our contact to our xml file and then going ahead and retrieving all the contacts out of the xml file.  So lets now check and see if it is even in there.

bool foundWhatINeed = false;

We are setting up this bool as kind of a switch that if the contact information is in collection then this switch will be true all all will be right in the land of oz.  If not the bad monkeys will come down and take us away and the switch will be false.

Contact theContact = null;

The reason we are setting this up is because if the contact does exist we still have something to do with the contact, like at least remove it.  To do this we need information about it so a good way to do is to get an instance of that contact.

foreach (Contact c in l)
{
    if(c.Name == contact.Name && c.Email == contact.Email)
    {
        theContact = c;
        foundWhatINeed = true;
    }
}

So, we are basically just iterating through all of our contacts, and since we know the specific information about our contact we just compare the name an email address of our hopefully completely unique name and e-mail address.  If it is in the collection we flip our switch and assign the instance of the object to theContact variable.

if (!foundWhatINeed)
        Assert.Fail("Contact was not in list");

Here is what is done with our little on off switch.  If our contact wasn't able to be found we force failure of the test with Assert.Fail and leave a message of why.  Please, be more descriptive than what I was when you do this.

bll.DeleteContact(theContact.sGuid);

And finally since we no longer need that data in the xml file because we added and checked that it was there we can go ahead and delete it from the xml file.

UpdateContact()

Code:

CropperCapture[15]

Test:

UpdateContact Test

I am not going to explain this code line by line as it does the exact same thing as the last 2 tests just a bit more involved.  I am going to do a bullet point description.

  • Add our initial contact and retrieve all contacts from the list
  • Setup our initial switch and object for getting the contact
  • Checks to see if contact is there if so then adds the contact to theContact object if contact is there test fails right there
  • Change a basic bit of information the name and assign the guid of the object to our original object that we are just updating
  • Update the contact
  • Next we just run through our check again to make sure it was all updated if not the test fails
  • then we delete the contact from the xml file.

DeleteContact()

Code:

DeleteContact()

Test:

DeleteContact Test

Same principle applies here as above you know what is going on so I am going to bullet point the explanation, but this is going to be even shorter since it is basically the same code.

  • Add the contact
  • Make sure it was added
  • Delete the contact
  • Make sure it was deleted

Wrap-Up

So in wrapping up this part of our TDD series I want to stress that these are in no way excellent tests that should be reproduced for all time because they are so great.  In fact they can use improvement and can be done different and better ways.  I just wanted to show you how to write some basic Unit Tests for existing code in an existing application.  I hope that this gives you an idea of A how you can write tests for code.  Stay tuned for our next part where we start using TDD on this application to add a new feature.

Final Notes

Here is a bit of homework please I am adding the files for you to download and play with please take a look and see if you can simplify the tests even more or see if you can write them a different way.  Please, play around a bit to see what you can do.

Also note that there are 2 BusinessLogicLayerFixture classes both have the same tests the one with 2 at the end is a simplified version of the other.  I wanted to include both to show that you should and can try to clean up your test to make them look and work better.  I left some more stuff to be cleaned up and move around in the Fixture2 hoping you would give it a shot. Please download and play.

TDDContactManagementApplication_UnitTests.zip (9.11 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

.NET | TDD | Tutorials

TDD for Beginners pt3 - The Application

by percent20 1/9/2008 5:36:00 PM

Part 1: TDD Test Driven Development for Beginners pt1
Part 2: TDD for Beginners pt2 - Pig Latin
Part 3: TDD for Beginners pt3 - The Application
Part 4: TDD for Beginners pt4 - Unit Tests

In Part 1 we went over the conceptual ideas of how TDD works.  In Part 2 we went over a basic how to do TDD doing string manipulation and going through each of the steps.  Here is a quick _rough_ recap of what we are going to do for the rest of the series

Part 4: Explain how to create tests for existing non-tested code
Part 5: Use TDD to add a search feature
Part 6: Refactor code to make things work a bit better
Part 7: How to use Mock Objects

NOTE: I started out this series using .NET 2.0, but have recently started using .NET 3.5 and using Visual Studio 2008. Since, this will be the first release of the project it will be in .NET 3.5 using VS 2008.

Getting Started

The application that we are going to be using is a console application that is a contact management system.  Something very basic that will allow you to view, add, update, and delete contacts that you know.  It will save out all the contact information into an XML file so that we can keep the data as long as we need.  I will start by saying that the UI portion of the code is ugly and pretty simple.  A lot of Console.WriteLine("");'s. With that being said I won't explain that portion of the code as it is fairly simple and quite repetitive.  First, I want to show you the solution explorer and I'll go over it a bit with you.

Solution Explorer

  • Tests - Just ignore this folder for now we will go into that on the next part.
  • BusinessLogicLayer.cs - this is our source code that our GUI will access to interact with data.
  • Contact.cs - Like was explained in Part 1 of our XML Series this is our Contact Class that acts as a data type for our application.
  • Contacts.xml - We store all of our data in this file.
  • DataAccess.cs - This holds all of our code to access data in our Contacts.xml file.
  • Program.cs - The main method is in this file along with the code for the GUI

The only things we are not going to discuss here is the Tests folder and the Program.cs file. First, though lets start with the DataAccess.cs and Contact.cs file.

DataAccess.cs

For a good understanding of this code please refer to the xml series I have previously posted as it is the exact same code.  The only change is the Contact.cs file and I will address that when it comes, but it is only code changed to be C# 3.0 compliant, it does the same thing.

Part 1: Write to XML File Using C#
Part 2: Reading Data from XML File Using C#
Part 3: Delete Data from XML File Using C#

Contact.cs

This class again is our custom class that we use as a data type as explained in Part 1 of the XML Series "Write to XML File Using C#".  There is only a minor change to the code to update it to C# 3.0 specs as you can see below.

CropperCapture[3]

BusinessLogicLayer.cs

First, I guess we should explain a bit about what a Business Logic Layer (BLL) is a bit.  There can be 3 main parts to your application to have good separation of concerns.  First you have your Data Access Layer, this layer is used strictly to do your CRUD only. Second layer is your Business Logic Layer, which is used to handle any data manipulation; like adding information to each piece of data and it doesn't necessarily need to be in the database.  In the BLL you could even use that point to combine pieces of information or format the data in a specific order.  Third you have your presentation layer which is basically where you present your stuff to the user for them to see and use.

Now, what we have gone through a brief explanation lets take a look at some code.

BusinessLogicLayer.cs

We will skip the first few lines as I am sure you can guess what they do so lets jump to line 9 and we'll go method by method or line by line.  I'll try to keep the explanations fairly straight forward and simple. (The below assumes you have gone through the the XML Series)

DataAcces da;

We are creating a variable of type DataAccess so we can have a global DataAccess object to the BusinessLogicLayer class so that we don't have to create an instance of the DataAccess object for every method call.

public BusinessLogicLayer(string xmlFile)
{
    da = new DataAccess(xmlFile);
}

This is the constructor for our class we are creating passing in the name of the xml file to use and then creating an instance of the DataAccess object with the name of the xml file. 

public List<Contact> RetrieveContacts()
{
    return da.RetrieveContacts();
}

With this we are just getting a collection of all the contacts in the xml file from our DataAccess object that access the xml file.

public void AddContact(Contact c)
{
    da.AddContact(c);
}

This simply is a layer of abstraction to the DataAccess class that adds the contact to the xml file.

public void UpdateContact(Contact c)
{
    da.DeleteContact(c.sGuid);
    da.AddContact(c);
}

Here is a bad way to update a contacts information, but it does work.  (I did this on purpose to explain something in a later part)

public void DeleteContact(string s)
{
    da.DeleteContact(s);
}

And on this one we delete the data from the XML file using a provided Guid that comes from our presentation layer.

At this point some people may be asking "why" would you not just use the DataAccess class directly.  Well I am glad you asked because that is an important thing to know.  One of the big reasons is, what if later we want to change this all to a database instead of an XML file?  Well with this program that really would be a problem, but if it was a huge application we could run into some problems.  Adding this Business Logic Layer adds the advantage of allowing you to just rewrite the Data Access Layer to use a database and all that is required for you to do is use the same method calls in the DAL.  Imagine being able to use this application later on with a DB if we only had to re-write one part of 3 parts of the code and it would be a guarantee to work then why wouldn't you want to do this, not to mention it adds to better readability.

Contacts.xml

This is our data store and is explained in the xml series part 1 Write to XML File Using C#

Program.cs

Finally we have the file that actually runs all the code I will just provide a download of the file for you to look at as it is long and ugly looking.

Program.cs (3.75 kb)

Wrap-Up

This is a nice little gap filler part that introduces you to the application and lets you download and play with.  I also wanted to inform you as to what was coming and get out of the way some preliminary conceptual "what is going on" with the application.  Please feel free to download the code below and play with it.  Please stay tuned for Part 4 of our TDD series.

TDDContactManagementApplication.zip (6.45 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

.NET | TDD | Tutorials

TDD for Beginners pt2 - Pig Latin

by percent20 12/5/2007 4:48:00 PM

Part 1: TDD Test Driven Development for Beginners pt1
Part 2: TDD for Beginners pt2 - Pig Latin
Part 3: TDD for Beginners pt3 - The Application
Part 4: TDD for Beginners pt4 - Unit Tests

I like to do "Real World Coding" and "Real World Contexts" when doing tutorials, if I can. Someone suggested that most people that want to learn and do TDD usually want to start using it with an existing project, and I should go about the series in that way. I liked that idea, but it presented a simple problem of teaching the very basics of TDD. My solution is this part 2. I am going to walk you through doing a _VERY_ basic Pig Latin converter, and how to use TDD to accomplish writing it. Then the rest of the series is going to be how to incorporate tests into an existing project, and a couple parts on adding new features using TDD.

Download NUnit
Before you can do TDD you need to get something to run your tests. I personally use
NUnit, but there are other options available.
Download
( Get the MSI for the latest version using .NET 2.0 Library )
Documentation

Next you need to Install it just run the installer. Just go through the normal next next next process.

How to configure Visual Studio to do Tests
This is pretty straight forward process and is a project by project basis. When you install NUnit it will add several NUnit assemblies to the GAC and when you start a new project that you are going to write tests for (which should be most now), you need to add new refernce, in the solution explorer, and choose NUnit.Framework assembly. Next you add the following line to your using statements.

using NUnit.Framework;

Once that is done you are pretty much set and ready to start writing tests.

Test Driven Development

Now that we have the preliminary stuff out of the way we can start to concentrate on what is important. Learning Test Driven Development. Sorry for the long post you are about to endure.

What we are going to write is a Converter class that allows us to convert words to another language. In the case of our example we are going write a class to be able to convert words to pig-latin (as long as the word doesn't start witha vowel). By writing it as a convter class it will make the code easier to use, implement, test, and extend.

TDD Process
There is a basic process you run through when doing Test Driven Development. I wrote about it in another post, but will re-list it here as it is very important and is the core to TDD.

  1. Write the Test Code
  2. Compile the Test Code (It should fail since you haven't implemented anything yet)
  3. Implement Just enough code to Compile
  4. Run the Test to see it fail
  5. Implement just enough to make it pass
  6. Run test to see it pass
  7. Refactor for clarity and eliminate duplication
  8. Rince and Repeat (repeat from the top)

I am going to walk you through each of these steps and explain them as I go.

Write the Test Code

First we need to create our test class file. So add a class file to a new console project (if you want following along) and name it ConverterFixture. The name means that this is a test file that will be testing the converter class.

Test For Converter Class

The above code is what we refer to as writing the test code first. Lets walk through each line.

[TestFixture]
This is the attribute we set in C# to let NUnit know this class containts tests. It is a Nike thing "Just do it" at the top of your test classes. The class also must be public for NUnit to find and use it.
public class ConvertFixture
This is the name of the class that is going to containt all of our tests for our Converter class.
[Test]
This is the attribute we set in C# to tell NUnit this is an actual test that will be run. All the code in this method below is used to ultimately run a test.
public void ShouldConvertWordToPiglatin()
In order for the method to be a test it needs to be public, void, non-static, and take no parameters. Our method meets all those requirements. The naming might seem odd, but the purpose is so that you can easily understand the purpose of what "should" happen by the end of this test (Look up Behavior Driven Development). This may be obvious by our method test, but when you get into more complex code then tests can become exponentially longer with the purpose being lost. Though nameing is up to you this is what I do.
Converter c = new Converter();
Creates a new instance of the Converter object.
string word = c.ToPigLatin("hello");
From this code we are converting a word "hello" to pig latin using the instance of the converter object from above and assigning to a string object. Or we are converting hello to pig latin.
Assert.AreEqual("ellohay", word);

This is the bread and butter, kind of, of tests. Assertions are how you actually test things in TDD and using Assert object is how you do it in NUnit. There are actually quite a few Assertions you can make, but the one we have here is Assert.AreEqual which compares what the output "Should be" to what it actually is. I suggest when you get this far take a look through intellisense at all that are available to you to use.

Now what we have is a test for our converter object that we haven't made yet.


Compile the Test Code

If you are following along and doing TDD the correct way when you hit compile you will get a big fat ERROR and it won't compile. Congrats that is exactly what it is supposed to do. If it does compile something is wrong.

Implement Just enough code to Compile

At this point we are ready to start writing code for our program. We will write just enough code for our program to compile. The reason behind this is so that you don't write unecessary code and the more code you try to write to pre-implement/pre-solve problems can lead to problems later. Writing just enough code to compile can keep you in check so that you don't write too much code. Here is the code that is just enough to compile the program.

- In this code you can see we created the class Converter.
- Created a method called ToPigLatin() with a return type of string and takes a string parameter.
- It then returns the string s.

Now try to compile. It should compile with 0 errors.

Run the Test to see it fail

Next is to actually run the test. To do that here are the steps I follow from finding and opening NUnit to hitting run. Once you open the assembly in NUnit all you need to do is just hit run from then on after each compile.

  1. Start
  2. All Programs
  3. NUnit 2.4.3
  4. Click NUnit GUI (.NET 2.0)
  5. File
  6. Open Project...
  7. Find assembly (which was in below folder)
  8. Location of Assembly
  9. Select Assembly
  10. Click Open
  11. Click Run

At this point it the test should fail

Test 1 Fails on First Run

 

Implement just enough to make it pass

No we are ready to add the functionality to make that stinking test pass so we can feel good about our code working.

The code above is the code needed to make the test pass. I will run through the code mostly line by line after the declaration of the method.

char[] theArray = s.ToCharArray
Here we are taking the string and spliting up each individual character into an array to so we can manipulate it better.
string final = "";
We are setting the variable final to a nothieng string because are going to run through a loop and add characters to it.
the whole for loop
This is basically going through the array for the word and starting at the second character and assigning it to the variable final. So basically it is taking "hello" and turning it into "ello".
return final + theArray[0] + "ay";
Here we are taking ello adding h to the end and then appending "ay" to it. The final looks like ellohay. We then take that and return it so the test can check if it was done right.

Run test to see it pass

Now you should be able to hit the bug run button in NUnit once you compile the program and get everything all Green.

Feels good doesn't it.

Refactor for clarity and eliminate duplication

In this case we really don't have anything that we need to refactor so we can do the next step.

 
Rince and Repeat
(repeat from the top)

If we had more to do then we start over from the top on the next method/functionality that we want to write. Remember though not to write to much functionality at once.

 

Wrap-up

Now that we have gone through all the steps i'll post up the final code and the code that implements the converter class we just wrote. Then the application that runs it.

ConverterFixture.cs

Converter.cs 

Implementation inside the main method

Program.cs

It actually running

 

Final Thoughts

As you can see Test Driven Development can be very effective in making sure that your code does work. What is great about TDD is that you can spend a while coding on a project and because you have tests later when you do some refactoring to make things prettier and work better you know if and where EVERYTHING is broken. Also TDD allows you to start almost anywhere in your application that you want so if you want to start in the business logic layer, lets say, and not in your data access layer you can because there are ways to test without haveing the Data Access Layer implemented, I will show that too later.

There are a lot of benefits and I can only talk about a couple of the benefits right now so as the series progresses I'll talk about more. In the next part, maybe couple of parts , of the series i'll post up the code for our application that doesn't have tests and do a walk through of all the code.

Please, feel free to download the code I have attached play with it maybe add your own language converter to it with some tests. Please give me any feedback you want good bad or indifferent.  

TDDSeries1PigLatin.zip (7.81 kb)

kick it on DotNetKicks.com

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

.NET | TDD | Tutorials

Real World Interfaces in C#

by percent20 11/26/2007 10:20:00 AM

I have been on a bit of a "quest" lately to learn interfaces better. While at work I hit up a couple of fellow developers on "why" you should use interfaces in the real world. Believe it or not after going through some code and getting some commentary on it I think I have an understanding of interfaces.  Here is my understanding in a possible "real world" situation.

Let’s say you want to render out commonly used objects to the screen.  They can be textbox's, images, or even labels.  Each of these might have a common set of properties like title, id, width,  and height; plus a method like Render() to show it on the screen.  Now in .NET we might call these objects controls so we will use that naming convention for example sake.  You might create an interface called IControl that all controls will inherit from.  One reason to use an interface instead of a separate class is because the render method could be different for all the different controls, but is all that is needed to be called in order to show the control.

So, let’s look at some basic code.  First we will look at the interface.

IControl Interface

This interface IControl has our common properties and the render method. We are going to implement different render methods for each of our different controls so we might not necessarily want to create a control class to inherit from. To illustrate this more let’s look at two different controls implementing the IControl interface

TextBox

TextBox Class Implementing IControl

Label

Label Class Implementing IControl

If you notice both the TextBox and the Label controls have slightly different render methods, but both contain the same properties because of the IControl interface. This is important to note because we KNOW that if the IControl interface is being used that you can always call the methods and properties from them. So that means you can make a method like the following which will always call the render method as long as the object implements the IControl interface no matter what the control is.

OutPut Method that calls IControl Render Method

With this you can create an instance of TextBox and Label and pass both of them to the above method and they will call the render method and output the correct information.

Here is some “example” code on how-to use and put together everything above.

Main Method Implementing Controls

Conclusion

To wrap it up you can make an interface and an interface basically says “hey I have at the very least these properties and methods and you can use them however you need without worrying about what they do to actually use them” Which means that you can write any code you want to implement each of the properties and methods and as long as you use the interface as your “datatype” there is no need to worry about what the code actually does for each and every object that implements the interface. In the case of the example there is no need to worry about how many or what the controls actually do when rendered because they will all be rendered by using the output method since the datatype of the parameter is IControl.

Please, feel free to leave comments and critiques on this. I am still learning about interfaces and this is as “real world” as I could figure out on how to use interfaces as that is what helps learn. Any help would be great and please feel free to download the code I have attached and play with it a bit. I am sorry for the length I just wanted to be thorough, I hope I was.

 

Interfaces.zip (6.33 kb)

kick it on DotNetKicks.com

Currently rated 4.0 by 4 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

.NET | Tutorials | Programming

Metablog .NET Library

by percent20 11/11/2007 11:49:00 AM

There are a couple of tools I have wanted to look into writing for my blog(s), but have no idea how to program for the MetaBlog API that most blogs now implement.  This was really perplexing to figure out how I was going to go about making my tools.  Luckily, I found someone who already was a step ahead of me and made a .NET library for the MetaBlog API

MetaBlogAPI Library 

This is going to make life so much simpler in the future.  I just want to say thank you to the guys at TagTooga for making this library.

If you make anything using this library post a comment as I am sure this will enable more people to do tools for blogs now.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | Awesome Stuff | Programming

Powered by BlogEngine.NET 1.3.0.0
Theme by Mads Kristensen


My Flare

AddThis Feed Button

National Blog Posting Month

Eagle Scout

I'm Test Driven

[Reserved for MVP status I want to earn]

View Buddy Lindsey's profile on LinkedIn

Twitter



Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Sign in