protected override void ExecuteMain()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                this.Status = StepStatusEnum.Executing;
                Impersonator impersonator = new Impersonator(
                    Properties.Settings.Default.DomainUserName,
                    Properties.Settings.Default.Domain,
                    Properties.Settings.Default.DomainPassword);

                foreach (string ruleId in Properties.Settings.Default.RuleIds)
                {
                    string sourcePath = Path.Combine(
                        Properties.Settings.Default.RuleSourceFolder,
                        "{0}.dat.gz".FormatWith(ruleId)
                        );
                    string destFolder = Properties.Settings.Default.RuleDestFolder;
                    if (!destFolder.EndsWith("\\"))
                    {
                        destFolder += "\\";
                    }
                    string destPath = Path.Combine(
                        Path.GetDirectoryName(destFolder),
                        "{0}.dat.gz".FormatWith(ruleId)
                        );
                    File.Copy(sourcePath, destPath, true);
                    sb.AppendLine("Copied {0} to {1}".FormatWith(sourcePath, destPath));

                    // Decompress is not needed any more after Harry's update to MixMerge.exe tool
                    //AsyncDecompress(destPath);
                    //Decompress(destPath);
                }

                impersonator.Undo();

                this.Status       = StepStatusEnum.Pass;
                this.ResultDetail = new StepResultDetail(sb.ToString() + "\r\nSuccessfully prepared the gz files.");
            }
            catch (Exception ex)
            {
                this.Status       = StepStatusEnum.Failed;
                this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex));
            }
            finally
            {
                if (this.ResultDetail != null)
                {
                    Log.Info(this.ResultDetail.Message);
                }
            }
        }
Beispiel #2
0
        protected virtual void PostExecute()
        {
            string logPath = Properties.Settings.Default.ResultLogPath.Trim();

            if (!string.IsNullOrEmpty(logPath))
            {
                ////FileAttributes attr = File.GetAttributes(logPath);
                ////if ((attr & FileAttributes.Directory) != FileAttributes.Directory)
                if (IsFilePath(logPath))
                {
                    // Only serialize when the logPath is a filename (not a directory name)

                    Impersonator impersonateor = new Impersonator(
                        Properties.Settings.Default.DomainUserName,
                        Properties.Settings.Default.Domain,
                        Properties.Settings.Default.DomainPassword);
                    try
                    {
                        // There was an error reflecting type 'RulePerf.Model.RestartMachinesStep'.
                        //XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
                        //using (XmlWriter writer = XmlWriter.Create(logPath))
                        //{
                        //    xmlSerializer.Serialize(writer, this);
                        //}
                        BinaryFormatter bf = new BinaryFormatter();
                        using (Stream output = File.OpenWrite(logPath))
                        {
                            bf.Serialize(output, this);
                            output.Flush();
                            output.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.CentralProcess(ex);
                    }
                    finally
                    {
                        try
                        {
                            impersonateor.Undo();
                        }
                        finally { }
                    }
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Execute this step.
        /// </summary>
        protected override void ExecuteMain()
        {
            this.Status = StepStatusEnum.Executing;
            string logPath = Properties.Settings.Default.ResultLogPath.Trim();
            string cmd     = UpsertArgument(Properties.Settings.Default.RemoteCommand, "ResultLogPath", logPath);

            Impersonator impersonator = new Impersonator(Properties.Settings.Default.RemoteUserName, Properties.Settings.Default.RemoteDomain, Properties.Settings.Default.RemotePassword);
            WMICmdHelper wmiHelper    = new WMICmdHelper(
                Properties.Settings.Default.RemoteMachine,
                cmd,
                Properties.Settings.Default.RemoteUserName,
                Properties.Settings.Default.RemotePassword,
                Properties.Settings.Default.RemoteDomain
                );

            wmiHelper.RunCommandReturnOutput();

            if (wmiHelper.ExitCodeCaptured)
            {
                if (wmiHelper.ExitCode == 0)
                {
                    this.Status       = StepStatusEnum.Pass;
                    this.ResultDetail = new StepResultDetail("Successfully executed the following command on {0} as user {2}.\r\n{1}".FormatWith(
                                                                 Properties.Settings.Default.RemoteMachine,
                                                                 Properties.Settings.Default.RemoteCommand,
                                                                 Properties.Settings.Default.RemoteUserName
                                                                 ));
                }
                else
                {
                    this.Status       = StepStatusEnum.Failed;
                    this.ResultDetail = new StepResultDetail("Failed to execute the following command on {0} as user {2}. The exit code is {3}. Please check log for more details.\r\n{1}".FormatWith(
                                                                 Properties.Settings.Default.RemoteMachine,
                                                                 Properties.Settings.Default.RemoteCommand,
                                                                 Properties.Settings.Default.RemoteUserName,
                                                                 wmiHelper.ExitCode
                                                                 ));
                }
            }
            else
            {
                // Check the log path
                Log.Info("Failed to get the exit code of the following command on {0}.\r\n{1}\r\nChecking log from network path...".FormatWith(
                             Properties.Settings.Default.RemoteMachine,
                             Properties.Settings.Default.RemoteCommand
                             ));
                try
                {
                    DateTime start   = DateTime.Now;
                    DateTime end     = DateTime.Now;
                    TimeSpan timeout = TimeSpan.MaxValue;
                    TimeSpan.TryParse(Properties.Settings.Default.RemoteTimeout.ToString(), out timeout);

                    Step step = null;

                    while (!File.Exists(logPath) || FileHelper.IsFileLocked(logPath) || (step = Step.GetFromFile(logPath)) == null)
                    {
                        if (end.Subtract(start).CompareTo(timeout) < 0)
                        {
                            System.Threading.Thread.Sleep(TimeSpan.FromMinutes(1));
                            end = DateTime.Now;
                        }
                        else
                        {
                            throw new TimeoutException("Timed out after {0} waiting for the result file {1}.".FormatWith(
                                                           timeout.ToString(), logPath
                                                           ));
                        }
                    }

                    if (step != null)
                    {
                        this.Status       = step.Status;
                        this.ResultDetail = new StepResultDetail("", new List <Exception>());
                        if (step.ResultDetail != null)
                        {
                            this.ResultDetail.Message += step.ResultDetail.Message;
                            if (step.ResultDetail.Exceptions != null && step.ResultDetail.Exceptions.Count > 0)
                            {
                                this.ResultDetail.Exceptions.AddRange(step.ResultDetail.Exceptions);
                            }
                        }
                    }
                }
                catch (TimeoutException tex)
                {
                    this.Status       = StepStatusEnum.Timeout;
                    this.ResultDetail = new StepResultDetail("Timed out when waiting for the result of '{0}' executed on {1} from network path.".FormatWith(
                                                                 Properties.Settings.Default.RemoteCommand,
                                                                 Properties.Settings.Default.RemoteMachine), tex);
                }
                catch (Exception ex)
                {
                    this.Status       = StepStatusEnum.Warning;
                    this.ResultDetail = new StepResultDetail("Failed to get the exit code of the following command on {0}.\r\n{1}".FormatWith(
                                                                 Properties.Settings.Default.RemoteMachine,
                                                                 Properties.Settings.Default.RemoteCommand
                                                                 ), ex);
                }
            }

            impersonator.Undo();
        }
        protected override void ExecuteMain()
        {
            string       log          = string.Empty;
            Impersonator impersonator = null;

            try
            {
                this.Status = StepStatusEnum.Executing;

                //foreach (string changeGroupXmlFile in Properties.Settings.Default.ChangeGroupXmlFiles)
                //{
                //    Properties.Settings.Default.DownloadRiMEConfigReferencedList.Add(changeGroupXmlFile);
                //}

                bool pass = true;
                this.ResultDetail = new StepResultDetail("Started.");

                string cmd = Properties.Settings.Default.ApplyChangeGroupCommand;
                impersonator = new Impersonator(
                    Properties.Settings.Default.DomainUserName,
                    Properties.Settings.Default.Domain,
                    Properties.Settings.Default.DomainPassword);

                foreach (string sourceFile in Properties.Settings.Default.ChangeGroupXmlFiles)
                {
                    string fileName = Path.GetFileName(sourceFile);
                    File.Copy(sourceFile, Path.Combine(Directory.GetCurrentDirectory(), fileName), true);
                    cmd = cmd.FormatWith(fileName);

                    int result = ThirdPartyProgramBLL.EnhancedRunCommand(out log, cmd);

                    switch (result)
                    {
                    case 0:
                        if (!log.Contains("Error occured. The remote name could not be resolved: ", StringComparison.InvariantCultureIgnoreCase))
                        {
                            this.ResultDetail.Message += "\r\nSuccessfully ran the command: {0}.".FormatWith(cmd);
                            pass = true;
                        }
                        else
                        {
                            this.Status = StepStatusEnum.Failed;
                            this.ResultDetail.Message += "\r\nThe command '{0}' failed.".FormatWith(cmd);
                            pass = false;
                        }
                        break;

                    case -1073741510:
                        this.Status = StepStatusEnum.Cancelled;
                        this.ResultDetail.Message += "\r\nUser cancelled the command: {0}.".FormatWith(cmd);
                        pass = false;
                        break;

                    case -532462766:
                        this.Status = StepStatusEnum.Warning;
                        this.ResultDetail.Message += "\r\nThis step has run successfully, but some exceptions had been thrown by that step during running. Please check log file for more detailed information.";
                        pass = false;
                        break;

                    default:
                        this.Status = StepStatusEnum.Failed;
                        this.ResultDetail.Message += "\r\nCommand didn't run successfully, please check log for more detailed information.";
                        pass = false;
                        break;
                    }

                    if (!pass)
                    {
                        break;
                    }
                }

                if (pass)
                {
                    this.Status = StepStatusEnum.Pass;
                }
            }
            catch (Exception ex)
            {
                this.Status       = StepStatusEnum.Failed;
                this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex));
            }
            finally
            {
                if (this.ResultDetail != null)
                {
                    Log.Info(this.ResultDetail.Message);
                }

                if (impersonator != null)
                {
                    impersonator.Undo();
                }
            }
        }
        protected override void ExecuteMain()
        {
            try
            {
                string log = "";
                this.Status = StepStatusEnum.Executing;
                Impersonator impersonator = new Impersonator(
                    Properties.Settings.Default.DomainUserName,
                    Properties.Settings.Default.Domain,
                    Properties.Settings.Default.DomainPassword);

                Properties.Settings.Default.RiskAPICaller_Count_Run = (Properties.Settings.Default.TransactionCountPerRule * Properties.Settings.Default.RuleIds.Count).ToString();

                Properties.Settings.Default.Save();

                string path = Path.Combine(Properties.Settings.Default.ReplayToolPath, "MixedMerge.exe");

                string cmd = "{0} Mix /SrcFileFolder:\"{1}\" /RuleID:\"{2}\" /DefaultDstCnt:{3} /DstFileFolder:\"{4}\" /ImpersonateUserName:{5} /ImpersonateDomain:{6} /ImpersonatePassword:{7}".FormatWith(
                    path,
                    Properties.Settings.Default.RuleDestFolder,
                    string.Join(",", Properties.Settings.Default.RuleIds.ToArray()),
                    Properties.Settings.Default.RiskAPICaller_Count_Run,
                    Properties.Settings.Default.RiskAPICaller_DataFilePath,
                    Properties.Settings.Default.DomainUserName,
                    Properties.Settings.Default.Domain,
                    Properties.Settings.Default.DomainPassword
                    );

                Log.Info("Starting {0}".FormatWith(cmd));

                int result = ThirdPartyProgramBLL.RunCommand(out log, cmd);

                switch (result)
                {
                case 0:
                    this.Status       = StepStatusEnum.Pass;
                    this.ResultDetail = new StepResultDetail(log + "\r\nSuccessfully ran mixed merge tool.");
                    break;

                case -1073741510:
                    this.Status       = StepStatusEnum.Cancelled;
                    this.ResultDetail = new StepResultDetail(log + "\r\nUser cancelled the replay tool run.");
                    break;

                case -532462766:
                    this.Status       = StepStatusEnum.Warning;
                    this.ResultDetail = new StepResultDetail(log + "\r\nThis step has run successfully, but some exceptions had been thrown by that step during running. Please check log file for more detailed information.");
                    break;

                default:
                    this.Status       = StepStatusEnum.Failed;
                    this.ResultDetail = new StepResultDetail(log + "\r\nFailed, please check log for more detailed information.");
                    break;
                }

                impersonator.Undo();
            }
            catch (Exception ex)
            {
                this.Status       = StepStatusEnum.Failed;
                this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex));
            }
            finally
            {
                if (this.ResultDetail != null)
                {
                    Log.Info(this.ResultDetail.Message);
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Setups the global settings.
        /// </summary>
        /// <returns>Rows affected.</returns>
        /// <exception cref="System.Exception">Tried all {0} 'CP RK Database Servers' as the target sql server on which to execute the following sql statement but none of the trials succeeded: \r\n{1}\r\nThe tried servers are: {2}.Format2(serverAssignment.CpRkDatabaseServers.Length, sql, string.Join(, , serverAssignment.CpRkDatabaseServers))</exception>
        public static int SetupGlobalSettings(
            string netUserName = "******", string netPassword = "******", string netDomain = ".",
            string sqlServerWindowsAuthUserName = "******",
            string sqlServerWindowsAuthPassword = "******",
            string sqlServerWindowsAuthDomain   = "."
            )
        {
            string sql    = @"IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID('tempdb.dbo.#Keys'))
	                            DROP TABLE dbo.#Keys;                            
                            CREATE TABLE #Keys (vcKey varchar(900), nvcValue nvarchar(MAX));
                            INSERT INTO #Keys (vcKey, nvcValue) VALUES {0};
                            IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID('tempdb.dbo.#NewKeysAndValues')) DROP TABLE dbo.#NewKeysAndValues;
                            SELECT DISTINCT C.vcKey, K.nvcValue INTO #NewKeysAndValues FROM RiMEConfig.dbo.Config C JOIN #Keys K ON C.vcKey LIKE '%.%.' + K.vcKey OR C.vcKey LIKE '%.%' + K.vcKey + '%.%';
                            UPDATE RiMEConfig.dbo.Config SET nvcValue = (SELECT KV.nvcValue FROM #NewKeysAndValues KV WHERE KV.vcKey = Config.vcKey) WHERE EXISTS(SELECT KV.nvcValue FROM #NewKeysAndValues KV WHERE KV.vcKey = Config.vcKey);";
            string values = string.Join(",", Settings.Default.GlobalSettings.Cast <string>().Select(value => { string[] arr = value.Split(new char[] { '\t', '=' }, StringSplitOptions.RemoveEmptyEntries); return("('" + arr[0].Replace("'", "''").Replace("%quote%", "\"") + "', N'" + arr[1].Replace("'", "''").Replace("%quote%", "\"") + "')"); }).ToArray <string>());

            sql = sql.FormatWith(values);
            string originalServer = SqlServerHelper.ConnectionString.Server;

            ServerAssignmentModel serverAssignment = ServerAssignmentModel.GetInstance(netUserName, netPassword, netDomain);

            //if (serverAssignment.CpRkRiskConfigServers.Length > 0)
            if (serverAssignment.CpRkDatabaseServers.Length > 0)
            {
                int rowsAffected         = 0;
                int exceptionCount       = 0;
                int mirrorExceptionCount = 0;

                for (int i = 0; i < serverAssignment.CpRkDatabaseServers.Length; i++)
                {
                    Impersonator impersonator = new Impersonator(sqlServerWindowsAuthUserName, sqlServerWindowsAuthDomain, sqlServerWindowsAuthPassword);
                    #region Sql server connection and sql execution
                    SqlServerHelper.ConnectionString.Server = serverAssignment.CpRkDatabaseServers[i];
                    try
                    {
                        Log.Info("Executing command on server '{1}': \r\n{0}".FormatWith(sql, SqlServerHelper.ConnectionString.Server));
                        rowsAffected = SqlServerHelper.Execute(sql);
                        break;
                    }
                    catch (SqlServerHelperException ex)
                    {
                        if (!(ex.InnerException != null && ex.InnerException is System.Data.SqlClient.SqlException &&
                              ex.InnerException.Message.Equals(@"The database ""RiMEConfig"" cannot be opened. It is acting as a mirror database.")))
                        {
                            ExceptionHelper.CentralProcess(ex);
                        }
                        else
                        {
                            mirrorExceptionCount++;
                        }
                        exceptionCount++;
                        continue;
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.CentralProcess(ex);
                        exceptionCount++;
                        continue;
                    }
                    finally
                    {
                        impersonator.Undo();
                    }
                    #endregion Sql server connection and sql execution
                }

                if (mirrorExceptionCount == serverAssignment.CpRkDatabaseServers.Length)
                {
                    throw new Exception(@"The database ""RiMEConfig"" cannot be opened on all these 'CP RK Risk Config' Server: {0}. It is acting as a mirror database.".FormatWith(string.Join(", ", serverAssignment.CpRkDatabaseServers)));
                }

                if (exceptionCount == serverAssignment.CpRkDatabaseServers.Length)
                {
                    throw new Exception("Tried all {0} 'CP RK Risk Config' Servers as the target sql server on which to execute the following sql statement but none of the trials succeeded: \r\n{1}\r\nThe tried servers are: {2}".FormatWith(serverAssignment.CpRkDatabaseServers.Length, sql, string.Join(", ", serverAssignment.CpRkDatabaseServers)));
                }

                SqlServerHelper.ConnectionString.Server = originalServer;
                return(rowsAffected);
            }
            else
            {
                return(SqlServerHelper.Execute(sql));
            }
        }
        protected override void ExecuteMain()
        {
            this.Status = StepStatusEnum.Executing;
            string log = string.Empty;

            try
            {
                Impersonator impersonator = new Impersonator(
                    Properties.Settings.Default.DomainUserName,
                    Properties.Settings.Default.Domain,
                    Properties.Settings.Default.DomainPassword);

                Properties.Settings.Default.ChangeGroupXmlFiles.Clear();
                for (int i = 0; i < Properties.Settings.Default.ChangeGroupLinks.Count; i++)
                {
                    string cmd = @"\\bedtransfer\transfer\RulePerf\MergeChangeGroupTool.exe Merge /retrieveFromRCM:false /isEnforceRefresh:true /Links:{0}".FormatWith(
                        Properties.Settings.Default.ChangeGroupLinks[i]
                        );

                    int result = ThirdPartyProgramBLL.EnhancedRunCommand(
                        out log,
                        cmd,
                        Properties.Settings.Default.ChangeGroupDownloadingReferencedList.ToArray()
                        );

                    switch (result)
                    {
                    case 0:
                        string fileName = log.Replace('\r', ' ').Replace('\n', ' ');
                        fileName = Regex.Replace(fileName, @".*Merge File: (\\\\bedtransfer\\transfer\\RulePerf\\MergeResult\\.+\.xml)\s*.*$", "$1");

                        Log.Info("Downloaded change group from {0} to {1}".FormatWith(
                                     Properties.Settings.Default.ChangeGroupLinks[i],
                                     fileName
                                     ));

                        string downloadedXmlFile = Path.Combine(Properties.Settings.Default.ChangeGroupDownloadTo, Path.GetFileName(fileName));
                        File.Copy(fileName, downloadedXmlFile, true);

                        Log.Info("Copied change group from {0} to {1}".FormatWith(
                                     fileName, downloadedXmlFile
                                     ));

                        Properties.Settings.Default.ChangeGroupXmlFiles.Add(downloadedXmlFile);
                        break;

                    default:
                        throw new Exception("Command didn't run successfully.{0}".FormatWith(log));
                    }
                }

                Properties.Settings.Default.RuleIds.Clear();

                List <string> ruleIds = new List <string>();

                for (int i = 0; i < Properties.Settings.Default.ChangeGroupXmlFiles.Count; i++)
                {
                    ruleIds.AddRange(GetRulesFromXmlFile(Properties.Settings.Default.ChangeGroupXmlFiles[i]));
                }

                foreach (string ruleId in ruleIds)
                {
                    Properties.Settings.Default.RuleIds.Add(ruleId);
                }

                Properties.Settings.Default.RiskAPICaller_Description = Path.GetFileNameWithoutExtension(Properties.Settings.Default.ChangeGroupXmlFiles[0]);

                SettingEntityModel.SaveAll();

                this.Status       = StepStatusEnum.Pass;
                this.ResultDetail = new StepResultDetail("");
                for (int i = 0; i < Properties.Settings.Default.ChangeGroupLinks.Count; i++)
                {
                    this.ResultDetail.Message += "\r\n" + "Successfully downloaded {0} to {1}".FormatWith(
                        Properties.Settings.Default.ChangeGroupLinks[i],
                        Properties.Settings.Default.ChangeGroupXmlFiles[i]
                        );
                }

                impersonator.Undo();
            }
            catch (Exception ex)
            {
                this.Status       = StepStatusEnum.Failed;
                this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex));
            }
            finally
            {
                if (this.ResultDetail != null)
                {
                    Log.Info(this.ResultDetail.Message);
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Execute this step.
        /// </summary>
        protected override void ExecuteMain()
        {
            // Note: This step is used by StepsProcessor to deploy other steps, it can NOT swallow exceptions by itself.
            try
            {
                this.Status = StepStatusEnum.Executing;

                //string selfPath = System.Windows.Forms.Application.StartupPath;
                string selfPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

                //Impersonator impersonator = new Impersonator("administrator", ".", "#Bugsfor$");
                Impersonator impersonator = new Impersonator(
                    Properties.Settings.Default.DeployUserName,
                    Properties.Settings.Default.DeployDomain,
                    Properties.Settings.Default.DeployPassword
                    );

                if (!Directory.Exists(Properties.Settings.Default.DeployTargetPath))
                {
                    Directory.CreateDirectory(Properties.Settings.Default.DeployTargetPath);
                }

                string targetPath = Path.Combine(Properties.Settings.Default.DeployTargetPath, Path.GetFileName(selfPath));
                for (int i = 0; i < 3; i++)
                {
                    try
                    {
                        File.Copy(
                            selfPath,
                            targetPath,
                            true);

                        if (Properties.Settings.Default.DeployReferencedList != null)
                        {
                            foreach (string referencedFile in Properties.Settings.Default.DeployReferencedList)
                            {
                                File.Copy(referencedFile, Path.Combine(Path.GetDirectoryName(targetPath), Path.GetFileName(referencedFile)), true);
                            }
                        }
                        break;
                    }
                    catch (IOException)
                    {
                        if (i < 3)
                        {
                            System.Threading.Thread.Sleep(1000 * 30);
                            continue;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                bool success = true;

                if (success)
                {
                    this.Status       = StepStatusEnum.Pass;
                    this.ResultDetail = new StepResultDetail("Successfully deployed to {0}.".FormatWith(targetPath));
                }
                else
                {
                    this.Status       = StepStatusEnum.Failed;
                    this.ResultDetail = new StepResultDetail("Deploying failed. Please check logs for more detailed information.");
                }

                Log.Info(this.ResultDetail.Message);
                impersonator.Undo();
            }
            catch (Exception ex)
            {
                // Make sure the exceptions are logged (If this step ran on a remote machine, we should log the exceptions on remote machine too)
                ExceptionHelper.CentralProcess(ex);
                throw;
            }
            finally
            {
            }
        }
Beispiel #9
0
        protected ServerAssignmentModel(string netUserName = "******", string netPassword = "******", string netDomain = ".")
        {
            this.netUserName = netUserName;
            this.netPassword = netPassword;
            this.netDomain   = netDomain;

            serverAssignmentXmlPath = Properties.Settings.Default.ServerAssignmentFilePath.Trim();

            if (File.Exists(serverAssignmentXmlPath))
            {
                xmlDoc = new XmlDocument();
                xmlDoc.Load(serverAssignmentXmlPath);
            }
            else
            {
                // Retry
                #region Deprecated
                //if (serverAssignmentXmlPath.StartsWith("\\\\"))
                //{
                //    IntPtr token = IntPtr.Zero;
                //    IntPtr dupToken = IntPtr.Zero;
                //    bool success = RemoteHelper.LogonUser(Properties.Settings.Default.DomainUserName, Properties.Settings.Default.Domain, Properties.Settings.Default.DomainPassword, RemoteHelper.LOGON32_LOGON_NEW_CREDENTIALS, RemoteHelper.LOGON32_PROVIDER_DEFAULT, ref token);

                //    Log.Info("success: {0}. token: {1}".Format2(success, token));
                //    if (!success)
                //    {
                //        RemoteHelper.RaiseLastError();
                //    }
                //    success = RemoteHelper.DuplicateToken(token, 2, ref dupToken);

                //    Log.Info("success: {0}. dupToken: {1}".Format2(success, dupToken));
                //    if (!success)
                //    {
                //        RemoteHelper.RaiseLastError();
                //    }

                //    WindowsIdentity ident = new WindowsIdentity(dupToken);
                //    using (WindowsImpersonationContext impersonatedUser = ident.Impersonate())
                //    {
                //        /*
                //        DirectoryInfo dirInfo = new DirectoryInfo(@"\\bedtransfer\transfer\v-jetian");
                //        FileInfo[] files = dirInfo.GetFiles();

                //        foreach (FileInfo fi in files)
                //        {
                //            Log.Info(fi.FullName);
                //        }
                //        */

                //        if (File.Exists(serverAssignmentXmlPath))
                //        {
                //            Log.Info("{0} exits.".Format2(serverAssignmentXmlPath));
                //            xmlDoc = new XmlDocument();
                //            xmlDoc.Load(serverAssignmentXmlPath);
                //        }
                //        else
                //        {
                //            throw new System.IO.FileNotFoundException("Can't find the Server Assignment Xml file '{0}' Even after logged on.".Format2(serverAssignmentXmlPath), serverAssignmentXmlPath);
                //        }

                //        impersonatedUser.Undo();
                //        RemoteHelper.CloseHandle(token);
                //    }
                //}
                #endregion Deprecated

                Impersonator impersonator = new Impersonator(this.netUserName, this.netDomain, this.netPassword);
                if (File.Exists(serverAssignmentXmlPath))
                {
                    xmlDoc = new XmlDocument();
                    xmlDoc.Load(serverAssignmentXmlPath);
                }
                else
                {
                    throw new System.IO.FileNotFoundException("Can't find the Server Assignment Xml file '{0}' or can't access it by user '{1}\\{2}'.".FormatWith(serverAssignmentXmlPath, this.netDomain, this.netUserName), serverAssignmentXmlPath);
                }
                impersonator.Undo();
            }
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            Impersonator i = null;

            try
            {
                // Change theses to a user on your domain
                string SampleUsername = "******";
                string SamplePassword = "******";
                string SampleDomain   = "";

                // Say Current User
                Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);

                #region Impersonating a User
                i = new Impersonator(SampleUsername, SampleDomain, SamplePassword);

                i.Impersonate();

                // ... Run Code
                // ...

                // Say Current User
                Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);

                i.Undo();
                #endregion

                // Say Current User
                Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);

                #region Impersonating a User with the using cluase
                using (Impersonator im = new Impersonator(SampleUsername, SampleDomain, SamplePassword))
                {
                    im.Impersonate();
                    // ... Run Code
                    // ...

                    // Say Current User
                    Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                }
                #endregion

                Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);

                #region Impersonating a User with a Timer
                i = new Impersonator(SampleUsername, SampleDomain, SamplePassword, 100);

                i.Impersonate();

                // ... Run Code
                System.Threading.Thread.Sleep(1000);

                // Say Current User
                Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);

                //TODO: Fix duplicat emessage in event log
                // i.Undo(); // NOTE: Note needed with a timer! but can be called.

                #endregion
            }
            catch (LogonException le)
            {
                Console.WriteLine(le.ToString());
            }
            finally
            {
                // Say Current User
                Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);

                Console.ReadLine();
            }
        }
Beispiel #11
0
        /// <summary>
        /// Run command. If the executable file is on a network path, then copy it to local machine first, then run
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="cmd">The CMD.</param>
        /// <returns>Last exit code</returns>
        public static int EnhancedRunCommand(out string log, string cmd, string[] referencedFiles = null,
                                             string userName = "", string password = "", string domain = "")
        {
            string[] cmdPart = cmd.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            string   executableFileFullName = cmdPart[0].Trim('\"');

            if (referencedFiles != null && referencedFiles.Length > 0)
            {
                try
                {
                    foreach (string file in referencedFiles)
                    {
                        string localFile = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(file));
                        if (!File.Exists(localFile))
                        {
                            File.Copy(file, localFile, true);
                        }
                        else
                        {
                            // TODO: only copy if the last updated time of remote file is newer
                            File.Copy(file, localFile, true);
                        }
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    // Retry
                    Impersonator impersonator = new Impersonator(
                        Properties.Settings.Default.DomainUserName,
                        Properties.Settings.Default.Domain,
                        Properties.Settings.Default.DomainPassword);

                    foreach (string file in referencedFiles)
                    {
                        string localFile = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(file));
                        if (!File.Exists(localFile))
                        {
                            File.Copy(file, localFile, true);
                        }
                        else
                        {
                            // TODO: only copy if the last updated time of remote file is newer
                            File.Copy(file, localFile, true);
                        }
                    }

                    impersonator.Undo();
                }
            }

            if (executableFileFullName.StartsWith("\\\\", StringComparison.InvariantCultureIgnoreCase))
            {
                // Copy it from network path to local machine
                string localFullName = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(executableFileFullName));
                if (!File.Exists(localFullName))
                {
                    try
                    {
                        File.Copy(executableFileFullName, localFullName);
                    }
                    catch (System.UnauthorizedAccessException)
                    {
                        // Retry
                        Impersonator impersonator = new Impersonator(
                            Properties.Settings.Default.DomainUserName,
                            Properties.Settings.Default.Domain,
                            Properties.Settings.Default.DomainPassword);

                        File.Copy(executableFileFullName, localFullName);

                        impersonator.Undo();
                    }
                }

                cmd = "\"" + localFullName + "\"" + cmd.Remove(0, executableFileFullName.Length);
            }

            return(RunCommand(out log, cmd, userName, password, domain));
        }