C#: Sending Email

To send email from your application or website do the following:

1. Add this config entry to your (App)(Web).config altering the host to the URL or IP address of your email server with the associated credentials.

    <system.net>

        <mailSettings>

            <smtp from="noreply@medimedia.com">

                <network host="localhost" password="" userName="" />

            </smtp>

        </mailSettings>

    </system.net>

2. Use the following code to create and send a MailMessage

Version:0.9 StartHTML:0000000105 EndHTML:0000007499 StartFragment:0000000105 EndFragment:0000007499

        private void SendEmail()

        {

            MailMessage message = new MailMessage();

            message.From = new MailAddress(_fromEmail);

            foreach (string email in _emailList)

            {

                message.To.Add(new MailAddress(email));

            }

            message.Subject =  _subject;

            message.IsBodyHtml = false;

            message.Priority = MailPriority.High;             

            message.Body = _body;


            try

            {

                SmtpClient client = new SmtpClient();

                client.Send(message);

            }

            catch (Exception ex)

            {

               //TODO: Handle exception

            }

        }

C#: Case Insensitive Generic Dictionary

This is a portion of a console app I was using to investigate the Dictionary class and its methods. I was running into issues with Keys not being found within a dictionary that was being auto-generated from incoming web service data, data which I of course had no control over. There were several clients hitting the service which were not using the outlined parameter names with the correct casing. The Dictionary class in .Net uses hashing algorithms to create unique Keys from the key that is entered when the Key/Value pair is added. Because of this hashing the same string with different casing will generate a different unique key. In order to overcome this I found all you have to do is  pass in StringComparer.CurrentCultureIgnoreCase in the constructor of the Dictionary at initialization and from that point on it no longer cares about the casing.

            try

            {

                Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

                dictionary.Add("KeyOne", "Value");

                dictionary.Add("keyone", "Value");

                foreach (KeyValuePair<string, string> valuePair in dictionary)

                {

                    Console.WriteLine(

                        string.Format("Key: {0}, Value: {1}",

                        valuePair.Key,

                        valuePair.Value));

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.Message);

            }

            Console.ReadLine();

C#: Embedding Resources in your DLLs

When you have resources such as images, css files or JavaScript files which you do not want exposed to users, editable, or possibly lost during deployment, a good option is to just embed those resources into your DLL and pull them out as needed.

An example would be an ASP.net custom server control used to handle Session Keep Alive. Lets say we have a .js file which holds our client side JavaScript that needs to be loaded and run on the user’s browser. Lets also say that this file exists within our project in the following directory path next to the .cs files which use it, ProjectName/Web/Utilities/.

To embed the .js file into our DLL you simply need to select the file in Visual Studio and in the ‘Properties’ window there is a option for ‘Build Action’ set it to ‘Embedded Resource’. This will cause the file to be embedded into the DLL the next time the project is built.

Next you need a way to pull that resource out at run time for inclusion in the response to the client. To do this you first need to add a reference to that resource in your ‘AssemblyInfo.cs’ file with is located in the ‘Properties’ folder in the project. Simply go to the bottom of that file and add a WebResource entry as seen below.

[assembly: System.Web.UI.WebResource("GraphicNetDesign.ServerControls.Web.Utilities.KeepAlive.js", "text/js")]

You will notice that the entire path (namespace) to the file needs to be specified. This will be the path you pass in when attempting to access the resource from your code. So now in your code you just do the following to pull the .js file and register it for client use.

Page.ClientScript.RegisterClientScriptResource(typeof(SessionKeepAlive),

                "GraphicNetDesign.ServerControls.Web.Utilities.KeepAlive.js");

C#: Check if Web Page is Up, Http Status Code

If you need to programmatically check to see if a web page or web service is active before you redirect a user or make a call you can use the HttpWebRequest object to make a call to a URL and get back the HttpWebResponse. Through the HttpWebResponse you can then check the HttpStatusCode to see if it is OK or an # of other statuses base on what you are looking for.

        private void CheckUrl()

        {

            const string SERVICE_URL =

                "https://www.google.com";

 

            WebRequest testRequest = WebRequest.Create(SERVICE_URL);

            testRequest.Proxy = null;

            HttpWebResponse testResponse = (HttpWebResponse)testRequest.GetResponse();

            if (testResponse.StatusCode != HttpStatusCode.OK)

            {

                throw new Exception(

                    "Unable to hit Google.");,

            }

        }

C# High Performance Counter

When accuracy is extremely important to you, you cannot rely on the standard DateTime or TimeSpan objects built into the .Net Framework. For real accuracy you need to go to the operating system itself. Here is a class which utilizes the operating system to count passing time.

using System.ComponentModel;

using System.Runtime.InteropServices;

using System.Threading;

 

namespace IPPoke.Library.Utilities

{

    public class HiPerformanceTimer

    {

        #region Private Fields

 

        [DllImport("Kernel32.dll")]

        private static extern bool QueryPerformanceCounter(

            out long lpPerformanceCount);

 

        [DllImport("Kernel32.dll")]

        private static extern bool QueryPerformanceFrequency(

            out long lpFrequency);

 

        private long _startTime, _stopTime;

        private readonly long _freq;

 

        #endregion

 

        #region Initializers

 

        /// 

        /// Initializes a new instance of the  class.

        /// 

        public HiPerformanceTimer()

        {

            _startTime = 0;

            _stopTime  = 0;

 

            if (QueryPerformanceFrequency(out _freq) == false)

            {

                throw new Win32Exception();

            }

        }

 

        #endregion

 

        #region Public Methods

 

        /// 

        /// Starts this timer instance.

        /// 

        public void Start()

        {

            Thread.Sleep(0);

            QueryPerformanceCounter(out _startTime);

        }

 

        /// 

        /// Stops this timer instance.

        /// 

        public void Stop()

        {

            QueryPerformanceCounter(out _stopTime);

        }

 

        /// 

        /// Gets the duration of the timer in seconds.

        /// 

        /// The duration in seconds.

        public double Duration

        {

            get

            {

                return (_stopTime - _startTime) / (double) _freq;

            }

        }

 

        #endregion

    }

}