Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, February 24, 2011

Create Linq To Entities Connection in Code

If you're like most people, you have several different database servers that you need to connect to and you want to be able to deploy an application to different environments while only changing configuration entries. Linq To Entities has a different connection string and offers a slightly different approach to configuring the connection.

First, the code...


private static EntityConnection connection()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = System.Configuration.ConfigurationManager.AppSettings["DataSource"].ToString();
sqlBuilder.InitialCatalog = System.Configuration.ConfigurationManager.AppSettings["InitialCatalog"].ToString();
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = System.Configuration.ConfigurationManager.AppSettings["UserID"].ToString();
sqlBuilder.Password = System.Configuration.ConfigurationManager.AppSettings["Password"].ToString();

EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = System.Configuration.ConfigurationManager.AppSettings["Provider"].ToString();
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = System.Configuration.ConfigurationManager.AppSettings["MetaData"].ToString();

EntityConnection entityConnection = new EntityConnection(entityBuilder.ToString());

return entityConnection;
}

The explanation...
First, create a SqlConnectionStringBuilder object. Next, assign the DataSource, InitialCatalog, User and Pass from values stored in the app.config. If you choose not to use Integrated Security set that property to false.

Now, create an EntityConnectionStringBuilder object. Assign the provider and metadata values. Assign the ProviderConnectionString property to the SqlConnectionStringBuilder.ToString() value.

Finally, create a new EntityConnection object and pass it the EntityConnectionStringBuilder.ToString() and you have yourself a new EntityConnection.

Wednesday, January 12, 2011

Facade Pattern in C#

O'Reilly's modern classic Head First Design Patterns describes the Facade pattern as a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

This pattern is nothing revolutionary and something that all programmers have done at some point, but it is good to have a common name to go by. Today I will demonstrate how to create and remove groups in Active Directory by building a facade.

First, start Visual Studio and create a new project using the class library template. Once created, add a reference to ActiveDs in the project. Next, add a new class named ActiveDirectoryFacade.cs and add Using System.DirectoryServices to that class. Now, add the following function to create a group...


public static bool CreateGroup(string groupName, out string result)
{
bool returnValue = false;
result = "";

try
{
DirectoryEntry groups = new DirectoryEntry();
groups.Path = "LDAP://ldap/OU=EmailGroups,DC=yourdomain,DC=com";
groups.AuthenticationType = AuthenticationTypes.Secure;

DirectoryEntry group = groups.Children.Add(String.Format("CN={0}", groupName), "group");
group.Properties["groupType"].Value = ActiveDs.ADS_GROUP_TYPE_ENUM.ADS_GROUP_TYPE_GLOBAL_GROUP;
group.Properties["mail"].Value = String.Format("{0}@yourdomain.com", groupName);
group.CommitChanges();

result = String.Format("Successfully created distribution list {0}", groupName);
returnValue = true;
}
catch (Exception ex)
{
result = ex.Message;
returnValue = false;
}

return returnValue;
}


...and add the following function to remove a group...


public static bool RemoveGroup(string groupName, out string result)
{
bool returnValue = false;
result = "";

try
{
DirectoryEntry groups = new DirectoryEntry();
groups.Path = "LDAP://ldap/OU=EmailGroups,DC=yourdomain,DC=com";
groups.AuthenticationType = AuthenticationTypes.Secure;

DirectoryEntry group = groups.Children.Find(String.Format("CN={0}", groupName));
if (group != null)
{
groups.Children.Remove(group);
group.CommitChanges();
}

result = String.Format("Successfully removed distribution list {0}", groupName);
returnValue = true;
}
catch (Exception ex)
{
result = ex.Message;
returnValue = false;
}

return returnValue;
}


We have just created a facade to add and remove Active Directory Groups with two functions. We can now use these functions in our applications.

Wednesday, December 8, 2010

Including Metadata When Creating a PDF File Using iTextSharp

This post is a continuation of the previous introduction to iTextSharp see http://wardlawclaims.blogspot.com/2010/10/introduction-to-pdf-file-creation-in-c.html.  In this post I will demonstrate adding metadata to a PDF created using iTextSharp.  Metadata is data included in a PDF file which is about the PDF file rather than part of its contents.  Metadata might include the author and title of the document.  Metadata could be used by an indexing service to locate files based on their metadata; for example by author.

Here is a screenshot of the sample application I will include for download at the end of this post.  I've added the ability to input the metadata for author, title, subject, and keywords.



The C# source code for the application has been modified to include calls to the appropriate methods that will add the metadata to the PDF.  Be aware that the metadata methods needs to called after the PdfWriter.GetInstance method is called.  If the metadata methods are called before GetInstance no exceptions will be thrown, but the metadata will not be included in the file.   The metadata methods must be called before the Close method is called on the Document object or else an exception will be thrown.

Here is the code for adding the metadata.  A link to download the source code for the application is included at the bottom of this post.


//add metadata
//metadata must be added after GetInstance is called
if (!string.IsNullOrEmpty(this.authorText.Text))
{
    pdfDocument.AddAuthor(this.authorText.Text);
}
if(!string.IsNullOrEmpty(this.subjectText.Text))
{
pdfDocument.AddSubject(this.subjectText.Text);
}

if (!string.IsNullOrEmpty(this.keywordsText.Text))
{
    //note that keywords should be separated by commas
    pdfDocument.AddKeywords(this.keywordsText.Text);
}

if (!string.IsNullOrEmpty(this.titleText.Text))
{
    pdfDocument.AddTitle(this.titleText.Text);
}

As you can see there are methods specifically for standard metadata such as author, subject, title, and keywords.

References
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.
http://api.itextpdf.com/ 

You can download the Visual Studio project  file for the example at: 
http://www.wardlawclaims.com/attachments/blog/jeremy/including-metadata-when-creating-a-pdf-file-using-itextsharp/HelloWorldWithMetadataPdfDemo.zip 

Tuesday, November 9, 2010

Basic ASP.Net MVC Site



In this post I will demonstrate how easy it is to create an ASP MVC site with basic CRUD operations on the Chinook database.

  1. Start Visual Studio and create a new project using the ASP.Net MVC 2 template. I'm a proponent of Unit Testing, but for today's demo let's do not create the unit tests.
  2. Right-click the Models folder and select Add->New Item->Data->ADO.Net Entity Data Model.
  3. Name the Model Chinook.edmx and choose the Artists table to import into the model.
  4. Right-click the Controllers folder and select Add->Controller. Name the controller ArtistController and check the box to Add action methods for our CRUD operations.
  5. Next, In the Index function select all artists from the Artists table in the Chinook database like this...
public ActionResult Index()
{
using (ChinookEntities chinook = new ChinookEntities())
{
var allArtists = from artists in chinook.Artists
orderby artists.Name
select artists;

return View(allArtists.ToList());
}
}
  • Right-click "View(allArtists)" and select Add View->Check the box for Create Strongly-Typed View->Select ChinookArist.Models.Artist->Select List for View Content->Hit the Add button.
  • Now add a link to our controller in the Site.Master and we're ready to go.
  • Run the project and hit the link to Artists and you get a list of all artists in the table.





To add the details view to our project add the following snippet to the Details(int id) function in ArtistController.cs...

public ActionResult Details(int id)
{
using (ChinookEntities chinook = new ChinookEntities())
{
var artist = (from a in chinook.Artists
where a.ArtistId == id
select a).First();

return View(artist);
}
}
Next, right-click "Details" and select Add View. Be sure to select Details for our View content drop-down. Voila, a Details.aspx page is create for us.

Editing a record works in a similar manner. Add the following code to ArtistController...
public ActionResult Edit(int id)
{
using (ChinookEntities chinook = new ChinookEntities())
{
var artist = (from a in chinook.Artists
where a.ArtistId == id
select a).First();

return View(artist);
}
}

This will return the record to edit. Right-click the Edit and follow the steps to create and edit page. In addition, you will need the following which will actually perform the editing...
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
using (ChinookEntities chinook = new ChinookEntities())
{
var artist = (from a in chinook.Artists
where a.ArtistId == id
select a).First();

artist.Name = collection[1].ToString();
chinook.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}



To creating a new record use the following...
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
using (ChinookEntities chinook = new ChinookEntities())
{
Artist artist = new Artist();
artist.Name = collection[0].ToString();
chinook.AddToArtists(artist);
chinook.SaveChanges();
}

return RedirectToAction("Index");
}
catch
{
return View();
}
}

Right-click Create and a new aspx page is created for us.

Deleting a record is similar to editing in that it requires two functions...
public ActionResult Delete(int id)
{
using (ChinookEntities chinook = new ChinookEntities())
{
var artist = (from a in chinook.Artists
where a.ArtistId == id
select a).First();

return View(artist);
}
}

and...

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
using (ChinookEntities chinook = new ChinookEntities())
{
var artist = (from a in chinook.Artists
where a.ArtistId == id
select a).First();
chinook.DeleteObject(artist);
chinook.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}

Once again, right-clicking the Delete function and following the prompts will create a delete.aspx page for us.


In just a few minutes I have created a simple, yet fully functional MVC application with complete CRUD operations on a table.


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.

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:



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.

Monday, September 13, 2010

Singleton Design Pattern

Sometimes you need to guarantee that only one instance of a class is created. One example might be a database object where you only want one connection. This class should be available globally, but should only have one instance. The Singleton creational pattern conforms to this requirement.

The O'Reilly book Head First Design Patterns By Eric and Elisabeth Freeman define the Singleton Pattern as a class that has only one instance and provides a global point of access to it.

The classic book Design Patterns by Gamma, Helm, Johnson and Vlissides (Gang of Four) add the following points.

Participants
  • Singleton
  1. Defines an Instance operation that lets clients access it unique instance. Instance is a class operation.
  2. May be responsible for creating its own unique instance.

For my example, I'll create a singleton class in c# using the .Net Framework 4.0 that has a connection object in it. First, start a new console app project. Next, add a new class and name it Singleton.cs with following code...

namespace SingletonExample
{
public sealed class Singleton
{
private static readonly SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=Chinook;Integrated Security=SSPI;");

static Singleton()
{
}

Singleton()
{
}

public static SqlConnection Connection
{
get
{
if (connection.State == ConnectionState.Closed) connection.Open();
return connection;
}
}
}
}

Now, in your program.cs file add the following code to Main...

static void Main(string[] args)
{
SqlConnection connection1 = singleton.connection;
SqlConnection connection2 = singleton.connection;
SqlConnection connection3 = singleton.connection;
SqlConnection connection4 = singleton.connection;
SqlConnection connection5 = singleton.connection;

Console.ReadLine();
}

As you step through the code run sp_who2 on the Chinook database and you will see only one connection added.

By the way, the Chinook database is on Codeplex and is designed as alternative to Northwind. It's small, will run on SQL Server, Oracle and MySQL and installs with a single script.