Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Creating a File Relay (proxy) using ASP.Net - Part 1 - Serving files.

In this series of posts I will walk you through implementing an ASP.Net based file relay mechanism using aspx pages. This will allow you to serve files hosted in the back-office (behind a firewall) from a frontend webserver.

To implement this solution we need to build two separate webpages, one for the backend server and one for the frontend server.

  • GetFile.aspx – The backend page which will surface the requested file to the frontend server.
  • RelayFile.aspx – The frontend page which will forward (relay/proxy) the request to the backend server.

In this first part I will show you how to send a file using an aspx page.

Implementing GetFile.aspx

The first thing we need to do is create the new aspx page and name it GetFile.aspx.

The Page Markup

Now let’s go ahead and remove all the content from the GetFile.aspx page, except for the Page directive; The purpose of this page is to return to contents of another file, so all the html markup is superfluous.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetFile.aspx.cs" Inherits="Backend.GetFile" %>

The Code Behind

With the markup out of the way, let’s focus on the actual code behind the page. The only method we will need to implement is Page_Load.

1. Ensure a clean response – We don’t want anything from the aspx processing pipeline to interfere with the result

Response.ClearHeaders();
Response.ClearContent();

2. Determine the target file – In this example the filepath will be passed with the querystring.

string filePath = (Request.QueryString["filePath"] ?? "").Trim();

3. Determine and set the response type – This will allow the browser to display the file correctly. Also, make sure you only serve expected file types! This feature circumvents the basic webserver file security mechanisms, avoid leaking your secrets to the world!

string contentType = null;
string extension = Path.GetExtension(filePath).ToLowerInvariant();
switch (extension)
{
   case ".csv":
      contentType = "text/csv";
      break;
   case ".mp4":
      contentType = "video/mp4";
      break;
   case ".pdf":
      contentType = "application/pdf";
      break;
   default:
      // Unsupported filetype
      // There are serious security implications with
      // serving up files from a webserver. Make sure
      // you do not open yourself up to an attack!
      throw new HttpException(403, "Forbidden."); 
      // Use an empty ContentType if the type is unknown
      //contentType = "";
      //break;
}
   
//Set the ContentType.
Response.ContentType = contentType;

4. Set the response content length so the client knows how much data to expect.

var fileInfo = new FileInfo(filePath);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());

5. Write the file contents to the response stream.

Response.WriteFile(filePath);

6. Flush the output buffers and end the response.

Response.End();

 

It’s a Wrap!

These 6 simple steps (7 if you count the page markup change) are all you need to implement a simple page to serve files from the filesystem. In the next part we will have a look at making this code more production ready by adding error checking and handling.

 

The Complete Page_Load Method

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:     // Clear headers and content to ensure a clean response
   4:     Response.ClearHeaders();
   5:     Response.ClearContent();
   6:   
   7:     // get target file path from querystring
   8:     string filePath = (Request.QueryString["filePath"] ?? "").Trim();
   9:     Debug.WriteLine("GetFile: filePath: '" + filePath + "'");
  10:   
  11:     // determine content type
  12:     string contentType = null;
  13:     string extension = Path.GetExtension(filePath).ToLowerInvariant();
  14:     switch (extension)
  15:     {
  16:        case ".csv":
  17:           contentType = "text/csv";
  18:           break;
  19:        case ".mp4":
  20:           contentType = "video/mp4";
  21:           break;
  22:        case ".pdf":
  23:           contentType = "application/pdf";
  24:           break;
  25:        default:
  26:           // Unsupported filetype
  27:           // There are serious security implications with
  28:           // serving up files from a webserver. Make sure
  29:           // you do not open yourself up to an attack!
  30:           throw new HttpException(403, "Forbidden.");
  31:        // Use an empty ContentType if the type is unknown
  32:        //contentType = "";
  33:        //break;
  34:     }
  35:   
  36:     //Set the ContentType.
  37:     Response.ContentType = contentType;
  38:     Debug.WriteLine("Mapped extension '" + extension 
  39:            + "' to content type '" + contentType + "'.");
  40:   
  41:     // determine and set file length
  42:     var fileInfo = new FileInfo(filePath);
  43:     Response.AddHeader("Content-Length", fileInfo.Length.ToString());
  44:   
  45:     //Write the file directly to the HTTP content output stream.
  46:     Response.WriteFile(filePath);
  47:   
  48:     // flush and end the response
  49:     Response.End();
  50:  }

How To Detect If The Command Prompt Is Running Elevated

As I was setting up my Console2 shell tabs I was curious if running Console2 as an administrator would transfer the elevated privileges token to the tabs as well.

Turns out detecting this was not as straightforward as I thought it would be!

TL;DR

If you need to know how to detect if the command prompt is running elevated (or your script) use the following command:

whoami /groups
If the output contains these lines the process is running elevated:
Mandatory Label\High Mandatory Level Label            S-1-16-12288
                    Mandatory group, Enabled by default, Enabled group

The Long Answer

With the addition of User Account Control to Windows Vista the platform gained integrity levels – an integrity level indicates how much an application can be trusted to perform  actions on the system, e.g. accessing files or the registry and interacting with other processes. By adding this additional security feature to the OS it now has another indicator to help isolate (sandbox) programs and prevent them from going rogue on your system. Very cool!

The following integrity levels are supported:

  • Untrusted – processes that are logged on anonymously are automatically designated as Untrusted
  • Low – The Low integrity level is the level used by default for interaction with the Internet. As long as Internet Explorer is run in its default state, Protected Mode, all files and processes associated with it are assigned the Low integrity level. Some folders, such as the Temporary Internet Folder, are also assigned the Low integrity level by default.
  • Medium – Medium is the context that most objects will run in. Standard users receive the Medium integrity level, and any object not explicitly designated with a lower or higher integrity level is Medium by default.
  • High – Administrators are granted the High integrity level. This ensures that Administrators are capable of interacting with and modifying objects assigned Medium or Low integrity levels, but can also act on other objects with a High integrity level, which standard users can not do.
  • System – As the name implies, the System integrity level is reserved for the system. The Windows kernel and core services are granted the System integrity level. Being even higher than the High integrity level of Administrators protects these core functions from being affected or compromised even by Administrators.
  • Installer – The Installer integrity level is a special case and is the highest of all integrity levels. By virtue of being equal to or higher than all other WIC integrity levels, objects assigned the Installer integrity level are also able to uninstall all other objects.

 

For more info see the Windows Integrity Mechanism Design.

Simple, Fast and Accurate Running Average in C#

Running averages, also called rolling average, rolling mean and moving average, can be calculated in several different ways:

  • Simple Moving Average
  • Cumulative Moving Average
  • Weighted Moving Average

For my scenario I needed a simple, fast and accurate average, so I settled on implementing the simple moving average calculator below.

   class SimpleRunningAverage
   {
      int _size;
      int[] _values = null;
      int _valuesIndex = 0;
      int _valueCount = 0;
      int _sum = 0;

      public SimpleRunningAverage(int size)
      {
         System.Diagnostics.Debug.Assert(size > 0);
         _size = Math.Max(size, 1);
         _values = new int[_size];
      }

      public int Add(int newValue)
      {
         // calculate new value to add to sum by subtracting the
         // value that is replaced from the new value;
         int temp = newValue - _values[_valuesIndex];
         _values[_valuesIndex] = newValue;
         _sum += temp;

         _valuesIndex++;
         _valuesIndex %= _size;
        
         if (_valueCount < _size)
            _valueCount++;

         return _sum / _valueCount;
      }
   }
 
 

Here is how to use it:

      SimpleRunningAverage avg = new SimpleRunningAverage(4);
      foreach (int i in new int[] { 1, 2, 3, 4, 4, 4, 4 })
      {
         Console.WriteLine(avg.Add(i));
      }

 

For an implementation with more bells and whistles check out Marc Cliftons great article.

How To Determine If A Window Is Active (In C)

As promised in my previous blog describing how to add activity notification flash to PuTTY here is another way to check if the window is active. Instead of keeping track of the current window state by handling the WM_ACTIVATE message you can directly query a window for its status with GetWindowInfo(). The WINDOWINFO.dwWindowStatus field will be set to WS_ACTIVECAPTION when the window is active.

Paste the following snippet at the end of window.c:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION2 */
/* SNIPPET ID: {CE84000D-9024-45f1-B0E6-5029AD1B257F} */
BOOL is_window_active()
{
   BOOL bActive=FALSE;
   BOOL bResult;
   WINDOWINFO wi;
 
   memset(&wi, 0, sizeof(wi));
   wi.cbSize=sizeof(wi);
 
   bResult=GetWindowInfo(hwnd, &wi);
 
   if(bResult)
      bActive = (wi.dwWindowStatus==WS_ACTIVECAPTION);
 
   return bActive;
}
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION2 */

Then add a forward declaration to the forward declarations (Snippet ID: D8B4F4A3-F870-4ded-B298-EEB71701D25D), it will look like this:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS */
/* SNIPPET ID: {D8B4F4A3-F870-4ded-B298-EEB71701D25D}-20090922*/
static void flash_window_activity(int mode);
static BOOL window_is_active=TRUE;
static BOOL activity_blink_done=FALSE;
BOOL is_window_active();
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS*/

 

With this new code in place all that is left is updating the activity detection logic to use it. This is implemented in the from_backend method, replace the use of the window_is_active boolean with the new is_window_active() method call so the code will look like this:

int from_backend(void *frontend, int is_stderr, const char *data, int len)
{
/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
/* SNIPPET ID: {9198643F-09DF-466f-971F-EB05EA15A85E}-20090922 */
   if(!is_window_active())
      flash_window_activity(2);
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
   return term_data(term, is_stderr, data, len);
}

 

All that is left now is compiling the code and firing up PuTTY!

Enjoy!

How to add Activity Notification to PuTTY

For over a decade PuTTY has been my Telnet/SSH client of choice for Windows. I mostly use it as a MUD client nowadays and missed one convenience feature: activity notifications. Chat clients all flash for attention when activity occurs and it would be a great addition to streamline my social mudlife, so I set out on a quest to add it…

First of all you need to have Microsoft Visual C++ installed to compile the sourcecode for Windows which can be found on the PuTTY Download page. Get the sources unzipped and load the workspace “putty-src\WINDOWS\MSVC\PUTTY.DSW”, you will need to go through a conversion to a Visual Studio 2008 solution when using VS2008. All code additions and changes are done in the file WINDOW.C in the “putty” project.

To support activity notification we need to know when there is activity and notify the user by making the window flash if the window is not active and it has not already done a flash. This brings us down to three problems to solve: detecting activity, knowing when the window is not active and flashing the window.

 

Flashing the PuTTY Window

PuTTY already has the option to use the window flash as a visual bell so that code can be used as a template. Notice how this feature also has been implemented in the PuTTY code itself to support flash on older Windows OSes that do not support the FlashWindowEx API method. (I have left this code in place, but it has not been tested.)

The following code snippet must be added at the end of the file:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS */
/* SNIPPET ID: {34060BBE-6F8C-4bc1-AF1F-97B3FC8D24A4} */
static void flash_window_timer_activity(void *ctx, long now)
{
    if (flashing && now - next_flash >= 0) {
      flash_window_activity(1);
    }
}
 
static void flash_window_activity(int mode)
{
   if(mode==0) {
      /* stop */
   } else if (mode==2)
   {
      /* start */
      if (!flashing && !activity_blink_done) {
         flashing = 1;
         activity_blink_done=TRUE;
         if (p_FlashWindowEx) {
            /* For so-called "steady" mode, we use uCount=2, which
            * seems to be the traditional number of flashes used
            * by user notifications (e.g., by Explorer).
            * uCount=0 appears to enable continuous flashing, per
            * "flashing" mode, although I haven't seen this
            * documented. */
            flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
               (cfg.beep_ind == B_IND_FLASH ? 0 : 2),
               0 /* system cursor blink rate */);
            /* No need to schedule timer */
         } else {
            FlashWindow(hwnd, TRUE);
            next_flash = schedule_timer(450, flash_window_timer_activity, hwnd);
         }
      }
   }
   else if(mode==1)
   {
      /* maintain */
      if (flashing && !p_FlashWindowEx) {
         FlashWindow(hwnd, TRUE);   /* toggle */
         next_flash = schedule_timer(450, flash_window_timer_activity, hwnd);
      }
 
   }
}
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS */

 

Add the following snippet to the forward declarations at the top of the file (surrounding code is show for reference to the location where it should be placed and must not be added):

#define TIMING_TIMER_ID 1234
static long timing_next_time;
 
/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS */
/* SNIPPET ID: {D8B4F4A3-F870-4ded-B298-EEB71701D25D}*/
static void flash_window_activity(int mode);
static BOOL window_is_active=TRUE;
static BOOL activity_blink_done=FALSE;
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS*/
 
static struct {
    HMENU menu;

The activity_blink_done boolean ensures the window flash gets triggered only one time once the window has become inactive and activity occurs.

 

Detecting the Window Active State

There are several ways of doing this, I embarked on the adventure of using a handler for the WM_ACTIVATE message to keep track of the current state because it seemed to blend in well with the rest of the code in place. The handler also clears the activity_blink_done variable so a new flash will be triggered when necessary.

Add the following snippet at the end of the file:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */
/* SNIPPET ID: {75B2CA9C-49F4-4eb5-AFCF-E3D743C37C44} */
int Do_WM_ACTIVATE(HWND a_hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   WORD wAction = LOWORD(wParam);
   WORD wMinimized = HIWORD(wParam);
 
   if(a_hwnd == hwnd) {
      switch(wAction)
      {
         case WA_INACTIVE:
            window_is_active = FALSE;
            activity_blink_done = FALSE;
            break;
         case WA_ACTIVE:
         case WA_CLICKACTIVE:
            if(!wMinimized)
               window_is_active = TRUE;
            break;
         default:
            break;
      }
   }
}
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */

 

With the message handler in place we need to hook it up in the window procedure. To do this we need to add a case statement for the WM_ACTIVATE message in the WndProc method. Insert the following code snippet right before default case handler (surrounding code shown for reference and must not be copied):

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */
/* SNIPPET ID: {5AFAA3AB-FB28-45e9-9DE7-E56648A1B5AF} */
      case WM_ACTIVATE:
         Do_WM_ACTIVATE(hwnd, message, wParam, lParam);
         break;
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */
      default:
         if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {

 

For completeness add a forward declaration below the previous forward declaration snippet we added:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION FORWARD DECLARATION */
/* SNIPPET ID: {D3292300-A6A3-402f-A0A5-CE259BD25EC0} */
int Do_WM_ACTIVATE(HWND a_hwnd, UINT message, WPARAM wParam, LPARAM lParam);
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION FORWARD DECLARATION */

 

Detecting Session Activity

With the window flash and window state support in place all that is left to do is hooking it up to the session activity detection. Find the from_backend method and insert the code snippet below so the method resembles the code block:

int from_backend(void *frontend, int is_stderr, const char *data, int len)
{
/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
/* SNIPPET ID: {9198643F-09DF-466f-971F-EB05EA15A85E} */
   if(!window_is_active)
      flash_window_activity(2);
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
   return term_data(term, is_stderr, data, len);
}

 

Enjoy!

That completes the code additions. Compile the code, fire up PuTTY and enjoy the new activity notification feature!

Quest complete! You gained 1 million XP.

How to parse and modify a URL in .Net

When you need to modify a url string in .Net code the most prudent way to do so is by using the UriBuilder class from the System namespace because it encapsulates all the quirky rules involved in url parsing. However simply creating a new UriBuilder instance initialized with the url string has the potential for throwing a UriFormatException which creates a serious performance hit whether the exception is caught and handled or, even worse, your program will fail on an unhandled exception if your code did not anticipate this.

The UriFormatException can be easily avoided by first converting the url string to a Uri class instance by calling Uri.TryCreate(...) and checking the return value for success. If TryCreate succeeded the resulting Uri instance can then be used to create a UriBuilder instance.

 

The code below shows a C# example of how to modify the hostname in a url without throwing exceptions.

[TestMethod]

public void ModifyUrlHost()

{

   string[] urls ={"http://brokensite.com/test/me.html?a=1&b=2"

                  , "https://brokensite.com"

                  , "https://brokensite.com/"

                  , "http://brokensite.com/default"

                  , "/test/me.html?a=1&b=2"

                  , String.Empty

                  , null

                 };

   string newHostName="www.somesite.com";

 

   foreach (string url in urls)

   {

      Debug.WriteLine("Original Url: " + url);

 

      string newUrl = url;

      Uri uri;

      if (Uri.TryCreate(url, UriKind.Absolute, out uri))

      {

         Debug.WriteLine("Uri.TryCreate succeeded");

         UriBuilder builder = new UriBuilder(uri);

         builder.Host = newHostName;

         newUrl = builder.Uri.ToString();

      }

      else

         Debug.WriteLine("Uri.TryCreate failed");

 

      Debug.WriteLine("New Url     : " + newUrl);

      Debug.WriteLine("");

 

      if(newUrl!=null)

         Assert.IsFalse(newUrl.Contains("brokensite.com"), "url still contains brokensite.com");

   }

}

This test generates the following output:

//Original Url: http://brokensite.com/test/me.html?a=1&b=2

//Uri.TryCreate succeeded

//New Url     : http://www.somesite.com/test/me.html?a=1&b=2

 

//Original Url: https://brokensite.com

//Uri.TryCreate succeeded

//New Url     : https://www.somesite.com/

 

//Original Url: https://brokensite.com/

//Uri.TryCreate succeeded

//New Url     : https://www.somesite.com/

 

//Original Url: http://brokensite.com/default

//Uri.TryCreate succeeded

//New Url     : http://www.somesite.com/default

 

//Original Url: /test/me.html?a=1&b=2

//Uri.TryCreate failed

//New Url     : /test/me.html?a=1&b=2

 

//Original Url:

//Uri.TryCreate failed

//New Url     :

 

//Original Url:

//Uri.TryCreate failed

//New Url     :     

Reusable Generic Exception Wrapper in C#

When crossing boundaries between software layers you are sometimes faced with the requirement to wrap a meaningless exception from a lower layer into a more meaningful exception for users from the higher layer. The pattern described below helps with implementing this requirement in a reusable way. It is in no way meant to be a catch-all for every situation where you have to deal with exceptions, but when applied correctly can prove to be an invaluable tool in your toolkit. See Framework Design Guidelines, Chapter 7 (7.2.3) for more one exception wrapping.

The approach used is to wrap the logic that can fail in a delegate and have this delegate executed by the WrapExceptions method. The WrapExceptions method then takes responsibility of handling the exceptions appropriately. It should be modified to handle only the applicable exceptions; some exceptions you might not want to wrap e.g. StackOverflowException, OutOfMemoryException and ThreadAbortException because you cannot recover from them. An added advantage of wrapping the failure prone code in a delegate is that it allows you to easily wrap it around existing code.

The WrapExceptions code snippet:

// public delegate void Action();

public static void WrapExceptions(Action action)

{

   try

   {

      action();

   }

   catch (MyApplicationException)

   {

      // just rethrow exception, it

      // was already properly handled

      throw;

   }

   catch (Exception e)

   {

      throw new MyApplicationException(e);

   }

}

And then you can use it as follows:

public void WrapMyException(string filepath, string myLine)

{

   WrapExceptions(delegate()

   {

      using (TextWriter writer = new StreamWriter(filepath))

      {

         writer.WriteLine(myLine);

      }

   });

}

Let me know your thoughts on this approach. What problems did it solve, and did it introduce new ones?

The Pitfall of ICloneable

Or, why you should never use ICloneable.

So I decided I needed to support cloning for my objects so I can modify the object and compare it to the original (very useful for unit-testing, dirty checking, etc.). The .Net framework comes with a handy interface to publish this ability called ICloneable. The documentation states "Supports cloning, which creates a new instance of a class with the same value as an existing instance". Great! It comes with one method: Clone. Can't be too hard to implement this interface, right?

A quick peek at the documentation for the Clone method says the implementation "Creates a new object that is a copy of the current instance". And so every textbook implementation goes on to show you how you do that:

public object Clone()
{
   return this.MemberwiseClone();
}

But what is the point of that, besides adding more code to maintain? EVERY object already supports MemberwiseClone! Oh yes, we were trying to satisfy an interface contract... But hold on, it gets worse as the documentation then opens up an infinite can of worms with this remark:

Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.

The resulting clone must be of the same type as or a compatible type to the original instance.

The Clone method, and thus the ICloneable interface just became a free-for-all, do as you like, contract. You may deep copy, shallow copy, heck you can even change the type! Technically this can all result in correct code, but the sheer absence of semantics turns the use of this interface into a humongous pitfall. Within your own sphere of influence you can set an expected semantic, but as soon as your code leaves this safe place, or you introduce code from another source which applied different semantics to the ICloneable interface you are in for a debugging session from hell.

ICloneable just became unusable.

Go ahead and mark it as obsolete in your copy of the framework. Not all is lost however, you can work around this issue by defining your own interface contract with its own semantics, but do not inherit it from ICloneable as this would reintroduce the issue. For example:

/// <summary>
/// Supports deep-copy cloning, which creates a 
/// new instance of a class of the same type and 
/// with the same value as an existing instance.
/// </summary>
/// <typeparam name="T">Type of the class 
/// being cloned.</typeparam>
public interface IDeepCloneable<T>
{
   /// <summary>
   /// Creates an equally typed deep-copy clone 
   /// of this object.
   /// </summary>
   /// <returns>An equally typed deep-copy clone 
   /// of this object.</returns>
   T Clone();
}

This interface contract sets a clear copy and type expectation (and gets rid of the pesky Object return type, that was so 1.0 baby!), but defining cloning semantics is not an easy task. Data containers, business- and UI-objects all have different needs and come with different cloning behaviors. Defining an interface for each of those will help keep expectations clear and ease integration with 3rd party components. However, unless you explicitly implement those interfaces on all classes you will also have to make sure the method names in those interfaces are unique else it will still be too easy to mix incompatible implementations. Always keep the consumer in mind while designing your interface!

I'm curious to know how you approached your cloning challenge. Leave me a comment!

 

References

Nerdettes are the source of beautiful code?

Emma McGrattan, the senior vice-president of engineering for computer-database company Ingres–and one of Silicon Valley’s highest-ranking female programmers–insists that men and women write code differently. Women are more touchy-feely and considerate of those who will use the code later, she says. They’ll intersperse their code–those strings of instructions that result in nifty applications and programs–with helpful comments and directions, explaining why they wrote the lines the way they did and exactly how they did it.
The code becomes a type of “roadmap” for others who might want to alter it or add to it later...

Did she just say I code like a girl? My pursuit of writing maintainable code is really an exploration of my feminine side? That is quite the flamebait Mrs. McGratten treated the nerdiverse on. :)

Her goal is noble, but I think Agile is wasted on Ingress:

In an effort to make Ingres’s computer code more user-friendly and gender-neutral, McGrattan helped institute new coding standards at the company. They require programmers to include a detailed set of comments before each block of code explaining what the piece of code does and why; developers also must supply a detailed history of any changes they have made to the code. The rules apply to both Ingres employees and members of the open-source community who contribute code to Ingres’s products.

My question to you: Do you get anything done? Or is 90% of time spent on adding code-pretties?

Does Universal Beautiful Code Exist?

A lot of debate is going on about "Beautiful Code". How can you measure the beauty of code? Is it "solid" code? Or perhaps easily readable for humans? An efficient algorithm, or a fast one? Terse sample code that shows a concept, or production code that is robust and fault tolerant? Perhaps a clever solution to a problem, or code that follows coding conventions and guidelines? Or should it be patterns based? What about curly-braces, indentation, comments, letter-casing (NO SHOUTING, IT'S RUDE!) or programming language? Should it exploit all features of the language it was written in, or only use some generic feature-set, libraries or framework commonly found in the language type (imperative, functional, .Net, C-Libraries)? What about cyclomatic complexity and other software metrics?

Most of those "beauty metrics" are purely gut-feeling based and enforcing metrics like a low cyclomatic complexity generally does not improve code beauty (good luck polishing a coal until it's a diamond). In my experience code often mirrors the authors' understanding of the problem and thought-process. No amount of computer assisted code analysis can improve that.

Beautiful code can come in the form of little one-liner gems, or huge elegant architectural diamonds that solve a real-world problem. You will generally find more little gems than big diamonds.

In the end nobody can win: Beauty is in the eye of the beholder!

I cannot put it better than David Hume:

Beauty in things exists merely in the mind which contemplates them.

Code beauty is determined by the observers' frame of reference; programming exposure (languages (C, C++, Java, Visual Basic, F#, Ruby, Lisp), Patterns, Algorithms, Operating Systems, formal training, experience (how many times has the beholder been burned by mistakes?), etc.), native language, organizational position (Junior Programmer vs. Senior Architect vs IT Director, they have different stakes in the code produced) and even aesthetical preferences.

Back to my original question: Does UNIVERSAL beautiful code exist?

Think about that for a minute, I'll wait... What do you think the Greys use as their programming language? Something based on hieroglyphs and flow-charts? What about my Ferengi friend Quark? Quantum languages like QCL or QFC?

Good luck getting consensus on that! :)

So, is there Beautiful Architecture?

Environment.TickCount: Int32 (aka SIGNED integer)

Did you know that Environtment.TickCount returns a signed 32 bit integer? Did you know the sign on this property flips every 24.9 days? From the MSDN documentation: The value of this property is derived from the system timer and is stored as a 32-bit signed integer. Consequently, if the system runs continuously, TickCount will increment from zero to Int32.MaxValue for approximately 24.9 days, then jump to Int32.MinValue, which is a negative number, then increment back to zero during the next 24.9 days. Ouch! Good thing windows updates get pushed once a month (and generally kindly coerce you to reboot); you might not notice the couple of days at the end when you're pulling negative numbers. But alas, today the negative tickcount decided to hit me. I was running unittests and noticed I was sending out negative request numbers?!? WTF! ROTFL! :) A little investigation turned up the culprit; trusty old TickCount wasn't that trusty after all. (That will teach me for stopping the windows update service to stop the reboot nagging, right?)
What happened to the days when you could boast about your system uptime? My linux box easily ran into hundreds of days (the resets were caused by power outtages)! What happened to my linux box?!?
What is a developer to do? Eureka! You can cast it to a Uint32! Twice the positive size, twice the fun, right?

UInt32 tickCount = (UInt32)Environment.TickCount;

Nah, you'll still wrap around after 59.8 days, which means you cannot use it to calculate the system uptime or measure time intervals... Here's how to calculate system uptime:

PerformanceCounter uptimeCounter = new PerformanceCounter("System", "System Up Time", true); uptimeCounter.NextValue();// init counter float uptime = uptimeCounter.NextValue(); // get uptime in secs TimeSpan uptimespan = TimeSpan.FromSeconds(uptime); Trace.WriteLine("Uptime: " + uptimespan.ToString());

And this is how you measure a time interval:

Stopwatch sw = new Stopwatch(); sw.Start(); // do lengthy stuff sw.Stop(); Trace.WriteLine("Elapsed: " + sw.Elapsed.ToString());

Enjoy! - Doc. How do YOU determine your system uptime programmatically?

ClientCertificates and WebException: The request was aborted: Could not create SSL/TLS secure channel.

If you are using X509 ClientCertificates with a webservice client called from IIS and the service endpoint uses the HTTPS protocol (SSL) the following exception can occur: WebException: The request was aborted: Could not create SSL/TLS secure channel.
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. at System.Web.Services.Protocols. WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols. HttpWebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols. SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
The curious part is that everything works great while running unittests on the service directly; it's IIS that throws a wrench in it. To add some more grief to the equation this particular scenario played out in a test environment with self-signed certificates. So my initial investigation concentrated on making sure the root certificate was in the right place (LocalMachine\My and Root). All seemed well, but the exception persisted. I resorted to disabling certificate verification, still the exception persisted. Finally Microsoft KB article 901183 'How to call a Web service by using a client certificate for authentication in an ASP.NET Web application' put me on the right track:
Step 2: Configure access to the client certificate In this step, you must grant permission for the ASP.NET account to access the client certificate that is stored in the local machine store. The Network Service account is the default account for running Web applications on Windows Server 2003. Therefore, you must grant access to the certificate for the Network Service account. If you have configured a custom account to run ASP.NET, you must grant access for the custom account. Note In Microsoft Internet Information Server (IIS) 5.0, ASP.NET runs under the ASPNET account and not under the Network Service account. Therefore, you must to grant permissions for the ASPNET account on a computer that is running IIS 5.0. To grant access for a specific user account, run the following command at a command prompt: WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s "IssuedToName" -a "AccountName"
And voila! My service client happily zoomed along again. Why did it work while unittesting and not in IIS? The certificate was installed under the developer account, which grants the necessary permissions to the private key for that account immediately, but the NetworkService account was lacking them which caused the underlying connection to be closed... Microsoft has included the tool FindPrivateKey in the Windows Communication Foundation (WCF), Windows Workflow Foundation (WF) and Windows CardSpace Samples which can help you locate the private key file and check (and change) its permissions. I hope it helps some of you out there struggling with the same issue!

My Latest Track