Wednesday, October 27, 2010

Creating a Unit Test in C#

Unit testing allows a developer to isolate different functions or parts of an application and show that those parts are working correctly. There are many benefits to creating unit tests, but two of the most important ones to me are finding bugs early in the development cycle and increasing the refactor-ability of the application with ability to run tests at any time. I'll now walk through a simple project with a unit test.


First, create a project called UnitTesting using the Class Library project template. Next, add a class named UnitTest to the project and add the following code snippet to that class so that it appears as follows...


namespace
UnitTesting
{
public static class UnitTest
{
public static bool IsMsSqlSmallDateTime(this DateTime input)
{
//January 1, 1900, through June 6, 2079
return (input >= new DateTime(1900, 1, 1) && input <= new DateTime(2079, 6, 6));
}
}
}

Next, right-click on the function name and select "Create Unit Tests...". A new project is added to the solution with a class named UnitTestTest.cs. Running the test now will result in an Inconclusive result, therefore let's look at the test code in more detail. Change the test method to the following code and then rerun the test...

[TestMethod()]
public void IsMsSqlSmallDateTimeTestTooOld()
{
DateTime input = new DateTime();
input = Convert.ToDateTime("01/01/1899");

bool expected = false;
bool actual;
actual = UnitTest.IsMsSqlSmallDateTime(input);

Assert.AreEqual(expected, actual);
}

This method sets the input to a date we know to be older than a valid SQL date and calls our function. We are expecting a false return then we assert that our assumption and the function return the predicted results. You could also create the following tests to check for date that is too new and one that is just right...

[TestMethod()]
public void IsMsSqlSmallDateTimeTestTooYoung()
{
DateTime input = new DateTime();
input = Convert.ToDateTime("01/01/2080");

bool expected = false;
bool actual;
actual = UnitTest.IsMsSqlSmallDateTime(input);

Assert.AreEqual(expected, actual);
}

[TestMethod()]
public void IsMsSqlSmallDateTimeTestJustRight()
{
DateTime input = new DateTime();
input = System.DateTime.Now;

bool expected = true;
bool actual;
actual = UnitTest.IsMsSqlSmallDateTime(input);

Assert.AreEqual(expected, actual);
}

This has been a brief intro to unit test, I hope this helps out.

Monday, October 25, 2010

Adding Contacts Using the Android SDK

There are a number of good blogs about building Android apps, but Christophe Coenraets has one of the better ones out there right now. He builds a contact application in 6 projects that start off small and build in complexity. The final sample uses a SQLite database to feed the application. I will not rehash what he has done, but one thing I added was the ability to add the contact to the actual Android contacts applet using the code snippet below. As you can see this is straightforward and requires little code to implement.

Intent addContactIntent = new Intent();
addContactIntent.setAction(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT);
addContactIntent.addCategory(Intent.CATEGORY_DEFAULT);
addContactIntent.setData(Uri.fromParts("tel", officeNumber, null));
addContactIntent.putExtra(ContactsContract.Intents.Insert.NAME, employeeNameText.getText());
addContactIntent.putExtra(ContactsContract.Intents.Insert.EMAIL, emailAddress);
this.startActivity(addContactIntent);



Another slight modification from the original work was to use a different icon for the launcher. There are three screen densities for the Android: Low, Medium and High. Low density (ldpi) uses a 36x36 px PNG file, Medium density (mdpi) uses 48x48 and High density (hdpi) uses 72x72. These three densities each have a folder in the project under the res folder. Simply dropping a png file named icon.png into each of these three folders will change the icon of your application. There is a table at developer.android.com as a reference.

Wednesday, October 20, 2010

Introduction to PDF File Creation in C# Using iTextSharp

There are numerous commercial and open source components that enable .NET developers to create PDF files.  I will be providing a brief introduction to using iTextSharp to create a PDF file using C#.  iTextSharp is an open source .NET library based on the iText Java library.  This post will provide some sample code using iTextSharp to create a PDF containing text entered using a Windows forms application.

Here is a screenshot of the user interface.


















For the purpose of this sample I have added all of the program's logic to the "Create PDF" button.  Here is a walkthrough of the relevant code. You must download the iTextSharp DLL or compile it from the source code and add a reference before you will be able to use the iTextSharp namespace in your project.

Here is the C# code that does the work of creating a basic PDF file.  A complete Visual Studio solution containing a Windows Forms application is available to download as well.  The link is at the end of this post.



//name of file to create, since directory is not specified it will be created in the same directory as the program executable file
string fileName = "hello.pdf";

//create file object
System.IO.FileStream destinationFile = new System.IO.FileStream(fileName, System.IO.FileMode.Create);

//create a new pdf document
iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document();

//associate document with file object
iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, destinationFile);

//must call open method before writing file content
pdfDocument.Open();

//loop through the lines input on the form
foreach (string source in this.sourceText.Lines)
{
    //create a block of text with the content of the line followed by a newline 
    iTextSharp.text.Phrase lineOfText = new iTextSharp.text.Phrase(source + "\n");

    //add block of text to PDF document
    pdfDocument.Add(lineOfText);
}

//close document object when we're done adding content
pdfDocument.Close();

//open pdf file in default PDF application
System.Diagnostics.Process.Start(fileName);


As you can see the code required to produce a basic PDF file is not too complicated.  

References

The iTextSharp library can be found at SourceForge:

The API documentation can be found at the link below.  Note that the documentation is for the Java version, but is useful to programmers using iTextSharp for .NET as well since the .NET library's API is based on the Java version.

The author of iText has published a book on the subject.  The book is based on the Java version of the library. 

You can download the Visual Studio project  file for the example at:



Wednesday, October 13, 2010

How to Make a 3D Logo in Photoshop

Create a new image, setting the width and height to 300 with a background color of #3d3d3d. Rename the only layer we currently have a "bottom".


Select the Custom Shape Tool.



From the tool bar at the top of the page I have chosen the checkbox for this demonstration.




Draw the checkbox. Go to the Main Menu and select Filter > Stylize > Emboss. Apply the following settings.

Angle: 135
Height: 5
Amount: 75%





Put your shape in the center of the document. Your image should look like mine.



Make sure the checkbox layer is the selected layer. Press and hold the Ctrl & Alt buttons and press the up arrow key about 12 times to create the 3D effect.




Select all the checkbox layers that you just created and use the Ctrl E keys to make them into one layer. You should now have two layers.



The next step is to add color to your logo. Notice that I have also added a Drop Shadow.



Add a layer below the checkbox layer and choose a color for your background. I have chosen white. Make the other background color invisible. Below is the finished product.

Sunday, October 3, 2010

Starting Out

I am thinking of a new career or adding to my income.

It’s not uncommon for the trainers at the Wardlaw Training Center to hear this from people that have lost jobs, or have realized that the job they are in is going nowhere for them. Even students fresh out of college may realize that a shrinking market for new employees could limit what job they may be employable for.

The path of becoming a successful independent insurance claims adjuster can be a very complex one. The adjusters that are deployed by Wardlaw Claims Service are fortunate because Wardlaw has helped make this life changing challenge an obtainable goal for most people.

Most people hear about these jobs from an adjuster working a claim for them or from knowing someone in the claims business already. Normally these types of resources are great starting points to asking questions and finding out about the job. Often times the people in these positions can give a true life experience as to what an adjuster is about.

The person asking the questions needs to remember that these people will usually tell them of the great money they can earn, all of the travel involved and seeing all the country. These are true facts and will generate quite a bit of interest.

BUT, in reality, becoming an adjuster shouldn’t be for the dollar or the sightseeing. It is a job that requires a great deal of empathy and the ability to handle difficult situations day in and day out. Take as an example, a large hurricane in a very populated area of a state. The claims volumes can be huge for most carriers and every adjuster on the storm site may have a voluminous amount of claims. The adjuster has to remember that every single person only cares about only one claim, their claim.

Given this example most people say they can handle this type of situation and are eager to start a new career. The biggest question now is HOW?

Starting out by gathering information about the job is a good idea.

Most states require that a person have a license to be an adjuster. This can be obtained several different ways but the most common and best way is to take a license class in a classroom setting. The advantage of the classroom course is the interaction with the instructor and other students. Networking is a very valuable resource in this profession. In a classroom course, the course will focus on the requirements set by the state and the contents needed to study for passing the license exam. Along the way, the student will be introduced to terminology to which they have never been exposed.

This is also a good way for students to develop a resume and have the instructor’s insight on the next steps after passing the test and obtaining the license.

Next blog …I have a license, now what?

Friday, October 1, 2010

Abstract Factory Pattern In C#.Net

Sometimes when building and application you need to plan for changes that you cannot possibly plan for. For example, if you are building an application to import data from different sources and you will receive that data in completely different formats one, approach might be to create a different application for each import. That's a valid approach, but one that requires a good deal of code duplication. Let us examine the Abstract Factory pattern and see how it might help us here.

Both the old classic Design Patterns (Gamma, Helm, Johnson and Vlissides) and the new classic Head First Design Patterns from O'Reilly (Freeman and Freeman) define the Abstract Factory pattern as a way to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes. " What does that actually mean? In the example business problem from above, we could create a class for each import type that implements an interface, therefore decoupling the import parsing from the persistence of the data. In other words, we don't have to write a new application for each import type, just a new class.

The first thing I will do is create a new project and then add an Enum named ParsableType and an Interface named IImportParsable.

public class ParsableTypes
{
public enum ParsableType
{
Excel = 1,
FixedFormat = 2
}
}

public interface IImportParsable
{
bool Parse();
}

Next, I will create 2 new classes that implement our interface...

public class ExcelParser : IImportParsable
{
public bool Parse()
{
//do some excel parsing here
return true;
}
}

public class FixedFormatParser : IImportParsable
{
public bool Parse()
{
//do some text file parsing here
return true;
}
}

Next, we need a factory to determine which parser to use...
public class ImportParsableFactory
{
public static IImportParsable GetImportParser(ParsableTypes.ParsableType parsableType)
{
IImportParsable importParsable = null;

switch (parsableType)
{
case ParsableTypes.ParsableType.Excel :
importParsable = new ExcelParser();
break;

case ParsableTypes.ParsableType.FixedFormat :
importParsable = new FixedFormatParser();
break;
}

return importParsable;
}
}

Finally, we just need a controller to get the parse type and then call the parse method...
public void Import(int parseID)
{
IImportParsable importParser = ImportParsableFactory.GetImportParser((ParsableTypes.ParsableType)parseID);
importParser.Parse();
}
}

As new parse needs arise, we just add an enum entry, create a new class that implements IImportParsable and add another case to our switch and we are done. We have a nice decoupled approach that we can use by itself or combine with the Facade or Decorator patterns to add even more pattern goodness.