Home » Microsoft Technologies

How do I re-establish a failed remote powershell connection or avoid leaking memory in C#

We are using C# code similar to following to establish a remote powershell session to manage an Exchange 2010 server:


MyCode {

            System.Security.SecureString securePassword = new System.Security.SecureString();

            foreach (char c in password.ToCharArray())





            PSCredential creds = new PSCredential(userName, securePassword);

            _r = RunspaceFactory.CreateRunspace();


            PowerShell powershell = PowerShell.Create();

            PSCommand command = new PSCommand();


            command.AddParameter("ConfigurationName", "Microsoft.Exchange");

            command.AddParameter("ConnectionUri", uri);

            command.AddParameter("Credential", creds);

            command.AddParameter("Authentication", "Default");


            PSSessionOption sessionOption = new PSSessionOption();

            sessionOption.SkipCACheck = true;

            sessionOption.SkipCNCheck = true;

            sessionOption.SkipRevocationCheck = true;

            command.AddParameter("SessionOption", sessionOption);

            powershell.Commands = command;



            powershell.Runspace = _r;


            Collection<PSSession> result = powershell.Invoke<PSSession>();

            foreach (ErrorRecord current in powershell.Streams.Error)


               // log errors



            if (result.Count != 1)

                throw new Exception("Unexpected number of Remote Runspace connections returned.");


            powershell = PowerShell.Create();

            command = new PSCommand();


            command.AddParameter("Name", "ra");

            command.AddParameter("Value", result[0]);

            powershell.Commands = command;

            powershell.Runspace = _r;



            powershell = PowerShell.Create();

            command = new PSCommand();

            command.AddScript("Import-PSSession -Session $ra");

            powershell.Commands = command;

            powershell.Runspace = _r;



            // Wait for incoming commands, invoke as they arrive



This approach works fine, unless, as in a particular environment, the heartbeat mechanism between the remote powershell and the server (every 3-4 minutes, as we understand it) fails for whatever reason.  In this case, an exception is thrown trying to execute a subsequent provisioning command:  << Exception calling "PromptForCredential" with "4" argument(s): "Cannot invoke this function because the current host does not implement it." >>


When this happens, we simply establish a new powershell session using the code above, and all is well, except that each time this occurs, the process eats up an additional 25-50 MB of memory.  We’ve tried calling combinations of powershell.Dispose(), powershell = null, _r.Dispose(), _r = null, System.GC.Collect() and “Remove-PSSession” to no avail.


Our question, then, is twofold:  a) Is there some other way to free up the memory used by the original connection, and/or b) Is there some way to “awaken” the original powershell session when the heartbeat has failed, to avoid having to create a new session?


Thanks in advance for any ideas.



We have installed SQL Server 2008 R2 on a virtual server (C-SQL) and SharePoint Server 2010 on another virtual server (C-SPOINT), with the SQL Backend of the SharePoint database residing on C-SQL. This worked fine.

SQL Server was installed with the domain administrator account and SharePoint with an account called 'visi' that has domain administrator privileges.

SSRS on C-SQL was initially installed as a native database. I changed this to a SharePoint integrated database with all authentications done as the visi user. Report server url was set to the normal http://C-SQL:80/ReportServer/.

On the SharePoint central administration site under General Application Settings -> Reporting Services Integration I filled in the details as required:

Report Server Web service URL: http://C-SQL/ReportServer/
Authentication mode: Windows Authentication
Credentials: Usr: DOMAIN\visi Pwd: ****
All site collections.

Clicking on the OK button it takes a while and then I get the following error:

Failed to establish connection with report server. Verify the server URL is correct or review ULS logs for more information. Product area: SQL Server Reporting Services, Category: Configuration Pages

Looking through the ULS Logs I find under the Area: SQL Reporting Services the following messages (with some other “Area” messages in between:

Exception encountered for SOAP method GetSystemProperties: System.Net.WebException: The request failed with HTTP status 401: Unauthorized.     at Microsoft.SqlServer.ReportingServices2010.RSConnection2010.SetConnectionProtocol()     at Microsoft.SqlServer.ReportingServices2010.RSConnection2010.SoapMethodWrapper`1.ExecuteMethod(Boolean setConnectionProtocol)
Exception in TestCurrentUrlConnection: System.Net.WebException: The request failed with HTTP status 401: Unauthorized.     at Microsoft.ReportingServices.SharePoint.UI.RSConnectionInfo.get_SPManagementProxy()     at Microsoft.ReportingServices.SharePoint.UI.RSUtility.CheckReportServerVersion(String& errorMessage)
Failed to retrieve RS configuration information: System.Net.WebException: The request failed with HTTP status 401: Unauthorized.     at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)     at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)     at Microsoft.SqlServer.ReportingServices2010.ReportingService2010.GetReportServerConfigInfo(Boolean ScaleOut)     at Microsoft.ReportingServices.SharePoint.UI.RSIntegrationSettings.GetReportServerConfigInfo(IList`1& configInfos)

This lead me to assume it is an IIS block. But under Authentication in IIS on the C-SQL server the windows authentication is enabled.

I have also read somewhere that the SharePoint web front end is a minimal install on the SQL Server for this type of setup, which I did.

Looking at the SQL Server logs on C-SQL, I get a weird logon error, which I don’t know if it is related:

Login failed for user 'DOMAIN\C-SPOINT$'. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors. [CLIENT:]
Error: 18456 Severity: 14 State: 11.

As you can see it is not the normal DOMAIN\User, it’s actually DOMAIN\ServerName, which doesn’t make sense at all.

I have been struggling with this for 2 weeks. Any advice / help will be greatly appreciated.


<!-- [if gte mso 10]> <mce:style>

Our Company, HOB Germany (www.hob.de) wants to implement a Client, which is able to connect to a Remote Assistance connection on a Windows home edition.


The Remote Assistance Connection is well documented in [MS-RAI] and [MS-RA], but sadly, we are not even able to get to the point, where the virtual channel data is exchanged (This is the point, where these documentations start at).


We started a Remote Assistance Connection by creating an invitation on a Windows XP home edition, which creates a *.msrcincident file of the form described in [MS-RAI] Appendix A (Remote Assistance Invitation File Format). This file is opened on the "helper's computer" with the Microsoft Help and Support Center, which starts the connection. The packets, which are exchanged in the start-phase of the connection are regular RDP-packets.

Now we tried to establish the same connection with our own Client, but the helpee's computer aborts the connection in an early stage: The exchange of the first packets seems to be normal, until the Client (=helper) sends a Client Info PDU and the helpee sends a so-called Licensing Error Message ([MS-RDPBCGR] that signals success (even though the name of the PDU suggests an error message). Weirdly, the helpee sends a packet which signals the end of the connection immediately afterwards.

Our Client obviously does something different than the Microsoft Help and Support Center. We compared all sent packets until the "Security Exchange PDU", and in our judgment our client did not send anything, which could have caused that abortion. The next PDU is the "Client Info PDU", which is the first packet sent encrypted, so don't know, what the Microsoft Help and Support Center sends in this package.

Sadly, the documentation of Remote Assistance does not describe any differences to RDP-communication at the stage, but assumes, that a RDP-connection with virtual channels was already established successfully. We found out, that the Client (=helper) requests a virtual channel called "remdesk" (which isn't documented either). When our client requests this channel exactly like the Microsoft Help and Support Center does, the connection is still aborted by the helpee after the same PDU, so this is not what we did wrong.


Our questions:

Is there any documentation, how the RDP-connection, which wraps the Remote Assistance Connection, is established or is there any documentation about the differences to regular RDP?

Is it possible, that the helpee requires special information in the "Client Info PDU", which we don't know about?


Your Answer would help us a lot.

Thanks a lot for you effort,


Johannes Bauer, HOB Germany


I am modifying a SharePoint site and so far so good.  Some of the objects were created using Visual Studio 2008 (C#).  I was able to modify these objects and implement them on the targete machine without issue.  The final step is to implement the ASPX pages that were modified using SharePoint Designer 2007.  These are aspx pages that are used to modify items in lists.  All the pages involved in this upgrade are customized.  I need to upgrade the target site with the modified version of these pages.  My intent is to copy the code from the page in the source site and past it into the same page on the target site.  I tried using the Remote Web Site connection tool in SharePoint Designer 2007 but received the following error message:

"Unable to open 'https://(site address)'.  Server Error:  Could not find a Web server at 'website'.  Please check to make sure that the Web server name is valid and your proxy settings are set correctly.  If you are sure that everything is correct, the Web server may be temporarily out of service."

I am not sure how to first check to see if the Web Server is temporarily out of service.  I would appreciate your input on how to verify this.

Background information of target machine:  WinServer 2008, IIS 7, Sharepoint (MOSS2007), site on port 80

I would appreciate inputs on this.  If there is a better way of upgrading the pages on the target site I would like to hear about that too.  Thanks.


Hi, I have 2 windows servers each running server version 2008. On each server I installed SQL 2008 enterprise. Each has remote connections allowed in SQL. On each server the firewall is disabled and file sharing is enabled. each servers user accounts are identical same name and password. also the sa account on each SQL installation is the same. From server A i am trying to access Server B from the SQL manamgement console and vice versa. I can see each PC from windows explorer for file sharing but each SQL server will not see each other.

Thank You



Here my code to establish the Connection ?

 string connect = "Data Source=xxx.xxx.xxx.xx,xxxx;Network Library=DBMSSOCN;database=channel;User ID=sa;Password=xxxxxx;";

      mycon.ConnectionString = connect;


Error while establishing connection:


A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.)


Please sort out my Issue ?


I have been following the steps in Jie Li's blog (http://blogs.msdn.com/b/opal/archive/2010/03/07/sharepoint-2010-with-windows-powershell-remoting-step-by-step.aspx) to set up a remoting connection to my SharePoint 2010 server using PowerShell.  However, after configuring everything I am getting the following error: 

Remote host method PushRunspace is not implemented.

Any ideas on what is the cause?




Hi All,

 we are migrating an 32 application from win server 2003 to win server 2008 R2  64 bit machine, as part of that i created a ODBC component to access database , userid and password to this ODBC component is obtained from a registry

when trying to get it from registry i am getting the following error:

Error Establishing Data Connection-[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user ''.

path which i gave to access the registry key values are :

const RegistryPathForKey = "\SOFTWARE\Wow6432Node\Microsoft\<specific values to my project>\

i created ODBC component from syswow64--> odbcad32.exe

created registry keys under node wow6432node

i tried to hardcord the values though i was able to continue with my application , later i got one more problem , there was error in creating the objects for com+ application and my application did not work

kindly help in any way on this

Thanks in Advance,

Fayaz K



My application uses a dll, that I simply link with the LoadLibrary function and then, using the getPRocAdrress, I take the addresses of the sported functions that I need to use.

Now, due to the sensible info in the dll, I need to crypt it with AES before save it on disk.

So, for its use now I have to modify my aplpication in order to:

1 - Decrypt the dll file, WITHOUT saving the decrypted data on disk, but only taking them in memory;

2 - Then, use the decrypted dll from memory. So my question is: Can I do a loadLibrary(or samething similar) from memory, and not from disk? Or, having the decrypted dll stored in a buffer inmemory, how can I extract the address of the functions that I need to use? 

3 - After that, I have to avoid anyone to perform a memory dump while my application is running. Can this be done? How?




Hi all,

I am trying to connect sql server using windows authentication . I am getting the fallowing when I try to establish a connection to sql server

A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Can any one tell me how to resolve this problem..


Hi All,

I have developed one application which sends the mails (100 mails at a time) to different domains (gmail,yahoo and rediff). First time I am able to send the mails to different domains (going as spam mails) and when trying to send second time the following error messages recording in event viewer.

"Message delivery to the remote domain 'gmail.com' failed for the following reason: The connection was dropped by the remote host."

"Message delivery to the remote domain 'yahoo.com' failed for the following reason: An SMTP protocol error occurred."

"SMTP could not connect to the DNS server ''. The protocol used was 'UDP'. It may be down or inaccessible." and here is the my code

emailsend(_Name, _EmailID, _FromEmailID, _CCEmailID, _Path)

Private Sub emailsend(ByVal _Name As String, ByVal _ToEmailID As String, ByVal _FromEmailID As String, ByVal _CCEmailID As String, ByVal _Path As String)
        Dim objEmail As New MailMessage()
        objEmail.[To] = _ToEmailID
        objEmail.From = _FromEmailID
        objEmail.Cc = _CCEmailID
        objEmail.Subject = (("" & " ") & drpdownMonth.SelectedItem.Text & "-") & drpdwnYear.SelectedItem.Text
        objEmail.Body = (("Hai " & _Name & "," & vbLf & vbLf & " ") & drpdownMonth.SelectedItem.Text & "-") & drpdwnYear.SelectedItem.Text & "." & vbLf & vbLf & vbLf & "Regards " & vbLf & "xyz" & vbLf & "abc" & vbLf & "mno"
        objEmail.Priority = MailPriority.High
        objEmail.Attachments.Add(New MailAttachment(Server.MapPath(((("Data\" & drpdownMonth.SelectedItem.Text & "-") & drpdwnYear.SelectedItem.Text & "\" & _EmpID & "-") & drpdownMonth.SelectedItem.Text & "-") & drpdwnYear.SelectedItem.Text & ".pdf")))

            lstboxEmail.Visible = True

            lstboxEmail.Items.Add("Your Email has been sent to" & "-" & _EmailID & "-" & "sucessfully " & vbLf)
        Catch exc As Exception
            lstboxEmail.Visible = True

            lstboxEmail.Items.Add("Send failure: " & exc.ToString())
        End Try
    End Sub

Can some help me how to send mails to different domains (gmail,yahoo and rediff) without spam through SMTP service.

Waiting for reply.........


Does anyone know how to use connection pooling to connect SQL Server using powershell script with minPoolSize 2??

I have a server we have many SQL Server Agent job. Out of them a a handful of jobs with more than 1 steps runs ever 2 minutes. This is server is already thrashed with heavy Logins and logout per second by a third party application. Last month at one incident it reached to 2000 login/logout per seconds.

We have decided to move frequently running jobs to OS tasks. Scripting language favored is powershell and we will use wait method.


We need to use a method that creates WPF user control inside a DLL of ours. Since we do not control the calling application and WPF UI must be created in an STA thread, we create a thread, set its apartment state to STA than call the method in its procedure.

Doing this causes massive amount of handle leaks that cannot be reclaimed by the system. Eventually, the system crashes.

// To use normal (no threads and no leaks), uncomment this
//#define USE_STA 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Controls;
using System.Windows.Documents;
using System.Threading;

namespace WPF_STA_Leak
      // Code that leaks handles if called inside from a thread
      privatestatic void TestLeak(object autoResetEvent)
         Label label = new Label();
         FixedPage fixedPage = new FixedPage();

         // Signal
         if(autoResetEvent != null)
            (autoResetEvent asAutoResetEvent).Set();

      #if USE_STA

      staticvoid Main(string[] args)
         constint count = 10000;

         bool useThread = Thread.CurrentThread.GetApartmentState() != ApartmentState.STA;
         Console.WriteLine("{0} hit Enter to start", useThread ? "Using threads" : "Not using threads");
         for(int i = 0; i < count; i++)
               using(AutoResetEvent autoResetEvent = newAutoResetEvent(false))
                  Thread thread = newThread(new ParameterizedThreadStart(TestLeak));

            Console.WriteLine("Iter {0} of {1}", i + 1, count); 


         Console.WriteLine("Done. Press Enter to exit");



I'm running in to the problem described in this thread: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/477e21d6-f0b1-47cd-bcef-1636acff084d/

Essentially, if I run a storyboard that animates fontsize long enough, it will raise a fontcachefullexception and crash the program.  Is this a known issue?  Are there any workarounds?

Using task_group in MFC project, I get huge memory leaks report. Just creating task_group instance is enough to reproduce this. Are these leaks real or memory is released after MFC memory leaks report? How can I prevent this report to be shown, and continue to track another memory leaks, not related to task_group?
Leaks reported also when using other resources, like reader_writer_lock.
I am developing a Silverlight application to do data sync. It seems to leak memory, does anyone have any guidance or solution?

Hi All,

I'm new to WPF development.  I have designed an application in WPF that scans table every 35 seconds and displays all records in a WPF Toolkit DataGrid control.    This application runs as a management console type and it scans table every 35 seconds 24 hours.   Apparently I noticed there a hughe memory leak.  In few days it goes upto easily 1.5 gb of memory.  Although I'm only displaying 600 rows x 7 columns in every scan.   The scan on the table that happens every 35 seconds is relatively same.    Through my investigation and running through ANTS profiling I came to know that:

a) System.Collections.Generic --Dictionary<Tkey,TValue>+Entry<DependencyProperty,bool[]> has live instances over 50,000 and it keep increasing.   After a bit looking into the profiler it appears that there are chain references and because of that it is not garbage collected.  The chain reference is from DataGridHelper._propertyTransferEnablemap --> Microsoft.Windows.Controls.Weakhasttable---> System.collections.Hastable + bucket[] --> system.Collections.GenericDictionary<windows.DependencyProperty, bool>

I don't understand what is the exact chain and how do I break the chain reference.   Here is what I do in code to bind the Observable Collection to DataGrid.DataContext

In nutshell

Private void PopulateGrid()   //this function is called every 35 seconds



jobs = new JobService();   //Jobs object basically has Observable collectin property called JobList.  This class basically connects to //Database and builds the collection of data retrieved

this.DataGrid.dataContext = Jobs


Private Void CleanGridView()


 if(jobs!=null){ Jobs.dispose(); Jobs = null}  //release manged code


Plz help here as my knowledge to WPG is relative very weak and I need to deploy this application in production where it will be running 365 days.  

Also I can send you the whole project to see in details but I don't know if I can attach a project here.

thanks in advance.





i have  hugh memory leak'in a application of mine. I found which object causes it but i don't understand it. I hope you guys can tell me why it leaks memory and how to solve it.

I have a object that is mapped with nhibernate to a table in the database. That object has a byte array which stores a image. Because that this object is part of a list of other object the memory leaks is very dangerous for my application (after running one day the memory consumtion is allmost 1gb).

With the ants profiler i see that the object is finalised. But it looks that .net don't release the the bytes and taking new memory for new objects. I'm looking with performance counters of only the unmanaged memory is increasing but don't have good results yet.

some tips to locate and solve this issue?


Hi all,

EffectiveValueEntry is leaking memory and attaching to the custom controls and to the thirdparty contentpanes. Is there anyway to remove this value from the attached property.

How to get all the registered dependency property for a control/page ?

In MSDM it is mentioned that "If you want to take all property value participants out of the process and set the value to the registered metadata default, you can obtain that default value definitively by querying the dependency property metadata" but how to get the default values so that i can reset and clean this leak.




I have created very simple console application which converts xaml file to jpeg. I have found that there is big memory leak when running this application. After some 5000 conversions almost all RAM is eaten (about 400 MBytes). I have tested this inside virtual PC 2007 with WindowsXP and Vista as guest operating system.

Any idea what can be wrong…












for(inti=0;i<  5000;++i)




































<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="101" Height="80">

<Image Width="101" Height="80" Source="00.jpg"/>

<TextBlock Width="101" Margin="0,10" Text="Hello!" TextAlignment ="center" Foreground="Navy" Background="AntiqueWhite"/>




I am writing a C# web service. But I am having memory leak problem with the web services.

To check the problem, I created a simple web service with just one function that will take two integers as parameters and return their addition. I created an application that consumes this web service and ran it for 10000 times.

But even this simple web service was consuming memory. I used the ANTS memory profiler to check the memory consumption. It showed that ‘Hashtable+bucket[]’ object is consuming most of the used memory. Looks like this object is storing server identity IDs for all the connections.

What exactly this object stores? Is there any way to release the memory used by this object? Or can we avoid using this object? How can I stop memory leak problem for the web services?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure