Tag: C#

Just found this out yesterday so I thought I would post and pass on to all two of you reading this.

Suppose you have a User table and a Contacts table and you wanted to find all the users that match up with the contacts table. Now suppose there is no direct correlation. What to do? You could do something really brilliant by joining the tables together on FirstName and LastName, because we all know that there will always only be one John Smith in either table. Screw you, I couldn’t think of a better example at the time.

This may be novel or really dumb, but I like it. Say you want to convert a Dictionary to a List of KeyValuePairs that are sorted by something within the dictionary Key or Value. Don’t ask why, just go with it. You could do this:

If nothing else, you don’t have to create or implement a System.Collections.IComparer class to use the .Sort method. That seems worth it. That and I think it just plain looks better, but that just me. If I am completely wrong here, refer to the title of this post. Just a thought really.

Ok here’s the next step in this testing kick. So now you have your test classes that create classes. Swell. Problem is, there are private fields on the base class of whatever class you are creating. So you’re screwed, right? Not really. Now what I am about to do is nothing new. It’s just basically using Reflection and FieldInfo to fill a field on a base class. Actually very easy. Here’s the code for the example.

using System;
using System.Collections.Generic;
using System.Reflection;
public classUserBase
{
private Boolean _isBaseUser;
public UserBase()
{
_isBaseUser = true;
}
public Boolean IsBaseUser
{
get
{
return _isBaseUser;
}
}
}
public classMainUser : UserBase
{
//Simple list used to "cache" the field info so reflection doesn't have to be used //again for a type that has already been used.private staticDictionary<Type, List<FieldInfo>> typeToInfoList;
/// <summary> /// This is used to fill in the needed field on the passed in object. This is done by reflection/ /// FieldInfo. Basically you get the field info you want off the type, then you use the info to /// fill the field on the object. /// </summary> /// <param name="objectToFill">This is the object that needs the field changed.</param> /// <param name="fieldName">This is the name of the field.</param> /// <param name="value">This is the value to be set.</param> /// <param name="typeToCheck">This is the type of the class that the field resides.</param>public staticvoid FillField(Object objectToFill, String fieldName, Object value, Type typeToCheck)
{
List<FieldInfo> fieldInfoList;
FieldInfo neededFieldInfo;
Boolean heldInfoList;
if (typeToInfoList == null)
{
typeToInfoList = new Dictionary<Type, List<FieldInfo>>();
}
//Check to see of the list already has the field info and save that //boolean for later use.
heldInfoList = typeToInfoList.ContainsKey(typeToCheck);
//If it is in the "cache", grab it. If not, create a new list //for the passed in type.
fieldInfoList = heldInfoList ? typeToInfoList[typeToCheck] : new List<FieldInfo>(typeToCheck.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));
//Now just look for the needed field info in the list.
neededFieldInfo = fieldInfoList.Find(currentItem => currentItem.Name == fieldName);
//Use the field info to set the value on the object.
neededFieldInfo.SetValue(objectToFill, value);
//Store the field info list if it isn't being stored already.
if (!heldInfoList)
{
typeToInfoList.Add(typeToCheck, fieldInfoList);
}
}
//Simple constructor to create the user.public staticMainUser Create()
{
MainUser testUser;
testUser = new MainUser();
return testUser;
}
}

That’s pretty much it. What the hell is all that? Well basically you have the UserBase as the base class for the example. MainUser that in inherits UserBase. The FillField method that does all the work. And lastly, the dictionary used as a lame cache for this example. Why cache anything? Well everything you get the field info, reflection is used. This can be expensive. So why bother getting the same field info for the same type every time this method is called? Just store it somewhere so that if the same class type is passed through again, you can easily access the field info for the class without going for reflection again.

This was basically an idea I had to have test classes inherit a TestBase that has a Static Create method on it. The reason for this is that I have found it easier to have a Create method that takes care of creating a temporary class of the type the test represents. Say I have a UserTest class and I need an address. Instead of creating and filling a whole address object in the UserTest, it easier to have a Create Method on the AddressTest class that gives me a premade Address object. Why would I want to redo a lot of the same code by having the create method on every class when I can have it on a base class and just have the non base classes specify how to create the object?

Is this really needed? I can’t argue absolutely, but this forces a Create method to appear on any test class that inherits from TestBase and by use of Exceptions, forces the child classes to define how to create the object they represent. (As in it forces AddressTest to define how to create an Address object.) This also allows the Create method to be static and inherited. You could make it abstract, to skip the need for the two create methods(Create and CreateInstance), but that would hose the whole situation since static abstract is a no no. Static is a must for this situation.

The idea behind the code is to have a static Create method on the TestBase class that when called will create the test class type passed in through generics.

Where J is the test class type to create. Once that test class is instantiated, the virtual method CreateInstance is called. This is where the test class creates the instance of the object it represents.

What is [TestClass]? Well that is an attribute you are adding to the class so that .net knows certain methods in it may be test methods. Guess what [TestMethod] does…

Ok so now I have a TestClass and TestMethod, now what? Well in the menu:

Test -> Windows -> TestView

You should see that your method now shows up on the list. Simple huh? If the method isn’t showing up on the list make sure it is:

Tagged with the [TestMethod] attribute

Contained in a PUBLIC [TestClass]

Public

void

Non static

If you have all of those and still nothing, right click the method name in the Test View and look at it’s properties. There is a property called “Non-Runnable Error”. This will tell you what you need to get it rolling.

All right, now you have everything set… so next? Simple, right click the method name in the Test View and you can either Run or Debug the test. If you just Run the test, the Test Results window will pop up and you’ll see the progress. If it passes, then yay. If not, it will give you things unhandled/expected exception, failed asserts, and expected exceptions. If you debug, the same happens except, CRAZY SURPRISE AHEAD!!!, you can step through it. Also, you can run multiple tests by selecting however many you want and running them.

There are some useful options in the test view. If you right click the column area, you can add columns such as Class Name to help with ordering. After all, you might have a bunch of methods that are named the same in different classes, which sucks. Another thing you can do is left click the down arrow to the right of the refresh button for group by options.

End Note: If you don’t recognize the word “attribute” that’s ok. Most likely you have seen the [Something] notation before if you have used web controls (Possibly winforms controls, no idea). Simply put, attributes are like attaching extra information to just about anything so that later on you can use that information at runtime to perform actions. With the use of reflection, you could, for instance, check for only specific properties on a class that you want to fill dynamically. Say you have a dataset with the “UserName” column and a User class with the property Name. If you wanted to fill that Name property normally you could do something like:

user.Name = dataset["UserName"];

but with relfection you could get the property info, check the properties for a the ones with a certain attribute, and match the value in the attribute to the column name.

This is really simple, but don’t feel bad if you didn’t know about this. No one tells me nothin’ either.

The other day while reading through a blog, I got schooled without going to class. I had no idea that passwords should be one way only, as in you shouldn’t be able to retrieve a forgotten password, only reset it. Well shoot, I missed that one. So they start talking about hashing the password and saving that. Good thing I had built something to hash request items in a url to help stop people with screwing with a site url. Well ok, I didn’t totally build it. I got the idea from somewhere else. But I f-ing integrated it so don’t look at me like that.

Basically you take a password, add a salt (fancy name for a predetermined string or number) to the password, and get the hash value for that.

Why getting the same hash everytime sucks

Well the problem with hashing, or really the reason why we are doing this, is that the word “pass” creates the same hash value every time. Now if some sort of mean person figures out the hash for “pass” (That isn’t too hard since most people use some sort of standard like the .net MD5CryptoServiceProvider), he/she could search for a slew of typical password words. See the problem? Now enters the salt. The salt is some word that you come up with to add anywhere you want. This makes it a little difficult to figure out since the word “passSalt” is no longer like “pass”. one could try every word known and still fail because said person doesn’t know to add the word “Salt”.

Why getting the same hash everytime is great:

Right now you might be wonder what the point of having a password saved that can’t be unhashed to check against. Easy, you don’t have to unhash. Since the hash for “passSalt” will always be the same, the password in the database will always match the entered password + the salt. So basically the user enters the password, the system adds the salt to the password, the system then gets the hash, and finally checks that against the database record. Fun huh?

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Enumerable.Range basically says, “Give me a collection of numbers from the first parameter to the second”, or in this case from 0 to length.

Select basically is a method that takes in an anonymous method (Lamdba expression in this case), goes through each of the items in the collection, and runs the anonymous method for every item in the collection. Not exactly sure what Select does specifically, but it is most likely something like this: (roughish psuedo code)

public static I RandomEnumeration<I>()
{
I enumerationToCheck;
Int32 indexToUse;
String[] names;
//Use activator to create an instance of the type I
enumerationToCheck = System.Activator.CreateInstance<I>();
//Make sure the instance is an Enumeration //Unfortunately you can't check that in the method //delcaring using "which".
if (enumerationToCheck as Enum == null)
{
throw new InvalidOperationException();
}
//Get the list of the enumeration item names
names = Enum.GetNames(typeof(I));
if (names.Length > 0)
{
//Grab a random name within the boundaries of the //names collection.
indexToUse = RandomInt32(0, names.Length);
//parse the name to create the random enum
enumerationToCheck = (I)Enum.Parse(typeof(I), names[indexToUse]);
}
return enumerationToCheck;
}

Usage:

SomeEnum test = RandomEnumeration();

Why bother? For unit testing and creating test classes. Possibly
for defaults on an enumeration, but not really needed since
they are value types. Oh yeah AND BECAUSE I FELT LIKE IT. I don’t
have to explain myself to you.