.Net C# Environment.SpecialFolder

There are a number of system folders on a typical windows computer. The following is a good article detailing them: Special Folder Enumeration list. This simple program shows how to access these folders:

using System;

namespace CsharpEnvSpecialFolderDemo
{
    class CsharpEnvSpecialFolderExample
    {
        static void Main()
        {
            Console.WriteLine("Folder path: {0}",
               Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
        }
    }
}

Using Watin to automate browser actions

Watin is a browser automation and testing tool that I’ve used in the past, it’s similar to Selenium but the API is different. Below is an example of some automation via a simple Watin program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using WatinTestApp.Helpers;

namespace WatinTestApp
{
    public static class CreateOrganisation
    {
        /// <summary>
        /// Add Organisations
        /// </summary>
        /// <param name="organisation">List organisations</param>
        public static void AddOrganisations(List<OrganisationDefinition> organisations)
        {
            IE browser = null;

            using (browser = new IE(WatinTestApp.Properties.Resources.SiteURLRef))
            {
                //#Warning: This will remove your browser cookies
                
                browser.ClearCache();
                browser.ClearCookies();

                try
                {
                    // Wait for the page to load
                    browser.WaitForComplete();

                    // Wait for the page to load
                    System.Threading.Thread.Sleep(10);

                    // Get the HTML
                    var pageText = browser.Html;

                    // Get the login string from the resources file
                    string loginTextField = WatinTestApp.Properties.Resources.LoginStringRef;

                    // Test if the login page is displayed
                    if (pageText.Contains(loginTextField))
                    {
                        Console.WriteLine("Need to Log in:");

                        //Login
                        browser.TextField(Find.ById("F_UserCode")).TypeText("si-jones");
                        browser.TextField(Find.ById("F_Password")).TypeText("si-jones");
                        browser.Button(Find.ByName("BB_OK")).Click();
                    }
                    else
                    {
                        Console.WriteLine("Already Logged in:");
                        // Call logout funtion here
                    }

                    // Press the identity manager button/user computer button
                    browser.Button(Find.ById("BA_Useradmin")).Click();
                    Console.WriteLine("Click the admin selection button:");

                    //Press the groups button
                    browser.Button(Find.ByName("BS_Sect_groups")).Click();
                    Console.WriteLine("Click the group selection button:");

                    //Wait for page to load
                    browser.WaitForComplete();

                    foreach (var orgs in organisations)
                    {
                        //Press the identity manager button
                        browser.Button(Find.ById("BA_Badd")).Click();
                        Console.WriteLine("Click the add organisations button:");

                        //Add to the username field
                        browser.TextField(Find.ById("F_UniqueName")).TypeText(orgs.OrganisationName);
                        Console.WriteLine("Fill in UniqueName button:");

                        browser.TextField(Find.ById("F_DisplayName")).TypeText(orgs.OrganisationName);
                        Console.WriteLine("Fill in DisplayName button:");

                        browser.SelectList(Find.ById("F_Type")).Select("Organisation");
                        Console.WriteLine("Add the group from the dropdown list:");

                        browser.SelectList(Find.ById("F_Firm")).Select(orgs.Firm);
                        Console.WriteLine("Add the group from the dropdown list:");

                        browser.TextField(Find.ById("F_OrganisationType")).TypeText(orgs.OrganisationType);
                        Console.WriteLine("Fill in EmailAddress button:");

                        browser.TextField(Find.ById("F_OrganisationSector")).TypeText(orgs.OrganisationSector);
                        Console.WriteLine("Fill in EmailAddress button:");

                        browser.Button(Find.ById("BTB_BA__Add")).Click();
                        Console.WriteLine("Click o.k. to addd to the group:");

                        browser.WaitForComplete();
                    }

                    browser.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.ShowDefault);
                }
                catch (WatiN.Core.Exceptions.WatiNException w)
                {
                    Console.WriteLine(" Error: {0}", w.Message);
                }
                finally
                {
                    browser.ClearCache();
                    browser.ClearCookies();
                    browser.Close();
                }
            }
        }
    }
}

.Net C# batch convert MS Word documents to PDF with ABCpdf

A quick program to batch convert a collection of MS word documents into PDF format using the ABCpdf library.

using System;
using System.Diagnostics;
using System.IO;
using WebSupergoo.ABCpdf7;
using WebSupergoo;

namespace CsharpWebSuperGooPDFDemo
{
    class CsharpWebSuperGooPDFExample
    {
        static void Main(string[] args)
        {
            const string dirname = @"C:\Temp\Word docs\";

            // Get the files
            var files = Directory.GetFiles(dirname, "*.doc", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                
                var pdffile = string.Empty;

                //Determine the file extension
                if (file.EndsWith(".doc"))
                {
                    pdffile = file.Replace(".doc", ".pdf");
                }

                //Test if pdf file exists
                var pdfexists = File.Exists(pdffile);

                //Process item
                if (!pdfexists)
                {
                    Doc doc = new Doc();

                    try
                    {
                        Console.WriteLine("Starting Processing {0}", dirname + file);

                        //Time the operation
                        var stopWatch = new Stopwatch();

                        stopWatch.Start();

                        //Setup read options
                        XReadOptions options = new XReadOptions();

                        options.FileExtension = ".tiff";

                        //Read the file
                        doc.Read(file, options);

                        //Replace the extension
                        var newfilename = string.Empty;

                        if (file.EndsWith(".doc"))
                        {
                            newfilename = file.Replace(".doc", ".pdf");
                        }

                        //Save as a new PDF file
                        doc.Save(newfilename);

                        //Clear resources
                        doc.Clear();

                        stopWatch.Stop();

                        // Get the elapsed time
                        var ts = stopWatch.Elapsed;

                        // Format and display the TimeSpan value
                        var elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                           ts.Hours, ts.Minutes, ts.Seconds,
                                                           ts.Milliseconds / 10);

                        Console.WriteLine("Finished Processing {0} in {1} seconds.", newfilename, elapsedTime);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        doc.Clear();
                    }
                }
                else
                {
                    Console.WriteLine("PDF already exists - skipping {0}.", pdffile);
                }
            }
        }
    }
}

.Net C# INotifyPropertyChanged example

A quick demo of the INotifyPropertyChanged interface on a simple class.

using System;
using System.ComponentModel;

namespace CsharpINotifyPropertyChangedDemo
{
    /// <summary>
    /// Defines the entry point of the application.
    /// </summary>
    class CsharpINotifyPropertyChangedExample
    {
        static void Main()
        {
            // New instance of the person class
            var person = new Person {FirstName = "A first name", LastName = "A last name"};

            // Show the properties
            Console.WriteLine(person.FirstName);

            Console.WriteLine(person.LastName);

            // Change the properties
            person.FirstName = "changed first name";

            person.LastName = "changed last name";

            // Show the changed properties
            Console.WriteLine(person.FirstName);

            Console.WriteLine(person.LastName);

            Console.ReadKey();
        }
    }

    /// <summary>
    /// Person class implements the INotifyPropertyChanged interface
    /// </summary>
    public class Person : INotifyPropertyChanged
    {
        private string _firstName;

        private string _lastName;

        public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                OnPropertyChanged(this, "FirstName");
            }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                _lastName = value;
                OnPropertyChanged(this, "LastName");
            }
        }

        // PropertyChanged event
        public event PropertyChangedEventHandler PropertyChanged;

        // Raise the PropertyChanged event
        private void OnPropertyChanged(object sender, string property)
        {
            if (PropertyChanged == null) return;
            PropertyChanged(sender, new PropertyChangedEventArgs(property));
            Console.WriteLine("Changed {0} ", property);
        }  
    }
}

Returns:

A first name
A last name
changed first name
changed last name

.Net MVC C# simplest form post example

A quick post on Razor form posting, this is a really simple example – I’d avoid ViewBag if at all possible.

Add a form helper to your (Razor) view:

  @using (Html.BeginForm("Index", "Home", new { id = 1 }, FormMethod.Post))
    {
            @Html.TextBox("Input","Your value here")
            <input type="submit" class="submit" value="Sign Up" />
    }

Add a new method to your (Home) controller:

  // Accept HTTP POST method
  [HttpPost]
  public ActionResult Index(FormCollection collection)
  {
     // Avoid Viewbag, but fine for simple demo.
    ViewBag.postedValue = collection.Get(0);

    return View("~/views/Home/Results.cshtml");
  }

Add a new view to handle the post results:

@{
    ViewBag.Title = "Results";   
}

<h2>Results</h2>

@ViewBag.postedValue

SQL Server TCP settings and why not using connection pooling is a bad idea

I’ve been talking to a contact who has been experiencing some connection issues with a large scale SQL Server implementation. The database is serving as the back-end to a well used Internet site. They reported that during the course of normal operation that they’d received dropped TCP connections and difficulty in achieving automatic failover at the database layer. They’d investigated the possibility of running without database connection pooling enabled. I advised that this was not a suitable idea. Afterwards this support article was found: support.microsoft.com/kb/328476

The article advises:

Note that Microsoft strongly recommends that you always use pooling with the SQL Server drivers. Using pooling greatly improves overall performance on both the client side and SQL Server side when you use the SQL Server drivers. Using pooling also considerably reduces network traffic to the computer that is running SQL Server. For example, a sample test that used 20,000 SQL Server connection opens and closes with pooling enabled used about 160 TCP/IP network packets, for a total of 23,520 bytes of network activity. With pooling disabled, the same sample test generated 225,129 TCP/IP network packets, for a total of 27,209,622 bytes of network activity.

The moral of the story – connection pooling is advised and think carefully before turning off.

The Gluten Summit – why you should listen

I’m a big advocate of eating gluten free, there’s plenty of research that suggests that eating gluten is not good for you. If you’re at all curious regarding gluten free lifestyles – take a look at the gluten summit.

This is what’s on:

  1. Learn about the latest research on gluten-related disorders
  2. Understand why we MUST call more attention to them
  3. Gain improved knowledge of proper diagnosis/treatment methods
  4. More frequently ask, “Could this health issue be due to gluten?”

The goal of The Gluten Summit is to shift the scientific discussion and clinical recognition of gluten-related disorders forward by five years. Meaning, we want the conversation between patients and doctors that will be happening five years from now to happen now.

JQuery AJAX request syntax

A simple JQuery AJAX implementation.

  var data = JSON.stringify({
                field1: xxx,
                field2: yyy
            });

            $(document).ready(function () {
                $.ajax({
                    type: 'POST',
                    data: data,
                    contentType: 'application/json',
                    url: '/path/'
                }).success(function (data) {
                    console.log(data);
                }).error(function (err) {
                    console.log(err);
                });
            });

.Net 4.5 C# using ExceptionDispatchInfo.Capture to rethrow exceptions

ExceptionDispatchInfo can rethrow an exception from this point where it was captured to the point where it is rethrown. Active exceptions will retain stack trace information. More information can be found at ExceptionDispatchInfo.Capture Method on MSDN.

using System;
using System.Collections.Concurrent;
using System.Runtime.ExceptionServices;
using System.Threading;

namespace CsharpExceptionDemo
{
    class CsharpExceptionExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            var exceptions = new BlockingCollection<ExceptionDispatchInfo>();

            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    ThrowOne();
                }
                catch (Exception ex)
                {
                    var exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex);
                
                    exceptions.Add(exceptionDispatchInfo);
                }
                exceptions.CompleteAdding();
            });

            foreach (var exceptionDispatchInfo in exceptions.GetConsumingEnumerable())
            {
                try
                {
                  exceptionDispatchInfo.Throw();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("{0}", ex);
                }
            }

            Console.ReadKey();
        }

        /// <summary>
        /// Throws Not Supported Exception.
        /// </summary>
        /// <exception cref="System.NotSupportedException"></exception>
        private static void ThrowOne()
        {
            Console.WriteLine("Throw Not Supported Exception");
            
            ThrowTwo();
            
            throw new NotSupportedException();
        }

        /// <summary>
        /// Throws Not Implemented Exception.
        /// </summary>
        /// <exception cref="System.NotImplementedException"></exception>
        private static void ThrowTwo()
        {
            Console.WriteLine("Throw Not Implemented Exception");
            
            ThrowThree();
            
            throw new NotImplementedException();
        }

        /// <summary>
        /// Throws Argument Null Exception.
        /// </summary>
        /// <exception cref="System.ArgumentNullException"></exception>
        private static void ThrowThree()
        {
            Console.WriteLine("Throw Argument Null Exception");
            
            throw new ArgumentNullException();
        }
    }
}

Returns:

Throw Not Supported Exception
Throw Not Implemented Exception
Throw Argument Null Exception
System.ArgumentNullException: Value cannot be null.
   at CsharpExceptionDemo.CsharpExceptionExample.ThrowThree() in c:\Users\csharper\
Documents\Visual Studio 2012\Projects\CsharpExceptionDemo\CsharpExceptionDemo\Cs
harpExceptionExample.cs:line 81
   at CsharpExceptionDemo.CsharpExceptionExample.ThrowTwo() in c:\Users\csharper\Do
cuments\Visual Studio 2012\Projects\CsharpExceptionDemo\CsharpExceptionDemo\Csha
rpExceptionExample.cs:line 68
   at CsharpExceptionDemo.CsharpExceptionExample.ThrowOne() in c:\Users\csharper\Do
cuments\Visual Studio 2012\Projects\CsharpExceptionDemo\CsharpExceptionDemo\Csha
rpExceptionExample.cs:line 55
   at CsharpExceptionDemo.CsharpExceptionExample.<>c__DisplayClass1.<Main>b__0(O
bject _) in c:\Users\csharper\Documents\Visual Studio 2012\Projects\CsharpException
Demo\CsharpExceptionDemo\CsharpExceptionExample.cs:line 21
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at CsharpExceptionDemo.CsharpExceptionExample.Main() in c:\Users\csharper\Docume
nts\Visual Studio 2012\Projects\CsharpExceptionDemo\CsharpExceptionDemo\CsharpEx
ceptionExample.cs:line 36