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

How to understand what is blocking the main STA thread - clr!GCInterface::WaitForPendingFinalizers

$
0
0

Hi Everyone.

I am way out of my depth in this part of the forum and do hope you can give me some guidance on what I should do.

Upon opening a second Excel file Excel 2007 hangs and eventually shows

"Microsoft Excel is waiting for another application to complete an OLE action"

This I understand is caused because the main UI or STA thread is blocked.  It appears to be blocked by my addin or I think by what VSTO does as a result of my addin.

Debugging in Visual Studio and attaching to Excel as it opens a file shows that the main STA thread is waiting for a join or another thread and I think shows

>    mscorlib.dll!System.GC.WaitForPendingFinalizers() Line 320 + 0x1b bytes    C#

I don't call nor use GC at all. It looks like VSTO is doing it.

Now I have downloaded and installed windbg and hope the following is how you guys can help me to understand what is going on. I cannot get Office or VSTO symbols with windbg. I got some of them when Visual Studio downloaded them but some are still missing.  So a simple !analyze -hang does not work.  I am able to use sos.dll with clr.

!Threads shows the following;

ThreadCount:      4
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   83c 005a30a0   2004220 Enabled  06ea12f8:06ea1fe8 0667f250     0 STA
  11    2  1878 005ae200      b220 Enabled  00000000:00000000 005944d8     0 MTA (Finalizer)
  12    3  1900 066831e8      1220 Enabled  00000000:00000000 005944d8     0 Ukn
  18    4  1668 06743ab0       220 Enabled  00000000:00000000 005944d8     0 STA

Thread 0 is the main UI thread and I assume the one that must be blocked.

kb on Thread 0

ChildEBP RetAddr  Args to Child              
003bcb44 767815e9 00000002 003bcb94 00000001 ntdll!NtWaitForMultipleObjects+0x15
003bcbe0 764519fc 003bcb94 003bcc08 00000000 KERNELBASE!WaitForMultipleObjectsEx+0x100
003bcc28 765f086a 00000002 7efde000 00000000 kernel32!WaitForMultipleObjectsExImplementation+0xe0
003bcc7c 76ab2bf1 00000050 00591048 ffffffff USER32!RealMsgWaitForMultipleObjectsEx+0x14d
003bcca8 76aa202d 00591048 ffffffff 003bccd0 ole32!CCliModalLoop::BlockFn+0xa1 [d:\w7rtm\com\ole32\com\dcomrem\callctrl.cxx @ 1222]
003bcd28 720ba2bd 00000002 ffffffff 00000001 ole32!CoWaitForMultipleHandles+0xcd [d:\w7rtm\com\ole32\com\dcomrem\sync.cxx @ 109]
003bcd90 720ba249 00000001 00591048 00000000 clr!MsgWaitHelper+0x80
003bcdb0 720eea17 00000001 00591048 00000000 clr!Thread::DoAppropriateAptStateWait+0x39
003bce44 720eead8 00000001 00591048 00000000 clr!Thread::DoAppropriateWaitWorker+0x17d
003bceb0 720eeb57 00000001 00591048 00000000 clr!Thread::DoAppropriateWait+0x60
003bcf04 71f7173e ffffffff 00000001 00000000 clr!CLREvent::WaitEx+0x106
003bcf18 72047660 ffffffff 00000001 00000000 clr!CLREvent::Wait+0x19
003bcf74 72107049 ffffffff aa761eae 003bcfc0 clr!WKS::GCHeap::FinalizerThreadWait+0x114
003bcfb4 718823d4 aa0fcc08 71f55c40 003bd53c clr!GCInterface::WaitForPendingFinalizers+0x71
003bcff4 71f5219b 76b15b5c 00000000 003bd080 mscorlib_ni+0x7c23d4
003bd004 71f8a7aa 003bd0d0 00000000 003bd0a0 clr!CallDescrWorker+0x33
003bd080 71f8a94c 003bd0d0 00000000 003bd0a0 clr!CallDescrWorkerWithHandler+0x8e
003bd1c0 71f8a981 718823a8 003bd2e4 003bd490 clr!MethodDesc::CallDescr+0x194
003bd1dc 71f8a9a1 718823a8 003bd2e4 003bd490 clr!MethodDesc::CallTargetWorker+0x21
003bd1f4 71fd8d54 003bd490 aa7602a2 003bd764 clr!MethodDescCallSite::Call_RetArgSlot+0x1c
003bd3b8 71fd90a6 71145d28 718823a8 710c1000 clr!CallWithValueTypes_RetArgSlotWrapper+0x5c
003bd67c 71fd9268 71145d28 00000000 00000000 clr!InvokeImpl+0x621
003bd748 7137d8c9 005a30a0 00000096 003bd764 clr!RuntimeMethodHandle::InvokeMethodFast+0x180
003bd79c 7137d610 06e9add4 00000096 06e9b50c mscorlib_ni+0x2bd8c9
003bd7d4 7137c22d 00000000 00000000 00000000 mscorlib_ni+0x2bd610
003bd7fc 71316bcc 00000000 00000000 06e897f4 mscorlib_ni+0x2bc22d
003bd950 71885fbd 00000000 00000000 00000000 mscorlib_ni+0x256bcc
003bd974 718ff890 00000000 00000000 00000000 mscorlib_ni+0x7c5fbd
003bd9e8 71f52581 003bddb8 00000000 005a0000 mscorlib_ni+0x83f890
003bda14 72045943 718ff7d0 71885fa0 06e9add4 clr!COMToCLRDispatchHelper+0x28
003bdaa8 72045a1c 71885fa0 06e9add4 00000001 clr!BaseWrapper<Stub *,FunctionBase<Stub *,&DoNothing<Stub *>,&StubRelease<Stub>,2>,0,&CompareDefault<Stub *>,2>::~BaseWrapper<Stub *,FunctionBase<Stub *,&DoNothing<Stub *>,&StubRelease<Stub>,2>,0,&CompareDefault<Stub *>,2>+0xfa
003bdacc 72045a82 005a30a0 003bdd60 05bdf9e0 clr!COMToCLRWorkerBody+0xb4
003bdb24 72046571 005a30a0 003bdd60 05bdf9e0 clr!COMToCLRWorkerDebuggerWrapper+0x34
003bdd34 03fca182 005a30a0 003bdd60 aa0fcc08 clr!COMToCLRWorker+0x614
WARNING: Frame IP not in any known module. Following frames may be wrong.
003bdd48 6928980d 003bdd90 003bddb8 00000000 0x3fca182
003bdddc 6928997a 05bdf9f8 00000000 00000621 VSTOLoader!DllRegisterServer+0x61bb
003bde0c 69277ccb 05c3e438 00000000 00000001 VSTOLoader!DllRegisterServer+0x6328
003bde20 692617de 00000621 00000003 003bdebc VSTOLoader!DllCanUnloadNow+0xb1cf
003bde34 2f421899 06436aa8 00000621 2f301ad4 VSTOLoader+0x17de
003bde88 2f4217f7 00000621 003bdebc 06058150 EXCEL!Ordinal40+0x221899
003bdecc 2f585aa1 00000621 06058168 00000000 EXCEL!Ordinal40+0x2217f7
003bdef4 2f3d1dad 00000001 00000012 00000000 EXCEL!Ordinal40+0x385aa1
003be1b0 2f328830 003beb04 00000012 00000000 EXCEL!Ordinal40+0x1d1dad
003be46c 2f32961e 00000000 003beb04 00000012 EXCEL!Ordinal40+0x128830
003be490 2f230ae1 003beb04 00000012 00000000 EXCEL!Ordinal40+0x12961e
003be6e0 2fb4ab31 00000001 003beb04 00000012 EXCEL!Ordinal40+0x30ae1
003bf7a4 2ff2f2cd 0670dba0 003bf818 0000fffe EXCEL!Ordinal40+0x94ab31
003bfc4c 2f5d20f9 003bfcb0 00000001 000080df EXCEL!LPenHelper+0x12f485
003bfcec 2f2282fa 00000000 30163708 765f0afa EXCEL!Ordinal40+0x3d20f9
003bfdd4 2f203b60 00000000 30163c58 004c4095 EXCEL!Ordinal40+0x282fa
003bfe44 2f203874 2f200000 00000000 004c4095 EXCEL!Ordinal40+0x3b60
003bfed4 7645336a 7efde000 003bff20 772bbf32 EXCEL!Ordinal40+0x3874
003bfee0 772bbf32 7efde000 7741c403 00000000 kernel32!BaseThreadInitThunk+0xe
003bff20 772bbf05 2f202f7c 7efde000 00000000 ntdll!__RtlUserThreadStart+0x70
003bff38 00000000 2f202f7c 7efde000 00000000 ntdll!_RtlUserThreadStart+0x1b


kb on Thread 11

ChildEBP RetAddr  Args to Child              
0905ee1c 7678149d 000007a0 00000000 00000000 ntdll!NtWaitForSingleObject+0x15
0905ee88 76451194 000007a0 ffffffff 00000000 KERNELBASE!WaitForSingleObjectEx+0x98
0905eea0 76451148 000007a0 ffffffff 00000000 kernel32!WaitForSingleObjectExImplementation+0x75
0905eeb4 76aa7690 000007a0 ffffffff 00542008 kernel32!WaitForSingleObject+0x12
0905eed8 76bca4d1 00542730 066d2d70 0905efe4 ole32!GetToSTA+0xad [d:\w7rtm\com\ole32\com\dcomrem\chancont.cxx @ 133]
0905ef08 76bccef0 0905efd0 0905f0f8 00542008 ole32!CRpcChannelBuffer::SwitchAptAndDispatchCall+0x140 [d:\w7rtm\com\ole32\com\dcomrem\channelb.cxx @ 4419]
0905efe8 76ac9d01 00542008 0905f0f8 0905f0e0 ole32!CRpcChannelBuffer::SendReceive2+0xef [d:\w7rtm\com\ole32\com\dcomrem\channelb.cxx @ 4076]
0905f064 76aa792b 00542008 0905f0f8 0905f0e0 ole32!CAptRpcChnl::SendReceive+0xaf [d:\w7rtm\com\ole32\com\dcomrem\callctrl.cxx @ 603]
0905f0b8 76bcce06 00000001 0b223f98 0905f0e0 ole32!CCtxComChnl::SendReceive+0x95 [d:\w7rtm\com\ole32\com\dcomrem\ctxchnl.cxx @ 679]
0905f0d4 75f5420b 0b217684 0905f124 75fd0149 ole32!NdrExtpProxySendReceive+0x49 [d:\w7rtm\com\rpc\ndrole\proxy.cxx @ 1932]
0905f0e0 75fd0149 a3604c8f 0905f52c 0700022b RPCRT4!NdrpProxySendReceive+0xe
0905f4f4 76bcc8e2 76adfa10 76ae49b8 0905f52c RPCRT4!NdrClientCall2+0x1a6
0905f514 76ac98ad 0000000c 00000008 0905f5ac ole32!ObjectStublessClient+0xa2 [d:\w7rtm\com\rpc\ndrole\i386\stblsclt.cxx @ 474]
0905f524 76aa805c 0b217684 0905f560 00000001 ole32!ObjectStubless+0xf [d:\w7rtm\com\rpc\ndrole\i386\stubless.asm @ 154]
0905f5ac 76a9d4b4 00521408 720c90da 0905f6b8 ole32!CObjectContext::InternalContextCallback+0x128 [d:\w7rtm\com\ole32\com\dcomrem\context.cxx @ 4299]
0905f5fc 720c879c 00521418 720c90da 0905f6b8 ole32!CObjectContext::ContextCallback+0x92 [d:\w7rtm\com\ole32\com\dcomrem\context.cxx @ 4184]
0905f714 720c8837 720c857a 0905f770 a3482652 clr!CtxEntry::EnterContext+0x312
0905f748 720c8665 00000000 a3482682 725695c8 clr!RCWCleanupList::ReleaseRCWListInCorrectCtx+0xdf
0905f798 720b1536 a34826fe 00000000 005ae200 clr!RCWCleanupList::CleanupAllWrappers+0xff
0905f7e4 720af497 00000001 0905f930 71fc76b3 clr!SyncBlockCache::CleanupSyncBlocks+0xde
0905f7f0 71fc76b3 005ae200 0905f930 00591088 clr!Thread::DoExtraWorkForFinalizer+0x3b
0905f804 720ef845 00000001 0905f8e8 005ae200 clr!WKS::GCHeap::FinalizerThreadWorker+0x9d
0905f818 720ef8c7 0905f930 a34829d2 0905f930 clr!Thread::DoExtraWorkForFinalizer+0x114
0905f8c8 720ef982 0905f930 a3482832 00000000 clr!Thread::ShouldChangeAbortToUnload+0x101
0905f928 720e5c8f 00000000 005944d8 00000000 clr!Thread::ShouldChangeAbortToUnload+0x399
0905f94c 720e5ca2 71fc7628 00000008 0905f994 clr!ManagedThreadBase_NoADTransition+0x35
0905f95c 720901ba 71fc7628 a348288e 00000000 clr!ManagedThreadBase::FinalizerBase+0xf
0905f994 720ef648 00000000 00000000 00000000 clr!WKS::GCHeap::FinalizerThreadStart+0x10c
0905fa34 7645336a 00591088 0905fa80 772bbf32 clr!Thread::intermediateThreadProc+0x4b
0905fa40 772bbf32 00591088 7e7fc1a3 00000000 kernel32!BaseThreadInitThunk+0xe
0905fa80 772bbf05 720ef600 00591088 00000000 ntdll!__RtlUserThreadStart+0x70
0905fa98 00000000 720ef600 00591088 00000000 ntdll!_RtlUserThreadStart+0x1b


I believe that the next step is to look at the clrstack on Thread 0

!clrstack on Thread 0

0:000> !clrstack
OS Thread Id: 0x83c (0)
Child SP IP       Call Site
003bcfc0 772a015d [InlinedCallFrame: 003bcfc0] System.GC._WaitForPendingFinalizers()
003bcfbc 718823d4 System.GC.WaitForPendingFinalizers()
003bd53c 71f5219b [DebuggerU2MCatchHandlerFrame: 003bd53c] 
003bd508 71f5219b [CustomGCFrame: 003bd508] 
003bd4dc 71f5219b [GCFrame: 003bd4dc] 
003bd4c0 71f5219b [GCFrame: 003bd4c0] 
003bd6e4 71f5219b [HelperMethodFrame_PROTECTOBJ: 003bd6e4] System.RuntimeMethodHandle._InvokeMethodFast(System.IRuntimeMethodInfo, System.Object, System.Object[], System.SignatureStruct ByRef, System.Reflection.MethodAttributes, System.RuntimeType)
003bd760 7137d8c9 System.RuntimeMethodHandle.InvokeMethodFast(System.IRuntimeMethodInfo, System.Object, System.Object[], System.Signature, System.Reflection.MethodAttributes, System.RuntimeType)
003bd7b4 7137d610 System.Reflection.RuntimeMethodInfo.Invoke(System.Object, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo, Boolean)
003bd7f0 7137c22d System.Reflection.RuntimeMethodInfo.Invoke(System.Object, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo)
003bd814 71316bcc System.RuntimeType.InvokeMember(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object, System.Object[], System.Reflection.ParameterModifier[], System.Globalization.CultureInfo, System.String[])
003bd974 71885fbd System.Type.InvokeMember(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object, System.Object[])
003bd98c 718ff890 DomainNeutralILStubClass.IL_STUB_COMtoCLR(IntPtr, Int32, IntPtr, System.StubHelpers.NativeVariant, IntPtr, IntPtr)
003bdb64 71f52581 [GCFrame: 003bdb64] 
003bdbd4 71f52581 [ContextTransitionFrame: 003bdbd4] 
003bdc08 71f52581 [GCFrame: 003bdc08] 
003bdd60 71f52581 [ComMethodFrame: 003bdd60] 

I would very much appreciate some help.  Maybe you could point out to me in the above the call that is most important and how then in windbg to find out maybe the handle or callee to narrow down where the problem is coming from.


Combo Box Data Duplication

$
0
0

Hi, 

    I'm having a problem concerning data duplication in a combo box in Visual Studio 2010. Can someone help me in allowing only different items in the combo box (i.e. I do not want to have similar items in the combo box)?



Excel Interop w/ VB.NET

$
0
0

Good Afternoon Everyone -

I am having difficulty accomplishing a few specific features within Excel Interop.  I can successfully open a text file using .OpenText but can't get the following things to occur - issue #2 is critical.  I am using VS2013, Framework 4.0 or 4.5, and Excel 2013 with Interoperability Libraries v15.0 loaded

1.  Autosize Fields to maximum size
2.  Field Type to be defined as "Text" to prevent leading Zero's from being dropped

I've read countless forums and google results but nothing works, I'm still loosing my leading zero's.  The code I'm using for the current process is below and any help for field formatting would be greatly appreciated.

Dim excelapp As New Microsoft.Office.Interop.Excel.Application

Dim Filename As String = file2convert
Dim Origin As Object = Excel.XlPlatform.xlWindows
Dim StartRow As Object = 1
Dim DataType As Object = Excel.XlTextParsingType.xlDelimited
Dim TextQualifier As Object
Dim ConsecutiveDelimiter As Object = False
Dim Tab As Object
Dim Semicolon As Object
Dim Comma As Object
Dim Space As Object
Dim Other As Object = False
Dim OtherChar As Object = False

excelapp.Workbooks.OpenText(Filename, Origin, StartRow, DataType, TextQualifier, ConsecutiveDelimiter, Tab, Semicolon, Comma, Space, Other, OtherChar)

excelapp.displayalerts = False
excelapp.ActiveWorkbook.SaveAs(Filename:=newfile, FileFormat:=51)
excelapp.ActiveWorkbook.Close(SaveChanges:=True)
excelapp.DisplayAlerts = True
excelapp.Quit()
excelapp = Nothing

--BCCGeorge

CLR Profiling API problem: IL rewriting issue "System.IO.FileLoadException: Loading this assembly would produce a different grant set from other instances"

$
0
0

Failure details: System.IO.FileLoadException: Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401)
   at System.Net.Sockets.TcpClient..ctor(String hostname, Int32 port)
   at com.altaworks.da.DsaPortRequestor.getPortUsingSocket(String hostName, Int32 httpPort)

This problem seems to match another blog posting on the Microsoft Forums and in that case a profiler was in the picture as well. The suggestion there was to turn off legacy code access security. Turning off legacy code access security ("LegacyCASModel=false") will fix the issue but that is not an acceptable solution.

The application profiled is a SharePoint 2013 application. Through IL rewriting the profiler is adding an assembly reference to an external helper assembly that is associated with the unmanaged profiler. That assembly is being loaded into the shared app domain apparently with Full Trust and in a Security Transparent manner. The problem was reproduced on Windows 7 but was first reported on W2k12-R1 and W2K12-R2. 

The helper assembly is attempting to send profiling data collected to another process.

Security Rule Set: Level1
Is Fully Trusted: True
Zone Evidence: MyComputer
Security Critical: False
Security SafeCritical: False
Security Transparent: True
Operating System: Windows 7 (Microsoft Windows NT 6.2.9200.0)
OS Version: 6.2.9200.0
.NET Version: 4.0.30319.18046
CLR running in: 64 bit mode

Memery leak in mixed mode program that use native DLLs.

$
0
0
I wrote a mixed mode program that calls the API of a third party library built using native code.  The third part library has a dependency on MFC90 and MSVCRT90/  I think there is some initialization code in the native DLLs that may allocate some memory for objects or such because if I debug my program and terminate the debug section without running to part of the code that utilizes any objects exported from the native library I get a memory leaks and just to say I get the memory leaks if the run the program normally.  I write a test program using native C++ to use the native library and after I cleaned all the objects I created I didn't have any memory leaks.  Is there something different that .net framework does when loading native libraries then the CRT does?  I would think that if the native libraries have initialization code that I can't touch then there is also shutdown code in them to deallocate  any objects created for internal usage.  Would it make sense for me to link at runtime rather than at build time i.e. "Loadlibrary" and "FreeLibrary"?

Kenney

Failure adding assembly to the cache: The module was expected to contain an as sembly manifest.

$
0
0

Hi

I got the error while running the below command

gacutil -i "C:\WINDOWS\system32\SFImpersonator.dll"

Failure adding assembly to the cache:   The module was expected to contain an as sembly manifest.

Can any one advice on this ?


shravan

Different compile option, different app behavior

$
0
0

Hello.

I have developed a windows phone 8 application. Many floating point operation are performed in it. When I ran the aplication in emulator (debug or release mode with anycpu target) all was ok. So I published  the app in windows phone store compiled in release mode and target anycpu. After install the app in a real ARM phone, I realized that the application had a "random" behavior. All calculations was completely wrong.

The problem was solved changing some option in compile option section of the project properties:

1) turning off code optimization

2) Changing debug info from pdb-only to full

I can not understand why the problem is solved in that manner. 

Thanks


CodeDom implicitly creating resource retrieval statements; causes unloadable code

$
0
0


I’m using a standard C# WinForms Designer to let the user create a Dialog box.  When the user wants to show the dialog box, I compile it into an Assembly file (a DLL) using my own subclass of CodeDomDesignerLoader, which I call FormEditorCodeDomDesignerLoader.

The code that creates the CodeCompileUnit in the FormEditorCodeDomDesignerLoader looks like this:

        protected override CodeCompileUnit Parse()
        {
            DesignSurface ds = new DesignSurface();
            ds.BeginLoad(typeof (Form));
            IDesignerHost idh = (IDesignerHost)ds.GetService(typeof(IDesignerHost));

           return CreateCCU (idh);
        }

        private CodeCompileUnit CreateCCU (IDesignerHost idh)
        {
            idh.RootComponent.Site.Name = "Form1";

            cg = new FormEditorCodeGen();
            CodeCompileUnit ccu = cg.GetCodeCompileUnit(idh);

            AssemblyName[] names = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
            for (int i = 0; i < names.Length; i++)
            {
                Assembly assembly = Assembly.Load(names[i]);
                ccu.ReferencedAssemblies.Add(assembly.Location);
            }

            codeCompileUnit = ccu;
            return ccu;
        }

       internal class FormEditorCodeGen
       {
         private CodeCompileUnit codeCompileUnit;
         private CodeNamespace ns;
         private CodeTypeDeclaration myDesignerClass = new CodeTypeDeclaration();
         private CodeMemberMethod initializeComponent = new CodeMemberMethod();
         private IDesignerHost host;
         private IComponent root;

         /// <summary>
         /// This function generates the default CodeCompileUnit template
        /// </summary>
         public CodeCompileUnit GetCodeCompileUnit(IDesignerHost host)
        {
            this.host = host;
            IDesignerHost idh = (IDesignerHost)this.host.GetService(typeof(IDesignerHost));
            root = idh.RootComponent;
            Hashtable nametable = new Hashtable(idh.Container.Components.Count);

            ns = new CodeNamespace("YetiFormEditor");
            myDesignerClass = new CodeTypeDeclaration();
            initializeComponent = new CodeMemberMethod();

            CodeCompileUnit code = new CodeCompileUnit();

            // Imports
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            ns.Imports.Add(new CodeNamespaceImport("AGI.FormEditor"));
            code.Namespaces.Add(ns);
            myDesignerClass = new CodeTypeDeclaration(root.Site.Name);
            myDesignerClass.BaseTypes.Add(typeof(Form).FullName);

            IDesignerSerializationManager manager =
                              host.GetService(typeof(IDesignerSerializationManager)) as IDesignerSerializationManager;

            ns.Types.Add(myDesignerClass);

            // Constructor
            CodeConstructor con = new CodeConstructor();

            con.Attributes = MemberAttributes.Public;
            con.Statements.Add(new CodeMethodInvokeExpression(
           new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "InitializeComponent")));
            myDesignerClass.Members.Add(con);

            // InitializeComponent
            initializeComponent.Name = "InitializeComponent";
            initializeComponent.Attributes = MemberAttributes.Private;
            initializeComponent.ReturnType = new CodeTypeReference(typeof(void));
            myDesignerClass.Members.Add(initializeComponent);
            codeCompileUnit = code;
            return codeCompileUnit;
 }
       }// class

 


The code that takes the CodeCompileUnit and turns it into an Assembly (DLL) file looks like this:

        public bool Build (string dllFileName)
        {
               Flush();

               // We need to collect the parameters that our compiler will use.
               CompilerParameters cp = new CompilerParameters();
               AssemblyName[] assemblyNames = Assembly.GetEntryAssembly().GetReferencedAssemblies();

               foreach (AssemblyName an in assemblyNames)
               {
                      Assembly assembly = Assembly.Load(an);
                      cp.ReferencedAssemblies.Add(assembly.Location);
               }

               cp.GenerateExecutable = false;  // only set to true for code that contains an entry point
               cp.OutputAssembly = dllFileName;

              // Remember our main class is not Form, but Form1!
             string mainClass = "YetiFormEditor.Form1";
             cp.MainClass = mainClass;

             CSharpCodeProvider cc = new CSharpCodeProvider();
             CompilerResults cr = cc.CompileAssemblyFromDom(cp, codeCompileUnit);

              return !cr.Errors.HasErrors;
        }


Here’s my problem:

Whenever any of the controls within the Dialog box being designed has a string Property that’s longer than 200 characters, the code in the generated DLL contains an implicit call to retrieve this string from the DLL Assembly’s resources – and the DLL Assembly doesn’t HAVE any string resources!  This causes an exception when attempting to call dllAssembly.CreateInstance (“YetiFormEditor.Form1”);.  If the string Property is 200 characters or shorter, this exception does not occur and the dialog box gets created successfully.

I looked at the C# code in the CodeCompileUnit (via CSharpCodeProvider.GenerateCodeFromCompileUnit() ).  If the string Property is 200 characters or less I’ll see this:

this.comboBox1.MyProperty = "012345678901234567890123456789012345678901234567890123456789012345678901234567890" +
"12345678901234567890123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789";

… but if the string Property is more than 200 characters I’ll see this:

this.comboBox1.MyProperty = resources.GetString("comboBox1.MyProperty");


I cannot believe no one else has run into this issue, considering how commonplace Properties longer than 200 characters must be (e.g. Image properties, the contents of a multi-line text edit, etc.).  So:

Is there a way to either make the CodeCompileUnit (or the CompileAssemblyFromDom() call) explicitly include the string resources this generated code depends on, or a way to make the CodeCompileUnit/CompileAssemblyFromDom() generate code for long strings that doesn’t require resources?


Thanks!


“Value does not fall within the expected range.” when trying to call a method on a COM object using c#

$
0
0

I get an exception when trying to call a method on a COM object using c#.

This only happens when I try to call the method without using the COM runtime callable wrapper (RCW) interop assembly generated by tlbimp.exe.

When strictly using the COM interop assembly, everything works perfectly.

The reason I don't want to use the COM interop assembly is because the CLSIDs and ProgIDs may be different on the target machine than when the interop assembly is created, but the method names, definitions, and structures are the same.

In this test, however, the COM server is registered using the same CLSIDs and ProgIDs as those defined in the runtime callable wrapper (RCW) which was directly generated from the running COM server assembly.

Running on Windows 7 SP1 64-bit.
C++ COM server is 32-bit
C# assembly is built using "Any CPU" and targets .NET Framework 4

C++ COM server IDL code snippet:

[object,
uuid(MyComObjectInterfaceGuid),
dual,
helpstring("MyComObject Interface"),
pointer_default(unique)]interfaceIMyComObject:IDispatch{#import "MyCustomStruct.h"[id(110), helpstring("Method110")] HRESULT Method110([out] MY_CUSTOM_STRUCT *pMyCustomStruct);}[
uuid(MyComObjectGuid),
helpstring("MyComObject")]
coclass MyComObject{[default]interfaceIMyComObject;};

MyCustomStruct.h:

typedefstruct MY_CUSTOM_STRUCT{
    bool            property1;longunsigned   property2;wchar_t         property3[42];int             property4;} MY_CUSTOM_STRUCT;

When the COM server DLL is registered, the rgs file inserts the ProgId registry values for example.

The runtime callable wrapper produces the following structure:

publicstruct MY_CUSTOM_STRUCT{publicbyte property1;publicuint property2;publicushort[] property3;publicint property4;}

C# code snippet that works:

using MyComObjectInteropNamespace;MyComObject myComObject =newMyComObject();

MY_CUSTOM_STRUCT myCustomStruct =new MY_CUSTOM_STRUCT();
myComObject.Method110(out myCustomStruct);// myCustomStruct contains the expected values

C# code snippet that throws an exception:

using MyComObjectInteropNamespace;Type myComObjectType =Type.GetTypeFromProgID("Company.Product.MyComObject",true);object myComObject =Activator.CreateInstance(myComObjectType);

MY_CUSTOM_STRUCT myCustomStruct =new MY_CUSTOM_STRUCT();object[] args ={ myCustomStruct };ParameterModifier parameterModifier =newParameterModifier(1);
parameterModifier[0]=true;ParameterModifier[] parameterModifiers ={ parameterModifier };

myComObjectType.InvokeMember(// exception is thrown here"Method110",BindingFlags.InvokeMethod,null,
    myComObject,
    args,
    parameterModifiers,null,null);// code does not get this far
myCustomStruct =(MY_CUSTOM_STRUCT)args[0];

Exception:

System.ArgumentException occurredHResult=-2147024809Message=Value does not fall within the expected range.Source=mscorlibStackTrace:
       at System.RuntimeType.InvokeDispMethod(String name,BindingFlags invokeAttr,Object target,Object[] args,Boolean[] byrefModifiers,Int32 culture,String[] namedParameters)
       at System.RuntimeType.InvokeMember(String name,BindingFlags bindingFlags,Binder binder,Object target,Object[] providedArgs,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParams)InnerException:

C# code snippet that also throws the same exception:

using MyComObjectInteropNamespace;Type myComObjectType =Type.GetTypeFromProgID("Company.Product.MyComObject",true);object myComObject =Activator.CreateInstance(myComObjectType);object[] args ={newUnknownWrapper(null)};ParameterModifier parameterModifier =newParameterModifier(1);
parameterModifier[0]=true;ParameterModifier[] parameterModifiers ={ parameterModifier };

myComObjectType.InvokeMember(// exception is thrown here"Method110",BindingFlags.InvokeMethod,null,
    myComObject,
    args,
    parameterModifiers,null,null);// code does not get this far
MY_CUSTOM_STRUCT myCustomStruct =(MY_CUSTOM_STRUCT)args[0];

C# code snippet that also throws an exception:

dynamic myComObject =Activator.CreateInstance(Type.GetTypeFromProgID("Company.Product.MyComObject",true));

MY_CUSTOM_STRUCT myCustomStruct =new MY_CUSTOM_STRUCT();
myComObject.Method110(out myCustomStruct);// exception is thrown here

Exception:

System.ArgumentException occurredHResult=-2147024809Message=Value does not fall within the expected range.Source=mscorlibStackTrace:
       at System.Runtime.InteropServices.Marshal.GetNativeVariantForObject(Object obj,IntPtr pDstNativeVariant)
       at System.Dynamic.UnsafeMethods.InitVariantForObject(Object obj,Variant& variant)InnerException:null

Also posted on stackoverflow here:

http://stackoverflow.com/questions/23074846/value-does-not-fall-within-the-expected-range-when-trying-to-call-a-method-on

Running wmic.exe using c# always produces the error message “The system cannot find the file specified.” when it works in a command prompt

$
0
0

Running wmic.exe using c# always produces the error message "The system cannot find the file specified." when it works in a command prompt.

C# assembly is built with "Any CPU" targeting .NET Framework 4.

string fileName =Path.Combine(Environment.SystemDirectory,"wbem","wmic.exe"); // c:\windows\system32\wbem\wmic.exestring arguments =@"/NAMESPACE:\\root\Microsoft\SqlServer\ComputerManagement10 PATH ServerNetworkProtocol";Process process =newProcess{StartInfo={FileName= fileName,Arguments= arguments,UseShellExecute=false,CreateNoWindow=true,RedirectStandardOutput=true,RedirectStandardError=true}};

process.Start();StreamReader output = process.StandardOutput;StreamReader error = process.StandardError;Console.WriteLine(output.ReadToEnd());Console.WriteLine(error.ReadToEnd());

process.WaitForExit();int exitCode = process.ExitCode;
process.Close();Assert.AreEqual(0, exitCode);

Error Message:

Assert.AreEqual failed.Expected:<0>.Actual:<-2147024894>.

Standard Console Output:

Node-MyComputerName
ERROR:Description=The system cannot find the file specified.

I have also tried using:

string fileName =Environment.ExpandEnvironmentVariables("%comspec%"); // c:\windows\system32\cmd.exestring arguments =string.Format(@"/C {0} /NAMESPACE:\\root\Microsoft\SqlServer\ComputerManagement10 PATH ServerNetworkProtocol",Path.Combine(Environment.SystemDirectory,"wbem","wmic.exe"));

but I experience the same issue.

When run on the command prompt, it produces the expected output and returns an exit code of zero:

c:\windows\system32\wbem\wmic.exe /NAMESPACE:\\root\Microsoft\SqlServer\ComputerManagement10 PATH ServerNetworkProtocol&& echo %errorlevel%EnabledInstanceNameMultiIpConfigurationSupportProtocolDisplayNameProtocolName
TRUE     SQLEXPRESS    FALSE                        SharedMemorySm
FALSE    SQLEXPRESS    FALSE                        NamedPipesNp
FALSE    SQLEXPRESS    TRUE                         TCP/IP               Tcp
FALSE    SQLEXPRESS    FALSE                        VIA                  Via0

In all cases, I am running as admin.

Also posted on stackoverflow here:

stackoverflow.com/questions/23089575/running-wmic-exe-using-c-sharp-always-produces-the-error-message-the-system-can

How to use a SafeHandle with the WinUSB API

$
0
0
For an application that uses the WinUsb API, I'm attempting to use a handle from a derived SafeHandle class in place of an IntPtr:

		[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
		[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
		internal class SafeWinUsbHandle : SafeHandle
		{
			private SafeWinUsbHandle()
				: base(IntPtr.Zero, true)
				{
				}
			[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
			protected override bool ReleaseHandle()
			{

			}
			
			public override bool IsInvalid
			{
				get
				{
					if (handle == IntPtr.Zero)
					{
						return true;
					}

					if (handle == (IntPtr) (-1))
					{
						return true;
					}
					return false;
				}
			}

private SafeWinUsbHandle _winUsbHandle;

Passing _winUsbHandle in the InterfaceHandle parameter of WinUsb_Initialize returns the error "SafeHandle cannot be null".

Setting:

_winUsbHandle = IntPtr.Zero;
returns the error "Cannot convert source type System.IntPtr to target type".

How can I use a SafeHandle with this function?


.NET Exit Code 80131506

$
0
0

Hi All,

I am trying to run some call management software on Windows 8 and, if it is used in a particular way, it crashes and the following error is received:

'Framework Version: v4.0.30319

Description: The process was terminated due to an internal error in the .NET Runtime at IP 7093F03B (707E0000) with exit code 80131506.'

I cannot seem to find any helpful info on this exit code and I'm not sure what is causing it. I believe that it is a Windows 8 issue as I have an identical setup that is running on Windows 7 and it works perfectly.

Thanks, J

Perform signedXml.ComputeSignature method manually

$
0
0

Hello,

I have tried to compute enveloped signature using signedXml.ComputeSignature() method as show in example below. It worked fine, signedXml.ComputeSignature() method have calculated hash value of data and signed it for me. However, the problem is that I need to perform all these steps manually.

I was not able to find out how i can calculate identical hash value of data in "Example.xml" manually, moreover i have tried to sign already calculated hash value using RSACryptoServiceProvider.SignHash() method and it gave me SignatureValue that is different form signedXml generated value.

Any ideas how i can compute hash and signature value manually, without using signedXml class?

Thanks for your help.

My attempt to sign hash value:

 CspParameters cspParams = new CspParameters();

   cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";// Create a new RSA signing key and save it in the container. 

   RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);byte[] hashSignature = rsaKey.SignHash(Convert.FromBase64String("e7jQRU4xmLaQmWVO9pVovhWSeGU="), CryptoConfig.MapNameToOID("SHA1"));



   Console.WriteLine(Convert.ToBase64String(hashSignature));

The following code example shows how to sign and verify an entire XML document using an enveloping signature:

//// This example signs an XML file using an// envelope signature. It then verifies the // signed XML.//using System;using System.Security.Cryptography;using System.Security.Cryptography.X509Certificates;using System.Security.Cryptography.Xml;using System.Text;using System.Xml;publicclass SignVerifyEnvelope

{



 publicstaticvoid Main(String[] args)

 {

  try

  {

   // Generate a signing key.

   RSACryptoServiceProvider Key = new RSACryptoServiceProvider();// Create an XML file to sign.

   CreateSomeXml("Example.xml");

   Console.WriteLine("New XML file created."); // Sign the XML that was just created and save it in a // new file.

   SignXmlFile("Example.xml", "SignedExample.xml", Key);

   Console.WriteLine("XML file signed."); // Verify the signature of the signed XML.

   Console.WriteLine("Verifying signature...");bool result = VerifyXmlFile("SignedExample.xml");// Display the results of the signature verification to \// the console.if(result)

   {

    Console.WriteLine("The XML signature is valid.");

   }

   else

   {

    Console.WriteLine("The XML signature is not valid.");

   }

  }

  catch(CryptographicException e)

  {

   Console.WriteLine(e.Message);

  }

 }



 // Sign an XML file and save the signature in a new file.publicstaticvoid SignXmlFile(string FileName, string SignedFileName, RSA Key)

 {

  // Create a new XML document.

  XmlDocument doc = new XmlDocument();// Format the document to ignore white spaces.

  doc.PreserveWhitespace = false;// Load the passed XML file using it's name.

  doc.Load(new XmlTextReader(FileName));// Create a SignedXml object.

  SignedXml signedXml = new SignedXml(doc);// Add the key to the SignedXml document. 

  signedXml.SigningKey = Key;



  // Create a reference to be signed.

  Reference reference = new Reference();

  reference.Uri = "";// Add an enveloped transformation to the reference.

  XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

  reference.AddTransform(env);



  // Add the reference to the SignedXml object.

  signedXml.AddReference(reference);



  

  // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).

  KeyInfo keyInfo = new KeyInfo();

  keyInfo.AddClause(new RSAKeyValue((RSA)Key));

  signedXml.KeyInfo = keyInfo;



  // Compute the signature.

  signedXml.ComputeSignature();



  // Get the XML representation of the signature and save// it to an XmlElement object.

  XmlElement xmlDigitalSignature = signedXml.GetXml();



  // Append the element to the XML document.

  doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));if (doc.FirstChild is XmlDeclaration) 

  {

   doc.RemoveChild(doc.FirstChild);

  }



  // Save the signed XML document to a file specified// using the passed string.

  XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

  doc.WriteTo(xmltw);

  xmltw.Close();

 }

 // Verify the signature of an XML file and return the result.publicstatic Boolean VerifyXmlFile(String Name)

 {

  // Create a new XML document.

  XmlDocument xmlDocument = new XmlDocument();// Format using white spaces.

  xmlDocument.PreserveWhitespace = true;// Load the passed XML file into the document. 

  xmlDocument.Load(Name);



  // Create a new SignedXml object and pass it// the XML document class.

  SignedXml signedXml = new SignedXml(xmlDocument);// Find the "Signature" node and create a new// XmlNodeList object.

  XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");// Load the signature node.

  signedXml.LoadXml((XmlElement)nodeList[0]);



  // Check the signature and return the result.return signedXml.CheckSignature();

 }



 // Create example data to sign.publicstaticvoid CreateSomeXml(string FileName)

 {

  // Create a new XmlDocument object.

  XmlDocument document = new XmlDocument();// Create a new XmlNode object.

  XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");// Add some text to the node.

  node.InnerText = "Example text to be signed.";// Append the node to the document.

  document.AppendChild(node);



  // Save the XML document to the file name specified.

  XmlTextWriter xmltw = new XmlTextWriter(FileName, 

why does .net suck at simple math???

$
0
0

take the simple subtraction 43.709719 - 43.7097189

which should yield 0.0000001, however when i type in that problem into the watch bar(or have a pair of values with sufficient precision i get a result like this:

WTF?!?!?!

how am I supposed to build a program that will handle high precision values if the language compiler can't even handle subtraction!  both visual studio 2010 and 2012 show this inability to handle subtraction of precision numbers

while i know for this example i could use a decimal declaration to handle them since both have fewer than 8 decimal places, i have values that are accurate to 14 decimal places that i need to work with.

Edit:

also trying things of a lower precision... from Watch 1

        1.0 - 0.9    0.099999999999999978    Double

Visual Studio: Referencing the Same Assembly Multiple Times framework 3.5

$
0
0

At work I have the somewhat esoteric requirement of referencing multiple versions of the same assembly from a consuming assembly.

I change the alias of the reference from global to "XXX" and in the first line of my class  I put

extern alias xxx;

But it steel much an error :

extern alias 'xxx' had not specified in option /reference	


I even tried to use The C# compiler (csc.exe) has a /reference switch to
supply references that takes the following format (from MSDN):

/reference:[alias=]filename

follopwing this article :http://kentb.blogspot.com/2008/11/visual-studio-referencing-same-assembly.html

But i steel have the problem.

My project is in .Net 3.5 and VisualStudio 2010

thanks


PrefView (1.6) - System.IndexOutOfRangeException

$
0
0

Hi, I was using PrefView 1.6 and on Windows 2008 Server and I keep getting the following exception when I try to open CPUStack for any processes. Is there any way to work around this, or would an older version of PerfView would work?

Thanks

Exception Occured: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Microsoft.Diagnostics.Tracing.Stacks.TraceEventStackSource.GetCallerIndex(StackSourceCallStackIndex callStackIndex)
   at Microsoft.Diagnostics.Tracing.Stacks.MutableTraceEventStackSource.GetCallerIndex(StackSourceCallStackIndex callStackIndex)
   at Diagnostics.Tracing.StackSources.FilterStackSource.GenerateStackInfo(StackSourceCallStackIndex stackIndex, StackInfo stackInfoRet)
   at Diagnostics.Tracing.StackSources.FilterStackSource.GetStackInfo(StackSourceCallStackIndex stackIndex)
   at Diagnostics.Tracing.StackSources.FilterStackSource.GenerateStackInfo(StackSourceCallStackIndex stackIndex, StackInfo stackInfoRet)
   at Diagnostics.Tracing.StackSources.FilterStackSource.GetStackInfo(StackSourceCallStackIndex stackIndex)
   at Diagnostics.Tracing.StackSources.FilterStackSource.GenerateStackInfo(StackSourceCallStackIndex stackIndex, StackInfo stackInfoRet)
   at Diagnostics.Tracing.StackSources.FilterStackSource.GetStackInfo(StackSourceCallStackIndex stackIndex)
   at Diagnostics.Tracing.StackSources.FilterStackSource.<>c__DisplayClass1.<ForEach>b__0(StackSourceSample sample)
   at Microsoft.Diagnostics.Tracing.Stacks.MutableTraceEventStackSource.ForEach(Action`1 callback)
   at Diagnostics.Tracing.StackSources.FilterStackSource.ForEach(Action`1 callback)
   at Microsoft.Diagnostics.Tracing.Stacks.CallTree.set_StackSource(StackSource value)
   at PerfView.StackWindow.<>c__DisplayClass3.<SetStackSource>b__0()
   at PerfView.StatusBar.<>c__DisplayClass8.<StartWork>b__6(Object param0)
An exceptional condition occured, see log for details.

IIS 7.5 new Application pool account is not working in Asp.net site

$
0
0

I have newly created application pool to use it in our new Asp.net website.

When i try to access the site i am getting response as

This page can't be displayed
  • Make sure the web address http://x.xx.xx.xx is correct.
  • Look for the page with your search engine.
  • Refresh the page in a few minutes. 

But my IP address is right, 

Wen i look at the windows logs its showing below error. please help me.

Faulting application name: w3wp.exe, version: 7.5.7601.17514, time stamp: 0x4ce7a5f8 Faulting module name: clr.dll, version: 4.0.30319.1022, time stamp: 0x52ccf666 Exception code: 0xc00000fd Fault offset: 0x003580b5 Faulting process id: 0x1f84 Faulting application start time: 0x01cf5df3f59dcae8 Faulting application path: C:\Windows\SysWOW64\inetsrv\w3wp.exe Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll Report Id: 3aa796c8-c9e7-11e3-99e0-001a646aa7d3

AppDomain issue with casting

$
0
0

Background:

The company I'm working for is developing an enterprise application.

We need the ability to load up multiple versions of our application releases into the same memory space.

The applications have the similar assembly names, namespaces, and classes.

The directory structure would look like this:

baseApplicationDirectory\ApplicationLoader.DLL
baseApplicationDirectory\bin\V1.0\AppModule1.DLL
baseApplicationDirectory\bin\V1.0\AppModule2.DLL
baseApplicationDirectory\bin\V2.0\AppModule1.DLL
baseApplicationDirectory\bin\V2.0\AppModule2.DLL

This sounds like the perfect oportunity to use AppDomain.

The Problem:

I successfully create the AppDomain, and everything looks fine till I try to perform a cast.

AppModule1Namespace.Class1 implements interface IFoo. AND MarshalByRefObject

This is how I create an instance of of Class1

        public static IFoo New(string classType)
        {
            IFoo sysFoo = null;
            bool canEdit = true;

            //Go out to the database and see what dll file
            //the classType is located in
            string dllName = _storage.GetLatestDllPath(classType, "", out canEdit);

            if (File.Exists(dllName))
            {
                try
                {
                    Assembly asm = Assembly.LoadFile(dllName);
                    object objMgr = (Activator.CreateInstance(asm.GetName().Name, classType).Unwrap());

                    if (objMgr != null && objMgr is IFoo)
                    {
                        sysFoo = (IFoo)objMgr;
                    }
                }
                catch
                {
                }
            }

            return sysFoo;
        }
    }

The line if (objMgr != null && objMgr is IFoo) Fails.  objMgr is the appropriate class.  However the cast test fails.  Forcing the cast causes an exception.

The above routine worked up till the point I tried to use app domains.

I'm suspecting that when I invoked the Activator.CreateInstance, it created a new instance of the object in a seperate AppDomain then the executing code.

I was wondering if there was a way to say, "Switch AppDomain Context" so when you are resolving class creation/activation, use this domain.

Edit: Passing the AppDomain to the Activator class does not help with the casting issue.

Curiously, when I try to move the execution point (set next statement) it pops up a dialog that says ,"[Resolve Ambiguity] Choose Specific Location" with two lines to the same New routine that look exactly the same.




COM interop assemblies and PrimaryInteropAssemblyCodeBase

$
0
0

We have a pretty big issue with registering 32-bit and 64-bit primary interop assemblies and maintaining IntelliSense support. We ship both 32-bit and 64-bit COM in-proc servers and register the corresponding 32-bit and 64-bit PIAs.  We use the PrimaryInteropAssemblyCodeBase value in the TypeLib entry to point to the location of our PIAs on disk.  This PrimaryInteropAssemblyCodeBase value is required to get Visual Studio to locate the XML IntelliSense file for rendering IntelliSense for that PIA -- you point the code base at the DLL and put the XML file next to it and Visual Studio renders the content.

The problem is that with Windows 7, the TypeLib section of the registry is shared, so you can only point PrimaryInteropAssemblyCodeBase at either the 32-bit or 64-bit PIA (not both).  If you point it at the 32-bit PIA, then building 64-bit apps using that PIA fails in Visual Studio (and vice-versa if you use the 64-bit PIA location).  If you don't use the PrimaryInteropAssemblyCodeBase value at all, then Visual Studio will resolve to the correct PIA via the GAC and builds work -- but IntelliSense is *not* rendered because the XML IntelliSense file obviously is not (typically) installed in the GAC.

Building the PIAs as "Any CPU" does work, but it feels "wrong" since PIAs *really* are, by definition, bitness-dependent.  This seems fundamentally broken and I'm wondering how others have not come across this.

Any help or insights are much appreciated.


Kirk Fertitta

IMetaDataImport::FindTypeRef fails to return TypeRef token for known Type from a reference assembly

$
0
0

I am writing and IL re-writing profiler for .NET assemblies.

I have the following code snippet and applying it to the EntityFramework.dll assembly function.

   

//Enumerate all reference assemblies for current assembly				

hResult = pMDAImport->EnumAssemblyRefs( &assemblyEnum, assemblyRefs, numElements( assemblyRefs ), &assemblyRefsCount );

// Walk through all referenced assemblies to find System.Data.IDbCommand token

// for( unsigned assemblyRefIdx = 0; (unmatchedTypes > 0) && (assemblyRefIdx < assemblyRefsCount); assemblyRefIdx++ ) { assemblyRef = assemblyRefs[ assemblyRefIdx ]; WCHAR tempAssName[50]; ULONG szAssNameRet = 0; hResult = pMDAImport->GetAssemblyRefProps(assemblyRef, NULL, 0, tempAssName, numElements(tempAssName), &szAssNameRet, NULL, NULL, 0, NULL); if (hResult == S_OK) { if( CLogger::isLevelEnabled( LL_Debug ) ) CLogger::Log( LL_Debug, "Searching for dependent types in assemblyRef(%08X) (%d/%d) - %S\n", assemblyRef, assemblyRefIdx + 1, assemblyRefsCount, tempAssName); } hResult = m_pMDImport->FindTypeRef( assemblyRef, L"System.Data.IDbCommand", &typeRef ); if( (m_idbCommandTypeToken == mdTokenNil) && SUCCEEDED( m_pMDImport->FindTypeRef( assemblyRef, L"System.Data.IDbCommand", &typeRef ) ) ) { m_idbCommandTypeToken = typeRef; }

The logging confirms it sees System.data as one of the referenced assemblies which should contain the TypeRef forSystem.Data.IDbCommand

014.04.22.15.33.50.951  [00002B0C]  DEBUG    Searching for dependent types in assemblyRef(23000003) (3/13) - System.Data

Can you tell me why the FindTypeRef fails and how to get around this ?

Regards

Sanjay

The hResult error is

CLDB_E_RECORD_NOTFOUND

0x80131130

Record not found on lookup.


Sanjay Mehta


Viewing all 1710 articles
Browse latest View live


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