ToDotNet

Convert.ToDotNet(InstanceOfWorld)

  Home :: Contact :: Syndication  :: Login
  172 Posts :: 0 Stories :: 172 Comments :: 22 Trackbacks

News





My Vista Score...
3.4




Archives

Post Categories

Image Galleries

Affiliations

Blogs I Read

Interesting Links

My Links

Thursday, May 15, 2008 #

The debate whether to use C# or Visual Basic .NET is not uncommon for most .NET developers. Certainly, one has a distinct preference, but the general idea is that you can do in C# what you can do in VB and vice versa, because the .NET Framework is our common denominator. No, I don't mean XML literals versus automatic properties. It's the end result that counts.

So I'm currently involved in some VB programming when we stumbled upon something peculiar. Here's a simplified form of what my predecessor, also preferring C#, tried to do:

Public Class PropertyClass

 

    Private m_name As String = String.Empty

 

    Public Property Name() As String

        Get

            If m_name = String.Empty Then

                Name = "Unknown"

            End If

            Return m_name

        End Get

        Set(ByVal value As String)

            m_name = value

        End Set

    End Property

End Class

Simple enough, and here's the C# version:

    class PropertyClass

    {

        private string m_name = string.Empty;

 

        public string Name

        {

            get

            {

                if (m_name == string.Empty) Name = "Unknown";

                return m_name;

            }

            set { m_name = value; }

        }

    }

What do you expect to happen here, using the C# version?

            PropertyClass pc = new PropertyClass();

            Console.WriteLine(pc.Name);

The output would show Unknown and that's expected, right?

And what would it be using the VB version?

        Dim pc As New PropertyClass

        Console.Write(pc.Name)

Well, surpsingly, at least to me, the output is... nothing! Yes, you try it. If we look at the compiler output. Here's what the C# compiler made of it:

    ...
   
L_0016: brtrue.s L_0024
    L_0018: ldarg.0
    L_0019: ldstr "Unknown"
    L_001e: call instance void CSharpProperty.PropertyClass::set_Name(string)
    L_0023: nop
    L_0024: ldarg.0
    ...
 

I'm no expert in reading IL, but clearly you see a call to the set_Name method. For VB, the compiler turns it into:

    L_0015: stloc.1
    L_0016: ldloc.1
    L_0017: brfalse.s L_001f
    L_0019: ldstr "Unknown"
    L_001e: stloc.0
    L_001f: nop
    L_0020: ldarg.0

It's completely gone. The compiler simply removed the

                Name = "Unknown"

It appears there's more difference between VB.NET and C# than I thought. I certainly hope to return to some C# code soon.

posted @ 11:59 AM | Feedback (2)

Wednesday, April 30, 2008 #

“Congratulations! On behalf of Microsoft, we are happy to welcome you to the Microsoft Certified Trainer (MCT) Program. You will be sent a Microsoft Certified Trainer Welcome Kit within four to six weeks.”

Yes, that's the e-mail I received this morning.

As part of my personal improvement plan, I decided to go for the MCT certification. There are several ways to achieve this, but basically you need to have a major Microsoft certification, such as one or more of these. Step two is to demonstrate instructional skills, like this. In my case, I chose option 2: Attend and pass a presentation skills course. The course I took was this one, by Monique Kerssens (in Dutch). Monique is a very experienced trainer herself, provides good feedback on your strengths and weaknesses. I really learned a lot from her.

I was a guest lecturer for strategic analysis (basically just statistical analysis) for about 4 years, but I'm not doing that anymore. But there the urge to teach was still present. Perhaps it's family related, as my mother was a teacher for 13 years. Anyway, according to my transcript, I'm allowed to teach over 80 different courses. I'm looking forward to teaching any of these.

 

posted @ 8:10 AM | Feedback (0)

Wednesday, April 23, 2008 #

It's something very trivial, but earlier today, I accidentilly closed the folders view in my source control explorer.

How to get them back? Would you consider this?

I didn't at first. But then again, it may be just me.

posted @ 12:44 PM | Feedback (0)

Monday, February 04, 2008 #

Upon checking rumors that SP1 for Vista was released today, I stumbled upon something else.

Windows Server 2008 on MSDN

That's right. Windows Server 2008 is available for download from the MSDN website! Check the date.

 

posted @ 4:00 PM | Feedback (0)

Saturday, November 17, 2007 #

According to the MSDN Subscriptions WebLog we can expect to see Visual Studio 2008 to be downloadable early next week.

“Visual Studio 2008 is anticipated out early next week, with availability for Subscribers. Check out the "Top Subscriber Downloads" area on http://msdn2.microsoft.com/subscriptions for VS 2008 downloads.

You will also be able to access these downloads by clicking on the Subscriber Downloads and Product Keys links that take you to all of your downloads. ”

(source: Ken Cox)

That would be great and just in time for a session I'm doing Friday on 'what's new in Visual Studio 2008'. More details on that here: http://www.newhorizonslearning.nl/New-Horizon-s-Developers-day.554.0.html (it's Dutch).

update: RTM has been reached and VSTS 2008 can be downloaded (source).

posted @ 8:43 PM | Feedback (0)

Tuesday, November 06, 2007 #

If you're attending the TechEd Developers conference in Barcelona this year, you are like me. I arrived yesterday and missed the keynote speech. Biggest news for most, but not everyone, is that Visual Studio 2008 will be available end of this month. Now, some may wonder about the initial announcement that Microsoft made about the launch of the new version on February 27th 2008. It's simply a matter of marketing. Creating a buzz around three major products - Visual Studio 2008, SQL Server 2008 and Windows Server 2008, on a single date is more effective than releasing the bits bit by bit. Even though the other products may not even be available end of February.

At least one product will be, and from a developer's perspective, it's the most important product :-)

An overview of the new features can be found here.

Anyway, if you're at TechEd, stop by in the ask-the-experts area at the Windows Vista booth for a chat.

posted @ 9:51 AM | Feedback (0)

Monday, October 01, 2007 #

Omar AL Zabir writes about how to use a Content Delivery Network (CDN). This is one of the 13 rules Yahoo suggests for making your web pages faster (2 - Use a Content Delivery Network).

It's been a while since I've made a CDN, but lack of time prevented me to do much work on it. It's working fine though, check http://channel9.www1.uricache.com/.

If you want to try it out  contact me through my weblog.

posted @ 8:42 PM | Feedback (0)

Sunday, September 16, 2007 #

Recently, I started a on a new project as a development coordinator. One of the tasks we face is a migration from Rational ClearCase to Team Foundation Server. A tool that should help in doing this has just been released. What a coincidence!

The Team Foundation Server Migration Tool for Rational® ClearCase® is a tool to help automate the migration process from Rational® ClearCase® to Team Foundation Server. This tool is available as a free download for Team Foundation Server users.
 
Brian Keller also points to other useful resources as well as a blog post on migrating from ClearCase to TFS. Just what we need.
 
update:
Actually, we cannot use the tool. It appears it only works with ClearCase, and we're using ClearCase LT. The differences can be found here. Bummer.
posted @ 5:49 PM | Feedback (0)

Monday, June 25, 2007 #

Microsoft has officially announced the logo for Information Card. The reason for having a logo is that it creates recognition. People will immediately see that a website support logon with an Information Card. This is what it looks like:

You can download the logo package here. Obviously, the logo comes in different sizes. I've already updated the login for my website, but I hope the little twist is ok with the guidelines. If you want to watch a webcast on Windows Cardspace, there's one on June 29th.

 

posted @ 9:02 PM | Feedback (0)

Friday, June 08, 2007 #

The new DevTips.NET website allows for people to comment on most content, unlike the old site. Obviously this opened up possibilities to add comment spam on all the places. There is a common technique to counter this, called CAPTCHA or “Completely Automated Public Turing test to tell Computers and Humans Apart”. There is also an easy ASP.NET control that you can implement on a website to implement this captcha from Miguel Jimenez. I use it on this blog. For some reason though, the captcha-image didn't display on the new site. Several options are available: figure out what's wrong, look for another control or... build one myself. Thinking that it shouldn't be too hard, and being a developer, I obviously chose the last option. So here goes:

First, we need an image to display. I chose to use an HttpHandler for this. Seemed like a good choice, since we only need to Response.Write an image, and store the generated code somewhere.

<%@ WebHandler Language="C#" Class="HipHandler" %>

 

using System;

using System.Web;

using System.Drawing;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;

using System.Drawing.Text;

 

public class HipHandler : IHttpHandler {

 

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "image/jpeg";

        SendImage(context);

    }

 

    public void SendImage(HttpContext context)

    {

        int fontSize = 24;               

        int width = 100;

        int height = 30;

 

        // Setup the rectangle to draw the text on

        RectangleF rectF = new RectangleF(0, 0, width, height);

        Bitmap pic = new Bitmap(width, height);

        Graphics g = Graphics.FromImage(pic);

        g.SmoothingMode = SmoothingMode.AntiAlias;               

        SolidBrush fgBrush = new SolidBrush(Color.RoyalBlue);

        SolidBrush bgBrush = new SolidBrush(Color.SkyBlue);

        g.FillRectangle(bgBrush, rectF);

 

        // Choose the font and style

        FontStyle style = FontStyle.Regular;       

        Font font = new Font("Arial", fontSize, style, GraphicsUnit.Pixel);

 

        // Make sure the text is centered

        StringFormat format = new StringFormat();

        format.Alignment = StringAlignment.Center;

 

        // Draw horizontal and vertical lines to make is less computer-readable

        Pen p = new Pen(new SolidBrush(Color.SteelBlue), 1);

        for (int i = 0; i < height; i=i+7)

        {

            g.DrawLine(p, 0, i, width, i);   

        }

 

        for (int i = 0; i < width; i=i+10)

        {

            g.DrawLine(p, i, 0, i, height);   

        }

 

        // Get 4 random characters, no weird ones

        string randomText = GenerateRandomText(4, false);

        System.Security.Cryptography.SHA256Managed hashAlg = new System.Security.Cryptography.SHA256Managed();

 

        // Hash the text so it can be verified after postback

        string hashText = HttpUtility.UrlEncode(hashAlg.ComputeHash(System.Text.Encoding.Default.GetBytes(randomText)));

        context.Response.AppendCookie(new HttpCookie("HipHash", hashText));

 

        // Write the text and send it to the browser

        g.DrawString(randomText, font, fgBrush, rectF, format);       

        pic.Save(context.Response.OutputStream, ImageFormat.Jpeg);       

    }

 

    public static string GenerateRandomText(int maxlength, bool ultraStrong)

    {

        char[] ultraChars = "!@#$%^&*~|=?{}[]qwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*~|=?{}[]".ToCharArray();

        char[] normalChars = "qwertyuiopasdfghjklzxcvbnm1234567890".ToCharArray();

 

        string password = string.Empty;

        for (int i = 0; i < maxlength; i++)

        {

            char n = ' ';

            if (ultraStrong) n = ultraChars[GetRandomNumber(ultraChars.Length - 1)];

            if (!ultraStrong) n = normalChars[GetRandomNumber(normalChars.Length - 1)];

            if (i % 2 == 0)

                password += n.ToString().ToUpper();

            else

                password += n;

        }

        return password;

    }

 

    public static int GetRandomNumber(int maxvalue)

    {

        System.Security.Cryptography.RandomNumberGenerator random =

            System.Security.Cryptography.RandomNumberGenerator.Create();

 

        byte[] r = new byte[1];

        random.GetBytes(r);

        double val = (double)r[0] / byte.MaxValue;

        int i = (int)Math.Round(val * maxvalue, 0);

        return i;

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

}

I'm reusing a method to generate random texts. It was originally intended to create random passwords, hence the variable names in the implementation of the method GenerateRandomText(). The randomly chosen four characters are displayed in the image and also stored in a cookie. No, not directly of course. The text is hashed making it impossible to read before it's stored in the cookie. Other storages, like session or response headers are unavailable or unusable in an HttpHandler. Using a session to store a code is bad practice anyway.

The second part is a Web User Control that displays the image and asks the user to enter the displayed code.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControlHip.ascx.cs"

 Inherits="UserControlHip" %>

<img src="HipHandler.ashx" alt="HIP" />

Enter the code:

<asp:TextBox ID="TextBoxHip" Width="100" runat="server"></asp:TextBox>

<asp:Label ID="LabelCodeStatus" runat="server" Text=""></asp:Label>

Obviously you can modify the html of this user control to fit your needs and style. The code-behind is a bit more elaborate.

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class UserControlHip : System.Web.UI.UserControl

{

    private string m_controlToVerify;

 

    public string ControlToVerify

    {

        get { return m_controlToVerify; }

        set { m_controlToVerify = value; }

    }

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (IsPostBack)

        {

            // Verify the submitted code to the generated code

            System.Security.Cryptography.SHA256Managed hashAlg = new System.Security.Cryptography.SHA256Managed();           

            string hashText = HttpUtility.UrlEncode(hashAlg.ComputeHash(System.Text.Encoding.Default.GetBytes(TextBoxHip.Text)));

            string hashTextFromHeader =  Request.Cookies["HipHash"].Value;

            LabelCodeStatus.Text = "";

            if (hashTextFromHeader != hashText)

            {               

                // If the code is not correct, save the contents of the control to verify (usually

                // a comments-textbox) in a session so visitors don't loose their elaborate entry

                // After that, redirect to the same page

                TextBox textBoxControl = (TextBox)this.Parent.FindControl(m_controlToVerify);

                Session["HipControlToVerifyValue"] = textBoxControl != null ? textBoxControl.Text : "";               

                Response.Redirect(Request.Url.PathAndQuery);

            }

        }

        if (!IsPostBack)

        {

            TextBox textBoxControl = (TextBox)this.Parent.FindControl(m_controlToVerify);

            // If return from a redirect, meaning the code entered was incorrect,

            // fill the textbox with the session-stored entry.

            if (Session["HipControlToVerifyValue"] != null)

            {

                textBoxControl.Text = HttpUtility.HtmlEncode((string)Session["HipControlToVerifyValue"]);

                LabelCodeStatus.Text = "Wrong code";

            }

            Session["HipControlToVerifyValue"] = null;

        }

    }

}

The most important part of the control is to verify the code entered. Since this is stored in a cookie, we retrieve it first and then compare the hashed value of the code with the hashed value stored in the cookie. If the values match we do... nothing. Just let the rest of the page render and do any processing it may need to. However, if values do not match, there's a Response.Redirect to the same page, so rendering and processing of the page stops.

It's certainly a pain if you've just entered an elaborate comment somewhere only to make a typo when you enter the captcha-code, thereby redirecting and losing everything you wrote. So, to make it more friendly, the control has a property “ControlToVerify”. Perhaps the naming is incorrect, but this allows you to store the value of a control, before redirecting and setting the value of the control after the redirect. In this code, it has to be a textbox, but you can change it to anything you like of course.

After all this, you can put the control on any ASP.NET web page, like this:

<%@ Register Src="UserControlHip.ascx" TagName="UserControlHip" TagPrefix="uc1" %>

This Register directive is to be set at the top of the page. The following code is placed at the position you want people to enter the verification code.

<uc1:UserControlHip id="UserControlHip1" runat="server" ControlToVerify="TextBox1"></uc1:UserControlHip> 

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 

<asp:Button ID="Button1" runat="server" Text="Button" />

That's it. Please add error handling code as you see fit. The rendered image is pretty simple, and you've probably seen more elaborate ones. But I think it'll do the job. If you want to see what it looks like, check out an article, code snippet or news item on DevTips.NET.

You can download a sample project that implements all this here.

posted @ 9:01 AM | Feedback (0)

Thursday, April 26, 2007 #

Hoster Poster made me aware of an interesting KB article that describes the issue of failures when hosting ASP.NET on Windows 2003. Simple reading the title really makes you wonder:

“You may receive an error message, or the computer may stop responding, when you host Web applications that use ASP.NET on a computer that is running Windows Server 2003“

Say what? If I host ASP.NET on Windows Server 2003 I may receive an error or the machine may stop responding altogether? Okay, the article itself explains the conditions under which this may occur. But it doesn't make me happy (as we're doing ASP.NET hosting too).

posted @ 7:43 AM | Feedback (0)

Wednesday, April 11, 2007 #

Here's something that bit me today. A few days ago, a Windows Service I built was redeployed to another machine. Most operations went on just fine, but some didn't. And as always: 'it worked on my machine'. As it had also worked in testing and on the previous production server. After some digging, we found that the regional settings for the service account on this machine were not what they were on the other servers. Yes, I know, don't depend on regional settings, but there was some legacy code (hah..it's not my fault) and it had never created issues before.

So, easy enough, we set the thread for the service to the required culture, like so:

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("nl-NL");

Unfortunately, it didn't have the desired effect. Nothing changed. As it turns out, you have to set the culture on every thread running. See the sample below:

using System;

using System.Globalization;

using System.Threading;

 

namespace RegionalTime

{

    class ClassDemo

    {

        public static void TimeNow()

        {

            Console.WriteLine("Date setting: {0} ({1})",

                DateTime.Now.ToLongDateString(),

                Thread.CurrentThread.CurrentCulture.DisplayName);

        }

 

        public delegate void TimeNowDelegate();

 

        [STAThread]

        static void Main(string[] args)

        {

            // Look at current regional settings

            TimeNow();

 

            // Switch to French

            Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

            TimeNow();

 

            // Switch to US

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            TimeNow();

 

            // Now through a delegate on a different thread.

            TimeNowDelegate methodDelegate = new TimeNowDelegate(TimeNow);

 

            IAsyncResult result = methodDelegate.BeginInvoke(null, null);

 

            while (!result.IsCompleted)

            {

                Thread.Sleep(500);

            }

 

        }

    }

}

As you will see, from running this code, the call through the delegate uses the regional settings from the active user.

Date setting: woensdag 11 april 2007 (Dutch (Netherlands))
Date setting: mercredi 11 avril 2007 (French (France))
Date setting: Wednesday, April 11, 2007 (English (United States))
Date setting: woensdag 11 april 2007 (Dutch (Netherlands))
Press any key to continue . . .

There seems to be no way to specify one culture for the entire AppDomain (note: I'm not talking about ASP.NET here, this was a multithreaded Windows Service). If any thinks or better yet, knows, that this is possible, let me know. I am always eager to learn.

 

posted @ 2:19 PM | Feedback (0)

Tuesday, April 10, 2007 #

It's taken quite some time, but I've finally put the new DevTips.NET website online. The old site was really... old. The codebase was from 2001 when I learned to code in C# myself. You can imagine it didn't incorporate best practices, since there were few practices to begin with.

So a rewrite was quite necessary. Now, I could have used DotNetNuke, or CommunityServer or any other project to base the new site on but where the fun in that ;-)

The entire code was written by me, but I did use TechTalk's Genome (sorry, Frans) as the O/R mapper which saved me a lot of time.

One of the decisions I made was to remove the forum. For one, the forum was not very active and this would prove dissappointing for people asking questions. Secondly, there are a number of Dutch forums already available (like the ones on www.dotned.nl, www.sdn.nl, and www.vbcentral.nl). Improvements have been made to the layout (most obvious), the commenting and rating system. Also, it's easier to edit content and publish news stories with more body than previously.

If you would like to add content to the site, e.g. news, codesnippets, articles or otherwise, please register an account. You can add and manage codesnippets immediately. If you want to publish news or articles, drop me a line.

If you spot any errors, please let me know.

posted @ 9:23 AM | Feedback (1)

Sunday, April 01, 2007 #

This just in: “The Microsoft MVP Award is our way of saying thank you and to honor and support the significant contributions you make to communities worldwide. As a recipient of Microsoft’s Most Valuable Professional award, you join an elite group of technical community leaders from around the world who foster the free and objective exchange of knowledge by actively sharing your real world expertise with users and Microsoft.  Microsoft salutes all MVPs for promoting the spirit of community and enhancing people’s lives and the industry’s success everyday.  To learn more about the MVP Program, visit: www.microsoft.com/mvp.”

What can I say? I've been active in the community this past year (mmm... not so much on this blog, I have to work on that), so I was hoping to get my MVP status renewed, but you never know for sure until you get this e-mail. I think it's also an encouragement to continue my efforts.

In fact, at this very moment I'm planning the sessions for our first Dutch .NET CodeCamp: http://www.code-camp.nl/. A joint effort of SDN, VBCentral and DotNed. It looks like we've got more session proposals (25) than we can accomodate (+/- 20), so it's going to be a packed day. If you haven't signed up, please hurry, because there's a limit of 120 attendees. Given that the event won't draw hundreds of people means you can more easily interact with your peers, and with the speakers. Subjects will range from: WPF, LINQ, XNA, WF, and many other MLA's (multi-letter-acronyms). However, it will not all be about great “new stuff”. We'll also cover topics that address issues we're having today. How about: COM Interop, ASP.NET Ajax, Designing Windows Controls. I'll do a session (if I can fit it in) on Visual C# 2005 tips and tricks. Although upon request, we dive into the new 'Orcas' release as well.

Anyway, I'm grateful to be nominated MVP again and hope to see you on May 12th.

posted @ 10:46 AM | Feedback (4)

Friday, January 05, 2007 #

So yes, I tried to escape but resistance is futile. André Obelink was kind enough to tag me, and therefore, it seems I need to divulge some trivia you may not know from me.

1. I learned computing around the age of 13 or 14. It was an Easter holiday and my parents decided I should go to 'computer camp'. Here I learned basic on a true and original Philips P2000. You can imagine my discomfort when my parents subsequently decided to buy a Commodore 64. A device I knew nothing about. Well, that didn't take long. With Latin classes at school, I was kinda showing off my skills by programming Dutch-Latin translation on the C64's that were on display at the nearby V&D. Well, local. Breda that is, since I grew up in Rijen.

2. My ambition was to be an astrophysicist. But then I discovered I sucked at chemistry and physics, so that was a nogo.

3. To finish my studies in public administration (and now for something completely different) I wrote my thesis on a comparative study between drugs policy in Rotterdam and Northern France. Mid nineties there was quite some publicity around the obvious differences, with France being more repressive and the Netherlands being ehmm 'pragmatic'. My findings can be found in this book.

4. In 1996 I went to Star Trek convention in... Italy. Well, just thought it would be fun even though I didn't speak much Italian. Obviously I knew at least one person to get me invited. Had a great time. I've been a Star Trek fan ever since the original series. You won't see me in a costume though, I like the series and science fiction in general, but I'm not crazy ;-) 

5. I met my wife Anja through my sister after visiting her, my sister that is, in India. Anja also went for a visit and brought back the sneakers I forgot. We got married in 2000 and have two kids now: Steven (5) and Michelle (3). You can check their stories at www.sanderenanja.com.

And now it's my turn to tag these: Peter van Ooijen, Emad Ibrahim , Egbert Nierop, Stefan Stranger, Nix


 Blog-Tag: A game for Virtual Party

posted @ 3:37 PM | Feedback (1)