Apr 122019
 

System.Security.Claims.ClaimsIdentity is the .Net class that helps management of a claims based user identity using which you can add claims to a .Net application for more granular user control based on the user claims provided by the issuer in your application.

MSDN Link to class documentation:
https://docs.microsoft.com/en-us/dotnet/api/system.security.claims.claimsidentity?view=netframework-4.7.2

For example…
1. switch the UI to a different view if role of user logged in is the company CEO.
2. switch site theme based on users favorite color.
3. switch site locale based on user country or show a customized greeting.
4. restrict access to site based on user age.
5. etc…

Here is a short script to assign claims to the current thread principal and verify user claims using PowerShell.

# Add assembly for displaying message box
Add-Type –AssemblyName System.Windows.Forms

# Claims
$claims = New-Object System.Collections.Generic.List[System.Security.Claims.Claim]

# Add claims to claims list
$claims.Add(((New-Object System.Security.Claims.Claim([System.Security.Claims.ClaimTypes]::Email, "nibu.bt@gmail.com"))))
$claims.Add(((New-Object System.Security.Claims.Claim("WebSite", "http://ntcoder.com"))))
$claims.Add(((New-Object System.Security.Claims.Claim("Primary Skill", "C++"))))
$claims.Add(((New-Object System.Security.Claims.Claim([System.Security.Claims.ClaimTypes]::Country, "India"))))
$claims.Add(((New-Object System.Security.Claims.Claim([System.Security.Claims.ClaimTypes]::Role, "CEO"))))


# Instantiate claims identity object
$cid = New-Object System.Security.Claims.ClaimsIdentity($claims, "Password")

# Assign principal
[System.Threading.Thread]::CurrentPrincipal =  New-Object System.Security.Claims.ClaimsPrincipal($cid)

Write-Host "Current Thread Principal: " -NoNewline
[System.Threading.Thread]::CurrentPrincipal | Select-Object -ExpandProperty Claims | Select-Object Issuer, Type, value | Format-Table -AutoSize

# Write authentication status
Write-Host "Authenticated: $($cid.IsAuthenticated)"

$tp = [System.Threading.Thread]::CurrentPrincipal

# Check if user is CEO, if yes then display a messagebox, check above role that we added 
if($tp.IsInRole("CEO"))
{
    $null = [System.Windows.Forms.MessageBox]::Show("Welcome CEO, opening CEO view...", "User", [System.Windows.Forms.MessageBoxButtons]::OK,[System.Windows.Forms.MessageBoxIcon]::Information)
}

# Check country of user, if India then display an Indian greeting message.
if($tp.HasClaim([System.Security.Claims.ClaimTypes]::Country, "India"))
{
    $null = [System.Windows.Forms.MessageBox]::Show("Namaskar!", "Greetings!", [System.Windows.Forms.MessageBoxButtons]::OK,[System.Windows.Forms.MessageBoxIcon]::Information)
}

Script output follows...

PS C:\> c:\NibuRoot\Powershell\powershellsnips\Claims.ps1
Current Thread Principal:
Issuer Type Value
------ ---- -----
LOCAL AUTHORITY http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress email@gmail.com
LOCAL AUTHORITY WebSite http://ntcoder.com
LOCAL AUTHORITY Primary Skill C++
LOCAL AUTHORITY http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country India
LOCAL AUTHORITY http://schemas.microsoft.com/ws/2008/06/identity/claims/role CEO

Authenticated: True

Oct 222014
 

Reading through few interesting articles on Microsoft.Net Versions and Dependencies in MSDN. Thought of sharing this out with you just in case if you need it…

.NET Framework Versions and Dependencies

How to: Determine Which .NET Framework Versions Are Installed

How to: Determine Which .NET Framework Updates Are Installed

Oct 212014
 

Introduction

I had a customer who was seeing several invalid handle exceptions in his application. These exceptions were thrown during finalization of  SafeProcessHandle objects. In their code they had a big collection of SafeProcessHandle objects hence too many objects in Finalization queue as well which means too many Invalid Handle exceptions as well.

What’s an Invalid Handle exception?

Invalid handle exceptions basically means the handle being closed has gone bad or has already been closed. In this case the second reason looked more valid to me as the exceptions were happening during finalization. There was a good chance that these handles got closed pretty early.

What’s the reason for these Invalid Handle exceptions?

Lots of Invalid handle exceptions were happening in his code while disposing a SafeProcessHandle object. This was because he’s was not properly serializing the process handles or SafeProcessHandle’s across app domain calls. We enabled MDA – ReleaseHandleFailed. This setting is also reporting something similar.

ReleaseHandleFailed was detected:
Message: A SafeHandle or CriticalHandle of type SafeProcessHandle failed to properly release the handle with value 0x00000000000020F0. This usually indicates that the handle was released incorrectly via another means (such as extracting the handle using DangerousGetHandle and closing it directly or building another SafeHandle around it.)

How to fix these Invalid Handle exceptions?

The only way to fix this invalid handle issue is to manage serialization of SafeProcessHandle objects across app domains. As of now its just a bitwise copy which results in two SafeProcessHandle’s owning a non-ref counted process handle. When either of these SafeProcessHandle objects are destroyed the second instance of SafeProcessHandle is bound to fail as the handle has already been destroyed/closed by the first instance.

Handle’s are indexes into a process handle table which in turn points to the real Kernel Object. This basically means we’ll have to duplicate this handle via DuplicateHandle API and which tells Kernel this object is still alive and not to destroy this Kernel Object. The duplicate handle refers to the same object as the original handle. Therefore, any changes to the object are reflected through both handles. For example, if you duplicate a file handle, the current file position is always the same for both handles.

SafeSerializableProcessHandle to fix Invalid Handle exceptions

Hence SafeSerializableProcessHandle is born. I wrote a dedicated class to manage this serialization. Made this class serializable as well. This class will automatically create a duplicate handle when serialized. For duplicating process handles we’re using the Windows API DuplicateHandle. Here’s how the code looks like…

using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics;

namespace NativeHandleWrappers
{
    [System.Security.SecurityCritical]
    [Serializable()]
    public class SafeSerializableProcessHandle : SafeHandleZeroOrMinusOneIsInvalid, ISerializable
    {
        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true, EntryPoint = "CloseHandle", CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool CloseHandleImport(IntPtr hObject);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true, EntryPoint = "DuplicateHandle", CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool DuplicateHandleImport(IntPtr hSourceProcessHandle,
                                           IntPtr hSourceHandle,
                                           IntPtr hTargetProcessHandle,
                                           out SafeSerializableProcessHandle lpTargetHandle,
                                           uint dwDesiredAccess,
                                           [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
                                           uint dwOptions);

        [Flags]
        public enum DuplicateOptions : uint
        {
            DUPLICATE_CLOSE_SOURCE = (0x00000001),// Closes the source handle. This occurs regardless of any error status returned.
            DUPLICATE_SAME_ACCESS = (0x00000002), //Ignores the dwDesiredAccess parameter. The duplicate handle has the same access as the source handle.
        }

        // Constructors //
        private SafeSerializableProcessHandle()
            : base(true)
        {
            handle = IntPtr.Zero;
        }

        // Constructor that is called automatically during deserialization.
        // Reconstructs the object from the information in SerializationInfo info
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        private SafeSerializableProcessHandle(SerializationInfo Info, StreamingContext Context)
            : base(true)
        {
            handle = ((IntPtr)Info.GetInt64("handle"));
        }

        public SafeSerializableProcessHandle(IntPtr handle)
            : base(true)
        {
            SetHandle(handle);
        }
        // End constructors //

        // 0 is an Invalid Handle
        internal static SafeSerializableProcessHandle InvalidHandle
        {
            get { return new SafeSerializableProcessHandle(IntPtr.Zero); }
        }

        [System.Security.SecurityCritical]
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        override protected bool ReleaseHandle()
        {
            bool Status = true;

            if (!SuppressRelease)
            {
                Status = CloseHandleImport(handle);
                if (!Status)
                {
                    DebugOutLastError();
                }
            }

            return Status;
        }

        void DebugOutLastError()
        {
            System.ComponentModel.Win32Exception we = new System.ComponentModel.Win32Exception();
            Debug.WriteLine("\n------------------------------------------\nLast error: " + we.Message + "\n------------------------------------------\n");
        }

        private bool _suppressRelease = false;
        protected bool SuppressRelease
        {
            get
            {
                return _suppressRelease;
            }

            set
            {
                _suppressRelease = value;
            }
        }

        // Serializes the object.
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            SafeSerializableProcessHandle hDupHandle = DuplicateHandlePrivate(handle);
            info.AddValue("handle", hDupHandle.handle.ToInt64());

            // Suppress close handle as the handle will be closed by the instance that's deserializing
            hDupHandle.SuppressRelease = true;
            hDupHandle.Close();
        }

        private SafeSerializableProcessHandle DuplicateHandlePrivate(IntPtr Handle)
        {
            SafeSerializableProcessHandle hDupHandle;
            bool Status = DuplicateHandleImport(Process.GetCurrentProcess().Handle,
                                                Handle,
                                                Process.GetCurrentProcess().Handle,
                                                out hDupHandle,
                                                0,
                                                true,
                                                (uint)DuplicateOptions.DUPLICATE_SAME_ACCESS);
            if (hDupHandle == null || !Status)
            {
                Debug.Assert(false);
                DebugOutLastError();
            }

            return hDupHandle;
        }
    }
}

//Function to test SafeSerializableProcessHandle class. This function also demonstrates usage of SafeSerializableProcessHandle
void Serialize()
{
    FileStream fs = new FileStream("DataFile.dat", FileMode.Create|FileMode.CreateNew);

    try
    {
        // Construct a BinaryFormatter and use it to serialize the data to the stream.
        BinaryFormatter formatter = new BinaryFormatter();

        // Serialize
        Process [] Proc = Process.GetProcessesByName("Explorer");
        SafeSerializableProcessHandle ssph = OpenProcess(ProcessAccessFlags.DupHandle | ProcessAccessFlags.Terminate, true, Proc[0].Id);
        formatter.Serialize(fs, ssph);

        //Deserialize.
        fs.Position = 0;
        SafeSerializableProcessHandle newssph = (SafeSerializableProcessHandle)formatter.Deserialize(fs);

        // Close both, this should work
        ssph.Close();
        newssph.Close();
    }
    catch (SerializationException e)
    {
        Console.WriteLine("Failed to serialize. Reason: " + e.Message);
        throw;
    }
    finally
    {
        fs.Close();
    }
}

Usage of SafeSerializableProcessHandle

Replace instances of SafeProcessHandle, which will be cross domained or serialized, with SafeSerializableProcessHandle. No other change will be needed. The effect is magical, no invalid handle exceptions any more. 🙂

Caveats/Disclaimer

Please note this class is not extensively tested. I did some basic tests and so far looks like this is working for our customer as well. So I guess this is pretty solid. If you run into issues you can let me know via a comment to this post but this post is given as is without any sort of support. You’re going to use this at your own risk.

Sep 172014
 

Issue

You get CannotUnloadAppDomainException when trying to unload an AppDomain on which a WPF window has been displayed. This is how the exception looks like…

---------------------------
AppDomainUnload
---------------------------
Error while unloading appdomain. (Exception from HRESULT: 0x80131015)
---------------------------
OK
---------------------------

The callstack associated with this exception is not at all informative. This is all that I have for this exception…

System.CannotUnloadAppDomainException occurred
_HResult=-2146234347
_message=Error while unloading appdomain. (Exception from HRESULT: 0x80131015)
HResult=-2146234347
IsTransient=false
Message=Error while unloading appdomain. (Exception from HRESULT: 0x80131015)
Source=mscorlib
StackTrace:
at System.AppDomain.nUnload(Int32 domainInternal)
at System.AppDomain.Unload(AppDomain domain)
InnerException:

Repro

This was the code that was shared by the customer which demonstrates the issue. Nothing proprietary hence sharing this out…

Private Sub Button_Click(sender As Object, e As RoutedEventArgs) Handles btn1.Click
    Try
        btn1.IsEnabled = False

        ‘Create a new AppDomain
        Dim ad As AppDomain = AppDomain.CreateDomain("ad2")
        Dim exeAssembly As String = [Assembly].GetEntryAssembly().FullName

        Dim newDomain As NewAppDomain = DirectCast(ad.CreateInstanceAndUnwrap(Assembly.GetEntryAssembly.FullName, GetType(NewAppDomain).FullName), NewAppDomain)

        'Call a subroutine to show a WPF window
        newDomain.ShowWPFWindow()
        AppDomain.Unload(ad)

        MsgBox("New AppDomain unloaded successfully")

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        btn1.IsEnabled = True
    End Try
End Sub

So in above code we’re creating an object in a new app domain (“ad2”) and we then call ShowWPFWindow on this new object which will show up the window in a new app domain. Once ShowWPFWindow returns we unload this AppDomain and this where CannotUnloadAppDomainException happens. We do see the application going unresponsive before this CannotUnloadAppDomainException.

Why does a CannotUnloadAppDomainException occur?

The million dollar question is why does this happen? Well from what we’ve found when a WPF Window is showed for the first time on a new app domain a Stylus input thread gets attached to this window for touch input events on touch enabled devices or at least on devices which such components installed.

When AppDomain.Unload call is made this thread fails to shutdown. We do see a thread abort request already sent to this stylus input thread but we don’t see a response yet.

Exception on top of the stack…

0:009> !pe
Exception object: 028280c4
Exception type:   System.CannotUnloadAppDomainException
Message:          Error while unloading appdomain. (Exception from HRESULT: 0x80131015)
InnerException:   <none>
StackTrace (generated):
SP       IP       Function
00000000 00000001 mscorlib_ni!System.AppDomain.nUnload(Int32)+0x2
07D3E320 793DCDE9 mscorlib_ni!System.AppDomain.Unload(System.AppDomain)+0x41

StackTraceString: <none>
HResult: 80131015

0:009> !threads
ThreadCount:      14
UnstartedThread:  0
BackgroundThread: 9
PendingThread:    0
DeadThread:       3
Hosted Runtime:   no
Lock
ID OSID ThreadOBJ    State GC Mode     GC Alloc Context  Domain   Count Apt Exception
0    1  e10 00b63f40   203a228 Preemptive  025EA018:00000000 00b573b8 0     MTA
2    2  a44 00b65bf0     2b228 Preemptive  0282A108:00000000 00b573b8 0     MTA (Finalizer)
XXXX    3    0 00bf2b18     30820 Preemptive  00000000:00000000 00b573b8 0     Ukn
XXXX    4    0 00c00a20     39820 Preemptive  00000000:00000000 00b573b8 0     MTA
XXXX    5    0 00c09b10     39820 Preemptive  00000000:00000000 00b573b8 0     MTA
5    6 1ec8 00c06d08   10b9228 Preemptive  0280C960:00000000 00b573b8 0     Ukn (Threadpool Worker)
7    7 2388 00c22128     ab028 Preemptive  02600420:00000000 00b573b8 0     MTA
8    8 20e4 00c2b2a8     ab228 Preemptive  025FA3DC:00000000 00b573b8 0     MTA
9    9 22b0 06ff0a58     a7028 Preemptive  0282CAF4:00000000 00b573b8 0     STA System.CannotUnloadAppDomainException 028280c4
11   10 1848 07098f78     2b228 Preemptive  026CE7D8:00000000 00b573b8 0     MTA
16   11 1e74 09e984c8     21228 Preemptive  00000000:00000000 00b573b8 0     Ukn
17   12 22b8 07087b90   102a228 Preemptive  00000000:00000000 00b573b8 0     MTA (Threadpool Worker)
  18   13 14f4 0702d878     2b229 Preemptive  027827CC:00000000 09e047a0 0     MTA <<<<--- Stylus input thread
19   14  a6c 07090058   10b9228 Preemptive  00000000:00000000 00b573b8 0     Ukn (Threadpool Worker)

The only thread in that domain is #18, a stylus input thread. A thread abort has already been posted and a debug suspend is pending as well…

0:018> !ThreadState 2b229
    Thread Abort Requested  <<<- Thread abort requested but yet to shutdown
Debug Suspend Pending
Legal to Join
Background
CLR Owns
CoInitialized
In Multi Threaded Apartment
Fully initialized

Please note this is the only thread on this AppDomain now that’s left to exit. Since it fails to exit we get a CannotUnloadAppDomainException.

Workaround for this CannotUnloadAppDomainException?

Only workaround is to move AppDomain+Window creation to a separate thread and then forcefully shutdown the Dispatcher thread (via calls to Dispatcher.CurrentDispatcher.InvokeShutdown()). InvokeShutdown alone can fail unless a GC is forced. Please see below code. I’ve added a new thread worker function called ‘DoWork’ which does the work of creating and displaying the AppDomain window…

‘Thread proc
Public Shared Sub DoWork()
    'Create a new AppDomain
    Dim ad As AppDomain = AppDomain.CreateDomain("ad2")
    Dim exeAssembly As String = [Assembly].GetEntryAssembly().FullName

    Dim newDomain As NewAppDomain = DirectCast(ad.CreateInstanceAndUnwrap(Assembly.GetEntryAssembly.FullName, GetType(NewAppDomain).FullName), NewAppDomain)

    'Call a subroutine to show a WPF window
    newDomain.ShowWPFWindow()
    Dispatcher.CurrentDispatcher.InvokeShutdown()  <<<--- Workaround
    GC.Collect() <<<—Workaround
    AppDomain.Unload(ad)

    MsgBox("New AppDomain unloaded successfully")
End Sub

Private Sub Button_Click(sender As Object, e As RoutedEventArgs) Handles btn1.Click
    '
    Try
        btn1.IsEnabled = False

        Dim ts As New ThreadStart(AddressOf DoWork)
        Dim WorkerThread As New System.Threading.Thread(ts)
        WorkerThread.SetApartmentState(ApartmentState.STA)
        WorkerThread.Start()
        WorkerThread.Join()

        MsgBox("New AppDomain unloaded successfully")

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        btn1.IsEnabled = True
    End Try
End Sub

Please note where we’re calling (workaround) InvokeShutdown.

Dispatcher.CurrentDispatcher.InvokeShutdown()
GC.Collect()

GC.Collect is important just to make sure the Pen/Stylus objects are cleared out from memory. Alternatively you can also write above code in a Window’s closing event so that the stylus input thread is detached from this window and the objects associated with it are cleared from memory.

Aug 282014
 
What’s DEVPATH

Being a .net developer you might have wondered if at all there is a way to tell .net assembly binding and loading mechanism (fusion) to look for your assemblies in your shared assembly folder as well. This will be really helpful if your assembly is used with multiple applications so that if they fail to locate an assembly in the appbase or privatepath’s then they start looking for it in your ‘bin’ folder. This prevents you from frequently installing and uninstalling the assembly to GAC for testing purpose.

This is exactly what DEVPATH environment variable does.

How to set DEVPATH

Following example shows you how to setup just need to set assembly look up path to this variable. For e.g.

set DEVPATH=”c:\sharedassemblies\”

To enable DEVPATH look up you’ll also need to modify machine.config file, in my case its located here: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config

<configuration>

<runtime>
<developmentMode developerInstallation=”true”/>
</runtime>

</configuration>

Verify DEVPATH is used

So next time when application runs and starts looking for your assembly it will for sure look in the above path. If fusion logger is enabled and if you open the log file for your assembly you should see something like this…

===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\myapp.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Found assembly in DEVOVERRIDE path C:\sharedassemblies\Test.DLL

Recently had a customer who asked this question and this looks like to have helped them so thought of sharing this out with you folks as well.

Watch outs
  1. Please be very aware that you’ve set this feature on. You could end up having erratic behavior if somehow DEVPATH has a path containing unsupported path chars like parentheses or if DEVPATH is set to empty.
  2. Please only use this feature in development environments as this feature by passes all normal assembly lookup features as fusion looks up DEVPATH first if enabled.
  3. Please note fusion will look up DEVPATH as if its an AppBase folder so be aware that it will look up subdirectories as well in this DEVPATH. Also all valid assembly name look ups will be done, for e.g. .dll, .exe etc.
Aug 052014
 

Do you run into following error when trying to run a VS2013 .net application on Windows XP?

Error: Not a valid Win32 application!

This happens because the application is targeting .net framework 4.5 which is not supported on Windows XP. Target a lower framework to get your application working on XP.

Aug 052014
 

What are DateTime Custom Formatters?

A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation . It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time. A custom format string consists of one or more custom date and time format specifiers. Any string that is not a standard date and time format string is interpreted as a custom date and time format string.

Custom date and time format strings can be used with both DateTime and DateTimeOffset values.

Issue with DateTime Custom Formatters?

Recently a customer opened a ticket thinking that there is an issue with the DateTime Custom Formatters. They had following piece of code.

namespace DateTimeDefect
{
 class Test
 {
   static void Main(string[] args)
   {
     DateTime dt = DateTime.Now;

     Console.WriteLine(dt.ToString("f"));
     Console.WriteLine(dt.ToString("ff"));
     Console.WriteLine(dt.ToString("fff"));

     Console.ReadLine();
   }
 }
}

Except for dt.ToString(“f”) the other two ToString calls were returning correct results. Here’s the output…

Friday, May 30, 2014 12:53 AM (Here’s the issue, customer expects a numeric value as shown below)
53
534

Here’s what MSDN says about custom formatter ‘f’, ‘ff’, ‘fff’.

“f”: The tenths of a second in a date and time value. More information: The “f” Custom Format Specifier.

Sample:
6/15/2009 13:45:30.617 -> 6
6/15/2009 13:45:30.050 -> 0

“ff”: The hundredths of a second in a date and time value. More information: The “ff” Custom Format Specifier.

Sample:
6/15/2009 13:45:30.617 -> 61
6/15/2009 13:45:30.005 -> 00

“fff”: The milliseconds in a date and time value. More information: The “fff” Custom Format Specifier.

Sample:
6/15/2009 13:45:30.617 -> 617
6/15/2009 13:45:30.0005 –> 000

 So what’s going wrong here with DateTime Custom Formatters

The issue here is that dt.ToString(“f”) is not recognized as a custom format specifier. Please read below documentation from MSDN…

A custom date and time format string consists of two or more characters. Date and time formatting methods interpret any single-character string as a standard date and time format string. If they do not recognize the character as a valid format specifier, they throw a FormatException. For example, a format string that consists only of the specifier “h” is interpreted as a standard date and time format string. However, in this particular case, an exception is thrown because there is no “h” standard date and time format specifier.

To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the “d”, “f”, “F”, “g”, “h”, “H”, “K”, “m”, “M”, “s”, “t”, “y”, “z”, “:”, or “/” custom format specifier by itself), include a space before or after the specifier, or include a percent (“%”) format specifier before the single custom date and time specifier.

For example, “%h” is interpreted as a custom date and time format string that displays the hour represented by the current date and time value. You can also use the ” h” or “h ” format string, although this includes a space in the result string along with the hour. The following example illustrates these three format strings.

Resolution

So in this case the date time formatting method is interpreting this single character string as a standard date and time format string. To work around this, following are the options that you have…

1. Use dt.ToString(“%f”)
2. Use dt.ToString(“ f”);// add a space before ‘f’
3. Use dt.ToString(“f ”);// add a space after ‘f’

So if we change above code to…

static void Main(string[] args)
{
  DateTime dt = DateTime.Now;
  Console.WriteLine(dt.ToString("%f"));
  Console.WriteLine(dt.ToString("ff"));
  Console.WriteLine(dt.ToString("fff"));
  Console.ReadLine();
}

Now program output looks as follows…

8
87
873

Based on last value output you can verify the first two. Issue resolved.

Aug 052014
 

Just saw this (.NET Reference Source)… (totally cool) J

http://referencesource.microsoft.com/

Channel nine video: http://channel9.msdn.com/Series/NET-Framework/How-to-browse-the-NET-Reference-Source

Further details on our blog: http://blogs.msdn.com/b/dotnet/archive/2014/02/24/a-new-look-for-net-reference-source.aspx

Feb 242014
 

Recently had a customer who faced this issue when his application is run from a network share. The exception information is as follows …

************** Exception Text **************

System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for dataConfiguration: That assembly does not allow partially trusted callers. (G:\System\Backoffice\Citrix2008\MediaExplorer\Rev2008\Prod\Mfm.MediaExplorer.exe.Config line 28) ---> System.Security.SecurityException: That assembly does not allow partially trusted callers.

   at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture
   at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
   at System.Configuration.TypeUtil.InvokeCtorWithReflectionPermission(ConstructorInfo ctor)
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
   at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
   --- End of inner exception stack trace ---

   at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)
   at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)

Collected dumps of the application at the point when the JIT dialog appeared…

Checked out the threads…

0:000> !threads
ThreadCount:      5
UnstartedThread:  0
BackgroundThread: 4
PendingThread:    0
DeadThread:       0
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1 11b08 007e2c38      6020 Enabled  03093658:03093fe8 007dc9f8     0 STA System.Configuration.ConfigurationErrorsException (02fcce20)
   2    2 11b10 007ee008      b220 Enabled  00000000:00000000 007dc9f8     0 MTA (Finalizer)
   5    3 11b24 0085a600   8009220 Enabled  00000000:00000000 007dc9f8     0 MTA (Threadpool Completion Port)
   6    4 10e78 00860b00   100a220 Enabled  00000000:00000000 007dc9f8     0 MTA (Threadpool Worker)
   8    5 11944 0087a1a8   200b220 Enabled  030911ac:03091fe8 007dc9f8     0 MTA

Yes there is a System.Configuration.ConfigurationErrorsException.

Callstack is as follows…

0:000> !pe 02fcce20
Exception object: 02fcce20
Exception type:   System.Configuration.ConfigurationErrorsException
Message:          An error occurred creating the configuration section handler for dataConfiguration: That assembly does not allow partially trusted callers.
InnerException:   System.Security.SecurityException, Use !PrintException 02fc55d0 to see more.
StackTrace (generated):
    SP       IP       Function
    0045E2EC 69D2E834 System_Configuration_ni!System.Configuration.BaseConfigurationRecord.EvaluateOne(System.String[], System.Configuration.SectionInput, Boolean, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object)+0xc8
    0045E3C8 69D2E655 System_Configuration_ni!System.Configuration.BaseConfigurationRecord.Evaluate(System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, Boolean, Boolean, System.Object ByRef, System.Object ByRef)+0x481
    0045E488 69D26F5D System_Configuration_ni!System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)+0x5bd
    0045E510 69D26F5D System_Configuration_ni!System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)+0x5bd
    0045E598 69D26F5D System_Configuration_ni!System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)+0x5bd
    0045E620 69D2698A System_Configuration_ni!System.Configuration.BaseConfigurationRecord.GetSection(System.String)+0x2a
    0045E630 69D2A5A9 System_Configuration_ni!System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(System.String)+0x55
    0045E644 69D210BF System_Configuration_ni!System.Configuration.ConfigurationManager.GetSection(System.String)+0x4f

There is an inner exception as well…

0:000> !PrintException 02fc55d0
Exception object: 02fc55d0
Exception type:   System.Security.SecurityException
Message:          That assembly does not allow partially trusted callers.
InnerException:   
StackTrace (generated):
    SP       IP       Function
    0045DC8C 6BD56349 mscorlib_ni!System.Security.CodeAccessSecurityEngine.ThrowSecurityException(System.Reflection.RuntimeAssembly, System.Security.PermissionSet, System.Security.PermissionSet, System.RuntimeMethodHandleInternal, System.Security.Permissions.SecurityAction, System.Object, System.Security.IPermission)+0xa9
    0045E1EC 6B7E9EF2 mscorlib_ni!System.RuntimeMethodHandle.PerformSecurityCheck(System.Object, System.IRuntimeMethodInfo, System.RuntimeType, UInt32)+0x22
    0045E208 6B772242 mscorlib_ni!System.Reflection.RuntimeConstructorInfo.Invoke(System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo)+0x82
    0045E298 6B7E9EBA mscorlib_ni!System.Reflection.ConstructorInfo.Invoke(System.Object[])+0x12
    0045E2A0 69D277C8 System_Configuration_ni!System.Configuration.TypeUtil.InvokeCtorWithReflectionPermission(System.Reflection.ConstructorInfo)+0x24
    0045E2B0 69D276AC System_Configuration_ni!System.Configuration.RuntimeConfigurationRecord+RuntimeConfigurationFactory.CreateSectionImpl(System.Configuration.RuntimeConfigurationRecord, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, System.Configuration.ConfigXmlReader)+0x2c
    0045E2D8 69D312DB System_Configuration_ni!System.Configuration.RuntimeConfigurationRecord+RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(System.Configuration.RuntimeConfigurationRecord, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, System.Configuration.ConfigXmlReader)+0x57
    0045E31C 69D2762A System_Configuration_ni!System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, System.Configuration.ConfigXmlReader)+0x5e
    0045E344 69D274E4 System_Configuration_ni!System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, System.Configuration.ConfigXmlReader, System.String, Int32)+0x4c

StackTraceString: 
HResult: 8013150a
SecurityException Message: 
The action that failed was:
LinkDemand
The assembly or AppDomain that failed was:
System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
The Zone of the assembly that failed was:
MyComputer
The Url of the assembly that failed was:
file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll

Hmm weird that the assembly having this issue is System.Configuration! CLR version is 4.0. Caspol shouldn’t kick in if that’s the case. Eventually this turned out to be a bug.

This is fixed via a hotfix: http://support.microsoft.com/kb/2580188
FIX: System.Security.SecurityException occurs when a .NET Framework 4-based application that calls a static method in the System.Configuration.ConfigurationManager class runs on a network share.

The KB article says the following…
The application calls a static method in the System.Configuration.ConfigurationManager class. For example, the application calls the ConfigurationManager.GetSection method.

For this case this was true and the application was indeed calling ConfigurationManager.GetSection.

Disclaimer:
————–
Please read through the hotfix to be very sure that this hotfix applies to you. A classic symptom would be .net 4.0 + ConfigurationManager.GetSection call.