Eval in DataList, DataGrid, and Repeater

by percent20 24. January 2008 14:09

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: ,

Coolness of SubSonic

by percent20 23. January 2008 17:17

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: , ,

Microsoft MVP as a goal - is it bad?

by percent20 23. January 2008 11:12

Short answer: No.

Here is how I got there and why I think it isn't bad.

First, I want to start off with 2 of my major goals in life then an analogy.  Afterwards I will tie it all together with regards to the Microsoft MVP award.

Goals:

Learn everything and help as many people as I can learn what I know.  Think about it you know you can't learn everything but you set your goal to learn everything imagine how much you can learn if you fall just short.  You will probably learn quite a bit.

Analogy:

If a person is going to run 5 miles no matter what.  Is it wrong for him to set a side goal of getting 1000 dollars if it is available.  To me no there isn't anything wrong since he is going to run no matter what. (just imagine for a moment strictly running for money is bad)

Now I am sure some of you are going huh about now. Here is how I look at having a goal of earning the MVP award.  I am going to help the community no matter what.  I have been doing so for 4 years and will continue to do so for as long as I am able.  Some of the things I have done and do are:

Blog
Attend DNUG meetings
Speak at DNUG meetings
Work on staff at Conference
Help Organize Dev Conference
Post on forums

Those are some of what I do to help, have done for a while and will continue to do them because I enjoy it. 

So, if I am going to do the above in order to obtain my original 2 goals above then I don't see a problem in having a side goal of earning MVP award if it is available.  For me the first two goals are most important over all others (within the non-political, non-religious, and non-family context).

Now some have said that the MVP isn't in my control so it isn't a very good goal to have.  I have to disagree to an extent.  Earning MVP may not totally be in your control, but there are things you can do so that it doesn't go the way of a dream.  To me a dream is something that would be nice, but isn't what you are going to pour your heart and soul into doing or getting.  Like going to space is a dream for me.  It would be nice, but I am not going to spend the time to do it (I'll wait until it is affordable).  Compared to that there is an amount of control in earning MVP, by helping the community.  Earning the MVP isn't all up to you, but you don't have to keep it in the same realm as going to space.

In the end to me if earning MVP isn't your primary goal then having it as a goal, namely side goal, isn't bad at all.  If it is a primary goal then I suggest re-assessing what you are doing and why because that is a lot of work for the chance of it not happening.  If the primary goal is helping others in the community and teaching; then by all means a side goal of MVP is not a bad thing.

Please let me know what you think especially if you don't agree with me. Please, let me know how I am wrong if I am.

 

EDIT: Just wanted to note that I am NOT and MVP, but want to become one.

Be the first to rate this post

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

Tags:

SQL Parameters in C#

by percent20 21. January 2008 07:03

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: , ,

IRSSI on Windows

by percent20 18. January 2008 16:12

One bad thing about me is I have several avenues of communication open to me.  From e-mail, IRC, IM to even Twitter.  My favorite though would have to be IRC, but there is one little snag.  I haven't found a "good" IRC client which as the UX (user experience) I am after.  There are a lot of GUI ones available, but the UI is wonky to work with and in windows that is pretty much it.  In *nix you have the opposite most IRC clients are command line based.  However, I will say the command line based ones give me a better UX than most GUI ones.  So until I find a good GUI one that I like I am stuck with what is available for windows.  Since, the command line based IRC clients are closest I was ecstatic the other day to find out that IRSSI is available now for windows.  So in honor of my great happiness of finding it I want to dedicate a post to setting it up and using it.

Step 1: Get IRSSI

First, we need to download IRSSI. Be sure to get the windows version of the binaries.

CropperCapture[33]

 

Step 2: Install IRSSI

Installation is pretty easy just download it and run the self-extracting executable.  I usually put it in a programs folder in my My Documents.

CropperCapture[34]

Step 3: Run IRSSI

Once you have it extracted proceed to the folder you extracted it to and run the irssi.bat file.

CropperCapture[35]

Step 4: Configure and Join IRC Server and channel

Pretty much all you have left to do is set your default username by typing

/set nick nickname

Then to join a server and then a channel

/server irc.freenode.net
/join #alt.net

When you have that done it should look like:

CropperCapture[36]

Now you should be able to chat with people.  For more configuration stuff visit IRSSI documentation page.  Specifically, the Startup HowTo.

Hope to see you in IRC.

Be the first to rate this post

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

Tags:

Hello World of Rhino Mocks

by percent20 16. January 2008 13:19

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 2 people

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

Tags: , ,

PowerShell Hello World Script

by percent20 15. January 2008 06:01

I have been wanting to learn PowerShell for a while now and one of the guys in the #alt.net irc channel talks about it all the time. So I decided to give it another shot.  The first thing I wanted to do was write a Hello World script that just out put that text to the screen running form a script file.  It wasn't so easy to figure it out believe it or not and there wasn't a good Hello World tutorial on the net I could find.  Finally, after a while of just trying stuff and following half instructions I figured out how to get a script to run.

First though you need to Download PowerShell. Please follow that how-to on downloading PowerShell.

After powershell is installed open up the powershell command window and notepad.  I'm not going to go into the why of powershell here because honestly I don't know yet.  Instead i'll give you quick instructions for writing a script that will run.

  • In notepad type out the following ( Write-Output "Hello World" ) without the parenthasis
  • Save file as HelloWorld.ps1
  • Switch to PowerShell command window
  • Navigate to the folder you saved the file in ( I just used C:\ to keep it easy at first )
  • Execute the following command: Set-ExecutionPolicy RemoteSigned (reduces security until you increase it.  There is a very annoying security policy in place for just dev work)
  • Next is to run the script just d: ./HelloWorld.ps1
It should have spit out Hello World do the console.  Congrats you just did a hello world script in powershell 

HelloWorld.ps1 (26.00 bytes)

Be the first to rate this post

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

Tags:

TDD for Beginners pt4 - Unit Tests

by percent20 14. January 2008 16:34

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: , , , ,

And the Beat is back - why we were down and what is up coming

by percent20 12. January 2008 14:16

Why we were down 

I am not sure if any of you have noticed, but the site has been down for the last 36'ish hours.  I have spent most of that time working with my hosting company to figure out the problem and to fix it. As you can tell it is now fixed. Smile

Here is basically what happened.  I had, and didn't relize it, Automatic Updates turned on to automatic.  Well Thursday night the update did its thing and then rebooted the server.  Well on boot-up it was getting a ton of errors and basically wouldn't boot-up at all.  I didn't find out about this until about 10:30 yesterday morning and immediatly try to start the server via my control panel through my host.  It didn't work. So we spent the next 36 hours trying to figure out what was going on.

My server is a VPS (virtual private server) and apprently you shouldn't do windows updates on a VPS because it can corrupt the install.  Well it corrupted the install and from what I gather took down that whole server itself that it was sitting on.  They ended up getting it back up and running, YAY.  Now my biggest concern was that if I can't do windows update then how am I going to get the latest security updates etc. Well, they have a main machine that they test everything and if that works out fine then they push it to all servers.  So I do have the latest updates I just don't have to manually apply them.

So the host learned something as well as did I.  I learned don't use windows update with a VPS in a server farm. They learned to actually start telling people to NOT do windows updates and to lockdown the boxes a bit more so people can't.

Upcomeing Stuff

I am going to continue with the TDD series and am going to spend a serious amount of time over the next week to knock that out as quick as possible.  I had planned to do that yesterday and today, but that didn't happen.

Also upcomeing after the TDD series I am going to do a project that I have wanted to do for a while and I am going to blog everystep of it because it all requires me to learn new stuff so it will be good content to blog about.  I'll post more details about what and how I am going to do it, but I basically plan to present the project and then go through as many steps of the development process, coding, and deployment as possible.  Please stay tuned. 

Be the first to rate this post

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

Tags:

TDD for Beginners pt3 - The Application

by percent20 9. January 2008 17:36

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: , , ,

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

RecentComments

Comment RSS