C# SQLCommand SELECT FROM Using Parameters

This example shows how to use SqlCommand Parameters when selecting data from a table. The important bits to look at are the SqlCommands CommandText, where you will see the @ symbol used and a variable name proceeding it.

In this instance I am using the variable @NAME in the SQL command text, the next line sets the value of the variable @NAME using the Parameters.AddWithValue() method.

 
      //build the connection string, change as appropriate
      var conStr = new SqlConnectionStringBuilder();
      conStr.DataSource = "localhost";
      conStr.IntegratedSecurity = true;
      conStr.InitialCatalog = "master";
 
 
 using (SqlConnection con = new SqlConnection())
        {
           con.ConnectionString = conStr.ToString();
 
           SqlCommand com = con.CreateCommand();
           com.CommandType = System.Data.CommandType.Text;
 
           //here we tell SQL to expect a parameter called NAME
           com.CommandText = "SELECT ID FROM MYTable WHERE Name = @NAME";
 
           //then add the Parameter using a Key Value Pair
           com.Parameters.AddWithValue("NAME", "James");
 
           con.Open();
 
           using (SqlDataReader sdr = com.ExecuteReader())
             {
                while(sdr.Read())
                  {
                     Console.WriteLine( sdr.GetValue(0) );
                  }
             }
        }

The SQLCommand has a Parameters array attached to it, every time you call com.Parameters.AddWithValue(name,value), you add another parameter to it. Please ask question!

C# Get Web Page Meta Tag Values

I have been tinkering with the HtmlAgilityPack. To install the HtmlAgilityPack Assembly run the Package Manager Console from Visual Studio as explained here. Once the HtmlAgilityPack Assembly is installed you can reference it in code with the using directive.

Setup the using directives.

using System;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

Now I have created a WePageObject class that will contain the meta tags from the webpage. This class will be used in a moment as a return type in our GetPageInfo method. I am only returning the heads meta tags, but this can be adapted to pull any tags from the html document.

  internal class WebPageObject
        {
            public string Title { get; set; }
            public string Description { get; set; }
            public string Keywords { get; set; }
            public string Url { get; set; }
            public string OgImage { get; set; }
            public string OgType { get; set; }
            public string OgDescription { get; set; }
 
        }

Next create a class with a method to pull the page information called GetPageInfo. GetPageInfo creates a new WebPageObject and fills its values using XPath expressions from each meta node using the SelectSingleNode() method of the HtmlDocument object.

internal class WebPageMeta
  {
 
     var doc = new HtmlAgilityPack.HtmlDocument();
 
    public async Task<WebPageObject> GetPageInfo(string Url)
      {
         WebPageObject wo = new WebPageObject();
         var title = "";
         var description = "";
         var keywords = "";
         var ogImage = "";
         var ogtype = "";
         var ogdescription = "";
 
 
         using(HttpClient client = new HttpClient())
           { 
 
         var headerName= "user-agent";
         var headerValue = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2;        WOW64; Trident/6.0)";
         client.DefaultRequestHeaders.Add(headerName, headerValue);
 
         using(HttpResponseMessage response = await client.GetAsync(Url))
            { 
               response.EnsureSuccessStatusCode();
               string responseBody = await response.Content.ReadAsStringAsync();
               doc.LoadHtml(responseBody);
            }
 
         var docNode = doc.DocumentNode;
 
         var titleNode =  docNode.SelectSingleNode("//title");
         if (titleNode != null)
           title = titleNode.InnerText;
 
         var descriptionXPath = "//meta[@name='description']";
         var descriptionNode = docNode.SelectSingleNode(descriptionXPath);
         if (descriptionNode != null)
            description = docNode.GetAttributeValue("content", "");
 
 
         var keywordXPath = "//meta[@name='keywords']";
         var keywordsNode = docNode.SelectSingleNode(keywordXPath);
         if (keywordsNode != null)
            keywords = keywordsNode.GetAttributeValue("content", "");
 
         var ogImageXPath = "//meta[@property='og:image']";
         var ogImageNode = docNode.SelectSingleNode(ogImageXPath);
         if (ogImageNode != null)
             ogImage = ogImageNode.GetAttributeValue("content", "");
 
         var ogType = "//meta[@property='og:type']";
         var ogTypeNode = docNode.SelectSingleNode(ogType);
         if (ogTypeNode != null)
           ogtype = ogTypeNode.GetAttributeValue("content", "");
 
         var ogDesriptionXPath = "//meta[@property='og:description']";
         var ogDescriptionNode = docNode.SelectSingleNode(ogDesriptionXPath);
         if (ogDescriptionNode != null)
            ogdescription = ogDescriptionNode.GetAttributeValue("content", "");
 
 
         wo.Url = Url;
         wo.Description = description;
         wo.Keywords = keywords;
         wo.OgImage = ogImage;
         wo.Title = title;
         wo.OgType = ogtype;
         wo.OgDescription = ogdescription;
 
        }
 
 
         return wo;
 
   }
}

I am using a HttpClient class to download the web page and then parse the document with the new HtmlAgilityPack.HtmlDocument().

     WebPageObject wpo = wpm.GetPageInfo("http://www.tamarsolutions.co.uk");
     Console.WriteLine(wpo.title);
     Console.WriteLine(wpo.Description);

Calling the GetPageInfo() returns a WebPageObject with pre filled values – nice!

C# RSS Feed Reader Tutorial

To parse RSS documents using C# you can use query expressions against the XDocument class and return a new anonymous type as illustrated below.

Firstly Load a new XDocument with the url of the RSS Feed and then using a LINQ query expression select the document elements that have the name ‘item’ (as is standard in rss feeds). Then set up a ‘new’ anonymous type (although it does not have to be) with the properties Title, Link, Description and PubDate. These property values are set using fluent LINQ queries to find the Single value of each node in the rss items.

 public static void ParseRss(string RssUri)
  {
 
      XDocument xdoc  = XDocument.Load(RssUri);
 
      var items = from x in xdoc.Descendants("item")
           select new 
             {
                Title = x.Descendants("title").SingleOrDefault().Value,
                Link = x.Descendants("link").SingleOrDefault().Value,
                Description = x.Descendants("description").SingleOrDefault().Value,
                PubDate = x.Descendants("pubDate").SingleOrDefault().Value,
 
              };
 
 
            //now iterate the returned IEnumerable anonymous type
            foreach (var item in items)
            {
                Console.WriteLine(item.Title);
                Console.WriteLine(item.Link);
                Console.WriteLine(item.Description);
                Console.WriteLine(item.PubDate);
            }
 }

Please note that some RSS Feeds do not provide a pubDate. If an RSS Feed is missing either Title, Link, Description or pubDate then calling x.Descendants will crash the program. So you will have to do some error checking!

To call this method see code below…

         ParseRss("http://www.tamarsolutions.co.uk/feed/");

C# Predicate delegate Tutorial

A Predicate is a delegate that returns a boolean, true or false value. A Predicate can be used to filter arrays as shown in this case. A predicate contains a precondition clause which determines a values inclusion in results.

The signature of a Predicate is thus:
public delegate bool Predicate<in T>(T obj);

Here you can see that a predicate always has to return a bool value and can take as an argument any type you wish, depending on context.

Below is a Predicate method that takes a Point as an argument and returns true or false as to whether it meets the criteria (in this case p.X == 2).

static bool MyPredicate(Point p)
        {
            return p.X == 2;
        }

So lets say we have an array of Point objects but we want to filter that array and produce a new Point array based on that filter.

  Point[] points = new Point[3];
  points[0] = new Point(2, 3);
  points[1] = new Point(2, 5);
  points[2] = new Point(4, 3);
 
  //filter our array using the predicate created above.
  Point[] filteredPoints = Array.FindAll(points, new Predicate<Point>(MyPredicate));

The second parameter of Array.FindAll expects a predicate to filter the results. This Predicate filter checks to see if the X point is equal to 2 and if so returns true.

What is in fact happening here is as Array.FindAll iterates over the collection it calls the predicate MyPredicate to check each value and see if it meets the predicates clause, if it does meet the criteria then it is added to the result collection in this case filteredPoints.

C# Converter delegate Tutorial

The Converter delegate allows you to convert an object from one type to another type. The Converter delegate takes an input type and and output type as show in the definition here: System.Converter<TInput, TOutput>.

A simple converter method is shown below that complies to a converter delegate, it takes a Point as its parameter and returns a Size. So it converts a Point to a Size. you can change the return type and parameter type to suit the conversion you require, but to work as a Converter it must only have one parameter and a return type, it cannot return void.

static Size converter(Point f)
        {
            return new Size(f); 
 
        }

Lets create a Point array with a mind to converting the array of Points to an array of Sizes!

            Point[] points = new Point[3];
            points[0] = new Point(1, 2);
            points[1] = new Point(2, 4);
            points[2] = new Point(4, 8);

To see a converter in action, take a look at the Array.ConvertAll method below. Firstly the ConvertAll method is declared with Point as its input and Size as its output.

var sizes = Array.ConvertAll(points, new Converter<Point,Size>( converter ));

Then a new Converter delegated method is passed into the ConvertAll method as its second argument. As you can see the Converter requires a delegate to perform the conversions. The full code is below.

using System;
using System.Drawing;
 
namespace TSCode
{
    public static class Program
    {
        static void Main(string[] args)
        {
            //set a Point[]
            Point[] points = new Point[3];
            points[0] = new Point(1, 2);
            points[1] = new Point(2, 4);
            points[2] = new Point(4, 8);
 
            //Create the Converter using the converter delegate
            var myConverter = new Converter<Point, Size>(converter);
 
            //Now call ConvertAll on Array passing our Point[] and converter
            var sizes = Array.ConvertAll(points, myConverter);
         }
     }
 
     //declare our converter to comply with the Converter delegate type
     //Converter<TInput, TOutput>
     static Size converter(Point f)
        {
            return new Size(f); 
 
        }
 
}

Apply the same format when converting any type to another type, just change the converter methods input and output to suit your needs. Have a play and let me know what you come up with… Please remember that you need to implement the conversion yourself.

Get Local IPV4 IP Address and HostName in C#

To find your computer’s local IP Address and hostname using C# you need to call methods on the static Dns class in the System.Net namespace. By calling Dns.GetHostName() you retrieve the Hostname of the local computer. Then by passing the hostname into the Dns.GetHostAddresses() method you get an array of IP Addresses.

There could be a lot of IP Addresses in this array, so firstly I check that the ip.AddressFamily == AddressFamily.InterNetwork to know that we have found the IPV4 IP Address.

using System;
using System.Net;
using System.Net.Sockets;
 
namespace TSCode
{
    public static class Program
    {
        static void Main(string[] args)
        {
            var hostName = Dns.GetHostName(); //gets hostname
 
            //Gets an array of IP Addresses using Dns
            IPAddress[] ips = Dns.GetHostAddresses(hostName);
 
            //now iterate the IPs
            foreach(var ip in ips)
            {
                //we just want IPV4 in this instance so filter with InterNetwork
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    Console.WriteLine("Your Host Name is {0}", hostName);
                    Console.WriteLine("Your Local IP Address is {0}", ip.ToString());
                }
            }
        }
    }
 
}

With the AddressFamily enum found in the System.Net.Sockets namespace you can filter the IP Address array to find IPV6 and many other IP Addresses such as IPX and Banyan or NetBios etc.

C# SMTP Client. Send Emails

Sending an email using SMTP in C# we need to use 3 classes, the SmtpClient, the NetworkCredential and the MailMessage classes. All contained in the System.Net and System.Net.Mail namespaces.

  1. The SmtpClient forms the connection to the SMTP server.
  2. The NetworkCredential class sets the username and password for the connection
  3. The MailMessage class allows us to build the message to send on the connection

Below I have written some simple self explanatory code to illustrate the methods taken to send an email using smtp.

using System;
using System.Net;
using System.Net.Mail;
 
namespace TSCode
{
 
    public static class Program
    {
        static void Main(string[] args)
        {
            //set up the connection to the SMTP Server
            //with usual port 25 for smtp - could be different
            SmtpClient smtp = new SmtpClient("smtp_mail_server", 25);
 
            //Set the NetworkCredentials for the connection
            NetworkCredential credentials = new NetworkCredential();
            credentials.UserName = "smtp_user_name";
            credentials.Password = "smtp_password";
 
            //and set the connections Credentials
            smtp.Credentials = credentials;
 
            //Now set up the message object
            //and assign to it the from and to emails.
            string from = "sender@domain.co";
            string to = "recipient@somewhere.com";
            MailMessage message = new MailMessage(from,to);
 
            //Create and set the Title of the email message
            message.Subject = "Testing SMTP From C#";
 
            //We can also send the email in HTML Format
            message.IsBodyHtml = true;
 
            //Then just create the body as you wish
            //if IsBodyHtml == true then we can use html...
            string body = "<html><head><title>Testing SMTP From C#</title>";
            body += "<head><body><p>Hello SMTP FROM C#</p></body></html>";
 
 
            //set the message body
            message.Body = body;
 
            //and send using the SMTP connection
            smtp.Send(message);
        }
    }
 
}

You can also set CC, BCC and Attachments using the MailMessage class, have a tinker and and see how easy it is!

C# Dictionary using foreach

There are 3 main ways to use the foreach statement with a C# Dictionary class.

Firstly below we run foreach over the keys and values within the dictionary object.

using System;
using System.Collections.Generic;
 
namespace TSCode
{
 
    public static class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> dict = new Dictionary<string, int>();
            dict.Add("Mum", 45);
            dict.Add("Dad", 47);
            dict.Add("Son 1", 19);
            dict.Add("Son 2", 15);
            dict.Add("Son 3", 13);
 
            //var here represents a KeyValuePair<string, int>
            foreach(var d in dict)
            {
                Console.WriteLine("Key: {0}, Value: {1}",d.Key,d.Value);
            }
 
        }
    }
 
}

But if you just want to find the values then just enumerate over the Values.

            //var here represents an int type 
            foreach (var v in dict.Values)
            {
                Console.WriteLine("Value: {0}", v);
            }

And if you wish to just retrieve the keys from the dictionary then just enumerate the Keys.

             //and var here represents a string type
            foreach (var k in dict.Keys)
            {
                Console.WriteLine("Key: {0}", k);
            }

C# Using Statement Tutorial

The ‘using statement’ is not the same as the ‘using directive’ that we use to reference assemblies within projects.

The using statement is a way to enforce that objects that implement the IDisposable interface are disposed of after use, which saves valuable system resources.

using statements should always be used when using types that expose the .Dispose method. The using statement block makes sure the object is disposed of when finished with.

A ‘using statement’ is used below encasing the WebClient (WebClient is disposable) within the using block. The purpose of this is to make sure that the WebClient is disposed after the block exits.

 
using System;
using System.IO;
using System.Net;
using System.Text;
 
 
namespace TSCode
{
 
  public static class Program
  {
      static void Main(string[] args)
      {
          using(WebClient client = new WebClient())
          { 
             string html = client.DownloadString("http://www.tamarsolutions.co.uk");
             Console.Write(html);
 
          } //disposed here  
 
     }
  }
 
}

Another example would be when using the FileStream class to access files. Notice that in the code below we do not need to call Close on the FileStream as when the using block statement exits, Close is called on disposal.

  using (FileStream f = File.Create("test.txt"))
            {
                string text = "Hello FileStream";
                byte[] bytesOfString = Encoding.ASCII.GetBytes(text);
                f.Write(bytesOfString, 0, bytesOfString.Length);
 
            }//closed & disposed!

Whenever you are dealing with a class that is accessing resources outside of the .NET environment, such as databases, files, urls etc, you should always check to see if it implements IDispose and if it does you must use the ‘using statement’. Hope this helps!

Get Count of Specific Character in string – C# Method Extension

This simple method extension, extends the string class with the method CharacterCount
A lambda expression is used to find the characters in the string that match the character variable and the count is returned.

using System;
using System.Linq;
namespace TSCode
{
        public static int CharacterCount(this string text, char character)
        {
            return text.Count<char>( (x) => { return x == character; } );
 
        }
}

Very simple really. You will notice that the string class does have a Count<T> extension method already attached to it (as long as you are referencing using System.Linq). But the string.Count<T> method expects a func every time you call it.

To implement the CharacterCount extension method simple create a new string object and you will find it has the new method available to it.

namespace TSCode
{
  static void Main(string[] args)
     {
 
         string text = "This is our string of text, how many 'i's are in it!";
 
         //set the char we want to count in the string
         char ch = 'i';
 
         //Call the method extension, count the 'i's in text set by ch.
         int count = text.CharacterCount(ch);
 
         Console.WriteLine("There are {0} '{1}' characters in the text", count, ch);
 
 
     }
}

Extension methods like this can help tidy up code and make working with types more natural to the developer.