Click here to Skip to main content
15,898,374 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I decide write my own multi thread rdp client. During work of my programm I've got an error - Error HRESULT E_FAIL has been returned from a call to a COM component. at MSTSCLib.IMsRdpClient7.set_UserName(String pUserName).Can anybody help me?
My code snippet:

C#
object [] args = new object[5];
args[0] = pathToSuccessHosts;
args[1] = pathToBadHosts;
args[2] = pathToErrors;
args[3] = _countDBRecords;

panelRdpControlContainer.Size = new Size(0, 0); //  container for AxMsRdpClient7NotSafeForScripting elements

 
			
int countThreads = 10;

 for (int i = 0; i < countThreads; i++)
	{  
		Thread th = new Thread(_doRDPConnection.DoRDPConnection);
	   
		th.IsBackground = true;
		th.SetApartmentState(ApartmentState.STA);
		
		AxMSTSCLib.AxMsRdpClient7NotSafeForScripting rdpclient = new AxMSTSCLib.AxMsRdpClient7NotSafeForScripting();
	 
		rdpclient.Name = string.Format("rdpClient{0}", i); 
		rdpclient.OcxState = (System.Windows.Forms.AxHost.State) rdpclient.GetOcx();  
		
		panelRdpControlContainer.Controls.Add(rdpclient); // Add control to System.Windows.Forms.Panel panelRdpControlContainer
	   
		args[4] = rdpclient; 
		
		th.Start(args);
	}
	public class RDPConnection
    {
        Form form1;
        public static volatile int _countThreads;
        public static volatile int _currentLine;
        public static volatile int _countHandledRecords;
        public volatile bool _shouldStop = false;
        public static Object _lockGenRDPFile = new Object();
        public static Object _lockSuccessHostsFile = new Object();
        public static Object _lockBadHostsFile = new Object();
        public static Object _lockErrorsFile = new Object();
        public static Object _lockProgressBar = new Object();
        public static Object _lockRDPClientControl = new Object();
        delegate void SetTextDelegate(string text);
        delegate void SetProgressValueDelegate(int value);
        SetProgressValueDelegate setProgressValueDelegate;
        SetTextDelegate d;

        [DllImport("user32.dll")]
        public static extern bool PostMessage(int hWnd, uint Msg, int wParam, Int64 lParam);

        public DoRDPConnection(Form  form)
        {
            d = SetCountThreads;
            setProgressValueDelegate = SetProgressValue;
            form1 = form;
        }

        public void RequestStop()
        {
            _shouldStop = true;
        } 
         
        public void SetCountThreads(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (form1.lblCountThreads.InvokeRequired)
            {
                form1.lblCountThreads.Invoke(d, new object[] { text });
            }
            else
            {
                form1.lblCountThreads.Text = text;
            }
        }

        public void SetProgressValue(int value)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (form1.progress.InvokeRequired)
            {
                form1.progress.Invoke(setProgressValueDelegate, new object[] { value });
            }
            else
            {
                form1.progress.Value = value;
            }
        }

        
        public void DoRDPConnection(object args)
        {
            try
            {
                bool bOnConnecting = false;
                bool bOnConnected = false;
                bool bOnLoginComplete = false;
                ManualResetEvent mre = new ManualResetEvent(false);
                RDPData rdpData = null;

                Array argArray = new object[3];
                argArray = (Array)args;

                string pathToSuccessHosts = (string)argArray.GetValue(0);
                string pathToBadHosts = (string)argArray.GetValue(1);
                string pathToErrors = (string)argArray.GetValue(2);
                long countDbRecords = (long)argArray.GetValue(3);
                
                AxMSTSCLib.AxMsRdpClient7NotSafeForScripting rdpclient = (AxMSTSCLib.AxMsRdpClient7NotSafeForScripting)argArray.GetValue(4);
                
                _countThreads++;
                SetCountThreads(string.Format("Threads:{0}", _countThreads));

                rdpclient.OnLoginComplete += delegate(object sender, EventArgs e)
                {
                    MessageBox.Show("OnLoginComplete"); 
                    bOnLoginComplete = true;

                    if (rdpData != null)
                    {
                        lock (_lockSuccessHostsFile)
                        {
                            using (StreamWriter w = new StreamWriter(pathToSuccessHosts, true))
                            {
                                w.WriteLine(string.Format("{0}@{1};{2}", rdpData.IP, rdpData.Login, rdpData.Password));
                            }
                        }
                    }
                };

                rdpclient.OnConnecting += delegate(object sender, EventArgs e)
                {
                    //MessageBox.Show("OnConnecting"); 
                    bOnConnecting = true;

                };

                rdpclient.OnDisconnected += delegate(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e)
                { 
                    mre.Set();
                };

                rdpclient.OnConnected += delegate(object sender, EventArgs e)
                {
                    //MessageBox.Show("OnConnected");
                    bOnConnected = true;
                };
 
                
                rdpclient.OnFatalError += delegate(object sender, AxMSTSCLib.IMsTscAxEvents_OnFatalErrorEvent e)
                {
                    //MessageBox.Show("OnFatalError");
                    lock (_lockErrorsFile)
                    {
                        using (StreamWriter w = new StreamWriter(pathToErrors, true))
                        {
                            w.WriteLine(string.Format("{0}@{1};{2} - {3}", rdpData.IP, rdpData.Login, rdpData.Password, e.ToString()));
                        }
                    }
                };

                string currentDirectory = Directory.GetCurrentDirectory();
                string pathToIpLoginPasswordDB = currentDirectory + "\\" + "IpLoginPasswordDB.txt";
                string pathToCurrentIP = currentDirectory + "\\currentIP.txt";
                long currentLine;

                if (!File.Exists(pathToCurrentIP)) File.Create(pathToCurrentIP);

                while (true)
                {
                    if (_shouldStop) break;

                    List<RDPData> listRdpData = new List<RDPData>();

                    lock (_lockGenRDPFile)
                    {

                        using (StreamReader r = new StreamReader(pathToCurrentIP))
                        {
                            long.TryParse(r.ReadLine(), out currentLine);
                        }

                        using (StreamReader r = new StreamReader(pathToIpLoginPasswordDB))
                        {
                            string IP = string.Empty;
                            int needReedLines = 1;  
                            string line = string.Empty;

                            for (int i = 0; i < currentLine; i++)
                            {
                                line = r.ReadLine();
                                if (string.IsNullOrEmpty(line)) goto Exit;
                            }

                            for (int j = 0; j < needReedLines; j++)
                            {
                                line = r.ReadLine();

                                if (!string.IsNullOrEmpty(line))
                                {
                                    currentLine++;

                                    string[] arrLines = line.Split(new char[] { ';' });

                                    if (arrLines != null && arrLines.Length == 3)
                                    {
                                        rdpData = new RDPData();

                                        rdpData.IP = arrLines[0];
                                        rdpData.Login = arrLines[1];
                                        rdpData.Password = arrLines[2];

                                        listRdpData.Add(rdpData);
                                    }

                                }
                                else break;
                            }
                        }

                        using (StreamWriter w = new StreamWriter(pathToCurrentIP))
                        {
                            w.WriteLine(currentLine.ToString());
                        }
                    }

                    mre = new ManualResetEvent(false); 

                    if (listRdpData.Count == 0) goto Exit;

                    for (int i = 0; i < listRdpData.Count; i++)
                    {
                        lock (_lockProgressBar)
                        {
                            
                            SetProgressValue(Convert.ToInt32(((_countHandledRecords * 100) / countDbRecords)));
                        }

                        rdpData = listRdpData[i];

                        if (rdpData != null)
                        {
                            lock (_lockRDPClientControl)
                            {
                                 
                                rdpclient.UserName = rdpData.Login;
                                //IMsTscNonScriptable secured = (IMsTscNonScriptable)rdpclient.GetOcx();
                                //secured.ClearTextPassword =  rdpData.Password;
                                rdpclient.AdvancedSettings2.ClearTextPassword = rdpData.Password;
                                rdpclient.Server = rdpData.IP;
                                rdpclient.Connect();
                            }

                            System.Threading.Timer timer = new System.Threading.Timer(delegate(object source)
                            {
                                rdpclient.Disconnect();
                                timer = null;
                            });

                            timer.Change(TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(-1));

                            mre.Reset();

                            mre.WaitOne();

                            if (!bOnLoginComplete && bOnConnected)
                            {
                                lock (_lockErrorsFile)
                                {
                                    using (StreamWriter w = new StreamWriter(pathToErrors, true))
                                    {
                                        w.WriteLine(string.Format("{0}@{1};{2}", rdpData.IP, rdpData.Login, rdpData.Password));
                                    }
                                }
                            }

                            if (!bOnLoginComplete && !bOnConnected && bOnConnecting)
                            {
                                lock (_lockBadHostsFile)
                                {
                                    using (StreamWriter w = new StreamWriter(pathToBadHosts, true))
                                    {
                                        w.WriteLine(string.Format("{0}", rdpData.IP));
                                    }
                                }
                            }

                            bOnConnecting = false;
                            bOnConnected = false;
                            bOnLoginComplete = false;

                            _countHandledRecords++;
                        }
                    }

                    lock (_lockProgressBar)
                    {
                        
                        SetProgressValue(Convert.ToInt32(((_countHandledRecords * 100) / countDbRecords)));
                    }
                }

            Exit: ;
                SetCountThreads(string.Format("Threads:{0}", --_countThreads));


                if (_countThreads == 0)
                {
                    int wParam = 0;
                    long lParam = 0;

                    PostMessage((int)form1.Handle, form1.queryCancelOperation, wParam, lParam);
                    SetCountThreads(string.Format("Finish! Потоков:{0}", 0));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\\n" + ex.StackTrace);
            }
        }
        
    }

    class RDPData
    {
        public RDPData() { }

        public string IP;
        public string Login;
        public string Password;
    }
Posted

1 solution

Please see your locking mechanisms. Be sure you don't have clashing threads when attempting to access rdpData.Login and set rdpClient.UserName..

Also, be sure rdpData.Login has a value.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900