Monday, December 23, 2013

Tortoise SVN Settings for Beyond Compare 4

I recently rebuilt my computer and had to re-enter my Tortoise SVN settings for Beyond Compare. Now I won't forget!

Diff Viewer
"C:\Program Files (x86)\Beyond Compare 4\BComp.exe" %base %mine /title1=%bname /title2=%yname /leftreadonly

Merge Tool
"C:\Program Files (x86)\Beyond Compare 4\BComp.exe" %mine %theirs %base %merged /title1=%yname /title2=%tname /title3=%bname /title4=%mname

Tuesday, October 15, 2013

Compress all JPG/JPEG files in a directory tree (simple console application)

I needed a quick application to increase the compression of all .jpg files in a directory tree. This application is a console program that takes three command-line parameters:
compressjpg inDir outDir compressionLevel extensions
compressLevel is a number from 0 to 100, where 0 is maximum compression and 100 is no compression. extensions is a comma/semi-colon delimited list of file extensions to process. For example:
C:> compressjpg c:\myfiles c:\newfiles 80 jpg;jpeg
Download the Visual Studio 2012, .NET 4.5 solution (source code) by clicking here.

Sunday, September 29, 2013

Load ASP.NET page routes from XML file using C#

Want to load your ASP.NET page routes from an XML file? Here is a sample file and a short snippet of code to load them. This supports not only basic page routes, but default items and route constraints.

Have fun!
<?xml version="1.0" encoding="utf-8" ?>
<pageRoute routeExisting="true">
   <routes>
      <!-- route with no defaults or constraints -->
      <route name="HomePage">
         <url>home</url>
         <file>~/default.aspx</file>
      </route>
      <!-- route with defaults -->
      <route name="FAQView">
         <url>faqs/{id}</url>
         <file>~/faqs/ViewFAQ.aspx</file>
         <defaults>
            <default key="id" value="1000" />
         </defaults>
      </route>
      <!-- route with constraints -->
      <route name="ProductView">
         <url>products/view/{id}</url>
         <file>~/products/ViewProduct.aspx</file>
         <constraints>
            <constraint key="id" value="\d+" />
         </constraints>
      </route>
   </routes>
</pageRoute>
Code:
private void RegisterRoutes(RouteCollection routes)
{
   routes.Ignore("{resource}.axd/{*pathInfo}"); 

   string path = Path.Combine(
      Server.MapPath("~/App_Data"),
      "PageRoute.xml");
   if (File.Exists(path))
   {
      // load file with all page routes
      XElement xmlPageRoutes = XElement.Load(path);

      // set some defaults
      routes.RouteExistingFiles = (bool)xmlPageRoutes.Attribute("routeExisting");

      // map each individual route
      foreach (XElement xmlRoute in xmlPageRoutes.XPathSelectElements("routes/route"))
      {
         // defaults
         RouteValueDictionary defaults = new RouteValueDictionary();
         foreach (XElement def in xmlRoute.XPathSelectElements("defaults/default"))
         {
            defaults.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
         }

         //constraints
         RouteValueDictionary constraints = new RouteValueDictionary();
         foreach (XElement def in xmlRoute.XPathSelectElements("constraints/constraint"))
         {
            constraints.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
         }

         routes.MapPageRoute(
            (string)xmlRoute.Attribute("name"),
            (string)xmlRoute.Element("url"),
            (string)xmlRoute.Element("file"),
            true,
            defaults,
            constraints);
      }
   }
}

Monday, August 19, 2013

Code Defensively

Code Defensively
  1. Use Microsoft's Code Contracts
  2. Don't call LINQ .FirstOrDefault without checking the return value
  3. Thow ApplicationException for internal checks (and check often)
  4. Check for null after casting a variable using "as"
  5. Think before you code  :-)

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

Wednesday, May 15, 2013

Precise moving and resizing using Visio without snapping

Visio 2013 improves a bit on some of the move and resize features.  Below is a quick summary of moving and resizing images related to grid/snapping.

To gain more precise control over a moving or resizing a shape, hold down the Alt key while dragging the shape to move, rotate, or resize; this will suspend all forms of snapping.

Alt + Drag applies to 1D and 2D shapes, as well as multi-shape selections. It also applies to connectors, but they will still snap to glue targets.

Alt + Drag also works in combination with Ctrl and Shift modifier keys for drag actions.

Move
Alt + Shift + Drag: non-snapping move in one direction Alt + Ctrl + Drag: non-snapping copy

Resize
Alt + Shift + Drag side handle: non-snapping "resize from center"
Alt + Shift + Drag corner handle: non-snapping "resize in both dimensions"

Thursday, May 9, 2013

Call stored procedure with parameters using Entity Framework 5 and return scalar

Entity Framework 5 using a DbContext
bool result = myDbContext.Database.SqlQuery<bool>(
   "myProc @param1, @param2",
   new SqlParameter("param1", id),
   new SqlParameter("param2", name))
   .First();

Monday, May 6, 2013

ASP.NET dynamic images without a separate aspx file

In the past, when I wanted to display a dynamically generated image in ASP.NET, I would have a standalone aspx page that would stream back the image bytes using a image ContentType.

I recently found out that you can also stream images by setting the src attribute of the image with encoded bytes. This can be easily done using the ASP.NET Image control. Assume you have "myobject" that contains an image byte[] property called "imagebytes":

image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(myobject.imagebytes);

This will increase the size of your HTML since the image bytes are encoded directly into the HTML source. But hey, you don't need a separate aspx file.

Yippie.

Thursday, April 4, 2013

Great jQuery widgit tutorial...finally

I was wanting to find a well-balanced tutorial on jQuery widgets. If you, like me, have searched far and wide only to find a mismash of tutorials, your wait is over. I found this great tutorial on jQuery widget creation. It provides a concise overview, demonstrates the basic construction, and provides just the right amount of complexity for those looking at widgets for the first time.

http://bililite.com/blog/understanding-jquery-ui-widgets-a-tutorial

Enjoy!

Monday, April 1, 2013

Easily open command prompt from Windows Explorer

When using Windows Explorer it is nice to open a command prompt with the initial directory from the one selected. I've known for years you could select a directory in the right window pane, then hold SHIFT and right click to get the context menu; the context menu contains an "Open command window here" option. Nice.

I recently learned there is another easy way to open the command prompt without using the mouse. With the directory selected in the right window pane, press F4 to move to the directory path input box at the top of the window, then simply type "cmd" and press Enter.

Presto! Look Mom, no mouse!

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 ...