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

Converting a SecureString object to byte array in .net

$
0
0

Hi

We are using SecureString to store passwords in the memory. However, I didn't find any secured way to convert the SecureString to the byte array. Is there a way to do this?

The idea is that i do not want to get the byte array via converting SecureString->String->byte array as string is immutable, but byte array can be easily cleared from memory after the work is done.

 

Thanks



CLR Profiling API and "unhandled exception in unknown module"

$
0
0

Hi!
I'm trying to use the CLR Profiling API on a WPF process and something strange happens.
When I run the WPF process in a normal way it runs fine.

But when I run it with the evnironment variables of my profiling DLL, I get the following exception:

An unhandled exception of type 'System.IO.FileLoadException' occurred in Unknown Module.
Additional information: Hash validation failed for file or assembly 'PresentationFramework, Version=4.0.0.0

(I managed to find it after attaching to the WPF process with a debugger)

When I try profile a winforms application it doesn't happen.

Why is it happening and how can I fix it?

thanks :)


CLR Profiler cannot start my C# Console Application

$
0
0

I've downloaded CLR Profiler.

I followed How To: Use CLR Profiler instructions, but it doesn't work. Here are my steps. 

- I execute 32-bit version with administrative priviliges. 

- I checked my CLR Version.

C:\Program Files\Microsoft Visual Studio 10.0\VC>clrver
Versions installed on the machine:
v2.0.50727
v4.0.30319

- so I choose target CLR Version:V4 Desktop CLR (otherwise it runs, but View menu and the Show Heap now button are disabled).

- check Allocations and Calls checkboxes

- select Start Application (or File -> Profile Application)

- Application isn't running

- On The Console I got message CLR Object Profiler Tool - turning off profiling for child processes

- View Menu options are disabled

- By pressing Show Heap now button I get the exception message window

************** Tekst wyjątku **************
System.IO.FileNotFoundException: Nie można odnaleźć pliku 'C:\Windows\TEMP\pipe_1240.log'.
Nazwa pliku: 'C:\Windows\TEMP\pipe_1240.log'
   w System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   w System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
   w System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   w CLRProfiler.MainForm.logFileOffset() w C:\CLRProfilerHelper\CLRProfiler\Sources\CLRProfiler\MainForm.cs:wiersz 2850
   w CLRProfiler.MainForm.showHeapButton_Click(Object sender, EventArgs e) w C:\CLRProfilerHelper\CLRProfiler\Sources\CLRProfiler\MainForm.cs:wiersz 2859
   w System.Windows.Forms.Control.OnClick(EventArgs e)
   w System.Windows.Forms.Button.OnClick(EventArgs e)
   w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   w System.Windows.Forms.Control.WndProc(Message& m)
   w System.Windows.Forms.ButtonBase.WndProc(Message& m)
   w System.Windows.Forms.Button.WndProc(Message& m)
   w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   w System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

- After closing bug window, on the console are displayed several WARNING: OpenEvent FAILED Will Attempt CreateVEent()

- Then Application runs and closes

I can't find out what i'm doing wrong.

Unable to add Oracle.Dataaccess.dll

$
0
0

I am unable to add reference of oracle.dataaccess.dll in visual studio 2003.

i am using oracle 11g and windows 8 (64 bit).

Following error appear "This is not a valid assembly or COM component. Only assemblies with extension 'dll' and COM components can be referenced. Please make sure that the file is accessible, and that it is a valid assembly or COM component"

Identify .NET dll's assemblies in Test System

$
0
0

Hi All,

1) Given set of binaries/dll's(assemblies) 650 no's comprising, Win 32 dll's, COM dll's, .NET pure assemblies,.NET assembly with com Interfaces all above categories of dll's,

and using Test System in particular Is there a way to identify/categorise the dll's from among the above.

2) I use the following methods in my development system(for similar dll's in test system) to segregate/categorise the dll's

a) COM/Win32: Regsvr32.exe <fullpath name/xyz.dll>  if registration is successful it is com dll otherwise it may be either of .NET Dll(pure) , .NET Dll with com Interface OR Win32

though, I guess is not the correct method , Is there better method to find the same for Dll's/assemblies in Test System(Windows 8) and application installed.?

 

Test System: Windows 8, .NET Framework 4.0 as per information from >>regedit/HKLM/Microsoft/../NetFramework/NDP/...

 

Development System: Windows 8 , .NET Framework 4.0, VS 2010 etc.,

any help in resolving the above queries would be much appreciable.

 

Thanks & Regards,

VishalK_90

 

 


Vishal_K89

VerifyData signed with "SHA256withRSA" algoritm always return false.

$
0
0

The SignedString is generated by "eid-web-applet-1.0-20121010.132118-1.jar" whit the algoritm "SHA256withRSA"

This is the code I use, but I d0n't understand why it returns me always false :

RSACryptoServiceProviderrsaCripto=(RSACryptoServiceProvider)certUserC.PublicKey.Key;

byte[]signedBytes=Convert.FromBase64String(SignedString)     

byte[]bytesToVerify=byteConverterUTF8.GetBytes(originalString);                

RSACryptoServiceProviderp=newRSACryptoServiceProvider();

 p.FromXmlString(publicKey);

          

SHA256mySHA256=SHA256Managed.Create();

  

bool verified=p.VerifyData(bytesToVerify,mySHA256,signedBytes);

               



Edoardo Molinaro Product Specialist E-Mail: edo106@gmail.com






Edoardo Molinaro Product Specialist E-Mail: edo106@gmail.com

Failed to debug C# application developed and compiled in .net 3.5 but targeted to .net 4.0 and 3.5 using windebug

$
0
0

Failed to debug C# application in a host having both .net 4.0 and 3.5 using windebug. This application was developed and compiled in .net 3.5 environment but targeted to .net 4.0 and 3.5 using windebug.

Any suggestions on this?

DIA SDK: thread safety of msdia library

$
0
0
 I can't find information about thread safety of msdia. Could you please give me some tips? Can I access the same session in different threads without own synchronization? Can I access and simultaneously load different sessions in different threads?

ADODB.Recordset VS ADO.NET

$
0
0

I have migrates an application from VB6 to .Net 2005 and found ADODB.Recordset in that. Should I leave it as it is or should I change it with ADO.Net? Any insight about how ADODB.Recordset works in .Net environment will be helpful.

Virtual mode in listview

$
0
0
How retrieve virtual item works when listview virtual mode property is true.

how to see all the errors without getting “Maximum number of errors has been exceeded” in .Net

$
0
0

I am compiling a VB.Net project. It is giving 102 errors. One error among 102 errors is "Maximum number of errors has been exceeded". What I understand from this error is, Visual Studio is not showing all the errors exist in the project. Can anybody let me know how to view all the errors of a project?

Please check is it a bug in clr

$
0
0

when i read the source code , i wonder, if the gc is trigger when one preemptive disable thread fall into the code (exactly method ofSpinUntil which is higlight as below),that will cause the app hang ,because all preemptive enabel threads is suspend, no handle is create or free.

------Handletablecache.cpp------------

void SyncTransferCacheHandles(OBJECTHANDLE *pDst, OBJECTHANDLE *pSrc, UINT uCount)
{
    WRAPPER_CONTRACT;

    /*
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    */
   
    // set up to loop
    // we loop backwards since that is the order handles are added to the bank
    // this is designed to reduce the chance that we will have to spin on a handle
    OBJECTHANDLE *pBase = pDst;
    pSrc += uCount;
    pDst += uCount;

    // loop until we've copied all of them
    while (pDst > pBase)
    {
        // advance to the next slot
        pDst--;
        pSrc--;

        // this version spins if there is no handle to read or no place to write it
        if (*pDst || !*pSrc)
        {
            SpinUntil(pSrc, TRUE);
            SpinUntil(pDst, FALSE);
        }

        // copy the handle and zero it from the source
        *pDst = *pSrc;
        *pSrc = 0;
    }
}

void SpinUntil(void *pCond, BOOL fNonZero)
{
    WRAPPER_CONTRACT;

    /*
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    */
   
    // if we have to sleep then we will keep track of a sleep period
    DWORD dwThisSleepPeriod = 1;    // first just give up our timeslice
    DWORD dwNextSleepPeriod = 10;   // next try a real delay

#ifdef _DEBUG
    DWORD dwTotalSlept = 0;
    DWORD dwNextComplain = 1000;
#endif //_DEBUG

    // on MP machines, allow ourselves some spin time before sleeping
    UINT uNonSleepSpins = 8 * (g_SystemInfo.dwNumberOfProcessors - 1);

    // spin until the specificed condition is met
    while ((*(UINT_PTR *)pCond != 0) != (fNonZero != 0))
    {
        // have we exhausted the non-sleep spin count?
        if (!uNonSleepSpins)
        {
#ifdef _DEBUG
            // yes, missed again - before sleeping, check our current sleep time
            if (dwTotalSlept >= dwNextComplain)
            {
                //
                // THIS SHOULD NOT NORMALLY HAPPEN
                //
                // The only time this assert can be ignored is if you have
                // another thread intentionally suspended in a way that either
                // directly or indirectly leaves a thread suspended in the
                // handle table while the current thread (this assert) is
                // running normally.
                //
                // Otherwise, this assert should be investigated as a bug.
                //
                _ASSERTE(FALSE);

                // slow down the assert rate so people can investigate
                dwNextComplain = 3 * dwNextComplain;
            }

            // now update our total sleep time
            dwTotalSlept += dwThisSleepPeriod;
#endif //_DEBUG

            // sleep for a little while
            __SwitchToThread(dwThisSleepPeriod);

            // now update our sleep period
            dwThisSleepPeriod = dwNextSleepPeriod;

            // now increase the next sleep period if it is still small
            if (dwNextSleepPeriod < 1000)
                dwNextSleepPeriod += 10;
        }
        else
        {
            // nope - just spin again
            YieldProcessor();           // indicate to the processor that we are spining
            uNonSleepSpins--;
        }
    }
}

Encrypting data using AES 256

$
0
0

I am new to this whole encryption thing. I am creating a program to send some information to a vendor of ours. The problem I am running into is that they require that no padding be applied to the input. From my understanding this cant be achieved using CBC (unless the data is always a multiple of the block size - 256)? Does this mean I need to use a different cipher mode to be able to do this with .NET or how should I go about this? It needs to be encrypted with AES 256 (both key and block size) with no IV.

What are my options to be able to do this?

string[] keyArray = key.Split(','); //key is string 32 numbers 45,-12,...

sbyte[] sBytes = new sbyte[keyArray.Length]; for (int i = 0; i < keyArray.Length; i++) { sBytes[i] = Convert.ToSByte(keyArray[i]); } byte[] bytes = (byte[])(Array)sBytes; RijndaelManaged tdes = new RijndaelManaged(); tdes.Key = bytes; tdes.BlockSize = 256; tdes.KeySize = 256; tdes.Mode = CipherMode.CBC; tdes.Padding = PaddingMode.None; ICryptoTransform crpyt = tdes.CreateEncryptor(); byte[] userData = Encoding.UTF8.GetBytes(userId); byte[] dateData = Encoding.UTF8.GetBytes(currentTime); byte[] userCipher = crpyt.TransformFinalBlock(userData, 0, userData.Length); byte[] dateCipher = crpyt.TransformFinalBlock(dateData, 0, dateData.Length); string encryptedUser = Convert.ToBase64String(userCipher); string encrpytedDate = Convert.ToBase64String(dateCipher); string url = baseURL + "username="+ encryptedUser + "&timestamp="+ encrpytedDate; Response.Redirect(url);


BC30456: 'InitializeCulture' is not a member of FIXES

$
0
0

Windows 2003 Server SP1, ASP.Net 2.0

BC30456: 'InitializeCulture' is not a member of

Have a bug in your code but throws this error instead of the actual error? Or getting this error randomly? Or a similar error complaining that an asp.net method is not a member of a class like 'Page' when it is!? and mashing refresh a few times sometimes makes it go away...

After 2 Days of extensive search on the internet and finding plenty of people with this error and very little replies and resolutions, I took upon myself to get to the bottom of this (unacknowledged ASP.net framework bug) and list some steps to help all of you work around it.

1. If you use Visual studio to publish your site, during the publishing stage on framework 2.0 uncheck the "allow this precompiled site to be updatable".

2. Ensure ASP.Net is installed correctly, I found that my Web Server root was configured to use ASP.Net 1.1 by default so ran the following line to fix it to 2.0 even though my site was configured for 2.0 at site level, eliminating this glitch seems logical.

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -i

This will also fix any mapping/installation problems.

Also ran aspnet_regiis -r

This will replace all mappings recursively to 2.0 regardless.

3. Make sure page directives at the top of aspx files are correct and ‘inherits’ is pointing to your class correctly. I could not see any problems with mine, so did not explore down this path to thoroughly, but noted others saying issues with ambiguous inheritance maybe related.

4. Declare culture in your web.config, example

<globalization uiCulture="en" culture="en-NZ" />

OR

<globalization uiCulture="auto" culture="auto" />

5. Change debug="true" to "false" in web.config and any pages which have it set (I recommend removing it entirely from pages and just using web.config)

* This final step eliminated the problem for me, very weird.

Now if this last step eliminates the problem, and later on down the track you get an error in your codebehind file while coding or debugging, you will no longer be pointed directly to the line in your codebehind file when an exception occurs, asp.net will just show you the line in the aspx file you called from. Temporarily switch debug back to true in web.config if you can't figure out the problem and then you can see it, if InitializeCulture crops back up instead, mash refresh a few times like you used to do! Then turn debug back off.

---

Does anyone else have anymore info?

My question to Microsoft, why does this behaviour exist? Is it by design or really a bug? If so, why is there no acknowledgment of it as a bug for ASP.Net 2.0?

-juicyjuice

Access violation in CLR when trying to release RCW's

$
0
0

Hello,

I have spent two days scratching my head trying to understand the following call stack...Any input/thoughts would be highly appreciated. Thanks in advance!

In order to diagnose heap corruption in the process, I enabled "Page heap" for it and attached it with WinDBG. I have been hitting access violation with the following call stack when invoking/instantiating a dialog in the application (it happens every time but the first invoke)

Looks like CLR is trying to cleanup a non-existent RCW. Any ideas on how can i find what RCW its trying to cleanup so that i can investigate the code in that area further?

>

Current frame: clr!SafeReleasePreemp+0x231
ChildEBP RetAddr  Caller, Callee
055dfb70 71936f36 clr!CtxEntry::EnterContext+0x3bf, calling clr!_EH_epilog3
055dfb9c 71935c17 clr!RCW::ReleaseAllInterfaces+0x70, calling clr!SafeReleasePreemp
055dfbb4 71935cb0 clr!RCW::ReleaseAllInterfacesCallBack+0x60, calling clr!RCW::ReleaseAllInterfaces
055dfbf0 71935d0c clr!RCW::Cleanup+0x41, calling clr!RCW::ReleaseAllInterfacesCallBack
055dfc24 71935e84 clr!RCWCleanupList::ReleaseRCWListRaw+0xd, calling clr!RCW::Cleanup
055dfc2c 71935e61 clr!RCWCleanupList::ReleaseRCWListInCorrectCtx+0xd1, calling clr!RCWCleanupList::ReleaseRCWListRaw
055dfc40 71936da2 clr!RCWCleanupList::CleanupAllWrappers+0x155, calling clr!RCWCleanupList::ReleaseRCWListInCorrectCtx
055dfc58 718511c5 clr!ClrFlsIncrementValue+0x9, calling clr!ClrFlsGetBlock
055dfc94 719f1800 clr!SyncBlockCache::DeleteSyncBlock+0xaa, calling clr!_EH_epilog3
055dfc9c 719f1725 clr!SyncBlockCache::CleanupSyncBlocks+0xd0, calling clr!RCWCleanupList::CleanupAllWrappers
055dfcec 719f168c clr!Thread::DoExtraWorkForFinalizer+0x81, calling clr!SyncBlockCache::CleanupSyncBlocks
055dfd04 71928744 clr!WKS::GCHeap::FinalizerThreadWorker+0x22f, calling clr!Thread::DoExtraWorkForFinalizer
055dfd44 71889843 clr!REGUTIL::EnvGetString+0xfc, calling clr!__security_check_cookie
055dfd4c 718c7d8d clr!Thread::DoExtraWorkForFinalizer+0x1ca
055dfd64 718c7dfb clr!Thread::DoExtraWorkForFinalizer+0x256, calling clr!Thread::DoExtraWorkForFinalizer+0x163
055dfd98 7196b5f2 clr!ThreadStore::TransferStartedThread+0xfd, calling clr!_EH_epilog3
055dfdd4 718898fd clr!SHash<StringSHashTraits<_ConfigStringKeyValuePair,unsigned short,CaseSensitiveStringCompareHash<unsigned short> > >::Lookup+0x11, calling clr!SHash<StringSHashTraits<_ConfigStringKeyValuePair,unsigned short,CaseSensitiveStringCompareHash<unsigned short> > >::Lookup
055dfde0 7188998a clr!EEConfig::GetConfiguration_DontUse_+0x1b0, calling clr!SHash<StringSHashTraits<_ConfigStringKeyValuePair,unsigned short,CaseSensitiveStringCompareHash<unsigned short> > >::Lookup
055dfe0c 718c7ec8 clr!Thread::DoExtraWorkForFinalizer+0x618, calling clr!Thread::DoExtraWorkForFinalizer+0x1d4
055dfe68 719141c6 clr!WKS::GCHeap::FinalizerThreadStart+0x198, calling clr!Thread::DoExtraWorkForFinalizer+0x5bd
055dfe84 77a9e023 ntdll!RtlFreeHeap+0x105, calling ntdll!RtlpLowFragHeapFree
055dfee4 7196a0c1 clr!Thread::intermediateThreadProc+0x4d
055dff74 7196a0af clr!Thread::intermediateThreadProc+0x3b, calling clr!_alloca_probe_16
055dff88 775733aa kernel32!BaseThreadInitThunk+0xe
055dff94 77aa9ef2 ntdll!__RtlUserThreadStart+0x70
055dffd4 77aa9ec5 ntdll!_RtlUserThreadStart+0x1b, calling ntdll!__RtlUserThreadStart




Principal.IsInRole first call is slow

$
0
0
I have a windows forms application running on .NET framework 4.0 on Windows 7 Professional client machines. The application was performing fine for about a year. In the code there is a call to process each role the user is a member of in AD. This first IsInRole call now takes around 40 seconds and the 7 or so subsequent calls are quick. Users are all members of very few groups. I did recently remove a windows 2003 domain controller from our environment and is replaced with a Server 2012 DC. I did the proper process of running DCPROMO to remove it from the domain and have made sure the Primary DC is set to a different server. I cannot help to think this is the cause though. If anyone could offer any suggestions of where I could look. I have 3 DCs on our network and none are remote they are all on a gigabit Ethernet network. 

To distinguish w.r.t .NET dll(pure) and .NET dll with COM Interface

$
0
0

Hi All,

I have a set of .NET dll's/assemblies (pure) as well as .NET dll's with COM Interfaces, Could it be possible to identify/segregate the dll's /assemblies belonging to the above two categories.

I tried using the Regasm <abc.dll>

Microsoft (R) .NET Framework Assembly Registration Utility 4.0.30319.1
Copyright (C) Microsoft Corporation 1998-2004.  All rights reserved.

Types Registered Successfully,

ii) Regasm.exe <xyz.dll>

Microsoft (R) .NET Framework Assembly Registration Utility 4.0.30319.1
Copyright (C) Microsoft Corporation 1998-2004.  All rights reserved.

RegAsm : warning RA0000 : No types were registered

I would categorize the former assembly(abc.dll) has .NET dll with COM Interface and latter (xyz.dll) into pure Or ha .NET dll/assembly only. Is my approach is correct OR  Is there any other method to segregate the above dll's or assemblies.

Details:

VS 2008 IDE, Windows 7 O/S.,

Regards,

VishalK_90


Vishal_K89

Unable to cast COM object of type 'Microsoft.GroupPolicy.GPMGPOCollectionClass' to interface type 'System.Collections.IEnumerable'.

$
0
0

On Windows 8 x64 Enterprise I have a test .NET 4.0 C# Console Program targeting 'any cpu' in Visual Studio 2012 to which I added the GPMC Assembly via the instructions here:

http://msdn.microsoft.com/en-us/library/windows/desktop/ff519502(v=vs.85).aspx

The exact path to the GPMC Assembly is C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.GroupPolicy.Management\v4.0_2.0.0.0__31bf3856ad364e35\Microsoft.GroupPolicy.Management.dll

When I run the following code :

GPDomain domain = new GPDomain();

GPSearchCriteria searchCriteria = new GPSearchCriteria();

GpoCollection gpos = domain.SearchGpos(searchCriteria);

On the searchGpos I get the following exception:

System.InvalidCastException was unhandled
  HResult=-2147467262
  Message=Unable to cast COM object of type 'Microsoft.GroupPolicy.GPMGPOCollectionClass' to interface type 'System.Collections.IEnumerable'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{496B0ABE-CDEE-11D3-88E8-00902754C43A}' failed due to the following error: 'No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))' and the COM component does not support IDispatch::Invoke calls for DISPID_NEWENUM.
  Source=mscorlib
  StackTrace:
       at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
       at Microsoft.GroupPolicy.GPMGPOCollectionClass.GetEnumerator()
       at Microsoft.GroupPolicy.Common.CreateCollectionWrapper[T](IEnumerable gpmCollection, Int32 capacity, CreateComWrapper`1 createComWrapperDelegate, Object data)
       at Microsoft.GroupPolicy.GPDomain.SearchGpos(GPSearchCriteria searchCriteria)
       at GpoTest.Program.GetGPOs(String domainname) in c:\Users\mccafferym\Documents\Visual Studio 2012\Projects\GpoTest\GpoTest\Program.cs:line 18
       at GpoTest.Program.Main(String[] args) in c:\Users\mccafferym\Documents\Visual Studio 2012\Projects\GpoTest\GpoTest\Program.cs:line 53
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

I if enable debugging with .NET reflector on the Microsoft.GroupPolicy.Management.dll the exception occurs here on List<T> list = new List<T>(capacity);

// Generated by .NET Reflector from C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.GroupPolicy.Management\v4.0_2.0.0.0__31bf3856ad364e35\Microsoft.GroupPolicy.Management.dll
namespace Microsoft.GroupPolicy
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Runtime.CompilerServices;
    internal static class Common
    {
        internal static IList<T> CreateCollectionWrapper<T>(IEnumerable gpmCollection, int capacity, CreateComWrapper<T> createComWrapperDelegate, object data)
        {
            List<T> list = new List<T>(capacity);
            foreach (object obj2 in gpmCollection)
            {
                list.Add(createComWrapperDelegate(obj2, data));
            }
            return list;
        }

The specified GUID & related CLSID when looked up in registry:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Interface\{496B0ABE-CDEE-11D3-88E8-00902754C43A}]
@="IEnumerable"

[HKEY_CLASSES_ROOT\Interface\{496B0ABE-CDEE-11D3-88E8-00902754C43A}\ProxyStubClsid32]
@="{00020424-0000-0000-C000-000000000046}"

[HKEY_CLASSES_ROOT\Interface\{496B0ABE-CDEE-11D3-88E8-00902754C43A}\TypeLib]
@="{BED7F4EA-1A96-11D2-8F08-00A0C9A6186D}"
"Version"="2.4"

[HKEY_CLASSES_ROOT\CLSID\{00020424-0000-0000-C000-000000000046}]
@="PSOAInterface"

[HKEY_CLASSES_ROOT\CLSID\{00020424-0000-0000-C000-000000000046}\InprocServer32]
@="C:\\Windows\\System32\\oleaut32.dll"
"ThreadingModel"="Both"

I also tried targeting x86 & x64 to see if it made any difference (it didn't).

Attempted to read or write protected memory

$
0
0

I am running a c# app (.Net v3.5 compiled as x64) registered as a COM dll on Windows Server 2008 R2.

The dll appears to have a memory management issue because I am getting the “Attempted to read or write protected memory” exception (see below for details).  The program does have some unmanaged code (see below).

The problem is that the program isn’t throwing the exception when the unmanaged code is executing.  It throws the exception when it attempts to perform an LDAP bind.  I checked the logs on the LDAP server, and the bind is failing before any events are logged there.

Also, the program works fine in running on an ESX VM.  The error happens when it runs on physical hardware.

I am at a loss as to how to debug this as I can’t easily debug interactively.  Any suggestions would be greatly appreciated.

EXCEPTION
Message:  Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
InnerException: 
Source:  System.DirectoryServices.Protocols
StackTrace:     at System.DirectoryServices.Protocols.Wldap32.ldap_connect(IntPtr ldapHandle, LDAP_TIMEVAL timeout)
   at System.DirectoryServices.Protocols.LdapConnection.Connect()
   at System.DirectoryServices.Protocols.LdapConnection.BindHelper(NetworkCredential newCredential, Boolean needSetCredential)
   at LDAPDatabase.openLDAPConnection()
   at LDAPDatabase.DeleteAttributeValue(String attributeName, String distinguisedName, Object[] values)
TargetSite:  Int32 ldap_connect(IntPtr, System.DirectoryServices.Protocols.LDAP_TIMEVAL)
Data:  System.Collections.ListDictionaryInternal

UNMANAGED CODE
int pointerSize = int.Parse(applicationKey.GetValue(Support.RegistryKeys.CertificatePointerSize).ToString());
IntPtr objectPointer = Marshal.AllocHGlobal(pointerSize);

module.GetCertificateProperty(Support.CertificateProperties.RawCertificate, (int)Support.PropertyType.PROPTYPE_BINARY, objectPointer);

IntPtr bstrPtr = Marshal.ReadIntPtr(objectPointer, 8);

int bstrLen = Marshal.ReadInt32(bstrPtr, -4);
byte[] certBytes = new byte[bstrLen];

Marshal.Copy(bstrPtr, certBytes, 0, bstrLen);

cert = new X509Certificate(certBytes);

Marshal.FreeHGlobal(objectPointer);

Internals of String type and String.Intern()

$
0
0

I've lately been analyzing (and trying to improve) performance of a string intensive application. When checking the way strings are stored in memory in the .NET framework I came across this funny memory layout for a string reference in memory:
(example compiled on an IA32 with VS2010SP1 targeting .NET 3.5)

79330c6c   00000005   00000004   0054 0065 0073 0074   0000 0000    80000000
V-Table(?) Length+1   Length     T    e    s    t      null-char    ??? unclear
for String                                          (4byte-aligned?)

I'd like to know the following:

-  Why do we have the string's Length and additionally seemingly Length+1 stored in the structure? Shouldn't the latter be computable? Am I getting something wrong?

-  How are strings aligned in memory, i. e. how many trailing null-chars do we get for a length of 3, 4, 5, 6, 7, 8 chars?

-  What is the ominous 0x80000000? I didn't find this when e. g. checking an array of strings built up at runtime. Is that a garbage collection pin or something? Just random data? ( I never found anything else but 0x00000000 and 0x80000000 in this place...)

-  Since strings are immutable, I would actually have expected to find an Int32 for the hash code of the string in the structure. For example instead of Length+1. However, it seems GetHashCode() will have no short exit for strings, i. e. hash codes are not cashed. Wouldn't that be a good idea?


A second mystery to me is the way String.Intern works. The documentation tells us:

If you are trying to reduce the total amount of memory your application allocates, keep in mind that interning a string has two unwanted side effects. First, the memory allocated for interned String objects isnot likely be released until the common language runtime (CLR) terminates. The reason is that the CLR's reference to the interned String objectcan persist after your application, or even your application domain, terminates.

Could somebody please be less cryptic and define the "not likely" and "can" in above documentation? I would like to have clarification under which circumstances an interned string is actually released if it's no longer used/referenced in the application/the process that interned it. Will it ever be released? Can we have details for each framework version about the behaviour in case it differs? (Regardless of the difference concerning String.Empty; that is understood.)

When the application finally terminates, under which circumstances will the string still live on? Will it live on forever? Will it live only if a second application/process references the same interned text? Is it ever collected at all?

In my evaluation tests at least it seemed the memory is never ever collected again during the lifetime of the application. Making it completely useless for our use cases. It's also more than unclear why the framework should behave this way. Any good reasons?

Anyway, after evaluating this, I went on a rant when I had the idea to simply implement a String table of my own for interning purposes by using HashSet<WeakString> where WeakString is a struct with a WeakReference targeting a string and with an int for saving a string's hashcode. It turned out to be impossible since HashSet<T> offers nothing resembling a Get(T item) method. This may not be a problem for mere value types, but for the intended purpose, it is simply useless though internally it definitely has got all it takes. Whatever references you put into a HashSet, you will never be able to retrieve them in the same quick way HashSet allows you to check whether an element is contained. This could (*cough*) be improved in a future .NET version.

Any good ideas for implementing an application level string pool without wasting too much memory are welcome. To me it seemed one will have to reinvent the wheel here because HashSet lacks a method that probably could be introduced in a few keystrokes...




Viewing all 1710 articles
Browse latest View live


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