Sunday, June 9, 2013

IIS URL Rewrite non-www site to www

Use the IIS URL Rewrite module to route a site without "www" prefix to your standard "www" site.  Below is the web.config section to do this.
<system.webserver>
   <rewrite>
      <rules>
         <rule name="Redirect to WWW" stopprocessing="true">
            <match url="(.*)">
            <conditions>
               <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$">
               </add>
            </conditions>
            <action appendquerystring="true" type="Redirect" url="http://www.{HTTP_HOST}/{R:0}">
         </action></match></rule>
      </rules>
   </rewrite>
</system.webserver>

C# file touch utility and source code

At some point you need a simple, tiny, utility to change the dates on Windows files.  Attached is one I wrote, intentionally keeping it basic.  I've included a link to both the source code and just the .exe if you want that.  It does save settings across executions (except for specific date/time values).  Have fun.

6/25/2013: Updated to allow all times to sync together.

Monday, June 3, 2013

Parsing string to C# DateTime from specific time zone into UTC

If you need to parse a string representation of a DateTime into a specific time zone, use the DateTimeOffset in C# to assist.  For example, assume your code is executing in PST and you have a string like "1/6/2013 11:00:21 AM" that represents a time in EST.  How to do you convert this into UTC format?

Use the TimeZoneInfo.BaseUtcOffset member to create a DateTimeOffset structure.  Using this structure, you can then easily convert to UTC by by calling DateTimeOffset.UtcDateTime.


private void CalculateTimeToEastern()
{
  DateTime utc = ParseToTimeZone("1/6/2013 11:00:21 AM", "Eastern Standard Time").UtcDateTime;
}

private DateTimeOffset ParseToTimeZone(string s, string timeZoneName)
{
  TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName);
  DateTimeOffset offset = new DateTimeOffset(DateTime.Parse(s), easternZone.BaseUtcOffset);

  return offset;
}

Note from MSDN (which is interesting)
These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, DateTimeOffset should be considered the default date and time type for application development.

Sunday, June 2, 2013

Capitalize each word in sentence using C#

For non-English cultures, change the TextInfo parameter.

public static string SentenceCase(string phrase)
{
   TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
   string capitalized = textInfo.ToTitleCase(phrase);

   return phrase;
}

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...