Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all 1710 articles
Browse latest View live

Returning an NTSTATUS to an unmanaged caller from .NET

$
0
0

Hi,

I'm currently trying to implement a Sub Authentication package for kerberos logons, and this requires getting Windows to call a DLL of mine (by entering the DLL name in a specific registry entry). I know ideally this should be in unmanaged C++ but as I only know VB.NET I'm trying to do it from that as I've done plenty of P/Invoke from it in the past. I've used a utility to export the function signature so that unmanaged code (the Windows logon process in this case) can call it, and I know that part is working fine as I can see my function is actually being called because I have it write the current time to a text file and that text file is indeed being updated every time a logon attempt takes place on the domain. However, the problem is that I don't seem to be returning the correct value as it acts as if I've returned an error code and therefore refuses to let anyone logon.

The documentation on MSDN for this function I've implemented in my .NET DLL is here (Msv1_0SubAuthenticationFilter: http://msdn.microsoft.com/en-gb/library/windows/desktop/aa378751(v=vs.85).aspx) and as you can see it says to just return STATUS_SUCCESS if you want to indicate that the logon validation was successful. According to everything I can find an NTSTATUS type is just a LONG really, and the platform invoke description here (http://msdn.microsoft.com/en-US/library/ac7ay120(v=vs.80).aspx) says a Long should just be an Int32 in .NET. So as I want to return STATUS_SUCCESS I just return 0 but as mentioned in the previous paragraph that doesn't seem to work. Do I need to marshal the Int32 that I'm returning back in some way?

Here's how I've currently got the method signature declared:

<DllExport()> _
Public Shared Function Msv1_0SubAuthenticationFilter(ByVal LogonLevel As UInt32, ByVal LogonInformation As IntPtr, ByVal Flags As UInteger, ByVal UserAll As IntPtr, ByRef WhichFields As UInteger, ByRef UserFlags As UInteger, ByRef Authoritative As Byte, ByRef LogoffTime As LARGE_INTEGER, ByRef KickoffTime As LARGE_INTEGER) As UInteger

I was originally returning a regular signed 32 bit integer but as you can see I've now changed that to an unsigned 32 bit integer just to test but that didn't make any difference.

Any ideas where I'm going wrong?

Thanks

Chris

 


My website (free apps I've written for IT Pro's) : www.cjwdev.co.uk My blog: cjwdev.wordpress.com


Why Garbage collector has only 3 generations adn how GC allocate memeory to generation 0 to 2 ?

$
0
0

Hello All,

I have very basic question about GC, I am learning about GC and I know about its execution algorithm of generation 0 to generation 2.

I have below two questions about GC .

1. How GC decide the specific amount of memory need to allocate the Generation 0, Generation 1 and Generation 2 , Is there any specific strategy that GC allocate some amount of memory to each generation ?

 

2. Why there are only 3 generations in GC , Why not more ?

Thanks in advance,

Aniruddha

System.ArgumentNullException: Value cannot be null. Parameter name: connection

$
0
0
 

I have migrated my web site files from Windows server 2003 to windows server 2008 r2.

We are using database from azure and connect to it.when the user tries to login to the website with their usernames ans passwords we get the following error.


System.ArgumentNullException: Value cannot be null.
Parameter name: connection
   at Microsoft.Practices.EnterpriseLibrary.Data.Database.PrepareCommand(DbCommand command, DbConnection connection)
   at Microsoft.Practices.EnterpriseLibrary.Data.Database.PrepareCommand(DbCommand command, DbTransaction transaction)
   at Microsoft.Practices.EnterpriseLibrary.Data.Database.LoadDataSet(DbCommand command, DataSet dataSet, String[] tableNames, DbTransaction transaction)
   at Microsoft.Practices.EnterpriseLibrary.Data.Database.LoadDataSet(DbCommand command, DataSet dataSet, String tableName, DbTransaction transaction)
   at SourceEdge.BCL.DataStore.LoadDataSet(DbCommand dbCommand)
   at SourceEdge.BCL.DataStore.LoadDataTable(Query qry)
   --- End of inner exception stack trace ---
   at SourceEdge.BCL.DataStore.LoadDataTable(Query qry)
   at SourceEdge.BCL.Query.LoadDataTable()
   at BLL.Users.GetUserDetails(String UserId) in C:\Documents and Settings\My Documents\Visual Studio 2005\Projects\BLL\Users.cs:line 605
   at User.Page_Load(Object sender, EventArgs e)

this error occurs for whoever tries to login though the logins have correct username and passwords.

also when this error occurs i try checking a healt page where it just tries to connect to the DB and shows success.

i have my Business layers and data access layers compiled into dll's and added reference to the main project. Is this the issue? but my other server (windows server 2003) had the same running for 4 years without any problems.

can anybody please help me.

No matching constructor found on type 'Session.Resources.Strings'. You can use the Arguments or FactoryMethod directives to construct this type.

$
0
0

I've got a strange problem with Visual Studio 2010 (4.0.30319 SP1 Rel) and not even sure where to start on it.

I've got a fairly simple WPF solution, that doesn't do anything out of the ordinary (MVVM Light, Moq, SVN, System.Diagnostics.Contracts, etc.), but every once in a while I get the following compiler error.

No matching constructor found on type 'Session.Resources.Strings'. You can use the Arguments or FactoryMethod directives to construct this type.

For some reason, it can't find the constructor of the generated code for my resx.  I am using the PublicResXFileCodeGenerator.  Usually, I have to do a full rebuild to make the problem go away.  When I look in SVN, it doesn't look like the file has changed.  It also doesn't seem to be affected by whether I actually add something to the resx or not.  I've included the generated code, just so you can see the constructor, which is Internal (not public like I would have expected), but should be fine.  I've been living with this for a month, but I'm hoping somebody knows of a workaround.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.586
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Session.Resources {
    using System;
    
    
    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Strings {
        
        private static global::System.Resources.ResourceManager resourceMan;
        
        private static global::System.Globalization.CultureInfo resourceCulture;
        
        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Strings() {
        }
        
        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Session.Resources.Strings", typeof(Strings).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }


Working at Jonas Software

Generate Hexadecimal digest for an SHA512 hash.

$
0
0

Hello and thank you for having a look at my question.

Today I have begun playing around with System::Security::Cryptography and have been trying to generate a hexadecimal digest for an SHA512 hash, but I can't seem to find a single piece of documentation regarding such matters, let alone much information on the System::Security::Cryptography digests that are available for use.

I have used the example available in the MSDN documentation library for system.security.cryptography.sha1 (I can't post links as my account isn't verified...) to generate my hash, but I am finding it hard to find a solution to my issue.

I hope someone has some experience in this area.

Thanks in advance.

Jai.

Is it possible my application is loading NativeImage and JIT versions of dll's?

$
0
0

When looking at my application startup with Fusion, I see the same dll seemingly loaded multiple times:

From the 'default' pane of fusion logger:

*** Assembly Binder Log Entry  (06/05/2013 @ 6:56:56 PM) ***

The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  F:\src\main\3dswin\bin\x64\Release\3dsmax.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: User = ADS\taylorst
LOG: DisplayName = PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
 (Fully-specified)
LOG: Appbase = file:///F:/src/main/3dswin/bin/x64/Release/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = 3dsmax.exe
Calling assembly : WPFToolkit, Version=3.5.40128.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: F:\src\main\3dswin\bin\x64\Release\3dsmax.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Version redirect found in framework config: 3.0.0.0 redirected to 4.0.0.0.
LOG: Post-policy reference: PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: Binding succeeds. Returns assembly from C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework\v4.0_4.0.0.0__31bf3856ad364e35\PresentationFramework.dll.
LOG: Assembly is loaded in default load context.

--------------------------------------------------------------------------------------------------------------

From the Native pane:

*** Assembly Binder Log Entry (06/05/2013 @ 6:55:33 PM) *** The operation was successful. Bind result: hr = 0x0. The operation completed successfully. Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll Running under executable F:\src\main\3dswin\bin\x64\Release\3dsmax.exe --- A detailed error log follows. === Pre-bind state information === LOG: User = ADS\taylorst LOG: DisplayName = PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (Fully-specified) LOG: Appbase = file:///F:/src/main/3dswin/bin/x64/Release/ LOG: Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache Base = NULL LOG: AppName = 3dsmax.exe Calling assembly : ManagedServices, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null. === LOG: Start validating all the dependencies.
<log emitted for brevity...>

LOG: [Level 1]Start validating IL dependency Accessibility, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. Native image has correct version information. LOG: Validation of dependencies succeeded. LOG: Bind to native image succeeded. Attempting to use native image C:\Windows\assembly\NativeImages_v4.0.30319_64\Presentatio5ae0f00f#\b686a51f20097a3a518cdc9d6730c1c2\PresentationFramework.ni.dll. Native image successfully used.

Is this a problem?  Could it be a glitch in Fusion Logger?  Would this be contributing to a slower startup time?

I am struggling to pass array of Struct from c # to Fortran. Please provide if any body has sample code for this.

$
0
0
I have been struggling to pass struct array from C# to Fortran. Please can someone provide me sample code. 

Getting error CLR20r3 on previous working application

$
0
0

Hi, I have a VB application which will not run on a W2008R2 terminal server but works fine on other PCs. This application ran fine till recently. All PCs run the application from a common network directory.

The application was originally compiled to .NET 2.0 & worked on all platforms. Then I recompiled it to .NET 4.0. There were various issues on the other PCs so I took it back to .NET 2.0.

Now on trying to start it on the server I get "The application has stopped working" with a CLR20r3 error. Google seems to imply this is a .NET problem.

I have removed .NET 4 - no change & reinstalled it again - no change. Tried to reinstall .NET 2 but I get an error saying it's part of the operating system..

Any thoughts?


System.ComponentModel.Win32Exception "Access Denied" retrieving process information as local admin using impersonation

$
0
0

Hi everyone.

I am encountering an issue when trying to get other processes informations from my app. This app is an "updater". When it starts, it checks if the process to update is running. And here is the issue. Some informations on the running processes throw a System.ComponentModel.Win32Exception "Access denied" Exception. I was able to understand the reason of the exception : the updater is lauched from a "user" account and the user cannot read other user's processes. Because the updater runs in a Terminal Service session, other users may have the app to update running. If that is the case, the updater should warn the user, but instead of doing it, it crashes when reader the running process info.

After reading a lot about over the internet, I decided to use impersonation to execute the updater so that it will execute as a different account. Because the updater must access a network share, I set a domain administrator account.

The code runs fine, the impersonation works, but the exception is still there, even when the the code is executed with the domain admin account. I also tried to put the domain admin account in the local "Administrators" group.

So... I don't understand what is going wrong...

Can you help me please ?

(The updater runs on a Windows Server 2003 x86, the .NET framework is the 3.5)

Here is the simplified code that trows the exception :

WrapperImpersonationContext c = new WrapperImpersonationContext("MyDomain", "MyDomainAdmin", "MyPassword") ;

int errorCode = 0 ;

c.Enter(out errorCode) ; // Impersonation...

Console.WriteLine(Environment.UserName) ; // = MyDomainAdmin, Impersonation OK!

// Looking for running process called "test". It may return mine or other users processes

Process[] ret = Process.GetProcessesByName("test"); List<Process> retList = new List<Process>(); for(int i = 0; i < ret.Length; i++) {

// The process here is a process that belongs to another user, that's why I get an exception FileInfo fi = new FileInfo(ret[i].MainModule.FileName); // System.ComponentModel.Win32Exception!!! Access denied on MainModule... }


Here is theWrapperImpersonationContext class code :

using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; using System.ComponentModel; namespace Common.ApplicationUpdater { public class WrapperImpersonationContext { [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); private const int LOGON32_PROVIDER_DEFAULT = 0; private const int LOGON32_LOGON_INTERACTIVE = 2; private string m_Domain; private string m_Password; private string m_Username; private IntPtr m_Token; private WindowsImpersonationContext m_Context = null; protected bool IsInContext { get { return m_Context != null; } } public WrapperImpersonationContext(string domain, string username, string password) { m_Domain = domain; m_Username = username; m_Password = password; } [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public bool Enter(out int errorCode) { errorCode = 0; if(this.IsInContext) return true; m_Token = new IntPtr(0); try { m_Token = IntPtr.Zero; bool logonSuccessfull = LogonUser( m_Username, m_Domain, m_Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref m_Token); if(logonSuccessfull ) { WindowsIdentity identity = new WindowsIdentity(m_Token); m_Context = identity.Impersonate(); } else { errorCode = Marshal.GetLastWin32Error(); return false; } return true; } catch(Exception ex) { errorCode = (int) Marshal.GetHRForException(ex); return false; } } [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public void Leave() { if(this.IsInContext == false) return; m_Context.Undo(); if(m_Token != IntPtr.Zero) CloseHandle(m_Token); m_Context = null; } }

}

Thank you for helping me!

Best regards.


Matteo, .NET Developer and System Engineer




Custom role provider in a console application

$
0
0

Hello,

I have written a role provider which assumes Windows authentication and so far works well with WCF services and ASP.NET. Is it possible to use it also with a console/WPF/WinForm applications? I tried a configuration like this on a very simple console app but the Initialize method of the provider doesn't even get called. Below is my app.config. Thanks in advance.

<configuration><system.web><authentication mode="Windows" /><roleManager enabled="true"
                     defaultProvider="Authorization.RoleProvider"><providers><clear/><add name="Authorization.RoleProvider"
                     type="Authorization.RoleProvider, Authorization.RoleProvider"
                     applicationName="urn:AuthorizationDemo:Program"
                     authorizationServiceUrl="net.pipe://localhost/Authorization/Authorization.svc"/></providers></roleManager></system.web></configuration>


Thanks Val

Custom code access permission throws SecurityException with message “Failure decoding embedded permission set object.”

$
0
0

Hello,

We have a pretty elaborate authorization system which requires the use of a custom permission somewhat similar to PrincipalPermission. I followed all suggestions on MSDN and looked at the code of PrincipalPermission and yet I have a pretty stubborn problem: if I declare the permission on the class level with one parameter and then I declare it on one of the methods with different (more specific) parameter the code access security builds a union of the two and calls Demand on it. My implementation of Demand returns with no exception and yet the system throws SecurityException with the cryptic message "Failure decoding embedded permission set object." What does it mean? I see all sorts of calls to my permission, includin ToXml and FromXml and I think that they all behave properly (or at least do not fail). Can someone out there think of what might be missing or done wrong here. Below is the code of the permission class (thanks in advance to anyone who will give it a thought):

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.ServiceModel;
using System.Threading;
using Authorization.DataContracts;
namespace Authorization
{
    [Serializable]
    public sealed class AuthorizationPermission : IPermission, IUnrestrictedPermission, ISerializable, IEquatable<AuthorizationPermission>
    {
        List<string> _activityIdentifiers = new List<string>();
        public AuthorizationPermission()
        {
        }
        public AuthorizationPermission(PermissionState state)
        {
            if (state == PermissionState.Unrestricted)
                _activityIdentifiers.Add(string.Empty);
        }
        public AuthorizationPermission(string activityIdentifier, bool unrestricted = false)
        {
            if (!unrestricted && string.IsNullOrWhiteSpace(activityIdentifier))
                throw new ArgumentNullException("activityIdentifier");
            if (unrestricted)
                _activityIdentifiers.Add(string.Empty);
            else
                _activityIdentifiers.Add(activityIdentifier);
        }
        protected AuthorizationPermission(SerializationInfo info, StreamingContext context)
        {
            var count = info.GetInt32("activityIdentifiersCount");
            for (var i=0; i<count; i++)
                _activityIdentifiers.Add(info.GetString("activityIdentifier_"+i));
        }
        public static bool HasPermission(string protectedIdentifier)
        {
            try
            {
                var auth = AuthorizationCache.GetAuthorization(Thread.CurrentPrincipal.Identity.Name, protectedIdentifier);
                return auth.Granted;
            }
            catch (CommunicationException)
            {
                return false;
            }
        }
        public bool Equals(AuthorizationPermission other)
        {
            if (ReferenceEquals(other, null))
                return false;
            if (ReferenceEquals(this, other))
                return true;
            return _activityIdentifiers.SequenceEqual(other._activityIdentifiers, StringComparer.OrdinalIgnoreCase);
        }
        public override bool Equals(object obj)
        {
            return Equals(obj as AuthorizationPermission);
        }
        public override int GetHashCode()
        {
            var hashCode = 53;
            foreach (var id in _activityIdentifiers)
                hashCode = 17 * hashCode + id.ToUpperInvariant().GetHashCode();
            return hashCode;
        }
        public static bool operator==(AuthorizationPermission left, AuthorizationPermission right)
        {
            return ReferenceEquals(left, null) 
                        ? ReferenceEquals(right, null) 
                        : left.Equals(right);
        }
        public static bool operator!=(AuthorizationPermission left, AuthorizationPermission right)
        {
            return !(left==right);
        }
        public override string ToString()
        {
            return ToXml().ToString();
        }
        public bool IsUnrestricted()
        {
            return _activityIdentifiers.All(id => string.IsNullOrWhiteSpace(id));
        }
        public IPermission Copy()
        {
            return new AuthorizationPermission
            {
                _activityIdentifiers = this._activityIdentifiers.ToList(),
            };
        }
        public void Demand()
        {
            if (IsUnrestricted())
                return;
            if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
                throw new SecurityException("The principal's identity is not authenticated.", GetType());
            if (!_activityIdentifiers.Any())
                throw new SecurityException("Access is denied.", GetType());
            AuthorizationDto auth = null;
            try
            {
                foreach (var id in _activityIdentifiers)
                {
                    if (string.IsNullOrWhiteSpace(id))
                        continue;
                    auth = AuthorizationCache.GetAuthorization(Thread.CurrentPrincipal.Identity.Name, id);
                    if (auth==null)
                        ThrowSecurityException("Access is denied.");
                    if (!auth.Granted)
                        ThrowSecurityException("Access is denied. " + auth.Message);
                }
            }
            catch (CommunicationException x)
            {
                throw new SecurityException("Access is denied.", x);
            }
        }
        void ThrowSecurityException(string message)
        {
            AssemblyName assemblyName = null;
            Evidence evidence = null;
            try
            {
                var callingAssembly = Assembly.GetCallingAssembly();
                assemblyName = callingAssembly.GetName();
                if (callingAssembly != Assembly.GetExecutingAssembly())
                    evidence = callingAssembly.Evidence;
            }
            catch (SecurityException)
            {
            }
            throw new SecurityException(
                        message,
                        assemblyName,
                        null,
                        null,
                        null,
                        SecurityAction.Demand,
                        this,
                        this,
                        evidence);
        }
        public IPermission Intersect(IPermission target)
        {
            var targetPermission = target as AuthorizationPermission;
            if (targetPermission == null)
                return null;
            if (IsUnrestricted())
                return targetPermission.Copy();
            if (targetPermission.IsUnrestricted())
                return Copy();
            var intersection = _activityIdentifiers.Intersect(targetPermission._activityIdentifiers, StringComparer.OrdinalIgnoreCase).ToList();
            if (!intersection.Any())
                return null;
            var result = new AuthorizationPermission
            {
                _activityIdentifiers = intersection,
            };
            return result;
        }
        public IPermission Union(IPermission target)
        {
            var targetPermission = target as AuthorizationPermission;
            if (targetPermission == null || IsUnrestricted())
                return Copy();
            if (targetPermission.IsUnrestricted())
                return targetPermission.Copy();
            var result = new AuthorizationPermission
            {
                _activityIdentifiers = _activityIdentifiers.Union(targetPermission._activityIdentifiers, StringComparer.OrdinalIgnoreCase).ToList(),
            };
            return result;
        }
        public bool IsSubsetOf(IPermission target)
        {
            var targetPermission = target as AuthorizationPermission;
            if (targetPermission == null)
                return false;
            if (targetPermission.IsUnrestricted())
                return true;
            if (IsUnrestricted())
                return false;
            var intersection = _activityIdentifiers.Intersect(targetPermission._activityIdentifiers, StringComparer.OrdinalIgnoreCase);
            return _activityIdentifiers.Count() == intersection.Count();
        }
        public void FromXml(SecurityElement e)
        {
            if (e == null)
                throw new ArgumentNullException("e");
            _activityIdentifiers = new List<string>();
            foreach (var ids in e.Children)
            {
                var identifiers = ids as SecurityElement;
                if (identifiers != null &&
                    identifiers.Tag == "activityIdentifiers")
                {
                    foreach (var id in identifiers.Children)
                    {
                        var identifier = id as SecurityElement;
                        if (identifier != null &&
                            identifier.Tag == "add")
                            _activityIdentifiers.Add(identifier.Text);
                    }
                    break;
                }
            }
        }
        public SecurityElement ToXml()
        {
            var element = new SecurityElement("IPermission");
            var nameComponents = GetType().AssemblyQualifiedName.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var className = string.Format(CultureInfo.InvariantCulture, "{0}, {1}", nameComponents[0], nameComponents[1]);
            element.AddAttribute("class", className);
            element.AddAttribute("version", "1");
            var activityIdentifiersElement = new SecurityElement("activityIdentifiers");
            foreach (var id in _activityIdentifiers)
                activityIdentifiersElement.AddChild(
                    new SecurityElement("add", SecurityElement.Escape(id)));
            element.AddChild(activityIdentifiersElement);
            return element;
        }
        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException("info");
            info.AddValue("activityIdentifiersCount", _activityIdentifiers.Count());
            for (var i=0; i<_activityIdentifiers.Count(); i++)
                info.AddValue("activityIdentifier_"+i, _activityIdentifiers.ElementAt(i));
        }
    }
}


Thanks Val

The exception 'System.OutOfMemoryException'

$
0
0

System Specification - Windows 7 [ 64 Bit ]

"APPLICATION" - Its Running as a 32 Bit Application in Same Environment

Build -  " APPLICATION " - Its Build on 32 bit machine with visual studio 2002 & Running on the Above Mentioned System i.e. 64 Bit Windows 7

This exception comes when i Try to open one of the windows form of MyApplication, while rest of the forms are not showing such trait.

RAM - 3966 MB

VM   - 5949 MB

At The Time Of Crash 

RAM - 1595 MB

************** Exception Text **************
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Windows.Forms.UnsafeNativeMethods.GetWindowText(HandleRef hWnd, StringBuilder lpString, Int32 nMaxCount)
at System.Windows.Forms.Control.get_WindowText()
at System.Windows.Forms.Control.set_CacheTextInternal(Boolean value)
at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args)
at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty)
at System.Windows.Forms.Layout.LayoutTransaction.DoLayout(IArrangedElement elementToLayout, IArrangedElement elementCausingLayout, String property)
at System.Windows.Forms.Control.OnResize(EventArgs e)
at System.Windows.Forms.Control.OnSizeChanged(EventArgs e)
at System.Windows.Forms.Control.UpdateBounds(Int32 x, Int32 y, Int32 width, Int32 height, Int32 clientWidth, Int32 clientHeight)
at System.Windows.Forms.Control.UpdateBounds()
at System.Windows.Forms.Control.WmWindowPosChanged(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.AxHost.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
Application
Assembly Version: 1.0.4885.30511
Win32 Version: 1.0.4885.30511
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/Application.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Data
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_32/System.Data/2.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
Microsoft.VisualBasic
Assembly Version: 8.0.0.0
Win32 Version: 8.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualBasic/8.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll
----------------------------------------
Routines
Assembly Version: 1.0.4885.30509
Win32 Version: 1.0.4885.30509
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/Routines.DLL
----------------------------------------
Csd
Assembly Version: 1.0.4885.30508
Win32 Version: 1.0.4885.30508
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/Csd.DLL
----------------------------------------
System.Xml
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Transactions
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_32/System.Transactions/2.0.0.0__b77a5c561934e089/System.Transactions.dll
----------------------------------------
System.EnterpriseServices
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_32/System.EnterpriseServices/2.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll
----------------------------------------
System.Configuration
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
Interop.Word
Assembly Version: 8.3.0.0
Win32 Version: 8.3.0.0
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/Interop.Word.DLL
----------------------------------------
AxInterop.MSComctlLib
Assembly Version: 2.0.0.0
Win32 Version: 2.0.0.0
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/AxInterop.MSComctlLib.DLL
----------------------------------------
AxInterop.SHDocVw
Assembly Version: 1.1.0.0
Win32 Version: 1.1.0.0
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/AxInterop.SHDocVw.DLL
----------------------------------------
AxInterop.MSFlexGridLib
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/AxInterop.MSFlexGridLib.DLL
----------------------------------------
Interop.SHDocVw
Assembly Version: 1.1.0.0
Win32 Version: 1.1.0.0
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/Interop.SHDocVw.DLL
----------------------------------------
Accessibility
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Accessibility/2.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------
mscomctl
Assembly Version: 10.0.4504.0
Win32 Version: 10.0.4504
CodeBase: file:///C:/Windows/assembly/GAC/mscomctl/10.0.4504.0__31bf3856ad364e35/mscomctl.dll
----------------------------------------
Interop.MSComctlLib
Assembly Version: 2.0.0.0
Win32 Version: 2.0.0.0
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/Interop.MSComctlLib.DLL
----------------------------------------
Interop.MSFlexGridLib
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Program%20Files%20(x86)/APPLICATION/ApplicationGUI/Interop.MSFlexGridLib.DLL
----------------------------------------
System.Web
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
CodeBase: file:///C:/Windows/assembly/GAC_32/System.Web/2.0.0.0__b03f5f7f11d50a3a/System.Web.dll
----------------------------------------

.Net assemblies not properly signed by microsoft

$
0
0

I am trying to validate the signature of the calling assemblies in my application.

One of the steps I am taking is verifying the calling assemblies are properly signed, using this:

[DllImport("mscoree.dll", CharSet = CharSet.Unicode)]
private static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool pfWasVerified);

For the most part this has been fine, but when my application runs as a windows service, these two assemblies report as unsigned:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll

C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceProcess\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.ServiceProcess.dll

So, they have public key tokens, but it is as if they were only Delay signed?

Does anyone have any insight as to why this would be? Thank you.

Edit: I am calling it like so:

var unusedVerify = false;
if (!StrongNameSignatureVerificationEx(assembly.Location, true, ref unusedVerify))
{
  throw new UnauthorizedAccessException("unsigned");
}

CLR

String Comparision

$
0
0

What is the fastest way to check the Equality of strings in .Net?

As per msdn we need to Explicitly use stringcomparision.ordinal to have a increase speed,
but it seems to be wrong in this case.

Without ordinal:

            time = Stopwatch.GetTimestamp();
            if (str.Equals("Hi"))
            {
                Console.WriteLine(true);
            }
            else
            {
                Console.WriteLine(false);
            }
            Console.WriteLine("The time taken = {0}", (Stopwatch.GetTimestamp() - time));

//With ordinal:

           time = Stopwatch.GetTimestamp();
            if (str.Equals("Hi",StringComparison.Ordinal))
            {
                Console.WriteLine(true);
            }
            else
            {
                Console.WriteLine(false);
            }
            Console.WriteLine("The time taken = {0}", (Stopwatch.GetTimestamp() - time));

The output was : 2934 for (i)
                             2646 for (ii)

Can anyone explain?


Error in Windows Service - The process was terminated due to an internal error in the .NET Runtime at IP 792EC7DD (79140000) with exit code 80131506.

$
0
0

Hi,

We got this error on a preproduction environment, on a windows service that was previously running in a stable fashion.

This crashed the service causing an outage.

Found this KB

http://support.microsoft.com/kb/2640103

But the fault address is slightly different.

Can someone confirm this is the same issue and whether we should apply the hotfix.

If not.. any suggestions on options?

Event Type:	Error
Event Source:	.NET Runtime
Event Category:	None
Event ID:	1023
Date:		23/05/2013
Time:		12:46:51
User:		N/A
Computer:	<<removed>>
Description:
Application: <<removed>>.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an internal error in the .NET Runtime at IP 792EC7DD (79140000) with exit code 80131506.


For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

Event Type:	Error
Event Source:	.NET Runtime 4.0 Error Reporting
Event Category:	None
Event ID:	1000
Date:		23/05/2013
Time:		12:46:54
User:		N/A
Computer:	<<removed>>
Description:
Faulting application <<removed>>., version 1.0.0.0, stamp 51963d28, faulting module clr.dll, version 4.0.30319.296, stamp 50484aa9, debug? 0, fault address 0x001ac7dd.

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Data:
0000: 41 00 70 00 70 00 6c 00   A.p.p.l.
0008: 69 00 63 00 61 00 74 00   i.c.a.t.
0010: 69 00 6f 00 6e 00 20 00   i.o.n. .
0018: 46 00 61 00 69 00 6c 00   F.a.i.l.
0020: 75 00 72 00 65 00 20 00   u.r.e. .

<<removed>>

00a8: 2e 00 20 00 31 00 2e 00   .. .1...
00b0: 30 00 2e 00 30 00 2e 00   0...0...
00b8: 30 00 20 00 35 00 31 00   0. .5.1.
00c0: 39 00 36 00 33 00 64 00   9.6.3.d.
00c8: 32 00 38 00 20 00 69 00   2.8. .i.
00d0: 6e 00 20 00 63 00 6c 00   n. .c.l.
00d8: 72 00 2e 00 64 00 6c 00   r...d.l.
00e0: 6c 00 20 00 34 00 2e 00   l. .4...
00e8: 30 00 2e 00 33 00 30 00   0...3.0.
00f0: 33 00 31 00 39 00 2e 00   3.1.9...
00f8: 32 00 39 00 36 00 20 00   2.9.6. .
0100: 35 00 30 00 34 00 38 00   5.0.4.8.
0108: 34 00 61 00 61 00 39 00   4.a.a.9.
0110: 20 00 66 00 44 00 65 00    .f.D.e.
0118: 62 00 75 00 67 00 20 00   b.u.g. .
0120: 30 00 20 00 61 00 74 00   0. .a.t.
0128: 20 00 6f 00 66 00 66 00    .o.f.f.
0130: 73 00 65 00 74 00 20 00   s.e.t. .
0138: 30 00 30 00 31 00 61 00   0.0.1.a.
0140: 63 00 37 00 64 00 64 00   c.7.d.d.
0148: 0d 00 0a 00               ....    



Where does .NET store its data?

$
0
0

[Newbie alert]

I am developing my 1st. .NET application, myApp.exe which was having an awful performance. After learning about .NET profilers, I narrowed down the problem to a long-running function, part of the OpenXML SDK. The diagnosis was that about 90% of the time was being wasted on "JIT overhead".

My next interesting discovery was NGEN which (I assumed) would compile the myApp.exe executable and replace it with speedier version. Much to my surprise (I checked the MD5sum before and after: they are identical) NGEN absconded with the "compiled" version of my app, and that of a critical component:DocumentFormat.OpenXML.

Here's the remarkable result:

Being curious by nature, I checked under the (newly discovered) directory \Windows\Microsoft.NET and found out that the only evidence of NGEN's handy work was a ngen.log file.

I also discovered that any identical copy (in the MD5sum sense) of the executable will execute very fast, but if I rebuild the executable (with identical source files) it will not be "recognized" and will perform very slowly again: such is the nature of NGEN's blessing.

Could a kind expert clarify what is going on behind the curtains?

TIA,

-Travis

Bad Image format

$
0
0

Hi guyz

When I compiled ILASM Code to exe file My code is

.method static void main()
{
    .entrypoint
    .maxstack 1

    ldstr "Hello world!"
    call void [mscorlib]System.Console::WriteLine(string)

    ret
}

I used commandline from Visual Studio Command Prompt "ilasm myfile"

It generates EXE file but when I execute it i get this error


Unhandled Exception: System.BadImageFormatException: Could not load file or asse
mbly 'code.exe' or one of its dependencies. The module was expected to contain a
n assembly manifest.

Can you please help me why i am getting this error. Because i am new to ILASM


---------------------Do the Impossible--------------------- Great Software at http://atosoft.webs.com/

DynamicMethod disassembling

$
0
0

I'm currently evaluating the power of DynamicMethod to create an environment that based on user input can create more or less volatile methods.

The user input finally forming these methods may be buggy and throw exceptions.

There's a ton of questions that arise from this fact since it virtually seems to be impossible to support users where their error is. I would like to know how Dynamic method compilation internally works and what exactly the reasons are for omitting tables containing IL to native sequence point mappings in the .NET framework when working with dynamic methods.

I've also been experimenting with dynamic types concerning the scenario and found it unlikely that we can use them. Reason 1 is that the customer induced hosting platform for the project may not even support .NET 4.0, so getting rid again of the method code may be virtually impossible. Running different Appdomains is out of the question because of performance reasons. Reason 2: The memory overhead induced by loading tons of dynamic assemblies (and in worst case additionally AppDomains even) would kill the project anyway, since the dynamically generated code may be long living.

When evaluating the possibilities, I also noticed that is is impossible to step into the native machine code generated by the JIT-compiler for a dynamic method. I. e. you can't even have a look at the code you just generated from the IL you emitted. Why is that so?

Furthermore, emitting the same IL through ILGenerators from DynamicMethod and a MethodBuilder seems to lead to different byte code. The differences seem to be in the encoding of addresses for methods we called from within the emitted IL (In a test simply Console.WriteLine - two different encodings for the same OpCodes.Call). That was where I really lost it. I would like to have more information about what is happening there and why this should be the case at all.

The best way to realize the planned environment would be to precompile the dynamic method code just as the IL byte-array and serialize it to disk (or maybe even put it in a database) and only recompile when the user input file has changed. When the functionality is needed, the dynamicmethod would be quickly instantiated from the saved IL-byte-array. However, regarding the aforementioned issue, I am quite uncertain whether that would work. If the method addresses change on a restart of the environment, things would simply break. What do the emitted addresses depend on? The loaded assemblies? Their order of loading?

Next question: Is there a guarantee that the JITted code for a static 'DynamicType' method (generated by a MethodBuilder (maybe even with sequence points)) and a (also static) DynamicMethod will be the same if they based on the same IL code? Is there a possibility to access the Native-to-IL mapping of the MethodBuilder method? If so, this could be a workaround to map the native offset when an exception occurs (the only information you seem to be able to obtain for an exception in a DynamicMethod) to the IL that was generated.

I would appreciate direct feedback from Microsoft clarifying these points.

Following is some example code we used for evaluation:

using System;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;


namespace test
{
    class MainClass
    {
        internal delegate int callconv(int i);

        public static void Main(string[] args)
        {
            try
            {
                Assembly asm = AppDomain.CurrentDomain.GetAssemblies()[0];
                Module mod = asm.GetModules()[0];
                AssemblyBuilder asmb = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("test"), AssemblyBuilderAccess.RunAndSave);
                ModuleBuilder modb = asmb.DefineDynamicModule("test", @"TestAssembly.dll", true);
                ISymbolDocumentWriter doc = modb.DefineDocument(@"F:\fantasy\path\mymodule.xlg", Guid.Empty, Guid.Empty, Guid.Empty);
                TypeBuilder typb = modb.DefineType("test");
                MethodBuilder mb = typb.DefineMethod("tesmeth", MethodAttributes.Static | MethodAttributes.Public,
                            CallingConventions.Standard, typeof(int), new Type[] { typeof(int) });
                DynamicMethod x = new DynamicMethod("test", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(int), new Type[] { typeof(int) }, modb, true);
                MethodInfo writelineint = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string), typeof(object) });
                ILGenerator ilg = x.GetILGenerator();
                //ilg.MarkSequencePoint(doc, 1, 2, 1, 32);
                ilg.Emit(OpCodes.Ldc_I4_4);
                ilg.Emit(OpCodes.Ldarg_0);
                ilg.Emit(OpCodes.Ldc_I4_2);
                ilg.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) }));
                ilg.Emit(OpCodes.Ldc_I4_3);
                ilg.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) }));
                //ilg.MarkSequencePoint(doc, 5, 2, 5, 32);
                ilg.Emit(OpCodes.Div);
                //ilg.MarkSequencePoint(doc, 7, 2, 7, 32);
                ilg.Emit(OpCodes.Box, typeof(int));
                ilg.Emit(OpCodes.Starg, 0);
                ilg.Emit(OpCodes.Ldstr, String.Intern("testres={0}"));
                ilg.Emit(OpCodes.Ldarg_0);
                ilg.Emit(OpCodes.Call, writelineint);
                ilg.Emit(OpCodes.Ldarg_0);
                ilg.Emit(OpCodes.Unbox, typeof(int));
                ilg.Emit(OpCodes.Ldobj, typeof(int));
                ilg.Emit(OpCodes.Ret);
                FieldInfo ilpropCode = ilg.GetType().GetField("m_ILStream", BindingFlags.Instance | BindingFlags.NonPublic);
                FieldInfo ilpropCodeLength = ilg.GetType().GetField("m_length", BindingFlags.Instance | BindingFlags.NonPublic);
                byte[] bytes = (byte[])ilpropCode.GetValue(ilg);
                int length = (int)ilpropCodeLength.GetValue(ilg);
                byte[] byIL = new byte[length];
                Array.Copy(bytes, byIL, length);
                object[] ats = x.GetCustomAttributes(true);

                callconv meth = (callconv)(x.CreateDelegate(typeof(callconv)));
                meth(2);
                Console.WriteLine("exec: {0}", meth(1));  // change to 0 here to get an exception for the dynamic method

                mb.DefineParameter(1, ParameterAttributes.In, "invalue");
                ilg = mb.GetILGenerator();
                ilg.MarkSequencePoint(doc, 2, 2, 2, 32);
                ilg.Emit(OpCodes.Ldc_I4_4);
                ilg.MarkSequencePoint(doc, 3, 2, 3, 32);
                ilg.Emit(OpCodes.Ldarg_0);
                ilg.Emit(OpCodes.Ldc_I4_2);
                ilg.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) }));
                ilg.Emit(OpCodes.Ldc_I4_3);
                ilg.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) }));
                ilg.MarkSequencePoint(doc, 5, 2, 5, 32);
                ilg.Emit(OpCodes.Div);
                ilg.MarkSequencePoint(doc, 7, 2, 7, 32);
                ilg.Emit(OpCodes.Box, typeof(int));
                ilg.Emit(OpCodes.Starg, 0);
                ilg.Emit(OpCodes.Ldstr, String.Intern("testres={0}"));
                ilg.Emit(OpCodes.Ldarg_0);
                ilg.Emit(OpCodes.Call, writelineint);
                ilg.Emit(OpCodes.Ldarg_0);
                ilg.Emit(OpCodes.Unbox, typeof(int));
                ilg.Emit(OpCodes.Ldobj, typeof(int));
                ilg.Emit(OpCodes.Ret);

                //mb.CreateMethodBody(byIL, byIL.Length);  // this will fail horribly
                Type typ = typb.CreateType();

                ilpropCode = ilg.GetType().GetField("m_ILStream", BindingFlags.Instance | BindingFlags.NonPublic);
                ilpropCodeLength = ilg.GetType().GetField("m_length", BindingFlags.Instance | BindingFlags.NonPublic);
                bytes = (byte[])ilpropCode.GetValue(ilg); // x.GetMethodBody().GetILAsByteArray(); // (byte[])getter.Invoke(d, null);
                length = (int)ilpropCodeLength.GetValue(ilg);
                byte[] byIL2 = new byte[length];
                Array.Copy(bytes, byIL2, length);

                if (!System.Linq.Enumerable.SequenceEqual<byte>(byIL, byIL2))
                {
                    Console.WriteLine("Code still differs!");
                }
                else
                {
                    Console.WriteLine("Equal code.");
                }

                MethodInfo mi = typ.GetMethod("tesmeth");

                callconv meth2 = (callconv)Delegate.CreateDelegate(typeof(callconv), mi);
                meth2(2);
                ats = meth2.Method.GetCustomAttributes(true);
                foreach (object o in ats)
                {
                    Console.WriteLine(o.ToString());
                }
                Console.WriteLine("exec2: {0}", meth2(0));


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                StackTrace trc = new StackTrace(ex, true);
                StackFrame sf = trc.GetFrames()[0];

                Console.WriteLine("meth:{2}, nat:{0}, il:{1}", sf.GetNativeOffset(), sf.GetILOffset(), sf.GetMethod().Name);
            }

            Console.ReadKey(true);
        }
    }
}




Application Hang When Call System.Runtime.InteropServices.GCHandle.Free()

$
0
0

In Device.Service.exe__PID__324__Date__04_26_2013__Time_10_40_01AM__291__Manual Dump.dmp GC is running in this process.The Thread that triggered the GC is 108

The following threads in Device.Service.exe__PID__324__Date__04_26_2013__Time_10_40_01AM__291__Manual Dump.dmp are waiting for .net garbage collection to finish. Thread 108 triggered the garbage collection.The gargage collector thread wont start doing its work till the time the threads which have pre-emptive GC disabled have finished executing. The following threads havepre-emptive GC disabled 9,12,135,136,141,142,143,146,149,150,151,

 

And Thread "12,135,136,141,142,143,146,149,150,151" is waiting thread "9"

 

Critical Section    0x00551448 

Lock State   Locked

Lock Count   1

Recursion Count   1

Entry Count   0

Contention Count   11

Spin Count   0

Owner Thread   108

Owner Thread System ID   5916

 

 

Critical Section    0x005532c0 

Lock State   Locked

Lock Count   10

Recursion Count   1

Entry Count   0

Contention Count   11

Spin Count   0

Owner Thread   9

Owner Thread System ID   4604

        

        

Thread 9 - System ID 4604

Entry point      0x00000000

Create time    2013-4-26 10:00:27

Time spent in user mode       0 Days 00:00:00.500

Time spent in kernel mode     0 Days 00:00:00.484

 

 

.NET Call Stack

Function

System.Runtime.InteropServices.GCHandle.InternalFree(IntPtr)

System.Runtime.InteropServices.GCHandle.Free()

System.Net.Sockets.SocketAsyncEventArgs.FreeOverlapped(Boolean)

System.Net.Sockets.SocketAsyncEventArgs.Dispose()

NLog.Internal.NetworkSenders.UdpNetworkSender.SocketOperationCompleted(System.Object, System.Net.Sockets.SocketAsyncEventArgs)

System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(System.Net.Sockets.SocketAsyncEventArgs)

System.Net.Sockets.SocketAsyncEventArgs.ExecutionCallback(System.Object)

System.Threading.ExecutionContext.runTryCode(System.Object)

System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)

System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)

System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)

System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)

System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError, Int32, System.Net.Sockets.SocketFlags)

System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)

System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)

 

Full Call Stack

Function          Source

ntdll!NtDelayExecution+15   

KERNELBASE!SleepEx+65      

clr!__DangerousSwitchToThread+48    

clr!__SwitchToThread+12      

clr!SpinUntil+3a     

clr!SyncTransferCacheHandles+34        

clr!TableQuickRebalanceCache+59       

clr!TableCacheMissOnFree+67     

clr!TableFreeSingleHandleToCache+56          

clr!HndDestroyHandle+9d    

clr!HndDestroyHandleOfUnknownType+19  

clr!DestroyTypedHandle+16

clr!MarshalNative::GCHandleInternalFree+ca     

System.Runtime.InteropServices.GCHandle.Free()      

System.Net.Sockets.SocketAsyncEventArgs.FreeOverlapped(Boolean)      

System.Net.Sockets.SocketAsyncEventArgs.Dispose()         

System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(System.Net.Sockets.SocketAsyncEventArgs)         

System.Net.Sockets.SocketAsyncEventArgs.ExecutionCallback(System.Object)        

System.Threading.ExecutionContext.runTryCode(System.Object)      

clr!CallDescrWorker+33         

clr!CallDescrWorkerWithHandler+8e   

clr!MethodDesc::CallDescr+194  

clr!MethodDesc::CallTargetWorker+21        

clr!MethodDescCallSite::CallWithValueTypes+1c         

clr!ExecuteCodeWithGuaranteedCleanupHelper+bb   

clr!ReflectionInvocation::ExecuteCodeWithGuaranteedCleanup+138        

System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)     

System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)        

System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError, Int32, System.Net.Sockets.SocketFlags)

System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)      

System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)        

clr!CallDescrWorker+33         

clr!CallDescrWorkerWithHandler+8e   

clr!DispatchCallBody+20       

clr!DispatchCallDebuggerWrapper+75         

clr!DispatchCallNoEH+53      

clr!BindIoCompletionCallBack_Worker+c1   

clr!Thread::DoExtraWorkForFinalizer+114   

clr!Thread::ShouldChangeAbortToUnload+101    

clr!Thread::ShouldChangeAbortToUnload+399    

clr!Thread::ShouldChangeAbortToUnload+43a    

clr!ManagedThreadBase::ThreadPool+15    

clr!BindIoCompletionCallbackStubEx+a3      

clr!BindIoCompletionCallbackStub+15

clr!ThreadpoolMgr::CompletionPortThreadStart+4e3          

clr!Thread::intermediateThreadProc+4b      

kernel32!BaseThreadInitThunk+e         

ntdll!__RtlUserThreadStart+70    

ntdll!_RtlUserThreadStart+1b

 

Thread 108 - System ID 5916

Entry point   0x00000000

Create time   2013-4-26 10:00:55

Time spent in user mode   0 Days 00:00:09.375

Time spent in kernel mode   0 Days 00:00:01.656

 

 

 

 

This thread is not fully resolved and may or may not be a problem. Further analysis of these threads may be required.

 

 

 

.NET Call Stack

 

 

 

Function

System.Text.StringBuilder..ctor(System.String, Int32, Int32, Int32)

System.Text.StringBuilder..ctor(Int32)

System.Environment.get_MachineName()

NLog.LayoutRenderers.Log4JXmlEventLayoutRenderer.Append(System.Text.StringBuilder, NLog.LogEventInfo)

NLog.LayoutRenderers.LayoutRenderer.Render(System.Text.StringBuilder, NLog.LogEventInfo)

NLog.LayoutRenderers.LayoutRenderer.Render(NLog.LogEventInfo)

NLog.Layouts.Log4JXmlEventLayout.GetFormattedMessage(NLog.LogEventInfo)

NLog.Layouts.Layout.Precalculate(NLog.LogEventInfo)

NLog.Targets.Target.PrecalculateVolatileLayouts(NLog.LogEventInfo)

NLog.Targets.Wrappers.AsyncTargetWrapper.Write(NLog.Common.AsyncLogEventInfo)

NLog.Targets.Target.WriteAsyncLogEvent(NLog.Common.AsyncLogEventInfo)

NLog.LoggerImpl.WriteToTargetWithFilterChain(NLog.Internal.TargetWithFilterChain, NLog.LogEventInfo, NLog.Common.AsyncContinuation)

NLog.LoggerImpl.Write(System.Type, NLog.Internal.TargetWithFilterChain, NLog.LogEventInfo, NLog.LogFactory)

NLog.Logger.WriteToTargets(NLog.LogEventInfo)

NLog.Logger.Log(NLog.LogEventInfo)

NLogEx.LoggerEx.WriteToLog(NLog.LogLevel, System.Exception, System.String, System.Object[])

……….

 

 

Full Call Stack

 

 

 

Function   Source

clr!StressLog::ETWLogOn+1b   

clr!StressLog::LogOn+1e   

clr!NTGetThreadContext+27   

clr!Thread::GetSafelyRedirectableThreadContext+58   

clr!Thread::HandledJITCase+40   

clr!Thread::SysSuspendForGC+5a6   

clr!WKS::GCHeap::SuspendEE+1dc   

clr!WKS::GCHeap::GarbageCollectGeneration+15f   

clr!WKS::gc_heap::try_allocate_more_space+162   

clr!WKS::gc_heap::allocate_more_space+13   

clr!WKS::GCHeap::Alloc+3d   

clr!Alloc+8d   

clr!FastAllocatePrimitiveArray+d0   

clr!JIT_NewArr1+1b4   

System.Text.StringBuilder..ctor(System.String, Int32, Int32, Int32)   

System.Text.StringBuilder..ctor(Int32)   

System.Environment.get_MachineName()   

NLog.LayoutRenderers.Log4JXmlEventLayoutRenderer.Append(System.Text.StringBuilder, NLog.LogEventInfo)   

NLog.LayoutRenderers.LayoutRenderer.Render(System.Text.StringBuilder, NLog.LogEventInfo)   

NLog.LayoutRenderers.LayoutRenderer.Render(NLog.LogEventInfo)   

NLog.Layouts.Log4JXmlEventLayout.GetFormattedMessage(NLog.LogEventInfo)   

NLog.Layouts.Layout.Precalculate(NLog.LogEventInfo)   

NLog.Targets.Target.PrecalculateVolatileLayouts(NLog.LogEventInfo)   

NLog.Targets.Wrappers.AsyncTargetWrapper.Write(NLog.Common.AsyncLogEventInfo)   

NLog.Targets.Target.WriteAsyncLogEvent(NLog.Common.AsyncLogEventInfo)   

NLog.LoggerImpl.WriteToTargetWithFilterChain(NLog.Internal.TargetWithFilterChain, NLog.LogEventInfo, NLog.Common.AsyncContinuation)   

NLog.LoggerImpl.Write(System.Type, NLog.Internal.TargetWithFilterChain, NLog.LogEventInfo, NLog.LogFactory)   

NLog.Logger.WriteToTargets(NLog.LogEventInfo)   

……….

Viewing all 1710 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>