Brig Lamoreaux - All posts by blamoreaux

Review of Copy Source As Html Tools

by blamoreaux 15. August 2007 09:12

It makes sense that as a blog about .net programming I should include samples of code. Code is easier to read when there is syntax highlighting and proper indentation. I'm going to look at four tools that provide a way of displaying source code in Html documents. The first tool is a general add in to Visual Studio and the last tools are specific to Windows Live Writer.

The contestants are the following:

CopySourceAsHtml

Insert Code for Windows Live Writer

Paste from Visual Studio

Code Snippet plugin for Windows Live Writer

The plugins for Live Writer really are not named very well, but I'll give them a shot anyway.

Screen Shot

In order to do a fair test, I will be comparing how the different tools handle the code in this screen:

CopySourceAsHtml

This is an add-in for Visual Studio. Right clicking on the code to copy displays a Copy As Html... option in the context menu. Once clicked, an option box appears which provides additional configuration. I've used this tool in the past and have always been satisfied with the results. I selected Wrap words and Embed styles as the only options for the copy which produce the following results:

<Example>

using System;

 

/// <summary>

/// Wizard represents a humanoid with special abilities

/// </summary>

public class Wizard

{

    const string Gretting = "Greetings and well met.";

 

    /// <summary>

    /// Says the greeting.

    /// </summary>

    public void SayGreeting()

    {

        // Ensure it is Daylight Saving Time

        if (DateTime.Now.IsDaylightSavingTime())

        {

            Console.Write(Math.Abs(Math.PI + 25.4));

        }

        else

        {

            Console.Write(Gretting);

        }

    }

}

 </Example>

Embedding the styles into the code gives the advantage of preserving the color highlighting when your post is picked up by an aggregator. If you do not embed the styles then you will lose the formatting and the code appears as normal text.

The tools provides options that really allow you to produce exactly what you want.

The only bad thing is I am forced to switch to html mode in order to insert the code snippet.

Insert Code for Windows Live Writer

This is the first tool I've used as a plugin for Windows Live Writer. After the installation, I see a new option in my Insert list for Insert Code...

The web site for Insert Code describes it as able to format a snippet of text in a number of programming languages such as C#, HTML, MSH, JavaScript, Visual Basic and TSQL.

Here is the results of the insert:

<Example>

using System;

/// <summary>
/// Wizard represents a humanoid with special abilities
/// </summary>
public class Wizard
{
    const string Gretting = "Greetings and well met.";

    /// <summary>
    /// Says the greeting.
    /// </summary>
    public void SayGreeting()
    {
        // Ensure it is Daylight Saving Time
        if (DateTime.Now.IsDaylightSavingTime())
        {
            Console.Write(Math.Abs(Math.PI + 25.4));
        }
        else
        {
            Console.Write(Gretting);
        }
    }
}

</Example>

Right away I can see that the color for strings is different that what I have defined in the original. More importantly I see I lost the specific font I had defined. The biggest advantage over CopySourceAsHtml is not forcing me to switch to html mode in order to insert the code. The plugin makes it completely transparent to me.

I think I'm going to run into trouble on some aggregators when it goes to process the code. Insert Code creates a <style> </style> section where it defines the css classes used to format the code. The tool doesn't provide the option for me to select embedded styles nor does it give me options to tweak the output.

One thing I do like is the ability to turn on alternate line background.

Paste from Visual Studio

This is also an plugin for Windows Live Writer and also has nearly the same number of downloads as Insert Code. From the description on the web page, it can easily transfer syntax highlighted source code from Visual Studio to elegant HTML in Windows Live Writer. Copy from Visual Studio and insert directly to Windows Live Writer to maintain your unique syntax highlighting settings.

<Example>

using System;

/// <summary>
/// Wizard represents a humanoid with special abilities
/// </summary>
public class Wizard
{
    const string Gretting = "Greetings and well met.";

    /// <summary>
    /// Says the greeting.
    /// </summary>
    public void SayGreeting()
    {
        // Ensure it is Daylight Saving Time
        if (DateTime.Now.IsDaylightSavingTime())
        {
            Console.Write(Math.Abs(Math.PI + 25.4));
        }
        else
        {
            Console.Write(Gretting);
        }
    }
}

</Example>

Sure enough, this tool has kept the colors and font I have defined in VS. The tool doesn't give me any type of user interface but takes the contents of the clipboard and inserts them as html. I'm guessing the tool uses the rich text formatting that VS provides and builds the styles. I do like that the styles are embedded in the code so I won't lose any formatting in the aggregators. However, I miss having the opportunity to add any tweaks to the output before it is committed.

Insert Code Snippet

The last Live Writer plugin to review is Code Snippet plugin for Windows Live Writer. This follows the same installation as the previous plugins. However, I do get the chance to make some changes before the code is inserted into my page.

I stick with the defaults and get the following results: 

<Example>

   1: using System;
   2:  
   3: /// <summary>
   4: /// Wizard represents a humanoid with special abilities
   5: /// </summary>
   6: public class Wizard
   7: {
   8:     const string Gretting = "Greetings and well met.";
   9:  
  10:     /// <summary>
  11:     /// Says the greeting.
  12:     /// </summary>
  13:     public void SayGreeting()
  14:     {
  15:         // Ensure it is Daylight Saving Time
  16:         if (DateTime.Now.IsDaylightSavingTime())
  17:         {
  18:             Console.Write(Math.Abs(Math.PI + 25.4));
  19:         }
  20:         else
  21:         {
  22:             Console.Write(Gretting);
  23:         }
  24:     }
  25: }

</Example>

Not too bad. In fact, besides not keeping my original color and font, I like the end result. I especially like how the styles are embedded inline. I don't think I would use the line numbers too often but I do like the alternate line background.

The Results

Among all of the tools I will keep two. I will keep CopyCodeAsHtml so I can get my code into html format whenever I want. For Windows Live Writer, I'm going to stick with the aptly named Code Snippet plugin for Windows Live Writer. I chose this as the winner because I am provided options over the results and it has inline styles. Insert Code for Windows Live Writer gives me almost the same features but doesn't provide inline styles which is a must when it comes to aggregators.

I do wish that more languages were supported in the plugins and hope this will come in time. I know there must be more tools out there to get source code to html but these are the four that I found. If you have a tool that you enjoy, please share it. I'm always looking for ways to improve and make life easier.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

How to Implement logging

by blamoreaux 15. August 2007 09:11

We are getting ready to send our first child off to kindergarten and I wish I could be a fly on the wall to see how he enjoys his first day of school. Secretly I want to make sure he remembers the one-two punch I taught him in case someone tries to bully him around. Fortunately at work I have much more control over keeping track of my applications once I send them into production. The secret is Logging.

Our team has used three major logging implementations. Log4Net, Enterprise Library, and a homegrown solution. What we have discovered is the importance of making the implementation transparent to our application.

The Logging Wrapper

The wrapper class minimizes the impact to your application when you switch out a logging implementation say from Log4Net to Enterprise Library Logging. I have found the following interface to completely accommodate our needs.

public interface ILogger

{

    void LogInformational(string message);

    void LogWarning(string message);

    void LogWarning(Exception ex);

    void LogError(Exception ex);

}

I use three categories for the messages specifically so I can turn on and off logging by setting a threshold level.

Informational
These messages will be used liberally throughout the code to provide process detailed information similar to debug traces.
Warning
Warnings are events the application can recover from. These include messages that provide more detail when the application responds to the user "Unable to save record". Warnings also include all exceptions that are handled in a try catch block.
Errors
Errors are exceptions that are logged from the global error handler.These are errors that the application did not expect.

The Implementation

We use Enterprise Library for .NET Framework 1.1, June 2005 in our projects. We are still evaluating Enterprise Library 3.0 – April 2007 (for .NET Framework 2.0 and 3.0). In the meanwhile this is how I configured EntLib.

First I include the following dlls

  • Microsoft.Practices.EnterpriseLibrary.Common
  • Microsoft.Practices.EnterpriseLibrary.Configuration
  • Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
  • Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging
  • Microsoft.Practices.EnterpriseLibrary.Logging

Then I create a class that implements ILogger and use EntLib to get the job done.

using System;

using Microsoft.Practices.EnterpriseLibrary.Logging;

using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

 

public class EntLib11Logger : ILogger

{

    public void LogInformation(string message)

    {

        Logger.Write(message, "Information", 1);

    }

    public void LogWarning(string message)

    {

        Logger.Write(message, "Warning", 5, 1, Severity.Warning);

    }

    public void LogWarning(Exception ex)

    {

        ExceptionPolicy.HandleException(ex, "Warning");

    }

    public void LogError(Exception ex)

    {

        ExceptionPolicy.HandleException(ex, "Error");

    }

}

Notice how both the Enterprise Library Logging and Exception Handling is used to provide functionality for our ILogger. With the Logging Block, I have to specify in the code the Priority level and Severity level. The Exception Handling Block allows those values to be set in the configuration file, which is what needs to be configure now.

Configuration

Configuration of Enterprise Library can be a little confusing but lets just go one section at a time.

The first thing we'll want to setup is the logging aspect. This makes the Exception Handling configuration a lot easier. Start up the EntLibConfig.exe tool and select File - Open Application and select the app.config file for the project. 

Logging Configuration

Select your app node and choose to add the Logging and Instrumentation Application Block. 

Add Block

The tool allows you to define categories, formatters, and sinks. Sinks are the final resting place for our messages. Sinks can be a flat file or an event log. Formatter are used to turn our message object into a plain text message. The category is where you define what happens to our message object when it is caught. 

I modify the Sinks section to have one sink for the Application Event Log.

Sink Setup

Modify the categories section to have the three categories defined during the implementation step

  • Information
  • Warning
  • Error

Notice how each category has a single destination. The destination tells Enterprise library to use the default Text Formatter and send it to the Application Event Log Sink.

Logging Category

One last step in logging is to set up a default category. I like to set mine to default to Error.

Default Category

At this point your application should be able to use LogInformational(string message) and LogWarning(string message)with no problems. Setting up the exception handling will take care of the rest.

Exception Handling Configuration

Select your app node and choose to add the Exception Handling Application Block. Select the application block and add a new Exception Policy with the name Error. Add a new Exception Type to the policy that catches all Exceptions. Finally add a new Logging Handler.

Error Exception Policy

The configuration I use for the Logging Handler of the Error Exception Policy is:

LogCategory Error
Priority 10
Severity Error

The Warning exception policy is exactly like the Error but with the following values for the Logging Handler:

LogCategory Warning
Priority 5
Severity Warning

Warning Exception Policy

With both exception policies setup and using the logging our ILogging class is fully functional. Now it is a simple configuration setting to turn on and off the different logging levels.

Any value larger than the MinimumPriority will be logged. Anything less will not be logged, simple. The values of the categories are: Error-10, Warning-5, and Information-1. I like to set the MinimumPriority to 10 in production.

Wrap Up

So far this method of logging has been very useful. There is a lot more you can do from here such as sending emails when a warning happens. I've only laid the foundation of a logging methodology.

In the future I plan to evaluate how the Enterprise Library 3.0 – April 2007 version handles logging and create an implementation for ILogger. Other things I've thought about is to create some sort of LoggingFactory or ServiceProvider to really disconnect my application from the implementation. Ideally I don't want to have any referenced dlls in my apps.

Tell me what your experience has been with logging. What works well for you, what doesn't. Do you see yourself using the ILogger interface. Please let me know because I would love to improve on what I have.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

When a Bug is Found

by blamoreaux 15. August 2007 09:09

James Shore talks about the concept of being bug free and has many recommendations on how to reach that goal. At my desk I have the following guide hanging on the wall to help me in my quest.

First:

  • Create a Test to Prove it:
  • Fix it:

You've fixed the problem, but you haven't solved the underlying cause.

Discover why that bug occurred.

  • Discuss the code process with your pairing partner.
  • Is there a design flaw that made this bug possible?
  • Can you change an API to make such bugs more obvious?
  • Is there some way to refactor the code that would make this kind of bug less likely?
  • Improve your design.

If you've identified a systemic problem, discuss it with the rest of you team in you next meeting or iteration retrospective.

Tell people what went wrong so they can avoid that mistake in the future.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Ruby Array Randomize

by blamoreaux 15. August 2007 09:09

I needed the ability to randomize the order of an array. This is useful when you have a set collection of questions in a survey that you want to shuffle before you present them to the user. After looking around a bit, I didn't find anything that worked. Here is what I pieced together with my limited knowledge of Ruby. 

# Created by Brig R. Lamoreaux
# Date: 11 July 2007
# Time: 10:38 am
 
# Randomize the contents of an Array
class Array
  def randomize
    a=self.dup
    result = []
    self.length.times do
      result << a.slice!(rand(a.length))
    end
    return result
  end
  def randomize!
    a=self.dup
    result = []
    self.length.times do
      result << a.slice!(rand(a.length))
    end
    self.replace result
  end
end

Here are some test that make sure it really works.

puts "Randomize Tests"
x = [1, 2, 3, 4, 5]
print "x: "
x.each do |i|
  print "#{i}"
end
 
y = x.randomize
print "\ny: "
y.each do |i|
  print "#{i}"
end
 
x.randomize! # x is now [3, 5, 4, 1, 2]
print "\nx: "
x.each do |i|
  print "#{i}"
end
 
x.randomize! # x is now [3, 5, 4, 1, 2]
print "\nx: "
x.each do |i|
  print "#{i}"
end

Special thanks to syntaxhighlighter on providing styles for ruby syntax highlighting.

Update: After doing a search for array shuffle, I found some useful examples.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Balance Simple Code and Expert Knowledge

by blamoreaux 15. August 2007 09:09

I enjoyed reading What’s Wrong With This Code (#16) because it got me thinking about having in depth knowledge on a subject and KISS. When I saw the code, I thought it was an overkill for the problem. In the comments I offered a solution that is simple and what seems to have solved the problem. I'll admit that I'm not an expert on JavaScript and I wouldn't be surprised if someone pointed out serious flaws with my code. While I make my way on the path to becoming an expert, I'll continue to solve problems with simple solutions. Borrowing the concept Red/Green/Refactor, from TDD, I think it is important for developers to follow the KISS/Learn/Revise model of development. It's impossible for me to become an expert in every field. But I should be trying to become an expert in the fields that I deal with. Just like eating an elephant, I needs to learn the technologies one piece at a time. The easiest way I do that is to glean from other's insight. It is amazing how much useful information is shared through blogs. I make it a practice to read the thoughts of the leaders in the industry several times a week. More importantly I am sharing my own thoughts. I recently searched my name and found that other people have found some of my solutions useful.

In answer to how to become an expert while keeping things simple, my solution is slow and steady, one article at a time.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Keeping the Blog Alive

by blamoreaux 15. August 2007 09:08

My daily routine involves reading several different blogs as my way of taking advantage of other people's great ideas. Most of the things that I read are technical, but mix in with the bunch has been a blog about blogs. For the most part many of the articles I read are in essence a variation on the same theme. It is refreshing to find a diamond in the rough article that really helps to clarify an idea or answer a difficult question. I don't expect this post to be a diamond, but I do plan for it to help me stay consistent with delivering my own ideas and experiences. The one piece of advice I've read is to keep a regular schedule of posting and that is what I'll do.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Objects, Data, and Actions

by blamoreaux 15. August 2007 09:08

I was recently asked what objects are in programming and how a database is related to them. Thinking long and hard about it, I came up with the following example:

Objects are containers that stores data and code. In fact objects are just like real life objects. Imagine an Animal object. Pick any animal you like, it will have Data and Actions. The data would be things like Height, Length, Age, Name, Color. And Actions could be Speak, Walk, Jump, Eat.

So a Lion could be:

MyLion.Height = 4

MyLion.Length = 7

MyLion.Age = 4

MyLion.Name = Mufasa

MyLion.Color = Yellow and Brown

Notice how these values can easily be stored in a database. But what about the actions? When MyLion performs an action, something gets done.

MyLion.Speak -> from my speakers I hear a  "ROAR!!!!"

MyLion.Eat ->  Now MyLion.Length = 7.5

See how actions can't really be stored as a value because they do something. A relational database can store all of my Properties but can't store what will happen when my object performs an action. But an OODB database can store objects. So I could save MyLion right to the database. I could also save MyChicken and MyHippo. Each object would do something a little different when I ask it to Speak or Eat.

Hope this helps.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.1.0.7
Theme by Mads Kristensen

Subscribe

About the author

Brig Lamoraeux Brig Lamoreaux
I'm a .Net developer.

E-mail me Send mail

Calendar

<<  November 2008  >>
MoTuWeThFrSaSu
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar

Pages

Recent posts

Recent comments

Tags

Categories


Archive

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2006-2008

Sign in