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

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?


How to pass the Current Thread Identity to a worker thread handling events from a COM Interop object ?

$
0
0

Hi,

Here after is a very simple piece of code to open Word using "Microsoft Office Interop Word" 1.14 and to execute some code when a document is opened within this instance of word.

The issue I experience is that the Identity set on the Main Thread is not passed on the Worker Thread executing the event handler.

I read that "delegates" run under the caller's security permissions, not the declarer's permissions. I presume therefore that Word being invoked through Interop, it does possibly not run with the Identity set on my application. If this is correct. How can I force Word to run with that Identity ?

Otherwise, what can I do to run the delegate under the current user Identity

using System;using System.Windows.Forms;using Microsoft.Office.Interop.Word;using System.Diagnostics;using System.Threading;using System.Security.Principal; namespace WordInterop
{    public partial class Form1 : Form    {        private ApplicationClass objWordApplication;        public Form1()        {            InitializeComponent();            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("It's me"), new string[] { });                    }        private void button1_Click(object sender, EventArgs e)        {            objWordApplication = new ApplicationClass();            objWordApplication.DocumentOpen += new ApplicationEvents4_DocumentOpenEventHandler(MyDelegateOpen);            objWordApplication.Visible = true;            objWordApplication.Activate();        }        private void MyDelegateOpen(_Document Doc)        {            Debug.Print("Delegate Thread Identity= " + Thread.CurrentPrincipal.Identity.Name);        }        private void Form1_Deactivate(object sender, EventArgs e)        {            Debug.Print("Main Thread Identity= " + Thread.CurrentPrincipal.Identity.Name);        }    }
}

To run this code in a Form, you need to add a reference on Microsoft.Office.Interop.Word,open the Properties tab for that reference in Visual Studio and set "Embed Interop Types" to "False".



Valéry Letroye



impersonateValidUser does not work for some PC,saying "Access to the path 'xxx' is denied."

$
0
0

hi.

    i would like to ask u to do me a favor to help me.

    i am using impersonateValidUser to copy file to a folder(if the folder does not exist it will create the folder).

   then i deploy and install the program on some user's PC.i found on some PC it does work(told access denied) but some PC works(for the PC which doesn't work,even i login with adimistrator it doesn't work,and for the PC which works,it works for all users,that is to say,it doesnt have relationship with users, but machines.)

    it seems that for function impersonateValidUser it works well since i was not told failed login.

   could anyone can do me a favor to help me?thank u very much in advance.

    for the PC which has error,the info is here :

See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.UnauthorizedAccessException: Access to the path 'xxxxx' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
   at System.IO.Directory.CreateDirectory(String path)
   at testWrite.Form1.button1_Click(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.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: 4.0.0.0
    Win32 Version: n/a
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
testWrite
    Assembly Version: 1.0.0.0
    Win32 Version: n/a
    CodeBase: file:///C:/testProject/testWrite.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: n/a
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: n/a
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: n/a
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

     and my code is:       
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
        WindowsImpersonationContext impersonationContext;
        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle); 
        private void undoImpersonation()
        {
            impersonationContext.Undo();
        }
        private bool impersonateValidUser(String userName, String domain, String password)
        {      
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;         
                if (RevertToSelf())
                {
                    if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                        LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                            if (impersonationContext != null)
                            {
                                CloseHandle(token);
                                CloseHandle(tokenDuplicate);
                                MessageBox.Show("return true");
                                return true;
                            }
                        }
                    }
                }
                if (token != IntPtr.Zero)
                    CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    CloseHandle(tokenDuplicate);   
            return false; 
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            if (impersonateValidUser("username", "domain", "psw"))
            {               
                if (!Directory.Exists(rootComplete))
                {               
                        Directory.CreateDirectory(rootComplete);                   
               
                }     
                File.Copy(filePath, doc, true);              
                undoImpersonation();
            }
            else
            {
                MessageBox.Show("fail login.palare con IT per favore");               
            }
        }

Peverify error - Unable to resovle token

$
0
0

hi,

I am writing a very simple example from a book and I am getting an error when I run Peverify.  It says it is unable to verify token.  There are two files in the example. 

 

The first one - CILCars.il doesn't throw up any errors when I run ilasm // dll CILCars.il

I verify it using peverify CILCars.dll and all is ok

 

here is the code :

 

// Reference mscorlib.dll and
// System.Windows.Forms.dll.
.assembly extern mscorlib
{
	.publickeytoken = (B7 7A 5C 56 19 34 E0 89)
	.ver 4:0:0:0
}

.assembly extern System.Windows.Forms
{
	.publickeytoken = (B7 7A 5C 56 19 34 E0 89)
	.ver 4:0:0:0
}

// Define the single-file assembly.
.assembly CILCars
{
	.hash algorithm 0X00008004
	.ver 1:0:0:0
}

.module CILCars.dll

// Implementation of CILCars.CILCar type.
.namespace CILCars
{
	.class public auto ansi beforefieldinit CILCar
	extends [mscorlib]System.Object
	{
	// The field data of the CILCar.
	.field public string petName
	.field public int32 currSpeed
	
	// The custom constructor simply allows the caller
	// to assign the field data.
	.method public hidebysig specialname rtspecialname
	instance void .ctor(int32 c, string p) cil managed
	{
	.maxstack 8
	
	// Load first arg onto the stack and call base class ctor.
	ldarg.0  // "this" object, not the int32!
	call instance void [mscorlib]System.Object::.ctor()
	// Now load first and second args onto the stack.
	ldarg.0 // "this" object
	ldarg.1 // int32 arg
	// Store topmost stack (int 32) member in currSpeed field.
	stfld int32 CILCars.CILCar::currSpeed
	// Load string arg and store in petName field.
	ldarg.0  // "this" object
	ldarg.2 // string arg
	stfld string CILCars.CILCar::petName
	ret
	}
   }
}	
.class public auto ansi beforefieldinit CILCarInfo
	extends [mscorlib]System.Object
	{
	.method public hidebysig static void
	Display(class CILCars.CILCar c) cil managed
		{
		.maxstack 8
		// We need a local string variable.
		.locals init ([0] string caption)
		// Load string and the incoming CILCar onto the stack.
		ldstr "{0}'s speed is:"
		ldarg.0
		// Now place the value of the CILCar's petName on the 
		// stack and call the static String.Format() method.
		ldfld string CILCars.CILCar::petName
		call string [mscorlib]System.String::Format(string, object)
		stloc.0
		// Now load the value of the currSpeed field and get its string
		// representation (note call to ToString().
		ldarg.0
		ldflda int32 CILCars.CILCar::currSpeed
		call instance string [mscorlib]System.Int32::ToString()
		ldloc.0
		// Now call the MessageBox.Show() method with loaded values.
		call valuetype [System.Windows.Forms]
		System.Windows.Forms.DialogResult
		[System.Windows.Forms]
		System.Windows.Forms.MessageBox::Show(string, string)
		pop
		ret
		}
	}

 

 

The second file CarClient.il throws up an error when I run peverfity.  Here is the code :

// External assembly refs.
.assembly extern mscorlib
{
	.publickeytoken = (B7 7A 5C 56 19 34 E0 89)
	.ver 4:0:0:0
}
.assembly extern CILCars
{
	.ver 1:0:0:0
}

// Our executable assembly.
.assembly CarClient
{
	.hash algorithm 0x00008004
	.ver 1:0:0:0
}
.module CarClient.exe

// Implementation of Program type.
.namespace CarClient
{
	.class private auto ansi beforefieldinit Program
	extends [mscorlib]System.Object
	{
		.method private hidebysig static void
		Main(string[] args) cil managed
		{
			// Marks the entry point of the *.exe.
			.entrypoint
			.maxstack 8
			
			// Declare a local CILCar variable and push
			// values onto the stack for ctor call.
			.locals init ([0] class
			[CILCars]CILCars.CILCar myCILCar)
			ldc.i4 55
			ldstr "Junior"
			// Make new CILCar; store and load reference.
			newobj instance void
				[CILCars]CILCars.CILCar::.ctor(int32, string)
				stloc.0
				ldloc.0
			// Call Display() and pass in topmost value on stack.
			call void [CILCars]
				CILCars.CILCarInfo::Display(
					class [CILCars]CILCars.CILCar)
					ret
		}
	}
}

Any ideas ?

 

 

EncryptedXml.DecryptDocument creates "\r\n\t" in Windows 8

$
0
0

In Windows 8, using EncryptedXml.DecryptDocument to decrypt a xml file will found that there are many "\r\n\t" created in the InnerXml.

While it does not happen in Windows 7 and before OS. (I use the same encrypted xml file).

Does anyone encounter the same issue or know the reason?

Thanks.

Need clarification : Loader Heap , High Frequency heap and method tables

$
0
0

Please verify if there is some gap in my understanding-

A) Loader Heap maintains type system for assembly loaded in the app domain.

B) For Each type the Loader Heap maintains -

     a) References to its instance types.

     b) pointer in the High frequency heap for each static variable.

     c)  pointer to its Method Table in the High Frequency heap.

C) Method table maintains pointer for each method's JIT compiled native code in the JITed Heap.

How to get local variable names defined in a method using reflection in C#.net

$
0
0

How to get local variable names defined inside a method using reflection(.net assembly).

I can get local variable info using MethodInfo.MethodBody().LocalVariables. But it gives data type of the local variables not the name.

So is there any way that i can get variable names.

unbind BindAsLegacyV2Runtime

$
0
0

So we have an application launcher which can (should) run new apps created in clickOnce and older apps that use a remoting type of logic

When trying to run the apps I received the following message

Cannot load assembly.Error details:System.IO.FileLoadException:Couldnot load 
file or assembly 'program'or one of its dependencies.Operationisnot
supported.(Exceptionfrom HRESULT:0x80131515)File name:'program'--->System.NotSupportedException:An attempt was made to load an assembly from
a network location which would have caused the assembly to be sandboxed in
previous versions of the .NET Framework.This release of the .NET Framework does not enable CAS policy bydefault, so this load may be dangerous.Ifthis load isnot intended to sandbox the assembly, please enable the loadFromRemoteSources switch.See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

Googling I found this piece of code which says update the app config

Loading blocked and network-hosted assemblies with .NET 4

That fix the older apps but now broke the newer apps

So then I found Setting useLegacyV2RuntimeActivationPolicy At Runtime

And this "works" in that if I load a new app first, no issue, then I load an older app and it is ok, but then if I go to load a new app it stops working.

So either I need to know how to unbind BindAsLegacyV2Runtime when I am about to run new apps. Or I need a whole other approach?

Thanks


Getting COM Error 80004005 while using Interop.Domino.dll

$
0
0

Hi,

I am using Visual Studio 2008 and .NET 3.5, i have case where in  i use a ASP.NET Web Application and a C# Windows Service to use this Interop.Domino.dll for accessing Lotus Notes and create a Session in NotesDB.

In these two applications , which ever access the  NOTES DB and creates session it holds a session and it is not  releasing it. When the other application tries to create a session in the NotesDB for a another user account i am getting this COM Error

 

error: Retrieving the COM class factory for component with CLSID {29131539-2EED-1069-BF5D-00DD011186B7} failed due to the following error: 80004005.

 

Any help would be highly appreciated, Thanks in advance.

Soundararajan Rajendran

Installing security certificates

$
0
0

Hello All,

Currently I am doing some testing with installing a security certificate in c#. It is a .cer file . I am using the X509Store to open the store and install. I noticed when I open the store for the currentuser and add the certificate into the trusted root I get a security warning popup. I am wondering if there is a way to install into this store and prevent the security warning from popping up.

X509Store CertStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);

Open winform window when widows service start

$
0
0

I want to display a winform window(not exe) when the windows service starts.

i am new to windows services, just implemented simple service to open a winform window at service start, but it displays the interactive Services Detection window .If i click view the message then display my winfrom window but does not show Windows desktop screen.

How i can solve and view the winform single window(display). can you tell me how can i achieve this post me any good example so that i will get some idea to do it.

Thread th = new Thread(new ThreadStart(MethodName));
            th.Start();
//i 've written these two lines in Onstart().


private void MethodName()
{
            Form12 form = new Form12();
             form.ShowDialog();
            Thread.Sleep(10000);
            form.Close();
}

Problems accessing a structure in a C# wrapper

$
0
0

Hi,

I have written a C# wrapper for a library of C functions. Most of the wrapper works correctly, when I call the C# methods, the underlying C functions perform as expected. The wrapper is compiled as a DLL which I've added as a reference in my project, and is brought in with "using CSWrapper"

I have a problem in that in my wrapper I have a structure:

 [StructLayout(LayoutKind.Explicit)]
        public struct tagDecodeCommand
        {
            [FieldOffset(0)]
            public int nSize;
            [FieldOffset(4)]
            public ulong ulCommand;
            [FieldOffset(12)]
            public ulong ulFlags;

            //[StructLayout(LayoutKind.Explicit)]
            //public struct Param
            //{
                [FieldOffset(20)]
                public Int64 i64Param;

                [FieldOffset(20)]
                public byte bParam;
                [FieldOffset(21)]
                public UInt16 usParam;
                [FieldOffset(23)]
                public int nParam;
                [FieldOffset(27)]
                public UInt32 ulParam;
                [FieldOffset(31)]
                public long lParam;
            //}
        }

I assgin values to the structure members with

CSWrapper.tagDecodeCommand Command = new CSWrapper.tagDecodeCommand();    

Command.nSize = Marshal.SizeOf(Command); Command.ulCommand = CSWrapper.ID_DECODE_SEEK; Command.ulFlags = CSWrapper.ID_DECODE_SEEK_FRAME | CSWrapper.ID_DECODE_INT; Command.i64Param = n64Pos;

The application compiles without any problems, however when I run the application I get an unhandled exception error: "tagDecodeCommand.nSize".

If I comment out the referece to nSize, I get a similar error for ulCommand

I cannot work out why I can't assign values to the members of the structure. I wrote a simpler app to test whether what I'm trying will work and it did:

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;

namespace StructTest
{
    class Program
    {
        [StructLayout(LayoutKind.Explicit)]
        struct TestStruct
        {
            [FieldOffset(0)]
            public int a;
            [FieldOffset(4)]
            public int b;
        }

        static void TestFunc(TestStruct t)// (Object obj)
        {
            //TestStruct t = (TestStruct)obj;


            Console.WriteLine("Test Func A: {0:d} B: {1:d}", t.a, t.b);
        }

        static void Main(string[] args)
        {
            TestStruct test;// = new TestStruct();

            test.a = 10;
            test.b = 20;

            Console.WriteLine("A: {0:d} B: {1:d}\n", test.a, test.b);

            TestFunc(test);

            Console.ReadKey();
        }
    }
}

Can someone please explain why I'm having trouble accessing the members of the structure in my Wrapper

Thanks in advance

Andrew

Referencing and using Managed C++ binaries in C#

$
0
0

Hello All,

I have a managed C++ dll built in DotNet 3.5 and my C Sharp application needs to call functions from it. The managed C++ dll internally uses unmanaged C++ dlls. While I am trying to use use the Managed C++ dll from a C sharp App built in DotNet 4/4.5, it is not able to load the dll because of assembly built DotNet version mismatch. Is this expected?

Another observation is that, when I try to test with a Visual Studio test project which is in DotNet 4.5 an able to use it.

Thanks,

Sujith

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?

Is there a way to know if there is a IWin32Window already created?

$
0
0

I don't know if this is the right place to ask.

But I came accross this exception the other time:

System.InvalidOperationException was unhandled by user code
Message=SetCompatibleTextRenderingDefault must be called before the first IWin32Win

Because I was doing:

System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

I understand why the error is happening, but I was wondering if there is a way to know if an IWin32Window was already created?

It is obvious from the Exception that the framework has access to that information. But I wanted to know if I could aswell know?

Thanks in advance for your help!


Dzyann.-


how to provide system.diagnostics.performancecounter impersonation through c#?

$
0
0
i have used the following code,
static void Main(string[] args)
{

PerformanceCounterCategory cat = new PerformanceCounterCategory("Processor", "172.16.2.171");
List<PerformanceCounter> counters = new List<PerformanceCounter>();
foreach (string instance in cat.GetInstanceNames())
counters.Add(new PerformanceCounter("Processor", "% Processor Time", instance, "172.16.2.171"));
for (int i = 0; i < 10000; i++)
{
foreach (PerformanceCounter counter in counters)
Console.Write(counter.NextValue() + " ");
}

}

it results the "Access is Denied Error", the remote system has the credentials suchas domainname, username, password . how can i provide credentials in performancecounter class to obtain the remote system performance

Pitfalls of Async?

$
0
0

I started to look into on simple examples how Async works and I find it extremely misleading that all tutorials and articles just talk about how great it is and almost none talk about the pitfalls (like with all hypes). I am not really interested how it works, but more interested in what situations it has to be avoided.

Let me draw an example. Assume I have an async method that I use as an event handler for a button. It's doing something timely, so I'm using async and await in the event handler code. The advantage is that as soon as wait is reached, the event handler will actually return, so the UI code can continue. Fine.

But, that also means that when the code fragment after the await actually continues in the event handler, then that code has to look around to see, what has changed since it got suspended. Why? During the suspension time, anything could change in the program. The button might have been long gone, maybe a completely different page is shown already, so continuing with the event handler code would even make no sense at all.

How is this situation is supposed to be handled?

Another example could be: how about if multiple requests are coming in, faster than the event handler can handle, so multiple event handler instances are called, each starting a new async branch. But what if this makes no sense from the program point of view and only one request should be kept (e.g. the last one)? How do you keep track how many branches you already "forked"?

If I have to keep track all ongoing async branches so that they can be cancelled, then I barely see the point of using async at all. It just makes you believe it's for async programming when it's really not. Async programming is much broader and includes also handling of all these issues. So how do you handle these things above?


Just in Time debugger for C# managed code - Revisited

$
0
0


I would like to use VS2010 as the JIT Debugger for my winforms application,
which contains managed and unmanaged 3rd party controls.

I have the set the following things:

1) In app.config i've inserted the following line (at the end of the config section):
<system.windows.forms jitDebugging="true" />

2) In VS, under Tools -> Options -> Debugging -> Just-In-Time
Managed, Native and Script are checked

3) In VS, the build configuration is set to DEBUG

4) The application is being configured as x86

5) In the registry
HKLM\SOFTWARE\Microsoft\Wow6432Node\.NETFramework\DbgManagedDebugger
has this line "C:\Windows\system32\vsjitdebugger.exe" PID %d APPDOM %d EXTEXT "%s" EVTHDL %d
and DbgJITDebugLaunchSetting is set to 2 hexadecimal.

If i completely remove (1) from the app.config, then .net dialog box appears whenever
and error occurs.  If i insert (1), then nothing happens. The program
just runs 'past' the error and not debugger pops up.

Any ideas?

Error: Cannot create more than one System.Windows.Application instance in the same AppDomain - Reflection of WPF Project

$
0
0

I am creating a visual studio plugin which will analyze code for WPF project. I am doing reflection activity to get metadata info and also to invoke some methods or constructor. As we know wpf project has App.xaml file which is a App class. So when i try to invoke a constructor of App class then it gives me error like "Cannot create more than one System.Windows.Application instance in the same AppDomain". Code to invoke constructor is as below:

Type t = _assembly.GetType(viewclassname);
ConstructorInfo ci = t.GetConstructors()[0];
ci.Invoke(null);

So i googled for this issue and found that it is not possible to create more than one instance of System.Windows.Application in same appdomain. So i googled again for how to create a new appdomain and how to load assembly into it. But i am unable to find how to get metadata info and how to invoke a method/constructor after load the assembly into new appdomain as i did in above code. I hope i clearly described my question.

Code that i used to create appdomain and load assembly into it.

AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
 newDomain.Load(assemblyPath);
I got this error "The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)" on executing above code.

So, how can i solve this issues and able to invoke constructor of System.Windows.Application class.

MainClass in a ReferencedAssembly

$
0
0

Dear all,

I have one assembly (a.dll) that process data (text files) in separate resource assemblies (r1.dll, r2.dll, r3.dll, etc...). Each resource assembly is processed, separately, by the "a.dll".

Therefore, I generate an executable assembly (for example: ar1.exe) where the EmbeddedResource is one resource assembly (for example: r1.dll) and the ReferencedAssembly is "a.dll".  Another executable assembly (for example: ar2.exe) where the EmbeddedResource is another resource assembly (for example: r2.dll) and the ReferencedAssembly is the same "a.dll".

The problem is specifying the MainClass to point to a class in the ReferencedAssembly. What is the syntax of specifying the MainClass that is in a ReferencedAssembly ?

Thank you

I can simplify the previous design by eliminating one step. Instead of having "a.dll" and "r1.dll" and then generate "ar1.exe" out of the two, I can generate "r1.exe" instead of "r1.dll" so that it contains the resources and reference "a.dll".
However, I still need to reference the MainClass that is contained in "a.dll" when generating "r1.exe".

Your help is much appreciated... thank you

Viewing all 1710 articles
Browse latest View live