public async Task <TaskResult> ExecuteAsync(TaskMessage taskMessage, TaskLogger taskLogger, CancellationToken cancellationToken)
        {
            string          message = String.Empty;
            MyAppParameters myAppParameters;

            try
            {
                myAppParameters = JsonConvert.DeserializeObject <MyAppParameters>(taskMessage.GetTaskMessageBody());
                if (String.IsNullOrWhiteSpace(myAppParameters.AgentName) ||
                    String.IsNullOrWhiteSpace(myAppParameters.AgentPoolName) ||
                    String.IsNullOrWhiteSpace(myAppParameters.AzureSubscriptionClientId) ||
                    String.IsNullOrWhiteSpace(myAppParameters.AzureSubscriptionClientSecret) ||
                    String.IsNullOrWhiteSpace(myAppParameters.TenantId) ||
                    String.IsNullOrWhiteSpace(myAppParameters.ResourceGroupName) ||
                    String.IsNullOrWhiteSpace(myAppParameters.PATToken))
                {
                    message = $"Please provide valid values for 'TenantId', 'AzureSubscriptionClientId', 'AzureSubscriptionClientSecret', 'ResourceGroupName', 'AgentPoolName','AgentName' and 'PATToken' in task body.";
                    await taskLogger.Log(message).ConfigureAwait(false);

                    return(await Task.FromResult(TaskResult.Failed));
                }
            }
            catch (Exception ex)
            {
                message = $"Task body deseralization failed: {ex}";
                await taskLogger.Log(message).ConfigureAwait(false);

                return(await Task.FromResult(TaskResult.Failed));
            }

            try
            {
                // Creates the container in Azure
                await MyApp.CreateContainer(taskLogger, myAppParameters);

                using (var taskClient = new TaskClient(taskMessage.GetTaskProperties()))
                {
                    // set variable
                    var variableName = "ContainerName";
                    await taskClient.SetTaskVariable(taskId : taskMessage.GetTaskProperties().TaskInstanceId, name : variableName, value : "AzPipelineAgent", isSecret : false, cancellationToken : cancellationToken);

                    // get variable
                    var variableValue = taskClient.GetTaskVariable(taskId: taskMessage.GetTaskProperties().TaskInstanceId, name: variableName, cancellationToken: cancellationToken);
                    message = $"Variable name: {variableName} value: {variableValue}";
                    await taskLogger.Log(message).ConfigureAwait(false);
                }


                return(await Task.FromResult(TaskResult.Succeeded));
            }
            catch (Exception ex)
            {
                message = $"MyFunction execution failed: {ex}";
                await taskLogger.Log(message).ConfigureAwait(false);

                return(await Task.FromResult(TaskResult.Failed));
            }
        }
Exemplo n.º 2
0
        private static async Task CreateContainerGroupWithPolling(TaskLogger taskLogger, IAzure azure, string azureRegion, MyAppParameters myAppParameters, Dictionary <string, string> envVariables)
        {
            string message;

            // Create the container group using a fire-and-forget task
            Task.Run(() =>
                     azure.ContainerGroups.Define(myAppParameters.AgentName)
                     .WithRegion(azureRegion)
                     .WithExistingResourceGroup(myAppParameters.ResourceGroupName)
                     .WithLinux()
                     .WithPublicImageRegistryOnly()
                     .WithoutVolume()
                     .DefineContainerInstance(myAppParameters.AgentName)
                     .WithImage("microsoft/vsts-agent")
                     .WithoutPorts()
                     .WithEnvironmentVariables(envVariables)
                     .Attach()
                     .CreateAsync()
                     );

            // Poll for the container group
            IContainerGroup containerGroup = null;

            while (containerGroup == null)
            {
                containerGroup = azure.ContainerGroups.GetByResourceGroup(myAppParameters.ResourceGroupName, myAppParameters.AgentName);
                await taskLogger.Log(".").ConfigureAwait(false);

                SdkContext.DelayProvider.Delay(1000);
            }

            Console.WriteLine();

            var i = 18000; // wait for 5 hrs

            // Poll until the container group is running
            while (containerGroup.State != "Running" && i > 0)
            {
                message = $"Container group state: {containerGroup.Refresh().State}";
                await taskLogger.Log(message).ConfigureAwait(false);

                Thread.Sleep(1000);
                i--;
            }

            if (containerGroup.State != "Running")
            {
                var errorMessage = $"Container group: {myAppParameters.AgentName} not moved to Running state even after 5hrs. Please check container status in Azure portal.";
                throw new Exception(errorMessage);
            }

            message = $"Container group: {myAppParameters.AgentName} in resource group '{myAppParameters.ResourceGroupName}' created with image 'microsoft/vsts-agent'. Container group state: {containerGroup.Refresh().State}";
            await taskLogger.Log(message).ConfigureAwait(false);
        }
Exemplo n.º 3
0
        public async Task <TaskResult> Execute(CancellationToken cancellationToken)
        {
            using (var taskClient = new TaskClient(taskProperties))
            {
                var taskResult = TaskResult.Failed;
                try
                {
                    // create timelinerecord if not provided
                    await CreateTaskTimelineRecordIfRequired(taskClient, cancellationToken).ConfigureAwait(false);

                    taskLogger = new TaskLogger(taskProperties, taskClient);

                    // report task started
                    await taskLogger.Log("Task started").ConfigureAwait(false);

                    await taskClient.ReportTaskStarted(taskProperties.TaskInstanceId, cancellationToken).ConfigureAwait(false);

                    await taskClient.ReportTaskProgress(taskProperties.TaskInstanceId, cancellationToken).ConfigureAwait(false);

                    // start client handler execute
                    var executeTask = taskExecutionHandler.ExecuteAsync(taskMessage, taskLogger, cancellationToken).ConfigureAwait(false);
                    taskResult = await executeTask;

                    // report task completed with status
                    await taskLogger.Log("Task completed").ConfigureAwait(false);

                    await taskClient.ReportTaskCompleted(taskProperties.TaskInstanceId, taskResult, cancellationToken).ConfigureAwait(false);

                    return(taskResult);
                }
                catch (Exception e)
                {
                    if (taskLogger != null)
                    {
                        await taskLogger.Log(e.ToString()).ConfigureAwait(false);
                    }

                    await taskClient.ReportTaskCompleted(taskProperties.TaskInstanceId, taskResult, cancellationToken).ConfigureAwait(false);

                    throw;
                }
                finally
                {
                    if (taskLogger != null)
                    {
                        await taskLogger.End().ConfigureAwait(false);
                    }
                }
            }
        }
Exemplo n.º 4
0
        private Process GetProcess(string serviceName)
        {
            int num = 0;

            try
            {
                num = this.GetProcessId(serviceName);
            }
            catch (Win32Exception ex)
            {
                TaskLogger.Log(Strings.UnableToGetProcessIdOfService(serviceName, ex.ToString()));
                return(null);
            }
            if (num == 0)
            {
                TaskLogger.Log(Strings.ServiceHasNoProcessId(serviceName));
                return(null);
            }
            Process result;

            try
            {
                result = Process.GetProcessById(num);
            }
            catch (ArgumentException ex2)
            {
                TaskLogger.Log(Strings.UnableToGetProcessForService(serviceName, ex2.ToString()));
                result = null;
            }
            return(result);
        }
Exemplo n.º 5
0
 private void UpdateOwaLPs()
 {
     TaskLogger.LogEnter();
     TaskLogger.Log(Strings.StartingToCopyOwaLPFiles);
     try
     {
         if (this.InstallVersion == this.ClientLPVersion)
         {
             TaskLogger.Log(Strings.SameOwaVersionDoNotCopyLPFiles);
         }
         else
         {
             string sourcePathForLPfiles       = string.Format("{0}\\ClientAccess\\owa\\prem\\{1}\\scripts\\", this.InstallPath.PathName, this.ClientLPVersion);
             string destinationPathForLPfiles  = string.Format("{0}\\ClientAccess\\owa\\prem\\{1}\\scripts\\", this.InstallPath.PathName, this.InstallVersion);
             string sourcePathForLPfiles2      = string.Format("{0}\\ClientAccess\\owa\\prem\\{1}\\ext\\def\\", this.InstallPath.PathName, this.ClientLPVersion);
             string destinationPathForLPfiles2 = string.Format("{0}\\ClientAccess\\owa\\prem\\{1}\\ext\\def\\", this.InstallPath.PathName, this.InstallVersion);
             this.CopyLanguageDirectories(sourcePathForLPfiles, destinationPathForLPfiles);
             this.CopyLanguageDirectories(sourcePathForLPfiles2, destinationPathForLPfiles2);
         }
     }
     finally
     {
         TaskLogger.Log(Strings.FinishedCopyingOwaLPFiles);
         TaskLogger.LogExit();
     }
 }
Exemplo n.º 6
0
        public static SetupComponentInfo ReadSetupComponentInfoFile(string fileName)
        {
            SetupComponentInfo setupComponentInfo = null;
            XmlReaderSettings  xmlReaderSettings  = new XmlReaderSettings();

            xmlReaderSettings.ConformanceLevel = ConformanceLevel.Document;
            xmlReaderSettings.ValidationType   = ValidationType.Schema;
            Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("component.xsd");

            xmlReaderSettings.Schemas.Add(null, XmlReader.Create(manifestResourceStream));
            string text;

            using (XmlReader xmlReader = RolesUtility.CreateXmlReader(fileName, xmlReaderSettings, out text))
            {
                try
                {
                    setupComponentInfo = (SetupComponentInfo)RolesUtility.GetComponentSerializer().Deserialize(xmlReader);
                    setupComponentInfo.PopulateTasksProperty(Path.GetFileNameWithoutExtension(fileName));
                    setupComponentInfo.ValidateDatacenterAttributes();
                }
                catch (InvalidOperationException ex)
                {
                    throw new XmlDeserializationException(text, ex.Message, (ex.InnerException == null) ? string.Empty : ex.InnerException.Message);
                }
                TaskLogger.Log(Strings.LoadedComponentWithTasks(setupComponentInfo.Name, setupComponentInfo.Tasks.Count, text));
            }
            return(setupComponentInfo);
        }
Exemplo n.º 7
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     TaskLogger.Log(Strings.RemovingFile(this.FilePath.PathName));
     try
     {
         File.Delete(this.FilePath.PathName);
     }
     catch (SecurityException exception)
     {
         base.WriteError(exception, ErrorCategory.SecurityError, null);
     }
     catch (UnauthorizedAccessException exception2)
     {
         base.WriteError(exception2, ErrorCategory.PermissionDenied, null);
     }
     catch (IOException exception3)
     {
         base.WriteError(exception3, ErrorCategory.ResourceUnavailable, null);
     }
     catch (Win32Exception exception4)
     {
         base.WriteError(exception4, ErrorCategory.InvalidOperation, null);
     }
     TaskLogger.LogExit();
 }
        public async Task <TaskResult> ExecuteAsync(TaskMessage taskMessage, TaskLogger taskLogger, CancellationToken cancellationToken)
        {
            string          message = String.Empty;
            MyAppParameters myAppParameters;

            try
            {
                myAppParameters = JsonConvert.DeserializeObject <MyAppParameters>(taskMessage.GetTaskMessageBody());
                if (String.IsNullOrWhiteSpace(myAppParameters.AgentName) ||
                    String.IsNullOrWhiteSpace(myAppParameters.AgentPoolName) ||
                    String.IsNullOrWhiteSpace(myAppParameters.AzureSubscriptionClientId) ||
                    String.IsNullOrWhiteSpace(myAppParameters.AzureSubscriptionClientSecret) ||
                    String.IsNullOrWhiteSpace(myAppParameters.TenantId) ||
                    String.IsNullOrWhiteSpace(myAppParameters.ResourceGroupName) ||
                    String.IsNullOrWhiteSpace(myAppParameters.PATToken))
                {
                    message = $"Please provide valid values for 'TenantId', 'AzureSubscriptionClientId', 'AzureSubscriptionClientSecret', 'ResourceGroupName', 'AgentPoolName','AgentName' and 'PATToken' in task body.";
                    await taskLogger.Log(message).ConfigureAwait(false);

                    return(await Task.FromResult(TaskResult.Failed));
                }
            }
            catch (Exception ex)
            {
                message = $"Task body deseralization failed: {ex}";
                await taskLogger.Log(message).ConfigureAwait(false);

                return(await Task.FromResult(TaskResult.Failed));
            }

            try
            {
                // Creates the container in Azure
                await MyApp.CreateContainer(taskLogger, myAppParameters);

                return(await Task.FromResult(TaskResult.Succeeded));
            }
            catch (Exception ex)
            {
                message = $"MyFunction execution failed: {ex}";
                await taskLogger.Log(message).ConfigureAwait(false);

                return(await Task.FromResult(TaskResult.Failed));
            }
        }
Exemplo n.º 9
0
 public async Task Cancel(CancellationToken cancellationToken)
 {
     taskLogger.Log("Canceling task ...");
     using (var taskClient = new TaskClient(taskProperties))
     {
         taskLogger = new TaskLogger(taskProperties, taskClient);
         this.taskExecutionHandler.CancelAsync(taskMessage, taskLogger, cancellationToken);
         await taskClient.ReportTaskCompleted(taskProperties.TaskInstanceId, TaskResult.Canceled, cancellationToken).ConfigureAwait(false);
     }
 }
Exemplo n.º 10
0
        public static int LogRunProcess(string fileName, string arguments, string path)
        {
            string processName = path + " " + fileName;

            TaskLogger.Log(Strings.LogRunningCommand(processName, arguments));
            int num = Utils.RunProcess(fileName, arguments, path);

            TaskLogger.Log(Strings.LogProcessExitCode(fileName, num));
            return(num);
        }
Exemplo n.º 11
0
        internal static SetupComponentInfoCollection GetRequiredComponents(string roleName, InstallationModes mode)
        {
            TaskLogger.LogEnter(new object[]
            {
                roleName
            });
            Role           roleByName   = RoleManager.GetRoleByName(roleName);
            RoleCollection currentRoles = RoleManager.GetCurrentRoles();

            currentRoles.Remove(roleByName);
            SetupComponentInfoCollection setupComponentInfoCollection = new SetupComponentInfoCollection();

            foreach (Role role in currentRoles)
            {
                setupComponentInfoCollection.AddRange(role.AllComponents);
            }
            SetupComponentInfoCollection allComponents = roleByName.AllComponents;
            SetupComponentInfoCollection setupComponentInfoCollection2 = new SetupComponentInfoCollection();

            if (mode == InstallationModes.BuildToBuildUpgrade)
            {
                setupComponentInfoCollection2.AddRange(allComponents);
            }
            else
            {
                using (List <SetupComponentInfo> .Enumerator enumerator2 = allComponents.GetEnumerator())
                {
                    while (enumerator2.MoveNext())
                    {
                        SetupComponentInfo candidate = enumerator2.Current;
                        bool flag = false;
                        if (candidate.AlwaysExecute)
                        {
                            TaskLogger.Log(Strings.RunningAlwaysToRunComponent(candidate.Name));
                            flag = true;
                        }
                        else if (setupComponentInfoCollection.Find((SetupComponentInfo sci) => sci.Name == candidate.Name) == null)
                        {
                            TaskLogger.Log(Strings.AddingUniqueComponent(candidate.Name));
                            flag = true;
                        }
                        else
                        {
                            TaskLogger.Log(Strings.AlreadyConfiguredComponent(candidate.Name));
                        }
                        if (flag)
                        {
                            setupComponentInfoCollection2.Add(candidate);
                        }
                    }
                }
            }
            TaskLogger.LogExit();
            return(setupComponentInfoCollection2);
        }
Exemplo n.º 12
0
        public async Task <TaskResult> ExecuteAsync(TaskMessage taskMessage, TaskLogger taskLogger, CancellationToken cancellationToken)
        {
            // get taskmessage
            // log some values from object
            // return result
            var myObject = JsonConvert.DeserializeObject <MyTaskObject>(taskMessage.GetTaskMessageBody());

            var message = $"Hello {myObject.Name}";
            await taskLogger.Log(message).ConfigureAwait(false);

            return(await Task.FromResult(TaskResult.Succeeded));
        }
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            Version unpackedVersion = RolesUtility.GetUnpackedVersion("AdminToolsRole");

            if (unpackedVersion != null && unpackedVersion < AdminToolsRole.FirstConfiguredVersion && RolesUtility.GetConfiguredVersion("AdminToolsRole") == null)
            {
                TaskLogger.Log(Strings.UpdatingAdminToolsConfiguredVersion(unpackedVersion.ToString()));
                RolesUtility.SetConfiguredVersion("AdminToolsRole", unpackedVersion);
            }
            TaskLogger.LogExit();
        }
Exemplo n.º 14
0
        public static Guid GetProductCode(string packagePath)
        {
            TaskLogger.LogEnter();
            StringBuilder stringBuilder = new StringBuilder();
            Guid          guid          = Guid.Empty;

            MsiUtility.PushUILevel(InstallUILevel.None);
            try
            {
                SafeMsiHandle safeMsiHandle;
                uint          num = MsiNativeMethods.OpenPackageEx(packagePath, OpenPackageFlags.IgnoreMachineState, out safeMsiHandle);
                if (num != 0U)
                {
                    Win32Exception ex = new Win32Exception((int)num);
                    throw new TaskException(Strings.MsiCouldNotOpenPackage(packagePath, ex.Message, (int)num), ex);
                }
                using (safeMsiHandle)
                {
                    uint num2 = 38U;
                    for (;;)
                    {
                        num2 += 1U;
                        if (num2 > 2147483647U)
                        {
                            break;
                        }
                        stringBuilder.EnsureCapacity((int)num2);
                        num = MsiNativeMethods.GetProductProperty(safeMsiHandle, "ProductCode", stringBuilder, ref num2);
                        if (234U != num)
                        {
                            goto Block_7;
                        }
                    }
                    throw new TaskException(Strings.MsiPropertyTooLarge);
Block_7:
                    if (num != 0U)
                    {
                        Win32Exception ex2 = new Win32Exception((int)num);
                        throw new TaskException(Strings.MsiCouldNotGetProdcutProperty("ProductCode", ex2.Message, (int)num), ex2);
                    }
                    guid = new Guid(stringBuilder.ToString());
                    TaskLogger.Log(Strings.MsiProductCode(guid));
                }
            }
            finally
            {
                MsiUtility.PopUILevel();
            }
            TaskLogger.LogExit();
            return(guid);
        }
Exemplo n.º 15
0
 private void ReplaceInFile(string filePath, string searchText, string replaceText)
 {
     if (File.Exists(filePath))
     {
         StreamReader streamReader = new StreamReader(filePath);
         string       text         = streamReader.ReadToEnd();
         streamReader.Close();
         text = Regex.Replace(text, searchText, replaceText);
         StreamWriter streamWriter = new StreamWriter(filePath);
         streamWriter.Write(text);
         streamWriter.Close();
         return;
     }
     TaskLogger.Log(Strings.MFLFileNotFound(filePath));
 }
Exemplo n.º 16
0
        private static string MakeAnswerFile(TempFileCollection tempFiles, AdamServiceSettings adamServiceSettings)
        {
            string text = tempFiles.AddExtension("ini");
            string path = Path.Combine(ConfigurationContext.Setup.SetupDataPath, "AdamInstallAnswer.ini");

            using (StreamReader streamReader = File.OpenText(path))
            {
                using (StreamWriter streamWriter = File.CreateText(text))
                {
                    string text2;
                    while ((text2 = streamReader.ReadLine()) != null)
                    {
                        if (!string.IsNullOrEmpty(text2) && text2[0] != ';')
                        {
                            if (text2.StartsWith("InstanceName"))
                            {
                                text2 = Utils.MakeIniFileSetting("InstanceName", adamServiceSettings.InstanceName);
                            }
                            else if (text2.StartsWith("DataFilesPath"))
                            {
                                text2 = Utils.MakeIniFileSetting("DataFilesPath", adamServiceSettings.DataFilesPath);
                            }
                            else if (text2.StartsWith("LogFilesPath"))
                            {
                                text2 = Utils.MakeIniFileSetting("LogFilesPath", adamServiceSettings.LogFilesPath);
                            }
                            else if (text2.StartsWith("LocalLDAPPortToListenOn"))
                            {
                                text2 = Utils.MakeIniFileSetting("LocalLDAPPortToListenOn", adamServiceSettings.LdapPort.ToString());
                            }
                            else if (text2.StartsWith("LocalSSLPortToListenOn"))
                            {
                                text2 = Utils.MakeIniFileSetting("LocalSSLPortToListenOn", adamServiceSettings.SslPort.ToString());
                            }
                            else if (text2.StartsWith("NewApplicationPartitionToCreate"))
                            {
                                text2 = Utils.MakeIniFileSetting("NewApplicationPartitionToCreate", "OU=MSExchangeGateway");
                            }
                            streamWriter.WriteLine(text2);
                            TaskLogger.Log(new LocalizedString("Answer File:" + text2));
                        }
                    }
                    streamWriter.Flush();
                }
            }
            return(text);
        }
Exemplo n.º 17
0
        public static RoleCollection GetCurrentRoles()
        {
            RoleCollection roleCollection = new RoleCollection();
            StringBuilder  stringBuilder  = new StringBuilder();

            foreach (Role role in RoleManager.Roles)
            {
                if (role.IsCurrent)
                {
                    roleCollection.Add(role);
                    stringBuilder.Append(role.RoleName);
                    stringBuilder.Append(" ");
                }
            }
            TaskLogger.Log(Strings.CurrentRoles(stringBuilder.ToString()));
            return(roleCollection);
        }
Exemplo n.º 18
0
        protected override IConfigurable ResolveDataObject()
        {
            TaskLogger.LogEnter();
            IConfigurable[] array = null;
            base.WriteVerbose(TaskVerboseStringHelper.GetFindDataObjectsVerboseString(base.DataSession, typeof(SmimeConfigurationContainer), this.InternalFilter, this.RootId, this.DeepSearch));
            try
            {
                array = base.DataSession.Find <SmimeConfigurationContainer>(this.InternalFilter, this.RootId, this.DeepSearch, null);
            }
            catch (DataSourceTransientException exception)
            {
                base.WriteError(exception, (ErrorCategory)1002, null);
            }
            finally
            {
                base.WriteVerbose(TaskVerboseStringHelper.GetSourceVerboseString(base.DataSession));
            }
            if (array == null)
            {
                array = new IConfigurable[0];
            }
            IConfigurable result = null;

            switch (array.Length)
            {
            case 0:
            {
                SmimeConfigurationContainer smimeConfigurationContainer = new SmimeConfigurationContainer();
                smimeConfigurationContainer.SetId(this.RootId as ADObjectId);
                smimeConfigurationContainer.Initialize();
                smimeConfigurationContainer.OrganizationId = base.CurrentOrganizationId;
                result = smimeConfigurationContainer;
                break;
            }

            case 1:
                result = array[0];
                break;

            default:
                TaskLogger.Log(Strings.SmimeConfigAmbiguous);
                break;
            }
            TaskLogger.LogExit();
            return(result);
        }
Exemplo n.º 19
0
 private static void CheckAdamInstallUninstallResults(bool installing)
 {
     using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\ADAM_Installer_Results"))
     {
         if (registryKey != null)
         {
             object value = registryKey.GetValue(installing ? "ADAMInstallWarnings" : "ADAMUninstallWarnings");
             if (value != null)
             {
                 string warning = value as string;
                 TaskLogger.Log(installing ? Strings.AdamInstallWarning(warning) : Strings.AdamUninstallWarning(warning));
             }
             object value2 = registryKey.GetValue(installing ? "ADAMInstallErrorCode" : "ADAMUninstallErrorCode");
             object value3 = registryKey.GetValue(installing ? "ADAMInstallErrorMessage" : "ADAMUninstallErrorMessage");
             if (value2 != null || value3 != null)
             {
                 if (value3 != null)
                 {
                     string error = value3 as string;
                     TaskLogger.Log(installing ? Strings.AdamInstallError(error) : Strings.AdamUninstallError(error));
                     if (installing)
                     {
                         throw new AdamInstallErrorException(error);
                     }
                     throw new AdamUninstallErrorException(error);
                 }
                 else
                 {
                     int num = (int)value2;
                     if (installing && 20033 == num)
                     {
                         TaskLogger.Log(Strings.AdamInstallFailureDataOrLogFolderNotEmpty);
                         throw new AdamInstallFailureDataOrLogFolderNotEmptyException();
                     }
                     TaskLogger.Log(installing ? Strings.AdamInstallGeneralFailureWithResult(num) : Strings.AdamUninstallGeneralFailureWithResult(num));
                     if (installing)
                     {
                         throw new AdamInstallGeneralFailureWithResultException(num);
                     }
                     throw new AdamUninstallGeneralFailureWithResultException(num);
                 }
             }
         }
     }
 }
Exemplo n.º 20
0
        private void SendWatsonReportForHungService(string serviceName)
        {
            Process process = null;

            try
            {
                process = this.GetProcess(serviceName);
            }
            catch (Win32Exception ex)
            {
                TaskLogger.Log(Strings.UnableToGetProcessForService(serviceName, ex.ToString()));
            }
            if (process == null)
            {
                try
                {
                    process = this.GetFarFetchedProcess(serviceName);
                }
                catch (Win32Exception ex2)
                {
                    TaskLogger.Log(Strings.UnableToGetProcessForService(serviceName, ex2.ToString()));
                }
            }
            if (process != null)
            {
                TaskLogger.Trace("Service {0} has process id {1}", new object[]
                {
                    serviceName,
                    process.Id
                });
                try
                {
                    ExWatson.SendHangWatsonReport(new System.ServiceProcess.TimeoutException(serviceName), process);
                    TaskLogger.Log(Strings.GeneratedWatsonReportForHungService(serviceName));
                }
                catch (Win32Exception ex3)
                {
                    TaskLogger.Log(Strings.UnableToGeneratedWatsonReportForHungService(serviceName, ex3.ToString()));
                }
                catch (InvalidOperationException ex4)
                {
                    TaskLogger.Log(Strings.UnableToGeneratedWatsonReportForHungService(serviceName, ex4.ToString()));
                }
            }
        }
Exemplo n.º 21
0
        private void BackupPerfRegistry(string backupFileNamePrefix)
        {
            string text      = string.Format("{0}-{1}.bak", backupFileNamePrefix, ExDateTime.Now.ToString("yyyyMMdd-hhmmss.fff"));
            string arguments = string.Format("\"/s:{0}\"", text);
            string text2     = Path.Combine(ConfigurationContext.Setup.LoggingPath, "lodctr_backups");

            Directory.CreateDirectory(text2);
            this.RunExecutable("lodctr.exe", arguments, text2, 1200000);
            string text3 = Path.Combine(text2, text);

            if (File.Exists(text3))
            {
                FileInfo fileInfo = new FileInfo(text3);
                if (fileInfo.Length > 0L)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(text2);
                    string        searchPattern = string.Format("{0}-{1}.bak", backupFileNamePrefix, "*");
                    FileInfo[]    files         = directoryInfo.GetFiles(searchPattern);
                    if (files.Length > 1)
                    {
                        foreach (FileInfo fileInfo2 in files)
                        {
                            if (fileInfo2.Name.CompareTo(text) != 0)
                            {
                                try
                                {
                                    fileInfo2.Delete();
                                }
                                catch (Exception ex)
                                {
                                    if (!(ex is IOException) && !(ex is SecurityException))
                                    {
                                        throw ex;
                                    }
                                    TaskLogger.Log(Strings.LanguagePackPerfCounterDeleteError(fileInfo2.FullName, ex.Message));
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 22
0
        protected override void InternalProcessRecord()
        {
            MofCompiler           mofCompiler           = new MofCompiler();
            WbemCompileStatusInfo wbemCompileStatusInfo = default(WbemCompileStatusInfo);

            wbemCompileStatusInfo.InitializeStatusInfo();
            int num = mofCompiler.CompileFile(this.MofFilePath, null, null, null, null, 0, 0, 0, ref wbemCompileStatusInfo);

            if (num == 0)
            {
                TaskLogger.Log(Strings.ExchangeTracingProviderInstalledSuccess);
                return;
            }
            if (num == 262145)
            {
                TaskLogger.Log(Strings.ExchangeTracingProviderAlreadyExists);
                return;
            }
            base.WriteError(new ExchangeTracingProviderInstallException(wbemCompileStatusInfo.HResult), ErrorCategory.NotSpecified, wbemCompileStatusInfo);
        }
Exemplo n.º 23
0
        public static string GetProductInfo(Guid productCode, string propertyName)
        {
            TaskLogger.LogEnter();
            StringBuilder stringBuilder     = new StringBuilder();
            string        productCodeString = productCode.ToString("B").ToUpper(CultureInfo.InvariantCulture);
            uint          num = (uint)stringBuilder.Capacity;

            MsiUtility.PushUILevel(InstallUILevel.None);
            try
            {
                uint productInfo;
                for (;;)
                {
                    num += 1U;
                    if (num > 2147483647U)
                    {
                        break;
                    }
                    stringBuilder.EnsureCapacity((int)num);
                    productInfo = MsiNativeMethods.GetProductInfo(productCodeString, propertyName, stringBuilder, ref num);
                    if (234U != productInfo)
                    {
                        goto Block_3;
                    }
                }
                throw new TaskException(Strings.MsiPropertyTooLarge);
Block_3:
                if (productInfo != 0U)
                {
                    Win32Exception ex = new Win32Exception((int)productInfo);
                    throw new TaskException(Strings.MsiCouldNotGetProdcutProperty(propertyName, ex.Message, (int)productInfo), ex);
                }
            }
            finally
            {
                MsiUtility.PopUILevel();
            }
            TaskLogger.Log(Strings.MsiProperty(propertyName, stringBuilder.ToString()));
            TaskLogger.LogExit();
            return(stringBuilder.ToString());
        }
Exemplo n.º 24
0
        private static async Task UpdateCheckSuiteResult(
            string accountUrl,
            string authToken,
            Guid projectId,
            Guid checkSuiteId,
            bool succeeded,
            string message,
            ILogger log,
            TaskLogger taskLogger,
            IDictionary <string, string> variables)
        {
            using (var httpClient = new HttpClient())
            {
                string authTokenString  = string.Format("{0}:{1}", "", authToken);
                string base64AuthString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(authTokenString));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64AuthString);

                HttpRetryHelper httpRetryHelper = new HttpRetryHelper(NumberOfHttpRetries);

                var     checkSuiteUpdate = new Dictionary <string, dynamic>();
                dynamic checkRunResult   = new { status = succeeded ? "approved" : "rejected", resultMessage = message };
                checkSuiteUpdate.Add(checkSuiteId.ToString(), checkRunResult);

                try
                {
                    var updatedCheckSuiteBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(checkSuiteUpdate));
                    var updatedCheckByteContent = new ByteArrayContent(updatedCheckSuiteBuffer);

                    updatedCheckByteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var updateCheckRunUrl = string.Format("{0}/{1}/_apis/pipelines/checks/runs/{2}?api-version=5.0", accountUrl, projectId, checkSuiteId);
                    CommonUtilities.LogInformation(string.Format("Invoking {0} to post current check status", updateCheckRunUrl), log, taskLogger, variables, null);
                    var updateCheckSuiteResponse = await httpRetryHelper.Invoke(async() => await httpClient.PostAsync(updateCheckRunUrl, updatedCheckByteContent));
                }
                catch (Exception e)
                {
                    await taskLogger?.Log($"Failed to fetch update check status with error message : {e.Message}");

                    CommonUtilities.LogInformation($"Error stack: {e.ToString()}", log, taskLogger, variables, null);
                }
            }
        }
Exemplo n.º 25
0
 public static void RunAndLogProcessOutput(string fileName, string arguments)
 {
     using (Process process = Process.Start(new ProcessStartInfo
     {
         FileName = fileName,
         Arguments = arguments,
         CreateNoWindow = true,
         WindowStyle = ProcessWindowStyle.Hidden,
         UseShellExecute = false,
         RedirectStandardOutput = true
     }))
     {
         StreamReader standardOutput = process.StandardOutput;
         string       processOutput;
         while ((processOutput = standardOutput.ReadLine()) != null)
         {
             TaskLogger.Log(Strings.OccupiedPortsInformation(processOutput));
         }
         standardOutput.Close();
     }
 }
Exemplo n.º 26
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     try
     {
         List <string> list = new List <string>();
         list.Add(this.InstallPath.PathName + "\\Setup\\Perf");
         string platform = base.Platform;
         list.Add(this.InstallPath.PathName + "\\Bin\\perf\\" + platform);
         foreach (string text in list)
         {
             if (Directory.Exists(text))
             {
                 if (Directory.GetDirectories(text).Length > 1)
                 {
                     MergePerfCounterIni mergePerfCounterIni = new MergePerfCounterIni();
                     mergePerfCounterIni.ParseDirectories(text);
                     this.ParsePerfCounterDefinitionFiles(text);
                 }
             }
             else
             {
                 TaskLogger.Log(Strings.ExceptionDirectoryNotFound(text));
             }
         }
         if (ManageServiceBase.GetServiceStatus("Winmgmt") == ServiceControllerStatus.Running)
         {
             this.UpdateMFLFiles();
         }
         else
         {
             TaskLogger.Log(Strings.SkippedUpdatingMFLFiles);
         }
         this.UpdateOwaLPs();
     }
     finally
     {
         TaskLogger.LogExit();
     }
 }
Exemplo n.º 27
0
        protected void LoadComponentList()
        {
            TaskLogger.LogEnter(new object[]
            {
                this.RoleName
            });
            string fileName = Path.Combine(ConfigurationContext.Setup.AssemblyPath, this.RoleName + "Definition.xml");

            this.allComponents = new SetupComponentInfoCollection();
            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();

            xmlReaderSettings.ConformanceLevel = ConformanceLevel.Document;
            xmlReaderSettings.ValidationType   = ValidationType.Schema;
            Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RoleDefinition.xsd");

            xmlReaderSettings.Schemas.Add(null, XmlReader.Create(manifestResourceStream));
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(SetupComponentInfoReferenceCollection));
            string        text;

            using (XmlReader xmlReader = RolesUtility.CreateXmlReader(fileName, xmlReaderSettings, out text))
            {
                TaskLogger.Log(Strings.ReadingComponents(this.RoleName, text));
                SetupComponentInfoReferenceCollection setupComponentInfoReferenceCollection = null;
                try
                {
                    setupComponentInfoReferenceCollection = (SetupComponentInfoReferenceCollection)xmlSerializer.Deserialize(xmlReader);
                }
                catch (InvalidOperationException ex)
                {
                    throw new XmlDeserializationException(text, ex.Message, (ex.InnerException == null) ? string.Empty : ex.InnerException.Message);
                }
                TaskLogger.Log(Strings.FoundComponents(setupComponentInfoReferenceCollection.Count));
                foreach (SetupComponentInfoReference reference in setupComponentInfoReferenceCollection)
                {
                    SetupComponentInfo item = this.LoadComponent(reference);
                    this.allComponents.Add(item);
                }
            }
            TaskLogger.LogExit();
        }
Exemplo n.º 28
0
 public void ParseDirectories(string sourceDir)
 {
     TaskLogger.Log(Strings.LanguagePackPerfCounterMergeStart);
     if (!Directory.Exists(sourceDir))
     {
         throw new ArgumentException();
     }
     this.GetLangugageDirs(sourceDir);
     if (this.languageDirs.Count == 0)
     {
         return;
     }
     foreach (string text in Directory.GetFiles(sourceDir, "*.ini"))
     {
         string str = Path.Combine(sourceDir, Path.GetFileNameWithoutExtension(text));
         if ((File.Exists(str + ".h") && File.Exists(str + ".xml")) || File.Exists(str + ".dll"))
         {
             TaskLogger.Log(Strings.LanguagePackPerfCounterMergeStatus(Path.GetFileName(text)));
             this.CreateLocalizedIniFile(text);
         }
     }
     TaskLogger.Log(Strings.LanguagePackPerfCounterMergeEnd);
 }
Exemplo n.º 29
0
 public bool Validate(string command, CommandParameterCollection parameters)
 {
     if (!this.AllowedCommands.Contains(command))
     {
         TaskLogger.Log(Strings.CmdletValidatorParseErrors(string.Format("Command {0} not allowed", command)));
         return(false);
     }
     if (this.NotAllowedParameters != null && this.NotAllowedParameters.ContainsKey(command))
     {
         HashSet <string> hashSet = this.NotAllowedParameters[command];
         foreach (CommandParameter commandParameter in parameters)
         {
             if (hashSet.Contains(commandParameter.Name))
             {
                 TaskLogger.Log(Strings.CmdletValidatorParseErrors(string.Format("Invalid parameter {0}", commandParameter.Name)));
                 return(false);
             }
         }
     }
     if (this.RequiredParameters != null && this.RequiredParameters.ContainsKey(command))
     {
         HashSet <string> hashSet2 = new HashSet <string>(this.RequiredParameters[command]);
         foreach (CommandParameter commandParameter2 in parameters)
         {
             if (hashSet2.Contains(commandParameter2.Name))
             {
                 hashSet2.Remove(commandParameter2.Name);
             }
         }
         if (hashSet2.Count > 0)
         {
             TaskLogger.Log(Strings.CmdletValidatorParseErrors(string.Format("Required parameters {0} not specified", string.Join(",", hashSet2))));
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 30
0
        public static ParameterCollection ReadSetupParameters(bool isDatacenter)
        {
            string text = null;

            text = (Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\ExchangeLabs", "ParametersFile", null) as string);
            if (string.IsNullOrEmpty(text))
            {
                if (isDatacenter)
                {
                    throw new RegistryValueMissingOrInvalidException("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\ExchangeLabs", "ParametersFile");
                }
                text = Path.Combine(Role.SetupComponentInfoFilePath, "bin\\EnterpriseServiceEndpointsConfig.xml");
            }
            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();

            xmlReaderSettings.ConformanceLevel = ConformanceLevel.Document;
            xmlReaderSettings.ValidationType   = ValidationType.Schema;
            Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("parameter.xsd");

            xmlReaderSettings.Schemas.Add(null, XmlReader.Create(manifestResourceStream));
            ParameterCollection parameterCollection = null;

            using (XmlReader xmlReader = XmlReader.Create(text, xmlReaderSettings))
            {
                try
                {
                    parameterCollection = (ParameterCollection)RolesUtility.GetParameterSerializer().Deserialize(xmlReader);
                }
                catch (InvalidOperationException ex)
                {
                    throw new XmlDeserializationException(text, ex.Message, (ex.InnerException == null) ? string.Empty : ex.InnerException.Message, ex);
                }
            }
            TaskLogger.Log(Strings.LoadedParameters(text, parameterCollection.Count));
            return(parameterCollection);
        }