.NET Why Code to Interface?
Posted: 06/08/2012 Filed under: Programming | Tags: .NET, C#, Design Patterns Leave a comment »You may have seen programming design patterns and practices encourage coding to interfaces. And you may have also seen examples as to how to achieve this. The question is, why? Why should a programmer make this his second nature.
The following example would hopefully, shed some light into this, and hopefully help you get into the habit of good coding habits.
Let’s just say we take the “Game of Thrones”. In the book and TV series you would have noticed the numerous characters involved. I begin with creating two classes, representing two types of characters, one for a Knight and another for a Lord.
class Knight { // TODO } class Lord { // TODO }
As you can see, they do absolutely nothing at the moment. But one of the main functionality for my program is to retrieve character’s attributes. I have the method for this ready, the idea of this method is to retrieve the attributes from a particular character and return them as a string array.
public string[] GetCharacterAttributes() { // TODO }
I could instantiate my required object from the concrete classes before as below.
public string[] GetCharacterAttributes() { var character = new Knight(); // Retrieve the attributes from Knight }
The above would be ok and have absolutely no problems. However, what if I needed to get attributes for a Lord character type as well? I could pass them in as parameters, as below.
public string[] GetCharacterAttributes(Knight character) { // Retrieve Knight attributes. } public string[] GetCharacterAttributes(Lord character) { // Retrieve Lord attributes. }
But this would make the code messy and complex. Alternatively, I could do something like the below instead.
public string[] GetKnightAttributes() { var character = new Knight(); // Retrieve the attributes from Knight } public string[] GetLordAttributes() { var character = new Lord(); // Retrieve the attributes from Lord }
The above will work, the code will not be messy, and there would not be any complications. However, I am repeating the code, and I have to do it for each of my concrete class or character. And for those of you who have read the “A Song of Ice and Fire” books would know that this will get insanely hard as more and more characters are introduced.
This is where coding to an interface becomes valuable. I first create an interface called ICharacter, and then use that interface on my concrete character classes as below.
// Interface for Game of Thrones Characters public interface ICharacter { string Name { get; set; } } // Implementation of Interface on Knight concrete class. class Knight : ICharacter { public string Name { get; set; } } // Implementation of Interface for Lord concrete class. class Lord : ICharacter { public string Name { get; set; } }
Now let’s go back to our method of retrieving character attributes. I can now have just the one method, with no issues. All I’m doing now, is passing in the interface as the method parameter.
public string[] GetCharacterAttributes(ICharacter character) { // character passed in can be a Knight or a Lord // or it can be any other new characters that may get // created using the ICharacter interface. }
As you can see from the above, by coding to an interface, I do not have to deal with messy or complex code, and I do not need to repeat my code. Please note, there are ways in improving this through, Dependency Injection, but that will be a another post. I hope this helps, thank you.
C# Simple Password Generator
Posted: 28/02/2012 Filed under: Programming | Tags: C# Leave a comment »One of the simplest and easiest approach to generating random passwords, is to use the GetRandomFileName() static method from the Path class.
Snippet below demonstrates this.
1: using System;
2: using System.IO;
3:
4: static void Main(string[] args)
5: {
6: // Calls the static method from the Path type
7: var randomFolderFile = Path.GetRandomFileName();
8:
9: // Strips out dot characters
10: randomFolderFile = randomFolderFile.Replace(".", "");
11: Console.WriteLine(randomFolderFile);
12: }
Happy Coding.
Error Object cannot be cast from DBNull to other types.
Posted: 22/02/2012 Filed under: Programming | Tags: C#, Error Leave a comment »This happens when the database is returning an object of type DBNull. Best approach towards handling this error would be to check if the object is of type DBNull first, before attempting to use it. Sample snippet below demonstrates this, using the Convert.IsDBNull method.
1: var reader = command.ExecuteReader() // assumes SqlCommand has been initialised
2:
3: if(!Convert.IsDBNull(reader["DateInDatabase"])) // if it is not returning DBNull
4: {
5: // Do Something
6: }
Hope this helps.
C# Sort DateTime in List<>
Posted: 20/02/2012 Filed under: Programming | Tags: C#, Collections 2 Comments »Do you need to sort your list of objects/types by DateTime? The snippet sample below shows you how.
UPDATED 21/02/2012
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4:
5: static void Main(string[] args)
6: {
7: var times = new List<string>
8: {
9: "18 APR 6:30 AM",
10: "14 MAR 4:50 PM",
11: "17 APR 3:15 PM",
12: "14 MAR 11:25 AM",
13: "22 OCT 11:25 PM"
14: };
15:
16: #region Appended
17:
18: var temp = new List<string>();
19:
20: // Split the string then add in year value into new string.
21: // The new string format can be converted to a DateTime type.
22: // Add new string into a new collection.
23: for (var i = 0; i < times.Count; i++)
24: {
25: var splitTime = times[i].Split(' ');
26: var newTimeFormat = splitTime[0] + " " + splitTime[1] + " 2012 " + splitTime[2] + " " + splitTime[3];
27:
28: temp.Add(newTimeFormat);
29: }
30:
31: #endregion
32:
33: #region Updated
34:
35: var list = temp.Select(Convert.ToDateTime).ToList();
36: // The above line is equilevant to the line below.
37: // var list = times.Select(t => Convert.ToDateTime(t)).ToList();
38:
39: #endregion
40:
41: list.Sort(DateTime.Compare);
42: // The above line is equilevant to the line below.
43: // list.Sort((d1, d2) => DateTime.Compare(d1, d2));
44:
45: foreach (var date in list)
46: {
47: Console.WriteLine(date);
48: }
49: }
Hope this helps.
C# Remove from a collection after comparing another collection.
Posted: 10/02/2012 Filed under: Programming | Tags: C# Leave a comment »This post shows you how it’s possible to compare two list collections and remove items/object when they do not match.
I have, for the purpose of this post, created a simple Record entity.
|
class Record |
Now I instantiate some record objects, and add them to two separate collections. Note how primaryRecords has duplicate objects of Record1? Also, note that secondaryRecords also has an object of Record1.
|
var primaryRecords = new List<Record> var secondaryRecords = new List<Record> |
Now, I compare my secondaryRecords and my primaryRecords to ensure that only unique records within the secondaryRecords is made available.
This is first accomplished by getting unique record objects from primaryRecords, which is achieved through the use of a HashSet<> object with little bit of lambda sprinkled in.
|
using System.Collections.Generic; // HashSet is used to eliminate duplicate records from primary record // remove records that also exist in recordsId |
A console output of enumerating and displaying secondaryRecords would be as below.
| Record4 Record5 |
Hope this helps you in moments of madness dealing with multiple collections.
C# Working with Timer Object
Posted: 13/01/2012 Filed under: Programming | Tags: C# Leave a comment »A timer object can be really helpful when there is a need of some form of scheduling. For example, writing entries into a log file hourly. MSDN defines the Timer class as an object that generates recurring events in an application.
The code snippet below shows a simple example using Timer to write out a line every 5 seconds (console application).
1: using System;
2: using System.Timers;
3:
4: static void Main(string[] args)
5: {
6: BeginSchedule();
7: Console.ReadKey();
8: }
9:
10: private static void BeginSchedule()
11: {
12: var timer = new Timer
13: {
14: // Gap between each event execution
15: // set to 5 seconds in miliseconds.
16: // Then timer is started.
17: Interval = 5000,
18: Enabled = true
19: };
20:
21: // Event that is called after each timer interval.
22: timer.Elapsed += new ElapsedEventHandler(TimerElapsedEvent);
23: }
24:
25: static void TimerElapsedEvent(object sender, ElapsedEventArgs e)
26: {
27: Console.WriteLine("5 seconds later.");
28: }
Code well.
C# Creating a CSV File
Posted: 13/01/2012 Filed under: Programming | Tags: C# Leave a comment »If you need to create a comma-separated values (CSV) file, then the code snippet below shows you how, quickly and easily.
1: using System;
2: using System.Collections.Generic;
3: using System.IO;
4: using System.Text;
5:
6: private static void CreateCsvFile()
7: {
8: var filePath = @"C:\Books.csv";
9:
10: // Initialise stream object with file
11: using (var wr = new StreamWriter(filePath, true))
12: {
13: // Collection of book titles
14: var row = new List<string>
15: {"A Game of Thrones", "A Clash of Swords", "A Feast for Crows", "A Dance with Dragons"};
16:
17: var sb = new StringBuilder();
18:
19: foreach (string value in row)
20: {
21: // Add a comma before each string
22: // this adds a comma before the book title
23: if (sb.Length > 0)
24: sb.Append(",");
25:
26: sb.Append(value);
27: }
28:
29: // write output to file
30: wr.WriteLine(sb.ToString());
31: }
32: }
Hope this helps, happy coding.
C# Sending and Receiving Information through URL
Posted: 11/01/2012 Filed under: Programming | Tags: C# Leave a comment »Imagine if you had an application that is not a web application but interacts with one. If this is your scenario, then we can use the WebClient class. As it states on MSDN, this class provides common methods for sending data to and receiving data from a resource identified by a URI.
Code snippet below shows a very basic example in accomplishing this.
1: using System.IO;
2: using System.Net;
3:
4: static void Main(string[] args)
5: {
6: // Initialise new WebClient object to send request
7: var client = new WebClient();
8:
9: // Add the QueryString parameters as Name Value Collections
10: // that need to go with the HTTP request, the data being sent
11: client.QueryString.Add("id", "00001");
12: client.QueryString.Add("author", "Harish Mathanan");
13: client.QueryString.Add("tag", "Programming");
14:
15: // Prepare the URL to send the request to
16: string url = "http://somerandomsite.com";
17:
18: // Send the request and read the response
19: var stream = client.OpenRead(url);
20: var reader = new StreamReader(stream);
21: var response = reader.ReadToEnd().Trim();
22:
23: // Clean up the stream and HTTP connection
24: stream.Close();
25: reader.Close();
26: }
C# Reading XML Files
Posted: 19/12/2011 Filed under: Programming | Tags: C#, XML 2 Comments »This post is written with the intention of showing you very quickly how to read an XML document through code.
Listed below is my XML file that I will be working on, filled with fictional data. It’s essentially a listing of books, with their Title, Publisher and Author.
1: <?xml version="1.0" encoding="utf-8" ?>
2: <!-- Listing of all Books -->
3: <Books>
4: <Book>
5: <Title>Master ASP.NET Development</Title>
6: <Publisher>MS Press</Publisher>
7: <Author>Scott Guthrie</Author>
8: </Book>
9: <Book>
10: <Title>Deep Dive Web Programming</Title>
11: <Publisher>MS Press</Publisher>
12: <Author>Scott Hanselman</Author>
13: </Book>
14: <Book>
15: <Title>ASP.NET Good Sense</Title>
16: <Publisher>MS Press</Publisher>
17: <Author>Jon Galloway</Author>
18: </Book>
19: </Books>
The simplest approach to reading this file would be to use the XmlTextReader class (part of the System.Xml namespace). The code snippet below shows you how to put this class into action.
1: // Initialise object by passing in a known path to XML file.
2: // This can also be an URL.
3: XmlTextReader xml = new XmlTextReader(@"C:\Projects\ConsoleReadXML\ConsoleReadXML\Books.xml");
4:
5: while (xml.Read()) // Ensure there is content.
6: {
7: if (xml.NodeType.Equals(XmlNodeType.Element)) // Find all nodes that are elements.
8: {
9: switch (xml.Name) // Evaluates each element by its name.
10: {
11: case "Title":
12: Console.WriteLine();
13: Console.WriteLine(xml.ReadElementString("Title")); // Reads the value of the element.
14: break;
15: case "Publisher":
16: Console.WriteLine(xml.ReadElementString("Publisher")); // Reads the value of the element.
17: break;
18: case "Author":
19: Console.WriteLine(xml.ReadElementString("Author")); // Reads the value of the element.
20: break;
21: default:
22: break;
23: }
24: }
25: }
My output for the above would be as below:
Master ASP.NET Development
MS Press
Scott Guthrie
Deep Dive Web Programming
MS Press
Scott Hanselman
ASP.NET Good Sense
MS Press
Jon Galloway
Press any key to continue . . .
Note, in the snippet above, I’ve used a pre-defined path to my XML document. The use the ReadElementString() method to get the value of the elements.
Although this approach is quick, there is a small annoyance with it. For example, what if I have a I would like to enumerate through all elements that belong to each book element? You could still achieve this but it’s gets messy, especially when you need to used the data from each book element.
The code snippet below shows you how to achieve this by using the XmlDocument class instead.
1: // Initialise and load Xml document from pre-defined path.
2: XmlDocument xml = new XmlDocument();
3: xml.Load(@"C:\Projects\ConsoleReadXML\ConsoleReadXML\Books.xml");
4:
5: // Retrieve the parent node of the document <Book>
6: XmlElement parent = xml.DocumentElement;
7: XmlNodeList children = parent.ChildNodes;
8:
9: for (int i = 0; i < children.Count; i++)
10: {
11: // Retrieve child nodes under parent
12: // as defined in xml document.
13: XmlNode title = children[i].FirstChild;
14: XmlNode publisher = title.NextSibling;
15: XmlNode author = publisher.NextSibling;
16:
17: Console.WriteLine();
18: Console.WriteLine(title.InnerText);
19: Console.WriteLine(publisher.InnerText);
20: Console.WriteLine(author.InnerText);
21: }
The output for the above will remain the same. Note however, I am looking for all elements within a parent element, in this case <Book> then listing them out. The reason I’ve used the XmlNode object is simply to keep things clean.
Why didn’t I just used NextSibling? Things would have got quite silly if I have more child elements involved. Imagine having something like this:
children[i].NextSibling.NextSibling.NextSibling.NextSibling.InnerText
You get the picture.
Happy coding.
C# Saving and Retrieving Image from Database
Posted: 14/11/2011 Filed under: Programming | Tags: C# Leave a comment »This post simplifies the whole approach to saving and retrieving of images from a database. In the real-world, it is highly recommended that your application be separated into separate layers and that validation be implemented for incoming and outgoing data.
The User Interface
A simple markup for uploading the image and displaying the image.
The Database
A table to store the image using the image sql db type.
2 stored procedures, one for Inserting a new image. And another for selecting an existing image based on it’s id.
The Code
I have my database connection string stored in my web.config with the name “SampleDB”.
Saving the image to the database is performed on the Upload button click event btnUpload_Click.
1: public void btnUpload_Click(object sender, EventArgs e)
2: {
3: string conn = ConfigurationManager.ConnectionStrings["SampleDB"].ConnectionString;
4:
5: // FIRST PART:
6: // get the uploded picture into a byte[] array
7: // from the FileUpload control (photoUpload)
8: byte[] content = new byte[this.photoUpload.PostedFile.InputStream.Length];
9: this.photoUpload.PostedFile.InputStream.Read(content, 0, content.Length);
10:
11: // SECOND PART:
12: // save the byte[] into the database image type
13: using (SqlConnection dbConn = new SqlConnection(conn))
14: {
15: dbConn.Open();
16: using (SqlCommand cmd = new SqlCommand("InsertNewPhoto", dbConn))
17: {
18: cmd.CommandType = CommandType.StoredProcedure;
19: cmd.Parameters.Add("@photo", SqlDbType.Image);
20: cmd.Parameters["@photo"].Value = content;
21:
22: cmd.ExecuteNonQuery();
23: }
24: }
25: }
Retrieving the image from the database is performed on the Page_Load event through the use of a Generic HTTP Handler created Photo.ashx
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: if (!this.Page.IsPostBack)
4: {
5: this.photoImage.ImageUrl = "Photo.ashx";
6: }
7: }
ProcessRequest method modified on the Photo.ashx Generic HTTP Handler.
1: public void ProcessRequest(HttpContext context)
2: {
3: // REAL WORLD:
4: // Retrieve an id that has been passed into a querystring.
5: // the id is then passed to the database to retrieve the relevant
6: // photo.
7:
8:
9: // This example passes in just the one particular value all the time.
10: byte[] content = null;
11: context.Response.ContentType = "image/jpeg";
12: context.Response.Clear();
13:
14: string conn = ConfigurationManager.ConnectionStrings["SampleDB"].ConnectionString;
15:
16: using (SqlConnection dbConn = new SqlConnection(conn))
17: {
18: dbConn.Open();
19: using (SqlCommand cmd = new SqlCommand("SelectPhotoById", dbConn))
20: {
21: cmd.CommandType = CommandType.StoredProcedure;
22: cmd.Parameters.Add("@photoId", SqlDbType.Int);
23: cmd.Parameters["@photoId"].Value = 1; // constant value being passed in
24:
25: using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
26: {
27: while (rdr.Read())
28: {
29: content = (byte[])rdr["Photo"];
30: }
31: }
32:
33: }
34: }
35:
36: context.Response.BinaryWrite(content);
37:
38: }