Thursday, May 17, 2007
Note that my blog has moved to http://www.pksoftware.net/devblog/.
This is the line of code that I keep forgetting...

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

Use it in (for example) the Program.Main function when the application starts up and the threads currrent principal is now the windows user. So...

Thread.CurrentPrincipal.Identity.IsAuthenticated

Will now be true and you can make use of the Identity.Name property etc.

Self reminder over...

More Notes...

If for example you need to perform unit tests as a windows user (to access the username or hit a resource) you can make use of the AppDomain.CurrentDomain.SetPrincipalPolicy method in the test fixture setup/teardown methods - see example below. I put the UnauthenticatedPrincipal setting in the teardown so that subsequent tests do not have their principal modified by accident...

using System;
using System.Security.Principal;
using System.Threading;
using NUnit.Framework;

namespace Tests.SetPrincipalPolicyExample
{
    [TestFixture]
    public class TestSomethingUsingCurrentWindowsPrincipal
    {
        /// <summary>Called once before all tests are run.</summary>
        [TestFixtureSetUp()]
        public void TestFixtureSetUp()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
        }

        /// <summary>Called once after all tests have run.</summary>
        [TestFixtureTearDown()]
        public void TestFixtureTearDown()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal);
        }

        [Test]
        public void VerifySomething()
        {
            string expectedUsername = Thread.CurrentPrincipal.Identity.Name;
            // more testing stuff
        }
    }
}


Thursday, May 17, 2007 1:32:42 PM (GMT Standard Time, UTC+00:00) |  | #
Note that my blog has moved to http://www.pksoftware.net/devblog/.
Search
Links
My blog has moved to http://www.pksoftware.net/devblog/
Products
Mini SQL Query
Mini SQL Query is a minimalist SQL query tool for multiple providers (MSSQL, Oracle, OLEDB, MS Access files etc.)

Verse Popper
The "Verse Popper" displays bible verses periodically in the lower right hand corner of your screen.

Blogroll
My blog has moved to http://www.pksoftware.net/devblog/