Creating a Text File Data Conduit (Part 1)

advertisement
Building a DIY Data Layer
In the course of this work we will go through a lot of steps in creating a DIY data
layer. What I mean by DIY is that we are going to code many of the features
ourselves. By doing this you will be exposed to a good range of C sharp features and
syntax.
The data layer we are going to create will use a text file to store a set of names. We
will then write a data conduit class to read the data from this file with the option of
specifying database parameters to select specific records.
Later in the module when we reach the point of looking at the ADO.NET classes for
controlling data you will see how a much more sophisticated data layer is in fact
simpler to code.
We will build this work on the previous lab exercise. If you have your own
completed version of the own work use that, otherwise download and extract the
solution Practice Lab 03.zip
The first step is to create our database file. One of the simplest data stores is a comma
delimited text file.
A comma delimited file has the following features...


Each record is defined on a single line and terminated by a carriage return
Each field is separated by a comma
The following example from an address book illustrates the structure.
1,123,The Street,LE1 1BP
2,9,The Road,CW12 4ED
3,1,The Square,LE4 5GG
4,45,The Terrace,LE44 6TG
The big advantage of a file like this is that it is very light on system resources. The
disadvantages are that we have none of the useful features provided by a sophisticated
Data Base Management System (DBMS). We are going to have to code much of this
functionality ourselves.
Using note pad create and save the following text file...
1,John
2,Jim
3,Janet
4,Jane
In this example we will create a folder in the solution called Database. The text file
will be called database.txt.
One way to test a class whilst in development is to create a web site / project purely
for development purposes.
What we will do is create a development web site that allows us to quickly test the
code as we create it.
Within the solution create a new web site called development. Create in the new site a
default web form and make sure that the new site is linked to the class library.
Right click on the new site and set it as the start up project.
Switch the default web form to design view and double click the page to access the
load event procedure...
We will use the event procedure of this form to quickly test the new data conduit class
as we develop it.
Once it is working we will then switch to our other site and implement it fully as a
finished class in the system.
It isn’t a bad idea to add the class library to the libraries imported by the web form.
(This makes the code we write a bit more concise.)
The next step is to create the data conduit that will read data from the text file. In the
class library add a new class called clsDataConduit.
Make sure that the class is set as public and make sure that you are able to instantiate
an object based on it in your default web form’s load event.
This is a useful test as it makes sure the site is configured correctly.
The next step is to decide on what the interface to the class is going to look like. This
would normally be modelled using a class diagram. On paper the class’s interface
will look like this...
clsDataConduit
Class name
Public QueryResults
Properties
Public void AddParameter(string
ParameterName, string ParameterValue)
Public void Execute(string
storedProcedureName)
Methods
QueryResults
will be a property that exposes a list of objects allowing us to
access the data in the underlying text file.
AddParameter
will allow us to add database parameters to search for data in
the file.
Execute
will run a specified query making use of the database
parameters.
For example the following code will create an instance of the class, add a database
parameter and then run a specific query.
clsDataConduit NameList = new clsDataConduit();
NameList.AddParameter(“@NameID”, “1”);
NameList.Execute(“sproc_NamesByID”);
The results of the query will be accessed by examining the QueryResults property.
The first feature we will implement is the facility to add database parameters to the
class. To do this we will implement a strongly typed list.
(Warning this could get potentially confusing. In the text that follows we will be
talking about two sorts of parameters. We will discuss parameters that are used to
query data in the database and parameters that may be passed a function. In order to
differentiate between the two we shall refer to them as database parameters and
function parameters.)
Creating a list of Objects in C Sharp
In this first example we will use a “list” type to create a list of a class that we define.
The list type is one of a number of generic classes that allows us to take a huge
amount of functionality “off the shelf” and customise it to our own requirements.
For example we could create a list (array) of string data type like so...
List<string> MyList = new List<string>();
Notice how we type the list like so <string>.
If we wanted to add items to the list we might do the following...
List<string> MyList = new List<string>();
MyList.Add("Rod");
MyList.Add("Jane");
MyList.Add("Freddy");
To obtain the count of items in the list we would access the object’s Count property...
int Count;
List<string> MyList = new List<string>();
MyList.Add("Rod");
MyList.Add("Jane");
MyList.Add("Freddy");
Count = MyList.Count;
...which would assign the value of 3 to Count.
We might access the value at a specific index like so...
int Count;
string SomeString;
List<string> MyList = new List<string>();
MyList.Add("Rod");
MyList.Add("Jane");
MyList.Add("Freddy");
Count = MyList.Count;
SomeString = MyList[1];
...which would assign Jane to the variable SomeString.
And we may remove an item from the list like so...
int Count;
string SomeString;
List<string> MyList = new List<string>();
MyList.Add("Rod");
MyList.Add("Jane");
MyList.Add("Freddy");
Count = MyList.Count;
SomeString = MyList[1];
MyList.RemoveAt(2);
...which would remove Freddy from the list.
Creating a List Based on a Custom Class
What we want to do rather than create a list of type string is to create a list based on a
class we create.
The first list will be a list of database parameters that may be used to query the data in
the text file.
To store the database parameter data we will add a second class to the class library
called clsParamater.
In this case we shall leave the class as private to the class library so only code in the
library namespace has access to it.
We will create two properties in this class.


ParameterName (string)
ParamaterValue (string)
This will require two member variables


paramaterName (string)
paramaterValue (string)
Set up your new class as follows...
class clsParameter
{
string parameterName;
string parameterValue;
public string ParameterName
{
get
{
return parameterName;
}
set
{
parameterName = value;
}
}
public string ParameterValue
{
get
{
return parameterValue;
}
set
{
parameterValue = value;
}
}
}
Save and close the new class and open the code for clsDataConduit.
At the tope of the class, just below the class name...
Add the code to declare our strongly typed list of database parameters...
Placing it at this point in the class file gives it class level scope.
The next step is to create the AddParamater method.
Within clsDataConduit create the following function.
This public void function will implement the method AddParameter.
The function will accept two function parameters ParameterName and
ParameterValue. It will create an instance of our class clsParameter and add the
resulting initialised object to the parameters list.
The following code does this...
Save and close your class and go back to the code for the web form.
Add the following code to the load event of your web form...
Using the Debugger to Inspect the Code so far
In order to test this and make sure the code is working we shall add a break point.
Add a break point to the code by placing the cursor on the declaration for NameList
and pressing F9.
Run the program and a soon as the forms load event is triggered the break point will
pause execution.
Press F10 once to step over the NameList declaration.
When the current line of execution is
Press F11 to step into the function that defines the method.
This should take you into the class file
Hold the mouse over the two function parameters. The debugger will allow you to
see their value.
Press F10 until the last line of code has executed
Hold the mouse over the parameters list object and notice how the debugger allows
you to inspect the value of each element in the list (so for only one element).
Notice how the debugger allows you to inspect both the private and public elements
of the class.
Press F10 a final time and you will find yourself back in the code for the web form.
Press F5 to exit debug mode.
The above code allows us to add database parameters to the class, however until we
have some mechanism of getting the data from the text file into the class (in a usable
form) it isn’t much use.
We will pause development of the list of database parameters until we have
completed code that reads the data from the text file into the class.
Modelling the Text File Structure within the Class
Before we set about reading in the data from the text file we need to have somewhere
to store it within the class. The most obvious way of doing this is to create a second
list of a class designed to store the data from the database.
The data in our text file contains the following...
1,John
2,Jim
3,Janet
4,Jane
To set up a class to model this data we will create a new class file called clsName
with the following properties...
clsName
Public string NameID
Public string AName
Using the following code...
public class clsName
{
private string nameID;
private string aName;
public string NameID
{
get
{
return nameID;
}
set
{
nameID = value;
}
}
public string AName
{
get
{
return aName;
}
set
{
aName = value;
}
}
}
Save and close the class. We will now create the code to create the list of type
clsName.
Within the data conduit declare a second strongly typed list called allNames...
The next step is to implement the code for that reads the data from the text file and
builds the contents of this list.
In order to do this we will make use of a .NET library class called the stream reader.
The .NET Stream Reader
The stream reader allows us to open a text file and read it in to RAM.
To operate it needs the path and file name of the text file.
Create the following function in your data conduit class...
(You will need to modify the path to the file based on where you have saved your
work.)

Notice that we have set the function to “public” when really it should be
“private”. Since we are developing this code by setting it to public means we
may test it directly from the test form.

Notice also the need to write two slashes all of the time \\ in the path
In C # you may use combination of \ and other characters to for example generate
characters not available on the keyboard or characters that may be ambiguous in the
code. This is called an escape sequence.
For example
\' - single quote
\" - double quote
\\ - backslash
\b - Backspace (character 8)
\f - Form feed (character 12)
\n - New line (character 10)
\r - Carriage return (character 13)
This creates a problem due to the fact that the \ symbol serves this function. To get
round this when we really do want a \ in our string then we need to type it as \\.
Testing the GetData method
Since we have made the method “public” we have the option of testing it within our
development web form. Modify the load event in the web form like so, placing a
break point on the declaration...
Run the program and use the debugger (F10 & F11) to examine the execution of the
code.
Reading Data from the File
The next issue we have is how do we read the data from the file?
The stream reader makes available a method called Peek. Peak reads the character
code of the next character to be read. If there are no more characters to read then it
produces a negative value.
We may create a loop that makes use of the method like so...
We have several options for reading data from the file.
We may read data
 One character at a time
 One line at a time
 The whole file at once
In this example we shall read it a line at a time.
The following code does this...
Run the program in debug mode and notice the format the data is in when it is read
into the variable ALine.
The problem is that we have data formatted as a single string when we want to access
the two fields delimited by the comma.
C sharp has a large range of string handling features, one very handy one is Split.
The Split Method
Split allows us to specify a character to split on and assigns the results to a string
array.
For example the following code would do this...
Using the data “1,John” it would split the data into a two element array.
In the resulting array, element 0 would contain 1 and element 1 would contain John.
If we create an instance of our class AName we may use this like so...
The last thing to do is to add the new instance of clsName to the list allNames. Below
is the completed code for the function.
Run your program to make sure that the data is being copied to the list.
In this example we have created a list of database parameters and a list of records
from the text file. In the next session we shall use the two to query the data and
ultimately make the resulting query available via the QueryResults method.
Download