Blog

XPath Find Elements with specific Attribute

Get all elements that have the style attribute => “//*[@style]”

Get all elements where style equals bold => “//*[@style=’bold’]”

Get all elements where style contains the string red => “//*[contains(@style,’red’)]”

Get all customer elements that have the age attribute => “//customer[@age]”

Get all customer that have both age and gender attributes => “//customer[@age and @gender]”

Regular Expression Collection

Opening and Closing HTML/XML Tags: Regex(“\s]+))?)+\s*|\s*)/?>”);

Self Closing HTML/XML Tags: Regex(“\s]+))?)+\s*|\s*)/>”);

Opening and Closing HTML/XML Tags: s]+))?)+s*|s*)/?>Locates Malicious Characters in User Input: ^[^`~!/@#}$%:;)(_^{&*=|’+]+$

Locates SQL Queries: (SELECTs[w*)(,s]+sFROMs[w]+)| (UPDATEs[w]+sSETs[w,’=]+)| (INSERTsINTOs[dw]+[swd)(,]*sVALUESs([dw’,)]+)| (DELETEsFROMs[dw’=]+)

Extracts Colors: ^(#){1}([a-fA-F0-9]){6}$

AMEX: ^([34|37]{2})([0-9]{13})$

Visa: ^([4]{1})([0-9]{12,15})$

Discover: ^([6011]{4})([0-9]{12})$

MC: ^([51|52|53|54|55]{2})([0-9]{14})$

Diners: ^([30|36|38]{2})([0-9]{12})$

US Phone Number: ^({1}[2-9]{1}[0-9]{2}){1}[ ]?[2-9]{1}[0-9]{2}(-| )?[0-9]{4}|[2-9]{1}[0-9]{2}[ ]{1}[2-9]{1}[0-9]{2}[ ]{1}[0-9]{4}|[2-9]{1}[0-9]{2}[2-9]{1}[0-9]{6}|[2-9]{1}[0-9]{2}-{1}[2-9]{1}[0-9]{2}-{1}[0-9]{4}){1}$

SSN: ^d{3}-d{2}-d{4}$

Password: ^(?=[^d_].*?d)w(w|[!@#$%]){7,20}

GUID: ^[{|(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[)|}]?$

Email: ^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$

Date mm/dd/yyyy: (0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)dd

File Extensions: ^.*(([^.][.][wW][mM][aA])|([^.][.][mM][pP][3]))$

Alphanumeric Strings: ^w+$

Alphanumeric with Spaces: ^[ws]+$

XML Namespaces: xmlns=”((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)”

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

Work-Around Browser Cache when it comes to Profile Images

If you allow users to change their profile pictures or if there are images which are frequently updated by users and those images use a standard name you can work-around browser caching by adding a version number to the image name when it is saved to the disk and stored in a database.

      //Set the image path.
      if (fileUpload.HasFile)
      {
        try
        {
          string imageFilePath = PortalSettings.HomeDirectoryMapPath;
          string imageName = USER_IMAGE + "." + 0 + ".jpg";
          if (!string.IsNullOrEmpty(location.UserImagePath))
          {
            //Find out what version the current file is at
            string[] parts = location.UserImagePath.Split('.');
            if (parts.Length == 3)
            {
              int version = int.Parse(parts[1]);
              int nextVersion = version + 1;
              imageName = USER_IMAGE + "." + nextVersion + ".jpg";

              string oldImagePath = imageFilePath + location.UserImagePath.Remove(0, 1);
              if (System.IO.File.Exists(oldImagePath))
                System.IO.File.Delete(oldImagePath);
            }
          }

          fileUpload.SaveAs(imageFilePath + imageName);
          location.UserImagePath = "/" + imageName;
          imgUserImage.ImageUrl = "/" + imageName;
          imgUserImage.Visible = true;
          AddImageToCache(imageFilePath + imageName);
        }
        catch (Exception ex)
        {
          if (ExceptionHandler.ProcessException(ex, ExceptionPolicy.General, ModuleConfiguration))
            throw;
        }
      }

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();
    }

ASP.net Dynamic Script Loading in HTML Head

To dynamically add script tags to the head section of an HTML page based on conditions at page load use the following code.

This one adds a link to an external .js file:

if(UseUrchin)
      {
        HtmlGenericControl Include = new HtmlGenericControl("script");
        Include.Attributes.Add("type", "text/javascript");
        Include.Attributes.Add("src", "/__utm.js");
        Page.Header.Controls.Add(Include);
      }

This one adds actual JavaScript code inside the script tag:

if(UseUrchin)
      {
        HtmlGenericControl Include = new HtmlGenericControl("script");
        Include.Attributes.Add("type", "text/javascript");
        Include2.InnerHtml = "alert('We added it to the head');";       
Page.Header.Controls.Add(Include);
      }