I8 converter – Download (sourcecode available)

One of my colleagues pointed out the new Fine-grained password policy feature in Windows Server 2008. As you can see in this post at The Sean Blog, some values have to be entered in the I8 format, which isn’t very user friendly. Because of that, he asked me if I could whip up a tool that converts days, hours, minutes and seconds to the I8 format. I quickly put together this small tool for him. It hasn’t been tested extensively, but I think it might be of some use to some of you.
For example, I used longs to store the info. When wanting to calculate huge values, this won’t work of course. This could be improved by using the multipliers divided by for instance 10,000,000 and add the appropriate amount of zeros (7) to the string after calculation, so the numerical value stays a lot smaller. Still, I think it does what it should do at this point. You can find the sourcecode over here, or if you would like te change anything: be my guest. Let me know if you find bugs or add cool features: I would like to know.

Info taken from Technet:

When you use the ldifde command to create PSOs, you must enter the values of these attributes in I8 format, which stores time in the intervals of -100 nanoseconds. (Schema: attributeSyntax = 2.5.5.16 (I8).) Windows Server 2003 Default Domain Policy employs this exact time unit for its corresponding time-related attributes. To set these attributes to appropriate values, convert time values in minutes, hours, or days to time values in the intervals of 100 nanoseconds, and then precede the resultant values with a negative sign.

Links
Tool: http://www.rickvandenbosch.net/downloads/I8Converter.zip
Source: http://www.rickvandenbosch.net/downloads/I8Converter Sourcecode.zip

Update
Because of a hosting shift, the tool is no longer available from the above locations. When interested: drop me a line. I’ll see if I still have the app/sourcecode floating around somewhere.

PageRequestManagerServerErrorException (status code 500)

In a quick AJAX demo I had to create today, I ran into a (somewhat cryptic) PageRequestManagerServerErrorException. I needed a simple form of the Cascading Dropdown, one that doesn’t use a (web)service for its data, but gets it from a simple method. Here’s the setup, and the cause…

Lets start with the exact error message:
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500

I needed 2 DropDownLists working together to enable users to first select a month, and then select a day. Of course, you want the second DropDownList to only display days available for the chosen month. Because of that I had two dropdownlists in an updatepanel, and set the first one to AutoPostback so it would trigger the updatepanel. The first one had items set to something like this: <select item>, January, February, March, and so on. The second one got its items from a method, based on the selected value in the first. This worked like a charm, and all was well. When I wanted to check every scenario, I found that selecting <select item> didn’t clear DropDownList2 like I coded it to, but it threw the Exception. What caused this?

When setting items throught the IDE, this HTML is generated:

<asp:ListItem>&lt;select item&gt;</asp:ListItem>
<asp:ListItem>First item</asp:ListItem>
<asp:ListItem>Second one</asp:ListItem>

Because the value property for the items wasn’t set explicitly, it is generated (or should we say substracted?) from the information that was entered. Therefore, the Value property of the first item was ‘<select item>’. I can imagine how something like that can mess up a JavaScript environment. ;) I opened up the items for the first DropDownList, and set the value properties for each item explicitly (although setting it to a decent value for the first item did the trick). That resulted in this HTML:

<asp:ListItem Value=”0″>&lt;select item&gt;</asp:ListItem>
<asp:ListItem Value=”1″>First item</asp:ListItem>
<asp:ListItem Value=”2″>Second one</asp:ListItem>

Notice the Value attribute in the ListItem tag? That’s the one that will keep your project from throwing a PageRequestManagerServerErrorException.

By |February 20th, 2008|.Net, Error, HowTo|1 Comment

Hooray (x 2) for MSDN library Community content

There are several steps to creating a custom web service to be hosted in SharePoint. The MSDN library has a walkthrough on creating a custom web service. After having followed this walkthrough thoroughly, I though my web service was good to go. Unfortunately all I saw was an error: “Could not load type ‘ThisAndThat’ from assembly ‘SoAndSo'”. Just as I was about to search for an answer somewhere online, I remembered that the MSDN library features the Community content for little over a year now (hooray!).

At the bottom of the walkthrough were some community additions to this specific walkthrough. Some have been incorporated in the main article, others are there to be found for guys (and girls!) like you and I. One of them exactly described my problem. In that same community content item another user had added this comment:
HI – I resolved this issue with a VB.net service by prefixing the class name in the .asmx file with the assembly namespace
And that was it! The WebService works like a charm, hosted in SharePoint. (hooray!)

So there you have it: that’s the power of [wikipedia:web 2.0] for you. Users benefit from the fact that they are now able to add to the otherwise pretty static information in something like the MSDN library. ;)

By |February 1st, 2008|.Net, HowTo, Link|0 Comments

HowTo: Set the Theme for a MasterPage (from code)

The MasterPage doesn’t have a property for setting the Theme at design time. Despite this, I wanted to set the Theme for a MasterPage, so I decided to set it from code. I was aware of the possibility to set the Theme through the web.config, but that wasn’t the way I wanted to set it. One of the reasons being it would result in the theme being applied to the entire website.

I tried to use the Page_Load, but that resulted in the error “The ‘Theme’ property can only be set in or before the ‘Page_PreInit’ event.”. That sounds logical, because the Theme makes the Page render in a specific way. So I added a Page_PreInit method with the right parameters, but that didn’t do anything. As it turns out, the Master Page doesn’t have a Page_PreInit…

To be able to set the Theme for a MasterPage from code, follow these steps:

  1. Add a class with the name ThemeModule (or any other name)
  2. Let the class inherit from IHttpModule
  3. Implement the init method as follows:

    public void Init(HttpApplication context)
    {
        context.PreRequestHandlerExecute += HandlePreRequest;
    } 

  4. void HandlePreRequest (object sender, EventArgs e)
    {
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null)
        {
            page.PreInit += delegate
                                {
                                    page.Theme = DetermineTheme();
                                };
        }
    }

  5. Add the HttpModule to your web application through the web.config:

     
    <
    httpModules>
        <add name=ThemeModule type=Howtos.ThemeModule/>
      </httpModules>

That’s it! Hope this helps.

A week ago I came up with this solution together with a good friend of mine. The code was on his machine, so he said I had to add a ‘thanks to’ in this post. Well, here it is: thanks 2 Sander van Kemenade! ;)

By |October 20th, 2007|.Net, HowTo|1 Comment

HowTo: Disable specific Code Analysis rules for a Team Build

Thanks to the MSDN forums (and specifically one Hua Chen), I found a way to disable specific code analysis rules for a team build. In this post I’ll combine the steps I followed earlier with the description given at the MSDN forum. I’ll start out with some steps earlier on in the process: how to quickly get a list of all the code analysis rules you want to disable (without having to type it all yourself ;) ).




  1. Start Visual Studio and create a new project


  2. Open the properties for the project and navigate to the ‘Code Analysis’ tab


  3. Set the code analysis rules the way you want them, and save the project (you don’t have to enable code analysis: the settings are saved anyway)


  4. Close the project/solution


  5. Open the .csproj file in a text editor like Notepad or UltraEdit


  6. Find the tag named CodeAnalysisRules and copy the value of that tag, which looks something like this:
    <CodeAnalysisRules>-Microsoft.Globalization#CA1301;-Microsoft.Naming#CA1709;-Microsoft.Usage#CA2208</CodeAnalysisRules>

    You now have a list containing all the rules you do not want enforced.


Now for the real deal: how to disable specific code analysis rules for a team build.




  • Open the TFSBuild.proj file in a text editor (double clicking the file from the source control explorer will open it in Visual Studio, which works fine as an editor)


  • Find the PropertyGroup tag containing the RunCodeAnalysis tag


  • Set the RunCodeAnalysis tag to an appropriate value (I used Always to override individual project settings)


  • Add a tag named CodeAnalysisRules, and paste the rules you copied in the steps numbered 1 to 6 above


  • Find the Microsoft.TeamFoundation.Build.targets file at the Team Build Server. It is typically located in C:Program FilesMSBuildMicrosoftVisualStudiov8.0TeamBuild


  • Open the .targets file, find the CoreCompile target and copy the entire target


  • Paste the CoreCompile target in the TFSBuild.proj at the end of the project file, before the </Project> tag


  • Find the following task in the CoreCompile target, this is the second task from the end of the CoreCompile target

    <!– Build using MSBuild task –>
        <MSBuild
              Condition=” ‘@(SolutionToBuild)’!=” “
              Projects=”@(SolutionToBuild)”
              Properties=”Configuration=%(ConfigurationToBuild.FlavorToBuild);Platform=%(ConfigurationToBuild.PlatformToBuild);SkipInvalidConfigurations=true;VCBuildOverride=$(MSBuildProjectDirectory)TFSBuild.vsprops;FxCopDir=$(FxCopDir);OutDir=$(OutDir);ReferencePath=$(ReferencePath);TeamBuildConstants=$(TeamBuildConstants);$(CodeAnalysisOption)”
              Targets=”Build” />


  • Import your CodeAnalysisRules to the task in the Properties attribute (see the red part):

    <!– Build using MSBuild task –>
           <MSBuild
              Condition=” ‘@(SolutionToBuild)’!=” “
              Projects=”@(SolutionToBuild)”
              Properties=”Configuration=%(ConfigurationToBuild.FlavorToBuild);Platform=% (ConfigurationToBuild.PlatformToBuild); SkipInvalidConfigurations=true;VCBuildOverride=$(MSBuildProjectDirectory)TFSBuild.vsprops;FxCopDir=$(FxCopDir);OutDir=$(OutDir);ReferencePath=$(ReferencePath); TeamBuildConstants=$(TeamBuildConstants);$(CodeAnalysisOption);CodeAnalysisRules=$(CodeAnalysisRules)
              Targets=”Build” />

That’s all of it. The rules you selected not to run (and pasted in the CodeAnalysisRules tag) will not be executed during the next build. Hope this helps!

By |September 4th, 2007|HowTo, MS Build, TFS|1 Comment

Disable specific Code Analysis rules for a Team Build

After searching a bit, I found a way to disable specific Code Analysis rules for a team build. Or at least I thought so… The RunCodeAnalysis tag in my build.proj file is set to ‘Always’ to override the individual project settings, and I added the ‘CodeAnalysisRules’ tag to exclude some rules as a test. (See below for a part of the build.proj file.) I ran a few builds, but the tag doesn’t seem to do what is supposed to. But when you use that tag in a project file, Visual Studio does recognize it as a valid tag… 


Unfortunately the build seems to execute all the rules, including the ones I tried to exclude by putting them in the CodeAnalysisRules tag with a ‘-‘ before them. I’m trying to find out if it is possible to exclude specific rules through the build file. I know it is possible to do so by putting the stuff in the CodeAnalysisRules tag my project file, but with a solution of 98 projects, this is not realy an option. ;)
I’ll keep you posted. And, as always, if you have any idea: drop me a line.


Snippet build.proj file:


    <RunCodeAnalysis>Always</RunCodeAnalysis>
    <CodeAnalysisRules>-Microsoft.Globalization#CA1301;-Microsoft.Globalization#CA1302;</CodeAnalysisRules>


Edit 1
I tried Jan’s suggestion (see the comments) and moved the ‘-‘ sign from in front if the Microsoft name to behind the #. This did not result in any rules being ignored either. So, unfortunately, our build still checks all rules, including the ones we don’t want it to check.
By the way, I know I can set Code Analysis rules as a check-in policy, and migrate those settings to the solution, but at this point it’s not possible to check out al of the 98 projects: several colleagues have projects checked out, and we’re working towards a deadline, so …

Edit 2
I also tried the suggestion David Kean posted over here, but to no avail. This might work for a project, but does not when entered in a TFS Build project. It looks like I will have to change the code analysis for all projects separately, in stead of being able to set it once for all projects in a build/solution. :(

By |August 31st, 2007|HowTo, MS Build, TFS|1 Comment

Unit Test Adapter threw an exception

“Unit Test Adapter threw exception: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information..”

This error popped up at one of the testers of our project this morning. The unittests he selected worked fine on my machine, but all failed on his with the above message. After searching a bit we found that the only thing which was different between my testrunconfig and his was that he enabled code coverage for the assembly these unittests were pounding away at. As it turns out, this error appears when code coveraging (is that even a word?) a signed assembly without re-signing it.

To re-sing an assembly, open the testrunconfig you are using and go to the ‘code-coverage’ element in the left pane. Locate the textbox ‘re-signing key file’ and enter the path to the key file which should be used to re-sign the assembly (or browse for it, of course). Hit ‘Apply’ and then hit ‘Close’. You’re done now! Happy unittesting….

re-signing key file.jpg

Defensive programming

We all encountered them in the field somewhere along the way: pieces of code that are based on assumptions. There’s something fundamentally wrong in assuming when writing code. I can understand that, looking at the big picture, you sometimes have to make an assumption when developing software. Some things you just can’t know for sure. This might concern something simple like the resolution of the targeted audience. But most of the time these kinds of assumptions are based on experience or plain old common sense. When these assumptions fail to be true, most of the time a mitigation strategy is at hand. And the software usually keeps running.

When it comes to actually writing lines of code, I think you should always check and never assume. I tend to compare it to riding on a motorcycle. My instructor teached me to drive defensively. To ‘Expect the unexpected’. Sure, you can assume there won’t come a kid running from inbetween the two parked cars, but why take the risk? It’s better to anticipate a kid running across the street, so you can react accordingly when it does. And if it doesn’t? You at least didn’t take a chance …

Sometimes, an assumption is obvious:





1
2
3
4
public string ConvertObjectToString(object objectToConvert)
{
return objectToConvert.ToString();
}

Here, you assume the object which is passed in will always contain an actual object. But when a null reference is passed in, this method will throw an exception because objectToConvert is not set to an instance of an object and therefore you can’t invoke ToString(). When this method is written ‘defensively’, it looks something like this*:





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public string ConvertObjectToString(object objectToConvert)
{
string returnValue;










if (null == objectToConvert)
{
returnValue = string.Empty;
}
else
{
returnValue = objectToConvert.ToString();
}

return returnValue;
}

That was an easy one. Sometimes, assumptions in code aren’t very transparent. Let’s take a look at this sample:





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <summary>
/// Method that ‘does something’ to a Control.
/// </summary>
/// <param name=”controlToWorkOn”>Control on which ‘someting will be done'</param>
/// <returns>A Control on which ‘something has been done'</returns>
public Control DoSomething(Control controlToWorkOn)
{
if (null != controlToWorkOn)
{
if (controlToWorkOn is TextBox)
{
//Do something important to a TextBox
}
else if (controlToWorkOn is Button)
{
//Do something important to a Button
}
}
return controlToWorkOn;
}

We will leave the ‘do something important to…’ parts out of this. The Control is checked for being null. The Control is typechecked so no wrong casts will be made. So nothing seems wrong, right? The problem here is the fact that you know this method only does something for a TextBox or a Button. But what happens if a year from now somebody gets the assignment to change the application, and he or she doesn’t know about the method only working for TextBoxes or Buttons? The method will return the Control unchanged, but the caller might think everything is OK. Often we write methods with certain constraints about the calls made to that method in the backs of our heads. And often without realy realizing it. But there might come a time that somebody who doesn’t know the constraints has to jump in.
To be sure passing in another type of Control will not give any problems, you might consider a solution like this one:





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/// <summary>
/// Method that ‘does something’ to a Control.
/// </summary>
/// <param name=”controlToWorkOn”>Control on which ‘someting will be done'</param>
/// <returns>A Control on which ‘something has been done'</returns>
public Control DoSomething(Control controlToWorkOn)
{
if (null != controlToWorkOn)
{
if (controlToWorkOn is TextBox)
{
//Do something important to a TextBox
}
else if (controlToWorkOn is Button)
{
//Do something important to a Button
}
else
{
throw new NotSupportedException(“Control-type not supported in this method”);
}
}
return controlToWorkOn;
}

Another way to solve this problem is to make the DoSomething method private and generate two public methods. One that takes a TextBox and one that takes a Button, both eventually calling the private DoSomething method. This would actually be the solution I would choose, because then the problem pops up compile time in stead of runtime. And I think it aids future developers better.

‘Defensive programming’. Writing software anticipating as many problems as possible to ensure correct functioning of the software. Even when the software is edited later by someone who doesn’t have your mindset.

Edit: Wikipedia has an article on defensive programming.
Edit2: Thanks Geraldo Hockx for your sharp eye! I changed the code samples: I made a few typo’s.


* Yes, you could initialize the local parameter to string.Empty and only have an if-statement. And yes, you could use the conditional operator. And of course you could use two return statements. But this is my coding style (at the moment) so this is how I would do it right now ;).

By |February 8th, 2007|.Net, HowTo|0 Comments

HowTo: determine which object (and method) called another method

Sometimes when you’re inside a method you would like to know which method called it. Or even which object. For instance when you write a TraceListener, it might be pretty cool to make the TraceListener smart enough to find out what object called him and from which method. The StackTrace object in .Net makes this pretty easy. Here’s a howto…

First, we iterate through the stackframes that are available on the stack, looking for the one we need. This method returns such a StackFrame. We skip the first StackFrame by starting the variable count at 1, because this method is always called from the method GetCallingMethod() (see below).

private StackFrame GetCallingStackFrame()
{
    StackTrace stack;
    StackFrame stackFrame;

    stack = new StackTrace(true);
    // Initialize the StackFrame by creating a default one.
   
stackFrame =
new StackFrame("ErrorDeterminingStackFrame", 0, 0);
    for (int count = 1; count < stack.FrameCount; count++)
    {
        // At my current project I skipped the StackFrame if the calling method was ‘WriteLine’, because that’s the WriteLine method in the TraceListener.
        if
(!stack.GetFrame(count).GetMethod().Name.Equals("WriteLine"))
        {
            stackFrame = stack.GetFrame(count);
            break;
        }
    }
    return stackFrame;
}

Next, we can get our information from the StackFrame. There’s lots of stuff on there, like the method, the filename and even line- and columnnumbers. The method below returns a string containing CallingObject.CallingMethod.

protected
string GetCallingMethod()
{
    string methodName;

    StackFrame stackFrame;
    stackFrame = GetCallingStackFrame();
    methodName = stackFrame.GetMethod().DeclaringType.Name;
    methodName +=
"." + stackFrame.GetMethod().Name;

    return methodName;
}

I know there’s some work in this code when it comes to defensive programming. For instance: who tells me GetMethod() will return anything containing a DeclaringType property. But that’s not the issue in this post ;)

HowTo: read your configfile when using no-touch deployment

Earlier I posted about reading a configfile when using no-touch deployment. Several people have contacted me to post the code, so here it is.

private static bool InitializeRemoting()
{
    string configFile;

    configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
    try
    {
        //try to read the configfile without tricks first
        RemotingConfiguration.Configure(configFile);
    }
    catch (RemotingException)
    {
        //When ‘normal’ reading fails, try it our special way.
       
string tempDir;
        WebClient webClient;

        //Get the location of the application data folder
        tempDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        tempDir +=
@"ApplicationName";
        if (!Directory.Exists(tempDir))
        {
            //Add a folder for our own application
            Directory.CreateDirectory(tempDir);
        }
       
try
       
{
            //Download the configfile to the new folder and use it to configure Remoting
            webClient =
new WebClient();
            webClient.DownloadFile(configFile, tempDir +
"ApplicationName.exe.config");
            RemotingConfiguration.Configure(tempDir +
"ApplicationName.exe.config");
        }
       
catch
       
{
           
return false;
        }
    }
    return true;
}

By |January 16th, 2006|.Net, HowTo|0 Comments