Rich Newman

February 17, 2012

Creating Code Listings in WordPress using Visual Studio

Filed under: code, Visual Studio, Wordpress — Tags: , , — richnewman @ 12:19 am

In WordPress it has historically been quite hard to paste code listings into the editors and get them to look good.  There are some plugins that try to do it, but none of them seem to work very well with code copied out of Visual Studio.

One option for creating code listings from Visual Studio is to paste an HTML version of the code into the HTML editor in WordPress.  In the past I’ve done this by pasting the code from Visual Studio into Word, saving as HTML, and then running a little bespoke program to tidy up the mess that Word makes of the resulting HTML.  All that was a pain.

Things are much easier in versions of Visual Studio after 2010.  In Visual Studio 2010 you can use an option in Microsoft’s Productivity Power Tools.  This is a Visual Studio extension (accessible via Tools/Extension Manager). It has an option to directly copy the code as HTML, amongst other things.  In versions of Visual Studio later than 2010 this option to copy the code as HTML is included in Visual Studio.

Unfortunately there’s no easy way to paste as HTML directly into the HTML editor in WordPress.  If you try you just get the text.

The trick here is to first paste into something that expects an HTML listing and will show all the tags as a result.  You can do this by adding an HTML page to your Visual Studio project and pasting into there.

So the steps to get a code listing from Visual Studio into WordPress in the same format as it is in Visual Studio are:

  1. In Visual Studio 2010, install the Productivity Power Tools in Visual Studio using Tools/Extension Manager.  In Visual Studio 2012 or later there’s no need to do this step.
  2. Add an HTMLPage item to your Visual Studio project
  3. Select the code you want to copy and hit Ctrl-C
  4. Go to your HTMLPage, right-click, Paste Alternate (not Paste: there should be a second paste option on the context menu).  This should show you the text with the HTML tags.
  5. Ctrl-A, Ctrl-C to select and copy the listing with the tags.
  6. Go to the HTML editor (‘Text’ tab at top) of your post in WordPress and paste the code in there at the appropriate point.

Below is an example of the results of this with a short method.  First what the end result looks like:

        static void MyMethod(int x, string y = "Hello"string z = "World") 
        {
            Console.WriteLine(y + " " + z + ": " + x);
        }

Then what the underlying HTML looks like.  You can tweak the generation of this in the Productivity Power Tools options but going with the defaults works fine for me:

<pre style="font-family:Consolas;font-size:13;color:black;background:white;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">void</span>&nbsp;MyMethod(<span style="color:blue;">int</span>&nbsp;x,&nbsp;<span style="color:blue;">string</span>&nbsp;y&nbsp;=&nbsp;<span style="color:#a31515;">&quot;Hello&quot;</span>,&nbsp;<span style="color:blue;">string</span>&nbsp;z&nbsp;=&nbsp;<span style="color:#a31515;">&quot;World&quot;</span>)&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Console</span>.WriteLine(y&nbsp;+&nbsp;<span style="color:#a31515;">&quot;&nbsp;&quot;</span>&nbsp;+&nbsp;z&nbsp;+&nbsp;<span style="color:#a31515;">&quot;:&nbsp;&quot;</span>&nbsp;+&nbsp;x);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</pre>

February 7, 2012

Delegate Syntax in C# for Beginners

Filed under: .net, beginners guide, c#, code syntax, delegate — Tags: , , , , — richnewman @ 3:48 am

Introduction

I have been programming with C# since it came out but I still find the delegate syntax confusing.  This is at least partially because Microsoft have changed the recommended syntax regularly over the years.  This article is a quick recap of the various syntaxes.  It also looks at some of the issues with using them in practice.  It’s worth knowing about all the various syntaxes as you will almost certainly see all of them used.

This article is just a recap: it assumes that you know what a delegate is and why you’d want to use one.

.Net and Visual Studio Versions

The first thing to note is that you can use any of these syntaxes as long as you are using Visual Studio 2008 or later and targeting .Net 2.0 or later.

Named methods were available in .Net 1.0, anonymous methods were introduced in .Net 2.0, and lambda expressions were introduced in .Net 3.0.  However, like much of .Net 3.0, which is based on the .Net 2.0 assemblies, lambda expressions will compile to .Net 2.0 assuming you have the appropriate version of Visual Studio.

Note also that lambda expressions can do (almost) everything anonymous methods can do, and effectively supersede them as the preferred way of writing inline delegate code.

Code

A listing of the code for this article is availableThe complete working program is also available.

The Delegate

For all of these examples we need a delegate definition.  We’ll use the one below initially.

        private delegate void TestDel(string s);

Named Methods

Named methods are perhaps the easiest delegate syntax to understand intuitively.  A delegate is a typesafe method pointer.  So we define a method:

        private void Test(string s)
        {
            Console.WriteLine(s);
        }

Now we create an instance of our method pointer (the delegate above) and point it at our method.  Then we can call our method by invoking the delegate.  The code below prints out ‘Hello World 1′.  This is easy enough, but all a little cumbersome.

            TestDel td = new TestDel(Test);
            td("Hello World 1");

There’s one slight simplification we can use.  Instead of having to explicitly instantiate our delegate with the new keyword we can simply point the delegate directly at the method, as shown below.  This syntax does exactly the same thing as the syntax above, only (maybe) it’s slightly clearer.

            TestDel td2 = Test;
            td2("Hello World 2");

There is an MSDN page on named methods.

Anonymous Methods

The anonymous method syntax was introduced to avoid the need to create a separate method.  We just create the method in the same place we create the delegate.  We use the ‘delegate’ keyword as below.

            TestDel td3 = 
                delegate(string s)
                {
                    Console.WriteLine(s);
                };
            td3("Hello World 3");

Now when we invoke td3 (in the last line) the code between the curly braces executes.

One advantage of this syntax is that we can capture a local variable in the calling method without explicitly passing it into our new method.  We can form a closure.  Since in this example we don’t need to pass our string in as a parameter we use a different delegate:

        private delegate void TestDelNoParams();

We can use this as below.  Note that the message variable is not explicitly passed into our new method, but can nevertheless be used.

            string message = "Hello World 4";
            TestDelNoParams td4 = 
                delegate()
                {
                    Console.WriteLine(message);
                };
            td4();

There is an MSDN page on anonymous methods.

Lambda Expressions

Lambda expressions were primarily introduced to support Linq, but they can be used with delegates in a very similar way to anonymous methods.

There are two basic sorts of lambda expressions.  The first type is an expression lambda.  This can only have one statement (an expression) in its method.  The syntax is below.

            TestDel td5 =  s => Console.WriteLine(s);
            td5("Hello World 5");

The second type is a statement lambda: this can have multiple statements in its method as below.

            string message2 = "Hello World 8";
            TestDel td6 =
                s => 
                { 
                    Console.WriteLine(s); 
                    Console.WriteLine("Hello World 7");
                    Console.WriteLine(message2);
                };
            td6("Hello World 6");

Note that this example also shows a local variable being captured (a closure being created).  We can also capture variables with expression lambdas.

There is an MSDN page on lambda expressions.

Return Values

Nearly all of the examples above can be extended in a simple way to return a value.  The exception is expression lambda which cannot return a value. Doing this is usually an obvious change: we change our delegate signature so that the method it points to returns a value, and then we simply change the method definition to return a value as usual.  For example the statement lambda example above becomes as below.  The invocation of tdr6 now returns “Hello ” + message2, which we write to the console after the invocation returns:

            string message2 = "World 8";
            TestDelReturn tdr6 =
                s =>
                {
                    Console.WriteLine(s);
                    Console.WriteLine("Hello World 7");
                    return "Hello " + message2;
                };
            Console.WriteLine(tdr6("Hello World 6"));

The full list of all the examples above modified to return a value can be seen in the code listing in the method ExamplesWithReturnValues.

Events

All of these syntaxes can be used to set up a method to be called when an event fires.  To add a delegate instance to an event we used the ‘+=’ syntax of course.  Suppose we define an event of type TestDel:

        private event TestDel TestDelEventHandler;

We can add a delegate instance to this event using any of the syntaxes in an obvious way.  For example, to use a statement lambda the syntax is below.  This looks a little odd, but certainly makes it easier to set up and understand event handling code.

            TestDelEventHandler += s => { Console.WriteLine(s); };
            TestDelEventHandler("Hello World 24");

Examples of setting up events using any of the syntaxes above can be found in the code listing.

Passing Delegates into Methods as Parameters: Basic Case

Similarly all of the syntaxes can be used to pass a delegate into a method, which again gives some odd-looking syntax.  Suppose we have a method as below that takes a delegate as a parameter.

        private void CallTestDel(TestDel testDel)
        {
            testDel("Hello World 30");
        }

Then all of the syntaxes below are valid:

            CallTestDel(new TestDel(Test));  // Named method
            CallTestDel(Test);               // Simplified named method
            CallTestDel(delegate(string s) { Console.WriteLine(s); });  // Anonymous method
            CallTestDel(s => Console.WriteLine(s));  // Expression lambda
            CallTestDel(s => { Console.WriteLine(s); Console.WriteLine("Hello World 32"); });  // Statement lambda

Passing Delegates into Methods as Parameters: When You Actually Need a Type of ‘Delegate’

Now suppose we have a method as below that expects a parameter of type Delegate.

        private void CallDelegate(Delegate del)
        {
            del.DynamicInvoke(new object[] { "Hello World 31" });
        }

The Delegate class is the base class for all delegates, so we can pass any delegate into CallDelegate.  However, because the base Delegate class doesn’t know the method signature of the delegate we can’t call Invoke with the correct parameters on the Delegate instance.  Instead we call DynamicInvoke with an object[] array of parameters as shown.

Note that there are some methods that take Delegate as a parameter in the framework (e.g. BeginInvoke on a WPF Dispatcher object).

There’s a slightly unobvious change to the ‘Basic Case’ syntax above if we want to call this method using the anonymous method or lambda expression syntax.  The code below for calling CallDelegate with an expression lambda does NOT work.

            CallDelegate(s => Console.WriteLine(s));  // Expression lambda

The reason is that the compiler needs to create a delegate of an appropriate type, cast it to the base Delegate type, and pass it into the method.  However, it has no idea what type of delegate to create.

To fix this we need to tell the compiler what type of delegate to create (TestDel in this example).  We can do this with the usual casting syntax (and a few more parentheses) as shown below.

            CallDelegate((TestDel)(s => Console.WriteLine(s)));  // Expression lambda

This looks a little strange as we don’t normally need a cast when assigning a derived type to a base type, and in any case we’re apparently casting to a different type to the type the method call needs.  However, this syntax is simply to tell the compiler what type of delegate to create in the first place: the cast to the base type is still implicit.

We need to do this for any of the syntaxes apart from the very basic named method syntax (where we’re explicitly creating the correct delegate):

            CallDelegate(new TestDel(Test));  // Named method
            CallDelegate((TestDel)Test);      // Simplified named method
            CallDelegate((TestDel)delegate(string s) { Console.WriteLine(s); });  // Anonymous method
            CallDelegate((TestDel)(s => Console.WriteLine(s)));  // Expression lambda
            CallDelegate((TestDel)(s => { Console.WriteLine(s); Console.WriteLine("Hello World 32"); }));  // Statement lambda

Actions/Funcs

There is one further simplification that we can use in the examples in this article.  Instead of defining our own delegates (TestDel etc.) we can use the more generic Action and Func delegates provided in the framework.  So, for example, everywhere we use TestDel, which takes a string and returns void, we could use Action<string> instead, since it has the same signature.

February 5, 2012

Why Some Password Security is a Waste of Time

Filed under: password, security — Tags: , — richnewman @ 11:53 pm

Introduction

This is very off-topic, but a recent MSDN article and a paper it referenced got me thinking about password security in our organization.  If my maths is right, the costs of the way we do this are huge.

Changing Passwords Monthly

I work for a very large bank (it has about 300,000 employees, or did have before the banking crisis).  Until recently this bank forced us to change our passwords monthly.  We have two passwords: Windows and ‘single sign on’.  These are the internal passwords we use to do our jobs.  The Windows one is used to log on to Windows obviously.  The single sign on password is to access almost any other internal resource: the timesheet system, the project management system, the issue tracking system, the performance management system etc. etc.

So I had to change both these passwords every month.  Let’s say that on average I can invent a new password, commit it to memory, and enter the old one and the new one twice in 30 seconds, allowing for getting it wrong occasionally.  If all 300,000 employees spend that long changing their two passwords monthly I reckon we spent roughly 35 working years per annum on this (2 x 0.5 x 12 x 300000 / (60 x 7 x 240)).

Internet Companies DONT Make You Change Your Password

Now, I have a number of online bank accounts and none of them expect me to change my password regularly.  Nor do any of the shopping sites that have my credit card details.  The reason for this is that if someone gets hold of my password it really doesn’t matter if I’m forced to change it a week later.  The thief is going to use it straightaway if they are going to use it at all.  The security controls need to prevent them getting hold of the password in the first place.

So why do it for passwords in a big organization?  There are some reasons I can think of, but are they worth the cost?

To be fair, the bank has realized this and reduced the frequency with which passwords have to be changed to 90 days.  This obviously cuts the cost by a factor of three so we now only spend about 12 working years per annum on this.  However, my personal opinion is that this is a control that could be removed completely.

Passwords for Every Application with Timeouts

Another bugbear is that our ‘single sign on’is far from ‘single’.  Every application we use forces us to enter it separately, and they are all set to time out after a short period of inactivity, not exceeding 30 minutes.  This is mandatory as part of our security policy.  Because this password is used for all our internal systems we all log into them frequently.  I estimate I enter this password about 10 times a day, and I expect that isn’t far from the average for the organization as a whole.

The estimated cost if everyone is doing this, assuming it takes me 15 seconds to enter my password (including periodically mistyping the mandatory capital letter) is about 1800 working years per annum (10 x 15 x 240 x 300000 / (60 x 60 x 7 x 240)).  Ouch.

So our organization spends 1800 working years per annum just logging in to systems.  This is a global organization, so it’s hard to know what rate to use to work out the cost of that.  However, even at the federal minimum wage of $7.25 per hour that’s $22 million.  I suspect an accurate fully-loaded cost would be several times that.

There is some momentum for changing this, at least in our group, since the benefits of kicking everyone out of an internal system after a few minutes of inactivity are even less clear than for password changing.

Conclusion

An organization with 300,000 employees changing two passwords monthly spends about 35 working years per annum on this activity.

The same organization with a security policy that compels every internal application to use a password-based login, and then logging everyone out after a short period of inactivity, spends about 1800 working years per annum on this activity.

These are large numbers and it’s not entirely clear that the cost justifies the saving in terms of more secure systems.

I’ll write about C# and derivatives again soon.

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 80 other followers