C# Access Modifiers

Knowing what can access your code as you write it and planning out the scope of access for your code is extremely important when it comes to the security of your code. In order to make sure your code is accessed as narrowly as possible increases the security or your code while decreasing the vulnerability at the same time. Here are the default access modifiers found in C#:

Definition: Class(es) => C# objects

Definition: Member(s) => variables, properties, methods

public: any and all code has access to classes or members which are public
private: the class or member is NOT accessible outside of itself  or the class that contains it
protected: the class or member is only accessible by the class that contains it or any class which is a decendant of that class (i.e. subclass)
internal: the class or member is only accessible by code that is within the same assembly (in other words .dll)
protected internal: the class or member is accessible by code in the same assembly (.dll) or by any subclass of that class that contains it.

C# Re-throwing Your Exceptions (the right way)

There are a lot of programmers out there who are unaware of what really happens when they re-throw Exceptions within their applications and that there are 2 ways in which it can be done. Based on what you are trying to accomplish there is a right way and a wrong way.

Lets say you are using an error/exception logging system and you want to make sure and preserve everything that happened when the Exception was thrown as well as the code which caused it. To get to the logging system you may be bubbling up the Exceptions through your code to a main Exception Handler.

Here is the most common re-throwing of exceptions which I have seen in my own earlier code as well as those developers whose code I have worked on.

 try { //your code does something bad }
catch (Exception ex) { throw ex; }

Discussion: the above code actually creates a brand new Exception within the current scope, this effectively deletes the Stack Trace held within the bubbling Exception. You have now lost all the information telling you what happened when the Exception was thrown and what code caused it. This is very bad when bubbling your Exceptions for logging.

try { //Your code does something bad }
catch (Exception ex) { throw; }

Discussion: The above code now just passes along any exception which is caught in the try-catch preserving the entire Stack Trace for your debugging enjoyment. This is very good when bubbling your Exceptions for logging.

C# Send Emails in .Net

Example code for sending emails in .Net using C#:

      //Send email
      try
      {
        MailMessage message = new MailMessage();
        message.From = new MailAddress(localizedContent.SendPasswordFromEmailAddress);
        MailAddressCollection toAddresses = message.To;
        toAddresses.Add(new MailAddress(_userInfo.Email));
        message.Subject = localizedContent.SendPasswordEmailSubject;
        message.Priority = MailPriority.Normal;
        message.BodyEncoding = Encoding.UTF8;
        message.Body = template;
        message.IsBodyHtml = true;       

        SmtpClient smtp = new SmtpClient(AppConfiguration.SmtpServer);
        smtp.Send(message);
        return true;
      }
      catch (Exception ex)
      {
        return false;
      }


	

C# DateTime Formatters (most common)


DateTime
.Now.ToUniversalTime().ToString("MMddyyyy", CultureInfo.InvariantCulture)

Day Formatters

d – Represents the day of the month as a number from 1 through 31

dd – Represents the day of the month as a number from 01 through 31

ddd – Represents the abbreviated name of the day of the week

dddd – Represents the full name of the day of the week

Month Formatters

M – Represents the month as a number from 1 through 12

MM – Represents the month as a number from 01 through 12

MMM – Represents the abbreviated name of the month

MMMM -Represents the full name of the month

Year Formatters

y – Represents the year as a one or two-digit number

yy – Represents the year as a two-digit number

yyy – Represents the year with a minimum of three digits

yyyy – Represents the year as a four-digit number

yyyyy – Represents the year as a five-digit number

Hour Formatters

h – Represents the hour as a number from 1 through 12

hh – Represents the hour as a number from 01 through 12

H – Represents the hour as a number from 0 through 23

HH – Represents the hour as a number from 00 through 23

Minute Formatters

m – Represents the minute as a number from 0 through 59

mm – Represents the minute as a number from 00 through 59

Second Formatters

s – Represents the seconds as a number from 0 through 59

ss – Represents the seconds as a number from 00 through 59

Time of Day Formatters

t – Represents the first character of the AM/PM designator

tt – Represents the AM/PM designator

: – Represents the time separator

/ – Represents the date separator

Reading Excel Files with C#

To read an excel file (.xls or .xlsx) use the following code.

    private const string excelConnectionXls = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=HMMasterlist.xls;Extended Properties=Excel 8.0";    private const string excelConnectionXlsx = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.xlsx;Extended Properties=Excel 12.0";

    private void LoadSourceDocument()
    {
      log.Append("Begin Loading Excel n");
      OleDbConnection oledbConn = new OleDbConnection(
excelConnectionXls);
      try
      {
        // Open connection
        oledbConn.Open();
        // Create OleDbCommand object and select data from worksheet Sheet1
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
        // Create new OleDbDataAdapter
        OleDbDataAdapter oleda = new OleDbDataAdapter();
        oleda.SelectCommand = cmd;
        // Fill the DataSet from the data extracted from the worksheet.
        oleda.Fill(sourceDS, "Locations");
        log.Append("Excel file loaded successfully. n");
      }
      catch (Exception ex)
      {
        log.Append("Loading Excel Spreadsheet Failed, ex: " + ex.Message + "n");
      }
      finally
      {
        // Close connection
        oledbConn.Close();
      }
    }

    private void UpdateLogoNames()
    {
      foreach (DataRow row in sourceDS.Tables[0].Rows)
      {
        string affiliateId = CheckAffiliateIdLength(row[0].ToString());
        List locations =
          SCCRetailPortal.SW_Locations.Where(x => x.AffiliateId.Equals(affiliateId)).ToList();
        if (locations.Count == 1)
        {
          locations[0].LocationShortName = row[1].ToString();
          log.Append(string.Format("Location {0}:{1} successfully updated. n", locations[0].LocationId,
                                   locations[0].LocationName));
        }
        else
        {
          log.Append(string.Format("FAILURE: No Location Found {0}:{1}. n", row[0], row[1]));
        }
      }
      SCCRetailPortal.SubmitChanges();
    }

C# Enumerations with Default Value Strings

This extension class adds an extension method to the Enum type. This created the ability for each value of an Enumeration to have a default text value associated with it by simple adding an attribute to each enum value.

public enum MyEnum
{
[DisplayValue("#FFFFFF")]
White
}

static public class EnumExtension
    {
        ///
        /// Will get the string value for a given enums value, this will
        /// only work if you assign the StringValue attribute to
        /// the items in your enum.
        ///

        ///
        ///
        public static string GetDisplayValue(this Enum value)
        {
            // Get the type
            Type type = value.GetType();

            // Get fieldinfo for this type
            FieldInfo fieldInfo = type.GetField(value.ToString());

            // Get the stringvalue attributes
            DisplayValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
                typeof(DisplayValueAttribute), false) as DisplayValueAttribute[];

            // Return the first if there was a match.
            return attribs.Length > 0 ? attribs[0].DisplayValue : null;
        }
    }

///

/// This attribute is used to represent a string value

/// for a value in an enum.

///

public class DisplayValueAttribute : Attribute

{

#region Public Properties

///

/// Holds the stringvalue for a value in an enum.

///

public string DisplayValue { get; protected set; }

#endregion

#region Constructor

///

/// Constructor used to init a StringValue Attribute

///

///

public DisplayValueAttribute(string value)

{

DisplayValue = value;

}

#endregion

}