Category Archives: 10411

O Estranho Caso Do Computador Que Acordava Sozinho Misteriosamente

Normalmente, quando eu vou dormir, também ponho o meu computador a dormir.

Mas, desde há alguns meses, o computador acordava sozinho e eu não conseguia percber porquê.

Com a ajuda do Pete consegui perceber porquê:

C:\>PowerCfg -LASTWAKE
Wake History Count - 1
Wake History [0]
  Wake Source Count - 1
  Wake Source [0]
    Type: Wake Timer
    Owner: [PROCESS] \Device\HarddiskVolume2\Windows\System32\services.exe
    Owner Supplied Reason: Windows will execute '\Microsoft\Windows\Media Center\mcupdate_scheduled' scheduled task that requested waking the computer.


Usando PowerCfg –LASTWAKE é possível saber o que acordou o computador da última vez que este acordou.



Afinal era apenas uma tarefa agendada do Media Center que acordava o meu computador.

The Strange Case Of The Mysterious Self Awaking Computer

Usually, when I go to sleep, I also put my desktop computer to sleep.

But, for the last couple of months, the computer would always wake up by itself and I couldn’t figure out why.

With the help of Pete I was able to find out:

C:\>PowerCfg -LASTWAKE
Wake History Count - 1
Wake History [0]
  Wake Source Count - 1
  Wake Source [0]
    Type: Wake Timer
    Owner: [PROCESS] \Device\HarddiskVolume2\Windows\System32\services.exe
    Owner Supplied Reason: Windows will execute '\Microsoft\Windows\Media Center\mcupdate_scheduled' scheduled task that requested waking the computer.


Using PowerCfg –LASTWAKE it is possible to know what woke up the computer the last time it woke up.



It turns out that it was a Media Center scheduled task that was waking up my computer.

How To Add And Remove SQL Server 2008 / 2008R2 Instances

After installing Visual Studio 2010 I, inadvertently ended up with SQL Server 2008 Express having already installed SQL Server 2008 Developer. Only when I was going to upgrade to SQL Server 2008R2 I found out I had two instances installed.

I looked everywhere for a place to remove the SQLEXPRESS instance but couldn’t find it.

Only when I decided to uninstall the entire SQL Server suite and start over I found how to do it.

On Windows 7, go to Programs and Features and choose Microsoft SQL Server 2008 R2 (64-bit) (or whatever your version of SQL Server you want to add or remove and instance from).

Choose Remove (or Add, if you want to add a new instance).

Follow the steps and choose which instance you want to remove.

Select the features of that instance you want to remove (select all to remove the instance).
Note: Don’t remove shared features if you don’t want to remove any other instances.

It’s probably something I should have known, but I didn’t and it wasn’t easy to find.

Fixing Windows Virtual PC Missing “Create Virtual Machine” Folder Option

Some of my Windows 7 systems, after installing Windows Virtual PC, were missing the Create virtual machine option.

Bob Comer directed me to this post from the Virtual PC Guy’s Blog but, before trying the recipes in the post (which involved logging out or restarting the system), I simply tried the Reset Folders option in the View tab of the Folder Options. And it immediately solved the problem.

So, if you are having this same problem, you might want to try this simple solution first.

In the end, just in case, I also added start menu shortcuts to:

  • Windows Virtual PC Wizard

    %SystemRoot%\System32\VPCWizard.exe

  • Windows Virtual PC Settings

    %SystemRoot%\System32\VPCSettings.exe

Is Your ASP.NET Development Server Not Working?

Since Visual Studio 2005, Visual Studio comes with a development web server: the ASP.NET Development Server.

I’ve been using this web server for simple test projects since than with Visual Studio 2005 and Visual Studio 2008 in Windows XP Professional on my work laptop and Windows XP Professional, Windows Vista 64bit Ultimate and Windows 7 64bit Ultimate at my home desktop without any problems (apart the known custom identity problem, that is).

When I received my new work laptop, I installed Windows Vista 64bit Enterprise and Visual Studio 2008 and, for my surprise, the ASP.NET Development Server wasn’t working.

I started looking for differences between the laptop environment and the desktop environment and the most notorious differences were:

System

Laptop

Desktop

SKU

Windows Vista 64bit Enterprise

Windows Vista 64bit Ultimate

Joined to a Domain

Yes

No

Anti-Virus

McAffe

ESET

After asserting that no domain policies were being applied to my laptop and domain user and nothing was being logged by the ant-virus, my suspicions turned to the fact that the laptop was running an Enterprise SKU and the desktop was running an Ultimate SKU. After having problems with other applications I was sure that problem was the Enterprise SKU, but never found a solution to the problem. Because I wasn’t doing any web development at the time, I left it alone.

After upgrading to Windows 7, the problem persisted but, because I wasn’t doing any web development at the time, once again, I left it alone.

Now that I installed Visual Studio 2010 I had to solve this. After searching around forums and blogs that either didn’t offer an answer or offered very complicated workarounds that, sometimes, involved messing with the registry, I came to the conclusion that the solution is, in fact, very simple.

When Windows Vista is installed, hosts file, according to this contains this definition:

127.0.0.1       localhost
::1             localhost


This was not what I had on my laptop hosts file. What I had was this:



#127.0.0.1       localhost
#::1             localhost


I might have changed it myself, but from the amount of people that I found complaining about this problem on Windows Vista, this was probably the way it was.



The installation of Windows 7 leaves the hosts file like this:



#127.0.0.1       localhost
#::1             localhost


And although the ASP.NET Development Server works fine on Windows 7 64bit Ultimate, on Windows 7 64bit Enterprise it needs to be change to this:



127.0.0.1       localhost
::1             localhost


And I suspect it’s the same with Windows Vista 64bit Enterprise.

Detecting User Regional Settings In The Web Browser

Recently, a friend of mine asked me something like: “How do I get the user’s regional settings for a request to a web server?”

As far as I know, web browser only send an Accept-Language HTTP header and nothing more. You can take this and use the default regional settings for that language but, if your user is anything like me, you’ll be wrong.

So, what’s the problem of getting it wrong?

If you are just generating HTML and keep it consistent, nothing’s wrong. But what if your user wants to copy some numeric and/or date values to, say, Excel? Or if you want to export some data as a CSV file?

A solution

Going through the JScript Language Reference, I found that both Number and Date have locale related toString methods and I started playing with them.

Numeric format settings

To the numeric format settings, first we need a number that will behave in a predictable manner in any culture (“any culture” means “any culture I know”) and for all possible settings and convert it to a string using the toLocaleString method:

var number = 111111111.111111111;
var numberString = number.toLocaleString();


(With my regional settings, numberString becomes 111 111 111.11)



To get the decimal separator, all it takes is getting the first non 1 from the end:



var decimalSeparator;
var decimalDigits;
for (var i = numberString.length - 1; i >= 0; i--) {
    var char = numberString.charAt(i);
    if (char != "1") {
        decimalSeparator = char;
        decimalDigits = numberString.length - i - 1;
        break;
    }
}


And if you count how many 1s were skipped, we get the number of decimal digits.



In a similar way, the first non 1 will be the digit grouping separator:



var groupSeparator;
for (var i = 0; i < numberString.length; i++) {
    var char = numberString.charAt(i);
    if (char != "1") {
        groupSeparator = char;
        break;
    }
}


Now that we have the digit grouping separator, we can get the digit groups (these groups might not all have the same size):



var digitGrouping = numberString.substring(0, numberString.length - decimalDigits - 1).split(groupSeparator);
for (g in digitGrouping) {
    digitGrouping[g] = digitGrouping[g].length;
}


Date and time settings


Date and time values are more difficult to parse and you might not need all information. So, I’ll just get the value and let the parsing to you:



var dateTime = new Date(9999, 11, 31, 23, 30, 45);
dateTimeString = dateTime.toLocaleString();


List settings


The last setting is the list separator (very useful for those CSV files):



var list = ["a", "b"];
listSeparator = list.toLocaleString().substring(1, 2);


Test page



Here is a test page the get all these settings:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>Test Page</title>
    <style type="text/css">
        label  { width: 8em; text-align: right; padding-right: 0.5em; white-space: nowrap; }
        span { border: 1px solid; white-space: nowrap; }
    </style>
    <script type="text/javascript">
        function init() {
            document.all.userLanguage.innerText = window.navigator.userLanguage;
            document.all.systemLanguage.innerText = window.navigator.systemLanguage;

            // Decimal separator and decimal digits
            var number = 111111111.111111111;
            var numberString = (111111111.111111111).toLocaleString();

            var decimalSeparator;
            var decimalDigits;
            for (var i = numberString.length - 1; i >= 0; i--) {
                var char = numberString.charAt(i);
                if (char != "1") {
                    decimalSeparator = char;
                    decimalDigits = numberString.length - i - 1;
                    break;
                }
            }
            document.all.decimalSeparator.innerText = decimalSeparator;
            document.all.decimalDigits.innerText = decimalDigits;

            // Digit grouping separator and digit goups
            var groupSeparator;
            for (var i = 0; i < numberString.length; i++) {
                var char = numberString.charAt(i);
                if (char != "1") {
                    groupSeparator = char;
                    break;
                }
            }
            document.all.groupSeparator.innerText = groupSeparator;

            var digitGrouping = numberString.substring(0, numberString.length - decimalDigits - 1).split(groupSeparator);
            for (g in digitGrouping) {
                digitGrouping[g] = digitGrouping[g].length;
            }
            document.all.digitGrouping.innerText = digitGrouping.toString();

            // Date format
            var dateTime = new Date(9999, 11, 31, 23, 30, 45);
            var dateTimeString = dateTime.toLocaleString();
            document.all.dateTimeFormat.innerText = dateTimeString;

            // List separator
            var list = ["a", "b"];
            var listSeparator = list.toLocaleString().substring(1, 2);
            document.all.listSeparator.innerText = listSeparator;
        }
    </script>
</head>
<body onload="init()">
    <p><label for="userLanguage">User language:</label><span id="userLanguage"></span></p>
    <p><label for="systemLanguage">System language:</label><span id="systemLanguage"></span></p>
    <p><label for="decimalSeparator">Decimal separator:</label><span id="decimalSeparator"></span></p>
    <p><label for="decimalDigits">Decimal digits:</label><span id="decimalDigits"></span></p>
    <p><label for="groupSeparator">Digit separator:</label><span id="groupSeparator"></span></p>
    <p><label for="digitGrouping">Digit grouping:</label><span id="digitGrouping"></span></p>
    <p><label for="dateTimeFormat">Date/Time format:</label><span id="dateTimeFormat"></span></p>
    <p><label for="listSeparator">List separator:</label><span id="listSeparator"></span></p>
</body>
</html>

Visual Studio: Setting Up The Current Project And Run

When I’m building a demo solution I usually have several projects to demo different features.


When I want to run one of the projects, I have to set it as the startup project (either in the Project menu or in the context menu of the Solution Explorer for the desired project) and start it with or without debugging.


I can start any project with debugging using the context menu for that project in the Solution Explorer, but I cannot start the project without debugging.


While preparing for my session at the upcoming Microsoft TechDays 2010, I decided to work around this by creating macros to set the current project as the startup project and start the project with or without debugging:


Sub SetAsStartUpProjectAndStartWithoutDebuggingMacro()
    DTE.ExecuteCommand("Project.SetasStartUpProject")
    DTE.ExecuteCommand("Debug.StartWithoutDebugging")
End Sub

Sub SetAsStartUpProjectAndStartWithDebuggingMacro()
    DTE.ExecuteCommand("Project.SetasStartUpProject")
    DTE.Debugger.Go(False)
End Sub


And I can bind those macros to keyboard shortcuts (Shift+Alt+F5 for starting with debugging and Ctrl+Shift+Alt+F5 for starting without debugging) and add them to a toolbar.

Web Site Globalization With ASP.NET Routing

For those who don’t know, I have this web site http://PauloMorgado.NET/ that I use both as a web presence besides my blogs and a playfield.

Because I write both in English and Portuguese, I wanted the web site to have both English and Portuguese versions. This is easily accomplished by using ASP.NET Globalization and Localization.

But I wanted to do more than guessing the user’s language form her/his web browser languages. I wanted something like the MSDN and TechNet web sites have where the culture is embedded in the URL which makes it easy for the user to choose in which language she/he wants to see the web site.

With the release of the ASP.NET Routing, this is as easy as writing a custom route handler that sets the culture for the request and returns the requested page handler.

Something like this:

public class GlobalizationRouteHandler : global::System.Web.Routing.IRouteHandler
{
    System.Globalization.CultureInfo culture;
    System.Globalization.CultureInfo uiCulture;

    public GlobalizationRouteHandler(System.Globalization.CultureInfo culture)
        : this(culture, culture)
    {
    }

    public GlobalizationRouteHandler(CultureInfo culture, CultureInfo uiCulture)
    {
        if (culture == null)
        {
            throw new ArgumentNullException("cultureInfo", "cultureInfo is null.");
        }

        if (uiCulture == null)
        {
            throw new ArgumentNullException("uiCulture", "uiCulture is null.");
        }

        this.culture = culture;
        this.uiCulture = uiCulture;
    }

    private GlobalizationRouteHandler()
    {
    }

    #region IRouteHandler Members

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        Thread.CurrentThread.CurrentCulture = this.culture;
        Thread.CurrentThread.CurrentUICulture = this.uiCulture;

        string path = "~/" + (requestContext.RouteData.Values["path"] as string);

        var physicalPath = requestContext.HttpContext.Server.MapPath(path);
        if (System.IO.Directory.Exists(physicalPath))
        {
            path = VirtualPathUtility.Combine(path, "Default.aspx");
        }

        var httpHandler = BuildManager.CreateInstanceFromVirtualPath(path, typeof(IHttpHandler)) as IHttpHandler;

        return httpHandler;
    }

    #endregion
}


And now it’s only a matter of registering the handled cultures:



routes.Add("en", new Route("en/{*path}", new GlobalizationRouteHandler(CultureInfo.GetCultureInfo("en-US"))));
routes.Add("pt", new Route("pt/{*path}", new GlobalizationRouteHandler(CultureInfo.GetCultureInfo("pt-PT"))));

Coupling ASP.NET Session State With Forms Authentication

Today I was talking with João about a way to couple the lifetime of the ASP.NET session state with the lifetime of Forms Authentication ticket.

My idea was to store the session ID in the UserData property of the forms authentication ticket upon logon and retrieve it with a custom session ID manager.

The login code would be something like this:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    bool isPersistent = this.Login1.RememberMeSet;
    string username = this.Login1.UserName;
    var ticket = new FormsAuthenticationTicket(
        0,
        username,
        DateTime.Now,
        DateTime.Now.AddMinutes(2),
        isPersistent,
        Guid.NewGuid().ToString("N"));

    // Encrypt the ticket.
    var encryptedTicket = FormsAuthentication.Encrypt(ticket);

    // Create the cookie.
    this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));

    // Redirect back to original URL.
    this.Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}



For the purpose of this test I am using a Guid as the session ID.




The session ID manager will return this session ID when queried by the session state HTTP module:




public class SessionIdManager : global::System.Web.SessionState.ISessionIDManager
{
    #region ISessionIDManager Members

    public string CreateSessionID(HttpContext context)
    {
        return GetDummySessionIdOrRedirectToLoginPage(context);
    }

    public string GetSessionID(HttpContext context)
    {
        return GetSessionIdFromFormsIdentity(context);
    }

    public void Initialize()
    {
    }

    public bool InitializeRequest(HttpContext context, bool suppressAutoDetectRedirect, out bool supportSessionIDReissue)
    {
        supportSessionIDReissue = false;
        return GetSessionIdFromFormsIdentity(context) == null;
    }

    public void RemoveSessionID(HttpContext context)
    {
    }

    public void SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
    {
        redirected = false;
        cookieAdded = false;
    }

    public bool Validate(string id)
    {
        return true;
    }

    #endregion

    private static string GetSessionIdFromFormsIdentity(HttpContext context)
    {
        var identity = context.User != null ? context.User.Identity as FormsIdentity : null;

        if ((identity == null) || (identity.Ticket == null) || string.IsNullOrEmpty(identity.Ticket.UserData))
        {
            return GetDummySessionIdOrRedirectToLoginPage(context);
        }
        else
        {
            return identity.Ticket.UserData;
        }
    }

    private static string GetDummySessionIdOrRedirectToLoginPage(HttpContext context)
    {
        if (context.Request.CurrentExecutionFilePath.Equals(FormsAuthentication.DefaultUrl, StringComparison.OrdinalIgnoreCase)
                        || context.Request.CurrentExecutionFilePath.Equals(FormsAuthentication.LoginUrl, StringComparison.OrdinalIgnoreCase))
        {
            return Guid.NewGuid().ToString("N");
        }
        else
        {
            FormsAuthentication.RedirectToLoginPage();
            return null;
        }
    }
}



NOTE: Although this might work, it’s just an intellectual exercise and wasn’t fully tested.


Playing With LINQ: Getting Interface Property Implementations

LINQ With C# (Portuguese)

Today, my friend Nuno was writing some code to get the PropertyInfos of a class implementation of an interface.

Given this interface:

public interface ISomeInterface { int IntProperty { get; set; } string StringProperty { get; } void Method(); }




and this class:



public class SomeClass : ISomeInterface
{
    int ISomeInterface.IntProperty { get; set; }
    public int IntProperty { get; private set; }
    public string StringProperty { get; private set; }
    public void Method() { }
}


Nuno wanted to retrieve:



  • Int32 ISomeInterface.IntProperty
  • System.String StringProperty


The code is fairly simple. First we need to get the interface mappings for the class:



typeof(SomeClass).GetInterfaceMap(typeof(ISomeInterface)).TargetMethods



and get all PropertyInfos for which the MethodInfo in the list is part of the implementation of the property (is either the set method or the get method).



Something like his:



public static bool Implements(this MethodInfo methodInfo, PropertyInfo propertyInfo)
{
    return (propertyInfo.GetGetMethod(true) == methodInfo) || (propertyInfo.GetSetMethod(true) == methodInfo);
}


But what caught my eye was that, with the above extension methods, I can use LINQ to retrieve a list of the desired PropertyInfos.



Something like this:



public static IEnumerable<PropertyInfo> GetInterfacePropertyImplementation(Type implementer, Type implemented)
{
    return (from propertyInfo in implementer.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).AsEnumerable()
            from methodInfo in implementer.GetInterfaceMap(implemented).TargetMethods.AsEnumerable()
            where methodInfo.Implements(propertyInfo)
            select propertyInfo).Distinct();
}



For the sample class and interface, the usage would be something like this:



var q = GetInterfacePropertyImplementation(typeof(SomeClass), typeof(ISomeInterface));

foreach (var p in q)
{
    Console.WriteLine(p);
}


Which would produce the following output:



Int32 ISomeInterface.IntProperty
System.String StringProperty


UPDATED: The previous implementation was overcomplicated and had some string based logic. Kudos to Nuno.