Sunday, November 22, 2009
Back to Basics: Looping
Pretty soon after learning conditional statements comes looping. Looping can be used to scan through a recordset, or to add items to a drop down or any number of things really. Looping is vital to almost any program. Today we will learn how to use for loops and while loops in both C# and VB.
For-Loop
In both C# and VB the for loop can come in two flavors. The more traditional what I will call the counting for loop, and a for each loop which will allow you to loop through a collection or enumeration of things.
First we will start off with the counting for loop. There are three main parts to this for loop. First is the counter and it's initialization. You can either define this outside of the loop and just reference it in the loop, or you can define it inline with the loop. This is the the method I prefer since the scope of the variable is localized to the for loop. Traditionally the counter variables are 'i', 'j', or 'k'. There is nothing wrong with using other variable names, but you will see these 3 used all the time. More often than not you will see 'i' being the most prevalent.
The second part is the ending criteria such as an upper or lower bound, it is essentially how many times the loop will execute. This is a very important piece because if you don't have it then you will enter into an infinite loop in which there is no way your program will exit until you run out of memory or hit the upper bound of the data type you are using (both are bad things). Since this is tested at the beginning of each iteration this is called a pre-test loop.
Lastly we define how are are going to increment our counter. Many times this is just up by one each time or down by one. But you can use any increment you wish. The increment happens after the end of the loop.followed by the check of the counter. If the ending criteria is not met the loop will execute again.
In this example we are just going to loop 10 times writing out to the screen the value of i each time
C#
//Example 1
for (int i = 0; i < 10; i++) {
Response.Write("i=" + i.ToString() + "<br/>");
}
//Example 2
int i;
for (i = 0; i < 10; i+=2) {
Response.Write("i=" + i.ToString() + "<br/>");
}
You can see how I defined the variable 'i' inside the for loop in the first example. In the second I declared the variable outside of the loop. Both are valid, and it is just personal preference. Just remember that the scope on each variable is different.
In the second example above we are incrementing by 2 each time through the loop. The += notation is the same thing as writing out the full expressoin i = i+2. It just makes the whole thing easier to read.
In VB.Net if you are going to increment by 1 each time around you do not need to define the last piece of the loop, it is built in. So in example 1 below we are just going to count up by one. In example 2 we will increment by 2 as before.
VB
//Example
For i As Integer = 0 To 10
Response.Write("i=" & i & "<br/>")
Next
//Example 2
For i As Integer = 0 To 10 Step 2
Response.Write("i=" & i & "<br/>")
Next
So as you can see in Example 2 using the step clause in VB will allow you to change what you increment (or step) by.
The next type of For loop is the for each, which is very useful in stepping though a collection of objects. For example, lets assume we have a collection, addressBook, of people using the class (person) we have been using in the past 2 posts. The examples are just going to loop through all of the items in the collection. Note how we do not have to declare a counter. .Net will handle fetching each item and knowing when to stop. This loop can be re-written into a counting for loop very easily. I would be willing to say that each foreach loop could be re-written as a counting for loop, but the reverse isn't true. I'm not positive on that, but I can't think of any examples to prove me wrong, if you can think of one put it in the comments below.
C#
foreach (person peep in addressBook) {
Response.Write(peep.LastName);
}VB
For Each peep As person In addressBook
Response.Write(peep.LastName)
Next
As you can see the syntax is almost identical between the two languages.
While Loops
While have the same purpose as a for loop, and they can be swapped in almost any case, but sometimes it just makes more sense to use a while loop instead of a for loop.
For example, lets say we have a loop that we really have no way of knowing how many times the loop would need to run. A great example of this is while reading a file from disk. We want to keep looping until we hit the end of file (EOF) character. I am sure you could probably find out the length of the file, divide the bytes and use a for loop, but it just feels better to use a while loop. After programming for a while you will get a good feel of when to use a while loop and when to use a for.
The first example, is just re-writing the counting loop from above just to show you how it is done. The second example is reading from an OracleDataReader. I am not going to show the opening of the data reader and all that, but I am just going to loop through it for you and am going to fill our addressBook from before. I am going to use some newer notation (.Net 3.5) to make the code a bit shorter for the initialization of the person object.
C#
//Example 1
int i;
while (i < 10) {
Response.Write("i=" + i.ToString());
i++;
}
//Example 2
while (reader.HasRows) {
person peep = new person { FirstName = reader["FirstName"], LastName = reader["LastName"], Age = reader["Age"] };
addressBook.Add(peep);
}
So those are your basic loops. There is one more type of loop that can be used the do-while. But haven't used that in many years and is only used in a few cases. The difference being the compiler will check the condition at the end of the loop instead of at the beginning, so your loop will always execute at least once, this is called a post test loop.
And a special thanks to
Brent for guest editing this post
Labels: .NET, Back to Basics
posted by Tom Becker at
|

Monday, November 9, 2009
Back to Basics: Conditional Statements
This is the second in my Back to Basics series, and this time we are going way back. Conditional statements are some of the very first things you learn in any introductory programing class. In this post I will show you the C# and VB syntax for if, if/else, and switch statements.
If-statement
We will start off with the simplest of conditional statements, the if-statement. This is just simple boolean logic that will evaluate true or false. If the result is true, it will execute the block, if false it will skip it. In this example we will check to see if a person is over the age of 21. We will be using the same person class as in my last
postC#
if (myPerson.Age >= 21)
canDrink = true; //Whatever logic you want
Notice that in C# you can omit the curly braces ({}) if the logic under the if statement is one line long. If it is longer than one line you must use the braces. If you omit those, then the line directly beneath the if statement will be the only one evaluated on a conditional basis the rest of the statements will always be executed.
However in the VB.Net syntax you must have a closing End If, even if the statement is a single line.
VB
If myPerson.Age >= 21 Then
canDrink = true
End If
If/Else
The next example is of an if/else statement. The same rules apply as before, we are just extending it a bit. You can chain together as many if/else statements as you wish, just by adding more conditions. However all of the conditions must before the else, with the else being the final statement (if needed, don't have to have an else).
Once the compiler finds a match for your statement it will not execute any more of the statements in your if/else block. This lets the compiler be more efficient.
C#
if (myPerson.Age < 18)
canDrink = canVote = false;
else if (18 <= myPerson.Age < 21) {
canVote = true;
canDrink = false;
}
else {
canDrink = canVote = true;
}
Note in this example that I mixed my curly braces. First condition I didn't need them since I had one line. Second one I did since I have more than one line. And the third I didn't need them but put them anyway.
VB
If myPerson.Age < 18 Then
canVote = canDrink = False
ElseIf 18 <= myPerson.Age < 21 Then
canVote = True
canDrink = False
Else
canVote = canDrink = True
End If
Switch Statement
The switch statement is a little more complicated than the if and if/else statements but it can be very useful and make your code look cleaner in a lot of places. They can be very useful when evaluating enumerations. In the example below lets assume that our person class has an enumeration of hair colors called (strangely) HairColors. So lets use an switch statement to evaluate our public property hair, and do some logic based on hair color. If the hair color is not in our list the default case will be evaluated. I realize that since we are using an enum we would never evaluate the default case, but just bear with me.
C#
switch (myPerson.hair) {
case HairColors.brown:
//You are a brunette
break;
case HairColors.blonde:
// you are blonde, duh
break;
case HairColors.red:
//You are a redhead
break;
case HairColors.black:
//You have black hair
break;
default:
//You have colorful hair
break;
}You must use the break statement to end each specific case. This will exit you out of the enclosing block, in this case the switch. The break statement can be used in any control flow statement, and it will have the same effect. In the switch statement though it is required, and the compiler will throw an error if you omit this step.
VB
Select Case myPerson.hair
Case HairColors.brown
'You are a brunette
Case HairColors.blonde
' you are blonde, duh
Case HairColors.red
'You are a redhead
Case HairColors.black
'You have black hair
Case Else
'You have colorful hair
End Select
In VB, the switch statement is known as a Select Case, and as you can see by the syntax it is very similar to C# other than the naming. In this case however, you do not need to include the break statement, the flow will stop when it hits the next case keyword.
As a bonus I will give you one more statement called the ternary operator. This works very well in C# because of
short-circuiting, but in VB you have to be careful because VB won't short circuit.
You can use the ternary operator to evaluate something and assign a value on one line. You can easily re-write it to be an if/else statement. Lets re-write our first statement using a ternary operator. The first part is your condition. So in this case we are checking to make sure person is over 21. After the question mark is the true part of the statement and the last is the false.
C#
canDrink = myPerson.Age >= 21 ? true : false;
VB
canDrink = IIf(myPerson.Age >= 21, True, False)
The syntax is very similar, however this isn't a true ternary operator since we are calling a function (iif), but it functions almost exactly the same. The difference being that in VB the second part of the statement (the false section) will still be evaluated. In this case it wouldn't matter if it is evaluated since nothing can go wrong.
Check here for some other reading on the subject of VB and iif.
Conclusion
So there are your basic control flow and conditional statements. I hope this was useful, and good luck.
Labels: .NET, Back to Basics
posted by Tom Becker at
|

Thursday, November 5, 2009
Back to Basics: Parameterizing Inline SQL
Things have been a bit slow with any interesting project work and I don't want this blog to fall
even more stagnant . So I am going to be writing a new series called "Back to Basics" containing best practices and some basic code references aimed at newer coders.
There are some situations in which you cannot use stored procedures in order to handle all of your data access. Some cases it is just because of the architecture where you are at, other times it is because you are building the SQL at run time (this still can be done in both P/L or T-SQL but in this case we are going to write it inline).
But no matter what the circumstance, it is still good practice to parameterize your statements. This can help with style as well as helping to protect against
SQL Injection (Wikipedia).
We will take a normal inline SQL statement and convert it to a parameterized statement. We will start with this.
public void Save() {
string sql = "INSERT INTO People (First_Name, Last_Name, Age) VALUES (\"" + this.FirstName + "\", \"" + this.LastName +
"\", \"" + this.Age + "\");";
using (OracleConnection conn = new OracleConnection("connstring"))
using (OracleCommand comm = new OracleCommand(conn, sql)) {
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
}This will work as is, and technically is correct. However, the readability goes out the window. With all the escape characters and everything in that statement it becomes hard to read very quickly. This is also a very small insert statement. Imagine a larger table with 15-20 rows. The statment would become huge and debugging would become hard if you mistyped something, so along with the readability, scaleability is bad as well.
So lets take that statement and parameterize it. This adds to the number of lines of code, but in this case it is well worth it. We take out all of the items in the VALUES clause and replace them with identifiers, much like you would if you were writing a full stored procedure. Then you can add the parameters to the command object. With this you can specify data types and sizes to even further restrict the data entered to help make sure no bad data gets through. This also allows you to significantly shorten your SQL statement, and allows you to add another value much easier than in the previous example.
public void Save() {
string sql = "INSERT INTO People (First_Name, Last_Name, Age) VALUES (:FirstName, :LastName, :Age);";
using (OracleConnection conn = new OracleConnection("connstring"))
using (OracleCommand comm = new OracleCommand(conn, sql)) {
comm.CommandType = CommandType.Text;
comm.Parameters.Add(":FirstName", OracleType.VarChar, 50).Value = this.FirstName;
comm.Parameters.Add(":LastName", OracleType.VarChar, 50).Value = this.LastName;
comm.Parameters.Add(":Age", OracleType.Int32).Value = this.Age;
comm.ExecuteNonQuery();
}
}This will work for both Oracle and MS SQL, you would just have to change from and Oracle connection and command to a SQL one. Also I think the preferred syntax when using MS SQL would be to use the @ symbol rather than the colon.
Labels: .NET, Back to Basics, SQL
posted by Tom Becker at
|

Monday, September 21, 2009
Custom Attributes in C#
An attribute in C# is a way for you to add meta-data around an element in your code. You can attach an attribute to many different targets, see
here for full list.
Attributes are useful in supplying extra information about the target at all stages of developement, from design to run time. They help you specify specific information about the target, such as the method type, such as designating a
WebMethod. Or to inform the compiler that a method is now obsolete, so that the compiler can warn you that you are using an outdated method. I think the most recognizable one that I think most people would have used an not even thought about it as an attribute is the
Serializable.You can also create your own custom attributes in C#, and basically all it takes is a small lightweight class that inherits from System.Attribute and has a constructor and some public properties. These properties can be then read at runtime through reflection.
In this example, we are going to create an attribute to denote a field that we can expect in an import from a user. So first we create the attribute. We are going to require that we have 3 pieces of meta-data in our attribute, a display name, whether or not the field is required in the upload, and a description of the field (used for display purposes). So let's create the class
using System;
using System.Collections.Generic;
using System.Text;
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false)]
public class ImportDescriptor : System.Attribute{
/// <summary>
/// Custom Property Attribute
/// </summary>
/// <param name="displayName">The string to be displayed in the Import UI (e.g. grid column) for this property.
/// <param name="required">If true, a value for this property is required for import. If false, the property value is optional.
public ImportDescriptor(string displayName, string description, bool required) {
DisplayName = displayName;
Required = required;
Desc = description;
}
public string DisplayName{
get { return (_displayName); }
set { _displayName = value; }
} private string _displayName = null;
public bool Required{
get { return (_required); }
set { _required = value; }
} private bool _required = false;
public string Desc{
get { return (_desc); }
set { _desc = value; }
} private string _desc = null;
}
As you can see we inherited from System.Attribute, and we are using an attribute called
System.AttributeUsage (msdn), that tells us how this attribute is going to be used.
Now we need to add that attribute to the properties on our class that we expect to see in an import. Assume we have a class Person that has properties of PersonID, FirstName, LastName, and Title. And lets assume that everything except title is required. So lets add the attributes to the Person class.
public class Person {
private int _personID;
private string _first_name;
private string _last_name;
private string _title;
public Person() {
//empty constructor
}
[ImportDescriptor("Person ID", "ID of the person", true)]
public int PersonID {
get { return _personID; }
set { _personID = value; }
}
[ImportDescriptor("First Name", "First Name of the pesron.", true)]
public string FirstName {
get { return _first_name; }
set { _first_name = value; }
}
[ImportDescriptor("Last Name", "Last Name of the person", true)]
public string LastName {
get { return _last_name; }
set { _last_name = value; }
}
[ImportDescriptor("Title", "The persons title in the company (CEO, Developer, etc.)", false)]
public string Title {
get { return _title; }
set { _title = value; }
}
}
We now have our class set up to use our attribute. We can add more fields to our Person class and add the ImportDescriptor attribute and our code will automatically expect to see the field in the import. So our framework is set up. We now just need to consume this. Below is an example of how to use reflection to read the attribute, and handle the line in the import accordingly. It is a brief example and will leave the rest of the import code as an exercise for you. In this example I am using reflection to read the attributes and store them in a class (ImportProperties) that we are using for the actual import. The variable _dataType is of type Object. I wanted this to be as generic as possible so that I could use this for any type of import, not just for the Person Class.
private List GetAttributes(Object dataType) {
PropertyInfo[] props = dataType.GetType().GetProperties();
PropertyInfo prop;
List<importproperties> lst = new List<importproperties>();
for (int i = 0; i < props.GetLength(0); i++) {
prop = props[i];
if (prop.GetCustomAttributes(typeof(ImportDescriptor), false).Length > 0) {
ImportDescriptor importDesc = (ImportDescriptor)prop.GetCustomAttributes(typeof(ImportDescriptor), false).GetValue(0);
ImportProperties import = new ImportProperties();
import.DisplayName = importDesc .DisplayName;
import.Desc= importDesc.Desc;
import.Required = importDesc .Required;
lst.Add(import);
}
}
return lst;
}
Since you can have multiple attributes per target we are only going to be looking for the ImportDescriptor, you can extend this to read all attributes.
Also, since this is using reflection and a list, you need to make sure you are using System.Reflection, and System.Collections.Generic in order to use PropretyInfo.
Labels: .NET
posted by Tom Becker at
|

Tuesday, August 18, 2009
CHAMPIONS!!
<Trumpet Flair>
Last night were the playoffs for Bottom of the Fifth. It was a single elimination tourney, and our first game was at 8 against Commonwealth Chapel. This is the team that has beat us twice, and seeded number 3 in the league. Since we were seeded number 2 we were home team.
The first inning they scored 1 quick run and we held them there for the next 3 innings. We were nervous this first inning and we bobbled a few there, but we held them once we settled down. Our offense though was much more productive than theirs. And we rolled over on them for the rest of the game. I think our biggest motivation to win this game was so we could go on to the finals and kick the crap out of Big League Chew.
We got a 10 minute break between our first game and the second, and we were under way.
Big League Chew was seeded number one at this point, and they we had beat them 2 out of the 3 times we went against them, and they are just all around annoying. So we really really really wanted to cream them. And we did. Both teams came out swinging. We were away this round so we were at bat first and put up a quick 5 runs. We were consistent and had an awesome day both pitching and batting and quickly moved up 15-2. They were ecstatic at every play of theirs, even going so far as calling out our players, asking them if they were ready. They were loud and vocal, and pretty annoying.
So since we were up by so much we flip flopped the last inning (as I have mentioned I am not a big fan of this). So score is still 15-2, and they are up at bat again. We get a strike out and a fly out to left field. 2 outs in the last inning. And we get real nervous just thinking too much ("Get out of your head Crash"). And they get a rally going. Again being really annoying and boastful after every hit. But it doesn't matter, cause we still won in the end. Final score was 15-13.
Hopefully the Fifth will be playing some fall ball, but that is still up in the air, have to make sure we have enough players.
But for now we are the reigning CHAMPIONS!

Labels: Softball
posted by Tom Becker at
|

Tuesday, August 11, 2009
The Pros
So this was the very last game of our regular season. Next week we have play offs and then we are off for a few weeks before fall ball (assuming we can get a team together).
Last nights game against the Pros was an interesting one. We were supposed to have two games yesterday but the first team we were supposed to play had to forfeit since they couldn't field a team. So apparently the commissioner of the league thought that we were going to forfeit our second game for some reason, and told the ump for our field as well as the Pros that we weren't going to be there.
So we get there with no umpire and the Pros leaving the field. We get everything squared away and find an umpire that was hanging around getting ready for a late game and we can finally start the game.
We were the home team, so we were out in the field first and the Pros came out swinging scoring 4 in the first inning. It should have been 3, but I bobbled a pop fly that landed foul, but I should have had anyway. It was in my glove, but it popped back out. Bummer, but we got out of the inning not to much longer after that. Bottom of the first we scored 3.
We rallied a few innings later and put some runs up making the score 13-4. It was about this time that our pitcher Craig took a line drive to the family jewels, and amazingly still made the out at first. It was fantastic. Such dedication, such grit. Needless to say he sat out for a few innings icing down the goods.
So we had to pull in our second string pitcher, Will, who did fine the first inning he pitched with some good fielding we held them that inning. We are up and score one or two runs maybe. I walked a few times, and we were sitting pretty.
The next inning (the fifth I believe) Will is pitching again, and just keeps walking people. They score 7 before Will throws in the towel. And amazingly Craig comes back in to finish the game. He closed out that inning and pitched one more striking out the go ahead run in the sixth.
It was a rollercoaster of a game, but it was a good one. I think everyone played very well, but Craig is the MVP of the game. The only pitcher I know to start, leave the game, and come in to earn save.
Next week are playoffs, and I'll let everyone know how we did. Crossing our fingers for the campionship!
Labels: Softball
posted by Tom Becker at
|

Friday, August 7, 2009
Fighting Cox round 2ish
Last two weeks have been rained out so it has been a while since we've had a game, but we came back from the break strong and won what would normally be our last game of the regular season.
It is usually pretty fun to play these guys. They are a team from the local radio station and are a good group. They were getting pretty frustrated with us though since we were taking so many of their pitches and we just kept walking around the bases. I think I was up 3 times, and walked twice, and the ball I hit was low and outside (practicing my golf swing). So there was some grumbling on their end this game, but I think we still had fun.
I don't have the score but I do know we were up 15-2 in the second inning, if that tells you anything.
Next week we have a double header, we are playing the two teams we missed playing the past two weeks, and then after that we are in the playoffs.
Labels: Softball
posted by Tom Becker at
|
