예제 #1
0
    public override bool Execute()
    {
        TaskLogger logger = new TaskLogger(this);

        List<string> compileGeneratedFiles;
        List<string> embeddedResourceGeneratedFiles;
        List<string> filesToDelete;

        bool debugMode = (ConditionalCompilationSymbols.Contains("PRESHARP_DEBUG") || Environment.GetEnvironmentVariable("PRESHARP_DEBUG") != null) &&
                         !(ConditionalCompilationSymbols.Contains("DISABLE_PRESHARP_DEBUG") || Environment.GetEnvironmentVariable("DISABLE_PRESHARP_DEBUG") != null);

        PreSharpEntryPoint.Process(
            logger,
            InPlaceFiles.Select(taskItem => taskItem.ItemSpec),
            TemplateFiles.Select(taskItem => taskItem.ItemSpec),
            TemplateIncludeFiles.Select(taskItem => taskItem.ItemSpec),
            TemplateLibraryFiles.Select(taskItem => taskItem.ItemSpec),
            DependencyPaths.Select(taskItem => taskItem.ItemSpec),
            Path.GetFullPath(Path.Combine(Path.GetDirectoryName(ProjectPath), OutputDirectory)),
            out compileGeneratedFiles,
            out embeddedResourceGeneratedFiles,
            out filesToDelete,
            /*createNewAppDomain*/false,
            /*debugMode*/debugMode,
            ConditionalCompilationSymbols);

        CompileGeneratedFiles = compileGeneratedFiles.Select(file => new TaskItem(file)).ToArray();
        EmbeddedResourceGeneratedFiles = embeddedResourceGeneratedFiles.Select(file => new TaskItem(file)).ToArray();
        FilesToDelete = filesToDelete.Select(file => new TaskItem(file)).ToArray();

        return logger.Success;
    }
    public override bool Execute()
    {
        TaskLogger logger = new TaskLogger(this);

        if (File.Exists("PreSharp.EmbeddedResourceGeneratedFiles.cache")) {
            EmbeddedResourceGeneratedFiles = File.ReadAllLines("PreSharp.EmbeddedResourceGeneratedFiles.cache").Select(file => new TaskItem(file)).ToArray();
            foreach (var file in EmbeddedResourceGeneratedFiles) {
                logger.LogMessage("File '" + file + "' was added to embedded resource list");
            }
        }

        return true;
    }
예제 #3
0
        protected override IConfigurable PrepareDataObject()
        {
            TaskLogger.LogEnter();
            ADUser aduser = (ADUser)base.PrepareDataObject();

            this.exchangeGuid = aduser.ExchangeGuid;
            this.mdbId        = aduser.Database;
            ProxyAddressCollection emailAddresses = aduser.EmailAddresses;

            if (!aduser.ExchangeVersion.IsOlderThan(ADUserSchema.ArchiveGuid.VersionAdded))
            {
                if (("Archive" == base.ParameterSetName || "RemoteArchive" == base.ParameterSetName) && aduser.RecipientType == RecipientType.UserMailbox && aduser.MailboxMoveStatus != RequestStatus.None && aduser.MailboxMoveStatus != RequestStatus.Completed && aduser.MailboxMoveStatus != RequestStatus.CompletedWithWarning)
                {
                    base.WriteError(new RecipientTaskException(Strings.ErrorMailboxBeingMoved(this.Identity.ToString(), aduser.MailboxMoveStatus.ToString())), ErrorCategory.InvalidArgument, aduser);
                }
                if (aduser.ArchiveGuid != Guid.Empty)
                {
                    if (!this.PreventRecordingPreviousDatabase)
                    {
                        aduser.DisabledArchiveGuid     = aduser.ArchiveGuid;
                        aduser.DisabledArchiveDatabase = aduser.ArchiveDatabase;
                    }
                    else
                    {
                        aduser.DisabledArchiveGuid     = Guid.Empty;
                        aduser.DisabledArchiveDatabase = null;
                    }
                }
                aduser.ArchiveRelease  = MailboxRelease.None;
                aduser.ArchiveGuid     = Guid.Empty;
                aduser.ArchiveName     = null;
                aduser.ArchiveDatabase = null;
                aduser.ArchiveDomain   = null;
                if (VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).CmdletInfra.RecoverMailBox.Enabled&& "Archive" == base.ParameterSetName)
                {
                    aduser.ArchiveStatus = (aduser.ArchiveStatus &= ~ArchiveStatusFlags.Active);
                }
                if ((aduser.RemoteRecipientType & RemoteRecipientType.ProvisionArchive) == RemoteRecipientType.ProvisionArchive)
                {
                    aduser.RemoteRecipientType = ((aduser.RemoteRecipientType &= ~RemoteRecipientType.ProvisionArchive) | RemoteRecipientType.DeprovisionArchive);
                }
            }
            if ("Archive" == base.ParameterSetName || "RemoteArchive" == base.ParameterSetName)
            {
                TaskLogger.Trace("DisableMailbox -Archive or -RemoteArchive skipping PrepareDataObject", new object[0]);
                TaskLogger.LogExit();
                return(aduser);
            }
            if (VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).CmdletInfra.RecoverMailBox.Enabled)
            {
                if (!this.PreventRecordingPreviousDatabase)
                {
                    aduser.PreviousDatabase     = aduser.Database;
                    aduser.PreviousExchangeGuid = aduser.ExchangeGuid;
                }
                else
                {
                    aduser.PreviousDatabase     = null;
                    aduser.PreviousExchangeGuid = Guid.Empty;
                }
            }
            aduser.PreviousRecipientTypeDetails = aduser.RecipientTypeDetails;
            int        recipientSoftDeletedStatus = aduser.RecipientSoftDeletedStatus;
            DateTime?  whenSoftDeleted            = aduser.WhenSoftDeleted;
            Guid       disabledArchiveGuid        = aduser.DisabledArchiveGuid;
            ADObjectId disabledArchiveDatabase    = aduser.DisabledArchiveDatabase;

            MailboxTaskHelper.ClearExchangeProperties(aduser, RecipientConstants.DisableMailbox_PropertiesToReset);
            aduser.SetExchangeVersion(null);
            aduser.MailboxRelease = MailboxRelease.None;
            aduser.OverrideCorruptedValuesWithDefault();
            aduser.propertyBag.SetField(ADRecipientSchema.RecipientSoftDeletedStatus, recipientSoftDeletedStatus);
            aduser.propertyBag.SetField(ADRecipientSchema.WhenSoftDeleted, whenSoftDeleted);
            if (disabledArchiveGuid != Guid.Empty)
            {
                aduser.propertyBag.SetField(ADUserSchema.DisabledArchiveGuid, disabledArchiveGuid);
                aduser.propertyBag.SetField(ADUserSchema.DisabledArchiveDatabase, disabledArchiveDatabase);
            }
            if (this.PreserveEmailAddresses)
            {
                aduser.propertyBag.SetField(ADRecipientSchema.EmailAddresses, emailAddresses);
            }
            TaskLogger.LogExit();
            return(aduser);
        }
예제 #4
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     base.SetVariable(base.Name, this.Value, base.Target);
     TaskLogger.LogExit();
 }
예제 #5
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            IRecipientSession recipientSession = (IRecipientSession)base.DataSession;

            if (this.GenerateExternalDirectoryObjectId && string.IsNullOrEmpty(this.DataObject.ExternalDirectoryObjectId))
            {
                this.DataObject.ExternalDirectoryObjectId = Guid.NewGuid().ToString();
            }
            if (this.BusinessNetID != null)
            {
                this.DataObject.ConsumerNetID = this.DataObject.NetID;
                this.DataObject.NetID         = this.BusinessNetID;
            }
            if (this.CopyShadowAttributes)
            {
                foreach (PropertyDefinition propertyDefinition in this.DataObject.Schema.AllProperties)
                {
                    ADPropertyDefinition adpropertyDefinition = propertyDefinition as ADPropertyDefinition;
                    if (adpropertyDefinition != null)
                    {
                        object value = null;
                        if (adpropertyDefinition.ShadowProperty != null && this.DataObject.propertyBag.TryGetField(adpropertyDefinition, ref value))
                        {
                            this.DataObject.propertyBag[adpropertyDefinition.ShadowProperty] = value;
                        }
                    }
                }
            }
            if (this.EnableAccount.IsPresent && this.DataObject.UserAccountControl == (UserAccountControlFlags.AccountDisabled | UserAccountControlFlags.PasswordNotRequired | UserAccountControlFlags.NormalAccount))
            {
                this.DataObject.UserAccountControl = UserAccountControlFlags.NormalAccount;
                using (SecureString randomPassword = MailboxTaskUtilities.GetRandomPassword(this.DataObject.Name, this.DataObject.SamAccountName))
                {
                    recipientSession.SetPassword(this.DataObject, randomPassword);
                }
            }
            if (base.Fields.IsModified(ADRecipientSchema.LEOEnabled))
            {
                this.DataObject.LEOEnabled = this.LEOEnabled;
            }
            if (base.Fields.IsModified("UpgradeMessage"))
            {
                this.DataObject.UpgradeMessage = this.UpgradeMessage;
            }
            if (base.Fields.IsModified("UpgradeDetails"))
            {
                this.DataObject.UpgradeDetails = this.UpgradeDetails;
            }
            if (base.Fields.IsModified("UpgradeStage"))
            {
                this.DataObject.UpgradeStage = this.UpgradeStage;
            }
            if (base.Fields.IsModified("UpgradeStageTimeStamp"))
            {
                this.DataObject.UpgradeStageTimeStamp = this.UpgradeStageTimeStamp;
            }
            if (base.Fields.IsModified("MailboxRelease"))
            {
                this.DataObject.MailboxRelease = this.MailboxRelease;
            }
            if (base.Fields.IsModified("ArchiveRelease"))
            {
                this.DataObject.ArchiveRelease = this.ArchiveRelease;
            }
            base.InternalProcessRecord();
            TaskLogger.LogExit();
        }
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     base.DeleteRegistryMarkers();
     TaskLogger.LogExit();
 }
예제 #7
0
        internal bool GenerateAndExecuteTaskScript(InstallationCircumstances installationCircumstance)
        {
            this.completedSteps = 0;
            bool flag = false;
            ConfigurationStatus configurationStatus = new ConfigurationStatus(this.taskNoun, this.InstallationMode);
            string text = string.Format("{0}-{1}", this.taskVerb, this.taskNoun);

            TaskLogger.LogEnter();
            bool          flag2         = this.ShouldExecuteComponentTasks();
            StringBuilder stringBuilder = new StringBuilder();

            List <TaskInfo> .Enumerator enumerator = default(List <TaskInfo> .Enumerator);
            this.PopulateContextVariables();
            try
            {
                string path  = string.Format("{0}-{1}.ps1", text, base.Fields["InvocationID"]);
                string text2 = Path.Combine(ConfigurationContext.Setup.SetupLoggingPath, path);
                base.WriteVerbose(Strings.WritingInformationScript(text2));
                if (this.shouldWriteLogFile)
                {
                    this.logFileStream           = new StreamWriter(text2);
                    this.logFileStream.AutoFlush = true;
                }
                this.WriteLogFile(Strings.SetupLogHeader(this.taskNoun, this.taskVerb, (DateTime)ExDateTime.Now));
                this.WriteLogFile(Strings.VariablesSection);
                if (base.ServerSettings != null)
                {
                    this.monadConnection.RunspaceProxy.SetVariable(ExchangePropertyContainer.ADServerSettingsVarName, base.ServerSettings);
                }
                this.SetRunspaceVariables();
                SortedList <string, object> sortedList = new SortedList <string, object>();
                foreach (object obj in base.Fields)
                {
                    DictionaryEntry dictionaryEntry = (DictionaryEntry)obj;
                    sortedList.Add((string)dictionaryEntry.Key, dictionaryEntry.Value);
                }
                foreach (KeyValuePair <string, object> keyValuePair in sortedList)
                {
                    string text3 = this.GenerateScriptVarCommand(keyValuePair.Key, keyValuePair.Value);
                    this.WriteLogFile(text3);
                    if (flag2)
                    {
                        this.ExecuteScript(text3, false, 0, LocalizedString.Empty);
                    }
                }
                this.FilterComponents();
                if (this.InstallationMode == InstallationModes.Uninstall)
                {
                    base.WriteVerbose(Strings.ReversingTaskList);
                    this.ComponentInfoList.Reverse();
                    foreach (SetupComponentInfo setupComponentInfo in this.ComponentInfoList)
                    {
                        setupComponentInfo.Tasks.Reverse();
                    }
                }
                List <SetupComponentInfo> .Enumerator enumerator5 = this.ComponentInfoList.GetEnumerator();
                bool flag3 = false;
                this.FindStartingTask(ref enumerator5, ref enumerator, ref flag3, this.InstallationMode, installationCircumstance);
                using (enumerator5)
                {
                    bool flag4 = true;
                    bool flag5 = true;
                    this.WriteLogFile(Strings.ComponentTaskSection);
                    this.totalSteps = this.CountStepsToBeExecuted(this.ComponentInfoList, this.InstallationMode, installationCircumstance);
                    while (flag4)
                    {
                        SetupComponentInfo setupComponentInfo2 = enumerator5.Current;
                        string             name = setupComponentInfo2.Name;
                        LocalizedString    localizedString;
                        if (string.IsNullOrEmpty(setupComponentInfo2.DescriptionId))
                        {
                            localizedString = Strings.SetupProgressGenericComponent;
                        }
                        else
                        {
                            try
                            {
                                Strings.IDs key = (Strings.IDs)Enum.Parse(typeof(Strings.IDs), setupComponentInfo2.DescriptionId, false);
                                localizedString = Strings.GetLocalizedString(key);
                            }
                            catch (ArgumentException)
                            {
                                localizedString = Strings.SetupProgressGenericComponent;
                            }
                        }
                        base.WriteVerbose(Strings.ProcessingComponent(name, localizedString));
                        this.WriteLogFile(Strings.ComponentSection(name));
                        while (flag5)
                        {
                            TaskInfo taskInfo = enumerator.Current;
                            string   task     = taskInfo.GetTask(this.InstallationMode, installationCircumstance);
                            if (string.IsNullOrEmpty(task))
                            {
                                flag5 = enumerator.MoveNext();
                            }
                            else if (!this.IsTaskIncluded(taskInfo, enumerator5.Current))
                            {
                                flag5 = enumerator.MoveNext();
                            }
                            else
                            {
                                string text4  = task;
                                string id     = taskInfo.GetID();
                                int    weight = taskInfo.GetWeight(this.InstallationMode);
                                bool   flag6  = !flag3 && taskInfo.IsFatal(this.InstallationMode);
                                flag3 = false;
                                string          description = taskInfo.GetDescription(this.InstallationMode);
                                LocalizedString localizedString2;
                                if (string.IsNullOrEmpty(description))
                                {
                                    localizedString2 = localizedString;
                                }
                                else
                                {
                                    try
                                    {
                                        Strings.IDs key2 = (Strings.IDs)Enum.Parse(typeof(Strings.IDs), description, false);
                                        localizedString2 = Strings.GetLocalizedString(key2);
                                    }
                                    catch (ArgumentException)
                                    {
                                        localizedString2 = localizedString;
                                    }
                                }
                                this.WriteLogFile(string.Format("# [ID = {0:x}, Wt = {1}, isFatal = {2}] \"{3}\"", new object[]
                                {
                                    taskInfo.GetID(),
                                    weight,
                                    flag6,
                                    localizedString2
                                }));
                                this.WriteLogFile(ExDateTime.Now + ":" + text4);
                                if (flag2)
                                {
                                    configurationStatus.Watermark = id;
                                    if (this.ImplementsResume)
                                    {
                                        RolesUtility.SetConfiguringStatus(configurationStatus);
                                    }
                                    if (!text4.Contains("\n"))
                                    {
                                        text4 = "\n\t" + text4 + "\n\n";
                                    }
                                    ExDateTime now      = ExDateTime.Now;
                                    bool       flag7    = this.ExecuteScript(text4, !flag6, weight, localizedString2);
                                    TimeSpan   timeSpan = ExDateTime.Now - now;
                                    if (ComponentInfoBasedTask.monitoredCmdlets.Contains(text.ToLowerInvariant()) && timeSpan.CompareTo(this.executionTimeThreshold) > 0)
                                    {
                                        if (taskInfo is ServicePlanTaskInfo)
                                        {
                                            ServicePlanTaskInfo servicePlanTaskInfo = (ServicePlanTaskInfo)taskInfo;
                                            stringBuilder.AppendLine(string.Format("Task {0}__{1} had execution time: {2}.", servicePlanTaskInfo.FileId, servicePlanTaskInfo.FeatureName, timeSpan.ToString()));
                                        }
                                        else
                                        {
                                            stringBuilder.AppendLine(string.Format("Task {0} had execution time: {1}.", taskInfo.GetID(), timeSpan.ToString()));
                                        }
                                    }
                                    flag = (!flag7 && flag6);
                                    if (flag)
                                    {
                                        base.WriteVerbose(new LocalizedString(string.Format("[ERROR-REFERENCE] Id={0} Component={1}", taskInfo.GetID(), taskInfo.Component)));
                                        base.WriteVerbose(Strings.HaltingExecution);
                                        break;
                                    }
                                }
                                flag5 = enumerator.MoveNext();
                            }
                        }
                        if (flag)
                        {
                            break;
                        }
                        flag4 = enumerator5.MoveNext();
                        if (flag4)
                        {
                            enumerator.Dispose();
                            enumerator = enumerator5.Current.Tasks.GetEnumerator();
                            flag5      = enumerator.MoveNext();
                        }
                    }
                    base.WriteVerbose(Strings.FinishedComponentTasks);
                }
            }
            catch (Exception ex)
            {
                base.WriteVerbose(Strings.ExceptionOccured(ex.ToString()));
                flag = true;
                this.OnHalt(ex);
                throw;
            }
            finally
            {
                if (!string.IsNullOrEmpty(stringBuilder.ToString()) && ComponentInfoBasedTask.monitoredCmdlets.Contains(text.ToLowerInvariant()))
                {
                    if (base.Fields["TenantName"] != null)
                    {
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ExecuteTaskScriptOptic, new string[]
                        {
                            text,
                            base.Fields["TenantName"].ToString(),
                            stringBuilder.ToString()
                        });
                    }
                    else if (base.Fields["OrganizationHierarchicalPath"] != null)
                    {
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ExecuteTaskScriptOptic, new string[]
                        {
                            text,
                            base.Fields["OrganizationHierarchicalPath"].ToString(),
                            stringBuilder.ToString()
                        });
                    }
                    else
                    {
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ExecuteTaskScriptOptic, new string[]
                        {
                            text,
                            string.Empty,
                            stringBuilder.ToString()
                        });
                    }
                }
                if (flag)
                {
                    if (this.IsCmdletLogEntriesEnabled)
                    {
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ComponentTaskFailed, this.GetComponentEventParameters(this.GetVerboseInformation(this.GetCmdletLogEntries())));
                    }
                    base.WriteProgress(this.Description, Strings.ProgressStatusFailed, 100);
                }
                else
                {
                    if (this.IsCmdletLogEntriesEnabled)
                    {
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ComponentTaskExecutedSuccessfully, this.GetComponentEventParameters(this.GetVerboseInformation(this.GetCmdletLogEntries())));
                    }
                    base.WriteProgress(this.Description, Strings.ProgressStatusCompleted, 100);
                    if (flag2)
                    {
                        RolesUtility.ClearConfiguringStatus(configurationStatus);
                        if (text == "Start-PostSetup")
                        {
                            foreach (string roleName in base.Fields["Roles"].ToString().Split(new char[]
                            {
                                ','
                            }))
                            {
                                RolesUtility.SetPostSetupVersion(roleName, (Version)base.Fields["TargetVersion"]);
                            }
                            RolesUtility.SetPostSetupVersion("AdminTools", (Version)base.Fields["TargetVersion"]);
                        }
                    }
                }
                if (this.logFileStream != null)
                {
                    this.logFileStream.Close();
                    this.logFileStream = null;
                }
                enumerator.Dispose();
                TaskLogger.LogExit();
            }
            return(!flag);
        }
예제 #8
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            Exception exception = null;

            if (!ReplicationTopology.TryLoadLocalSiteTopology(this.DomainController, out this.replicationTopology, out exception))
            {
                this.WriteErrorAndMonitoringEvent(exception, ExchangeErrorCategory.ServerOperation, null, 1002, "MSExchange Monitoring EdgeSynchronization");
                return;
            }
            if (this.replicationTopology.EdgeSyncServiceConfig == null)
            {
                this.ReportStatus(new EdgeSubscriptionStatus(string.Empty)
                {
                    SyncStatus    = ValidationStatus.NoSyncConfigured,
                    FailureDetail = Strings.EdgeSyncServiceConfigMissing((this.replicationTopology.LocalSite != null) ? this.replicationTopology.LocalSite.Name : string.Empty)
                });
                return;
            }
            if (this.replicationTopology.SiteEdgeServers.Count == 0)
            {
                this.ReportStatus(new EdgeSubscriptionStatus(string.Empty)
                {
                    SyncStatus    = ValidationStatus.NoSyncConfigured,
                    FailureDetail = Strings.NoSubscription((this.replicationTopology.LocalSite != null) ? this.replicationTopology.LocalSite.Name : string.Empty)
                });
                return;
            }
            List <EdgeSubscriptionStatus> list = new List <EdgeSubscriptionStatus>(this.replicationTopology.SiteEdgeServers.Count);

            foreach (Server server in this.replicationTopology.SiteEdgeServers)
            {
                if (string.IsNullOrEmpty(this.TargetServer) || this.TargetServer.Equals(server.Name, StringComparison.OrdinalIgnoreCase) || this.TargetServer.Equals(server.Fqdn))
                {
                    EdgeSubscriptionStatus edgeSubscriptionStatus = new EdgeSubscriptionStatus(server.Name);
                    EdgeConnectionInfo     edgeConnectionInfo     = new EdgeConnectionInfo(this.replicationTopology, server);
                    if (edgeConnectionInfo.EdgeConnection == null)
                    {
                        goto IL_3D5;
                    }
                    edgeSubscriptionStatus.LeaseHolder               = edgeConnectionInfo.LeaseHolder;
                    edgeSubscriptionStatus.LeaseType                 = edgeConnectionInfo.LeaseType;
                    edgeSubscriptionStatus.LeaseExpiryUtc            = edgeConnectionInfo.LeaseExpiry;
                    edgeSubscriptionStatus.LastSynchronizedUtc       = edgeConnectionInfo.LastSynchronizedDate;
                    edgeSubscriptionStatus.CredentialRecords.Records = CredentialRecordsLoader.Load(server);
                    edgeSubscriptionStatus.CookieRecords.Load(edgeConnectionInfo.Cookies);
                    if (this.VerifyRecipient != null)
                    {
                        RecipientValidator recipientValidator = new RecipientValidator(this.replicationTopology);
                        edgeSubscriptionStatus.RecipientStatus = recipientValidator.ValidateOneRecipient(edgeConnectionInfo, this.VerifyRecipient.ProxyAddressString);
                    }
                    else if (this.InitializeSubscriptionStatus(edgeConnectionInfo, ref edgeSubscriptionStatus))
                    {
                        if (!(DateTime.UtcNow > edgeSubscriptionStatus.LeaseExpiryUtc + this.GetAlertPaddingTimeSpan()))
                        {
                            bool flag = false;
                            if (edgeSubscriptionStatus.CookieRecords.Records.Count > 0)
                            {
                                using (MultiValuedProperty <CookieRecord> .Enumerator enumerator2 = edgeSubscriptionStatus.CookieRecords.Records.GetEnumerator())
                                {
                                    while (enumerator2.MoveNext())
                                    {
                                        CookieRecord cookieRecord = enumerator2.Current;
                                        if (DateTime.UtcNow > cookieRecord.LastUpdated + this.GetAlertPaddingTimeSpan())
                                        {
                                            flag = true;
                                        }
                                    }
                                    goto IL_2EC;
                                }
                                goto IL_2E9;
                            }
                            goto IL_2E9;
IL_2EC:
                            if (!flag)
                            {
                                edgeSubscriptionStatus.SyncStatus = ValidationStatus.Normal;
                                goto IL_313;
                            }
                            edgeSubscriptionStatus.SyncStatus    = ValidationStatus.Failed;
                            edgeSubscriptionStatus.FailureDetail = Strings.CookieNotUpdated;
                            goto IL_313;
IL_2E9:
                            flag = true;
                            goto IL_2EC;
                        }
                        edgeSubscriptionStatus.SyncStatus    = ValidationStatus.Failed;
                        edgeSubscriptionStatus.FailureDetail = Strings.LeaseExpired;
IL_313:
                        if (this.fullCompareMode)
                        {
                            try
                            {
                                this.LoadValidators();
                                edgeSubscriptionStatus.TransportConfigStatus       = this.transportConfigValidator.Validate(edgeConnectionInfo);
                                edgeSubscriptionStatus.TransportServerStatus       = this.transportServerValidator.Validate(edgeConnectionInfo);
                                edgeSubscriptionStatus.AcceptedDomainStatus        = this.acceptedDomainValidator.Validate(edgeConnectionInfo);
                                edgeSubscriptionStatus.RemoteDomainStatus          = this.remoteDomainValidator.Validate(edgeConnectionInfo);
                                edgeSubscriptionStatus.MessageClassificationStatus = this.messageClassificationValidator.Validate(edgeConnectionInfo);
                                edgeSubscriptionStatus.SendConnectorStatus         = this.sendConnectorValidator.Validate(edgeConnectionInfo);
                                if (!this.ExcludeRecipientTest.IsPresent)
                                {
                                    edgeSubscriptionStatus.RecipientStatus = this.recipientValidator.Validate(edgeConnectionInfo);
                                }
                                goto IL_3F5;
                            }
                            catch (ExDirectoryException ex)
                            {
                                edgeSubscriptionStatus.FailureDetail = ex.Message;
                                goto IL_3F5;
                            }
                            goto IL_3D5;
                        }
                    }
IL_3F5:
                    base.WriteObject(edgeSubscriptionStatus);
                    list.Add(edgeSubscriptionStatus);
                    continue;
IL_3D5:
                    edgeSubscriptionStatus.SyncStatus    = ValidationStatus.Failed;
                    edgeSubscriptionStatus.FailureDetail = Strings.SubscriptionConnectionError(edgeConnectionInfo.FailureDetail);
                    goto IL_3F5;
                }
            }
            if (this.MonitoringContext)
            {
                this.ReportMomStatus(list);
            }
            TaskLogger.LogExit();
        }
 protected override void InternalValidate()
 {
     TaskLogger.LogEnter();
     base.InternalValidate();
     TaskLogger.LogExit();
 }
예제 #10
0
        protected override void InternalValidate()
        {
            bool flag  = base.Fields.IsModified("Event");
            bool flag2 = base.Fields.IsModified("Action");
            bool flag3 = base.Fields.IsModified("Condition");
            bool flag4 = base.Fields.IsModified("CustomResponseCode");
            bool flag5 = base.Fields.IsModified("CustomResponseText");
            bool flag6 = base.Fields.IsModified("Description");
            bool flag7 = base.Fields.IsModified("TimeInterval");
            bool flag8 = base.Fields.IsModified("Path");

            this.xmlNeedsUpdating = (flag2 || flag || flag3 || flag4 || flag5 || flag7 || flag6 || flag8 || base.Fields.IsModified("Identity"));
            if (base.Fields.IsModified("ExpireTime") && DateTime.UtcNow > this.ExpireTime.ToUniversalTime())
            {
                base.WriteError(new LocalizedException(Strings.InterceptorErrorExpireTimePassed(this.ExpireTime.ToString("G"))), ErrorCategory.InvalidData, "ExpireTime");
            }
            this.DataObject = (InterceptorRule)this.ResolveDataObject();
            if (this.xmlNeedsUpdating)
            {
                try
                {
                    this.rule = InterceptorAgentRule.CreateRuleFromXml(this.DataObject.Xml);
                    this.rule.SetPropertiesFromAdObjet(this.DataObject);
                }
                catch (FormatException exception)
                {
                    base.WriteError(exception, ErrorCategory.InvalidData, null);
                    TaskLogger.LogExit();
                    return;
                }
                catch (InvalidOperationException exception2)
                {
                    base.WriteError(exception2, ErrorCategory.InvalidData, null);
                    TaskLogger.LogExit();
                    return;
                }
            }
            if (this.rule.RuleVersion > InterceptorAgentRule.Version)
            {
                base.WriteError(new LocalizedException(Strings.InterceptorErrorModifyingNewerVersion(this.rule.RuleVersion.ToString())), ErrorCategory.InvalidOperation, null);
            }
            if (flag2 || flag)
            {
                InterceptorAgentRuleBehavior action = flag2 ? this.Action : this.rule.Action.Action;
                InterceptorAgentEvent        interceptorAgentEvent = flag ? this.Event : this.rule.Events;
                LocalizedString localizedString;
                if (!InterceptorHelper.ValidateEventActionPairs(interceptorAgentEvent, action, out localizedString))
                {
                    base.WriteError(new LocalizedException(localizedString), ErrorCategory.InvalidArgument, this.Condition);
                }
                this.rule.Events = interceptorAgentEvent;
                string customResponseCode;
                if (flag2 && !flag4 && InterceptorHelper.TryGetStatusCodeForModifiedRejectAction(this.Action, this.rule.Action.Action, this.rule.Action.Response.StatusCode, out customResponseCode))
                {
                    this.CustomResponseCode = customResponseCode;
                    flag4 = base.Fields.IsModified("CustomResponseCode");
                }
            }
            if (flag3)
            {
                LocalizedString localizedString;
                List <InterceptorAgentCondition> conditions;
                if (!InterceptorHelper.TryCreateConditions(this.Condition, out conditions, out localizedString))
                {
                    base.WriteError(new LocalizedException(localizedString), ErrorCategory.InvalidData, this.Condition);
                    return;
                }
                InterceptorAgentEvent evt = flag ? this.Event : this.rule.Events;
                if (!InterceptorHelper.ValidateEventConditionPairs(evt, conditions, out localizedString))
                {
                    base.WriteError(new LocalizedException(localizedString), ErrorCategory.InvalidArgument, this.Condition);
                }
                this.rule.Conditions = conditions;
            }
            if (flag)
            {
                LocalizedString localizedString;
                if (!flag3 && !InterceptorHelper.ValidateEventConditionPairs(this.Event, this.rule.Conditions, out localizedString))
                {
                    base.WriteError(new LocalizedException(localizedString), ErrorCategory.InvalidArgument, this.Condition);
                }
                this.rule.Events = this.Event;
            }
            if (flag6)
            {
                this.rule.Description = this.Description;
            }
            this.SetAction(flag4, flag5, flag2, flag8, flag7);
            this.ResolveTargets();
        }
예제 #11
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            try
            {
                ADUser            dataObject       = this.DataObject;
                IRecipientSession recipientSession = (IRecipientSession)base.DataSession;
                recipientSession.Save(dataObject);
                ADUser aduser = (ADUser)base.DataSession.Read <ADUser>(dataObject.Identity);
                if (aduser == null)
                {
                    throw new LocalizedException(Strings.ErrorReadingUpdatedUserFromAD(dataObject.OriginatingServer, recipientSession.LastUsedDc));
                }
                aduser.UserAccountControl = UserAccountControlFlags.None;
                if (this.LogonEnabled)
                {
                    using (SecureString randomPassword = MailboxTaskUtilities.GetRandomPassword(this.Name, aduser.SamAccountName))
                    {
                        recipientSession.SetPassword(aduser, randomPassword);
                        goto IL_98;
                    }
                }
                aduser.UserAccountControl |= UserAccountControlFlags.AccountDisabled;
IL_98:
                aduser.UserAccountControl |= UserAccountControlFlags.NormalAccount;
                this.DataObject            = aduser;
                base.InternalProcessRecord();
            }
            catch (ADObjectAlreadyExistsException ex)
            {
                base.WriteVerbose(Strings.UserCreateFailed(this.Name, ex.Message.ToString()));
            }
            LocalizedString localizedString = LocalizedString.Empty;

            try
            {
                base.WriteVerbose(Strings.VerboseGrantingEoaFullAccessOnMailbox(this.DataObject.Identity.ToString()));
                ADGroup adgroup = base.RootOrgGlobalCatalogSession.ResolveWellKnownGuid <ADGroup>(WellKnownGuid.EoaWkGuid, base.GlobalConfigSession.ConfigurationNamingContext.ToDNString());
                if (adgroup == null)
                {
                    localizedString = Strings.ErrorGroupNotFound(WellKnownGuid.EoaWkGuid.ToString());
                }
                else
                {
                    DirectoryCommon.SetAces(new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), null, (IDirectorySession)base.DataSession, this.DataObject.Id, new ActiveDirectoryAccessRule[]
                    {
                        new ActiveDirectoryAccessRule(adgroup.Sid, ActiveDirectoryRights.GenericAll, AccessControlType.Allow, ActiveDirectorySecurityInheritance.All)
                    });
                }
            }
            catch (ADTransientException ex2)
            {
                localizedString = ex2.LocalizedString;
            }
            catch (ADOperationException ex3)
            {
                localizedString = ex3.LocalizedString;
            }
            catch (SecurityDescriptorAccessDeniedException ex4)
            {
                localizedString = ex4.LocalizedString;
            }
            if (LocalizedString.Empty != localizedString)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorGrantingEraFullAccessOnMailbox(this.DataObject.Identity.ToString(), localizedString)), ErrorCategory.InvalidOperation, this.DataObject.Identity);
            }
            TaskLogger.LogExit();
        }
예제 #12
0
        public static bool HandleTaskWritePagedResult <T>(IEnumerable <T> dataObjects, IEnumerable <T> dataObjects2, SyncCookie inputCookie, ref SyncCookie outputCookie, SyncTaskHelper.ParameterlessMethod <bool> isStopping, SyncTaskHelper.OneParameterMethod <bool, IConfigurable> shouldSkipObject, SyncTaskHelper.VoidOneParameterMethod <IConfigurable> writeResult, int pages, Task.TaskVerboseLoggingDelegate writeVerbose, Task.TaskErrorLoggingDelegate writeError, out bool hasOutput) where T : IConfigurable, new()
        {
            TaskLogger.LogEnter(new object[]
            {
                dataObjects
            });
            int  num   = 1000;
            int  num2  = 0;
            bool flag  = true;
            bool flag2 = true;

            SyncTaskHelper.CookieObjectTriple <T> cookieObjectTriple = null;
            int num3 = 1;
            ADPagedReader <T> adpagedReader  = dataObjects as ADPagedReader <T>;
            ADPagedReader <T> adpagedReader2 = dataObjects2 as ADPagedReader <T>;

            byte[] pageCookie = null;
            byte[] array      = null;
            byte[] cookie     = adpagedReader.Cookie;
            byte[] cookie2    = adpagedReader2.Cookie;
            byte[] array2     = cookie2;
            hasOutput = false;
            for (;;)
            {
                using (IEnumerator <T> enumerator = flag ? dataObjects.GetEnumerator() : dataObjects2.GetEnumerator())
                {
                    bool flag3 = enumerator.MoveNext();
                    bool flag4 = !flag && ((cookieObjectTriple == null && num2 == 0) || (cookieObjectTriple != null && num2 == num - 1));
                    if ((adpagedReader.LastRetrievedCount == 0 && adpagedReader.Cookie != null && adpagedReader.Cookie.Length != 0) || (adpagedReader2.LastRetrievedCount == 0 && adpagedReader2.Cookie != null && adpagedReader2.Cookie.Length != 0))
                    {
                        return(false);
                    }
                    while (!isStopping() && flag3)
                    {
                        T t = enumerator.Current;
                        if (flag)
                        {
                            pageCookie = adpagedReader.Cookie;
                        }
                        else if (array != adpagedReader2.Cookie)
                        {
                            array2 = array;
                            array  = adpagedReader2.Cookie;
                        }
                        flag3 = enumerator.MoveNext();
                        if (!shouldSkipObject(t))
                        {
                            hasOutput = true;
                            if (cookieObjectTriple != null)
                            {
                                if (num2 == num - 1 || flag2)
                                {
                                    outputCookie = cookieObjectTriple.Cookie;
                                }
                                else
                                {
                                    outputCookie = null;
                                }
                                writeResult(cookieObjectTriple.DataObject);
                                flag2 = false;
                                if (num2 == num - 1)
                                {
                                    num2 = 0;
                                    num3++;
                                }
                                else
                                {
                                    num2++;
                                }
                                if (outputCookie != null)
                                {
                                    pages--;
                                    if (pages < 0)
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                pageCookie = cookie;
                                array      = cookie2;
                                array2     = cookie2;
                            }
                            cookieObjectTriple = new SyncTaskHelper.CookieObjectTriple <T>(num3, t, new SyncCookie(inputCookie.DomainController, inputCookie.LowWatermarks, inputCookie.HighWatermarks, pageCookie, flag4 ? array : array2));
                        }
                    }
                    if (pages >= 0)
                    {
                        if (!flag && !flag3 && cookieObjectTriple != null && pages >= 0)
                        {
                            outputCookie = new SyncCookie(inputCookie.DomainController, inputCookie.HighWatermarks, WatermarkMap.Empty, null, null);
                            writeResult(cookieObjectTriple.DataObject);
                        }
                        else if (flag)
                        {
                            flag = false;
                            continue;
                        }
                    }
                }
                break;
            }
            TaskLogger.LogExit();
            return(true);
        }
 protected override void InternalValidate()
 {
     TaskLogger.LogEnter();
     base.InternalValidate();
     if (this.RollbackGls)
     {
         if (!this.DataObject.InPostGLSSwitchState())
         {
             base.WriteError(new InvalidOperationException(Strings.ErrorRollbackGlsExpectsPostGlsState(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
         }
         if (!base.Fields.IsModified(TenantRelocationRequestSchema.RelocationStateRequested))
         {
             this.RelocationStateRequested = RelocationStateRequestedByCmdlet.SynchronizationFinishedFullSync;
         }
         else if (this.RelocationStateRequested != RelocationStateRequestedByCmdlet.SynchronizationFinishedFullSync)
         {
             base.WriteError(new InvalidOperationException(Strings.ErrorRollbackGlsExpectsSynchronizationFinishedFullSync(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
         }
     }
     if (base.Fields.IsModified(TenantRelocationRequestSchema.RelocationStateRequested) && (this.AutoCompletionEnabled || (!base.Fields.IsModified(TenantRelocationRequestSchema.AutoCompletionEnabled) && this.DataObject.AutoCompletionEnabled)))
     {
         base.WriteError(new InvalidOperationException(Strings.ErrorRelocationStateRequestedIsNotAllowed(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
     }
     if (base.Fields.IsModified(TenantRelocationRequestSchema.AutoCompletionEnabled) && !this.AutoCompletionEnabled && !base.Fields.IsModified(TenantRelocationRequestSchema.RelocationStateRequested))
     {
         base.WriteError(new InvalidOperationException(Strings.ErrorRelocationStateRequestedIsMandatory(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
     }
     if (base.Fields.IsModified(TenantRelocationRequestSchema.RelocationStateRequested))
     {
         if (this.RollbackGls || (this.RelocationStateRequested == RelocationStateRequestedByCmdlet.SynchronizationFinishedFullSync && this.DataObject.InLockdownBeforeGLSSwitchState()) || (this.RelocationStateRequested == RelocationStateRequestedByCmdlet.SynchronizationFinishedFullSync && this.DataObject.RelocationStatusDetailsSource == RelocationStatusDetailsSource.SynchronizationFinishedDeltaSync))
         {
             this.applyTransitionFromCmdlet = true;
         }
         else if (this.RelocationStateRequested < (RelocationStateRequestedByCmdlet)this.DataObject.RelocationStatusDetailsSource)
         {
             base.WriteError(new InvalidOperationException(Strings.ErrorRelocationStateRequestedIsTooLow(this.Identity.ToString(), this.RelocationStateRequested.ToString(), this.DataObject.RelocationStatusDetailsSource.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
         }
         if (this.DataObject.RelocationStateRequested == Microsoft.Exchange.Data.Directory.SystemConfiguration.RelocationStateRequested.Cleanup && this.RelocationStateRequested != (RelocationStateRequestedByCmdlet)this.DataObject.RelocationStateRequested)
         {
             base.WriteError(new InvalidOperationException(Strings.ErrorCleanupRequestedNoRollback(this.Identity.ToString(), this.RelocationStateRequested.ToString(), this.DataObject.RelocationStateRequested.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
         }
         if (this.RelocationStateRequested == RelocationStateRequestedByCmdlet.Cleanup)
         {
             if (this.DataObject.RelocationStatusDetailsSource != RelocationStatusDetailsSource.RetiredUpdatedTargetForest)
             {
                 base.WriteError(new InvalidOperationException(Strings.ErrorCleanupRequestedAtWrongStage(this.Identity.ToString(), this.RelocationStateRequested.ToString(), this.DataObject.RelocationStatusDetailsSource.ToString(), RelocationStatusDetailsSource.RetiredUpdatedTargetForest.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
             }
             if (!this.DataObject.IsRetiredSourceHoldTimedOut())
             {
                 base.WriteError(new InvalidOperationException(Strings.ErrorSourceHoldNotTimedOut(this.Identity.ToString(), TenantRelocationRequest.WaitTimeBeforeRemoveSourceReplicaDays.ToString(), this.DataObject.RetiredStartTime.Value.ToUniversalTime().ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
             }
         }
     }
     if ((base.Fields.IsModified("ResumeParameter") && !this.Resume) || (base.Fields.IsModified("SuspendParameter") && !this.Suspend))
     {
         base.WriteError(new InvalidOperationException(Strings.ErrorSuspendAndResumeDontSupportFalse), ErrorCategory.InvalidOperation, this.DataObject.Identity);
     }
     if (this.Resume && !this.DataObject.Suspended)
     {
         base.WriteError(new InvalidOperationException(Strings.ErrorCannotResumeIfNotSuspended), ErrorCategory.InvalidOperation, this.DataObject.Identity);
     }
     TaskLogger.LogExit();
 }
예제 #14
0
        public static bool HandleTaskWritePagedResult <T>(IEnumerable <T> dataObjects, SyncCookie inputCookie, ref SyncCookie outputCookie, SyncTaskHelper.ParameterlessMethod <bool> isStopping, SyncTaskHelper.OneParameterMethod <bool, IConfigurable> shouldSkipObject, SyncTaskHelper.VoidOneParameterMethod <IConfigurable> writeResult, int pages, Task.TaskVerboseLoggingDelegate writeVerbose, Task.TaskErrorLoggingDelegate writeError, out bool hasOutput) where T : IConfigurable, new()
        {
            TaskLogger.LogEnter(new object[]
            {
                dataObjects
            });
            ADPagedReader <T> adpagedReader = dataObjects as ADPagedReader <T>;

            hasOutput = false;
            using (IEnumerator <T> enumerator = dataObjects.GetEnumerator())
            {
                bool flag = true;
                SyncTaskHelper.CookieObjectTriple <T> cookieObjectTriple = null;
                byte[] cookie = adpagedReader.Cookie;
                bool   flag2  = enumerator.MoveNext();
                if (adpagedReader.LastRetrievedCount == 0 && adpagedReader.Cookie != null && adpagedReader.Cookie.Length != 0)
                {
                    return(false);
                }
                while (!isStopping() && flag2)
                {
                    T      t             = enumerator.Current;
                    byte[] pageCookie    = adpagedReader.Cookie;
                    int    pagesReturned = adpagedReader.PagesReturned;
                    flag2 = enumerator.MoveNext();
                    if (!shouldSkipObject(t))
                    {
                        hasOutput = true;
                        if (cookieObjectTriple != null)
                        {
                            if (cookieObjectTriple.CurrentPage != pagesReturned || flag)
                            {
                                outputCookie = cookieObjectTriple.Cookie;
                            }
                            else
                            {
                                outputCookie = null;
                            }
                            writeResult(cookieObjectTriple.DataObject);
                            if (outputCookie != null)
                            {
                                pages--;
                                if (pages < 0)
                                {
                                    break;
                                }
                            }
                            flag = false;
                        }
                        else
                        {
                            pageCookie = cookie;
                        }
                        cookieObjectTriple = new SyncTaskHelper.CookieObjectTriple <T>(pagesReturned, t, new SyncCookie(inputCookie.DomainController, inputCookie.LowWatermarks, inputCookie.HighWatermarks, pageCookie));
                    }
                }
                if (!flag2 && cookieObjectTriple != null && pages >= 0)
                {
                    outputCookie = new SyncCookie(inputCookie.DomainController, inputCookie.HighWatermarks, WatermarkMap.Empty, null);
                    writeResult(cookieObjectTriple.DataObject);
                }
            }
            TaskLogger.LogExit();
            return(true);
        }
예제 #15
0
        protected sealed override void InternalProcessRecord()
        {
            TaskLogger.LogEnter(new object[]
            {
                this.DataObject
            });
            if (this.DataObject.MajorVersion != LocalServer.GetServer().MajorVersion)
            {
                base.WriteError(new CannotModifyCrossVersionObjectException(this.DataObject.Id.DistinguishedName), ErrorCategory.InvalidOperation, null);
                return;
            }
            ClientAccessServer clientAccessServer = new ClientAccessServer(this.DataObject);

            if (base.Fields.IsModified("ClientAccessArray"))
            {
                ClientAccessArray clientAccessArrayFromIdParameter = this.GetClientAccessArrayFromIdParameter();
                if (clientAccessArrayFromIdParameter == null)
                {
                    clientAccessServer.ClientAccessArray = null;
                }
                else
                {
                    if (clientAccessArrayFromIdParameter.IsPriorTo15ExchangeObjectVersion)
                    {
                        base.WriteError(new InvalidOperationException(Strings.ErrorCannotSetToOldClientAccessArray(clientAccessArrayFromIdParameter.ExchangeVersion.ToString(), ClientAccessArray.MinimumSupportedExchangeObjectVersion.ToString())), ErrorCategory.InvalidOperation, this.Identity);
                        return;
                    }
                    clientAccessServer.ClientAccessArray = (ADObjectId)clientAccessArrayFromIdParameter.Identity;
                }
            }
            bool flag = false;
            ADServiceConnectionPoint adserviceConnectionPoint = null;
            ADObjectId childId = clientAccessServer.Id.GetChildId("Protocols").GetChildId("Autodiscover").GetChildId(clientAccessServer.Name);

            if (base.Fields.IsModified("AutoDiscoverServiceInternalUri") && this.AutoDiscoverServiceInternalUri == null && base.Fields.IsModified("AutoDiscoverSiteScope") && this.AutoDiscoverSiteScope == null)
            {
                adserviceConnectionPoint = new ADServiceConnectionPoint();
                adserviceConnectionPoint.SetId(childId);
                base.DataSession.Delete(adserviceConnectionPoint);
                ADObjectId  parent      = adserviceConnectionPoint.Id.Parent;
                ADContainer adcontainer = new ADContainer();
                adcontainer.SetId(parent);
                base.DataSession.Delete(adcontainer);
                flag = true;
            }
            else
            {
                adserviceConnectionPoint = ((IConfigurationSession)base.DataSession).Read <ADServiceConnectionPoint>(childId);
                if (adserviceConnectionPoint == null)
                {
                    adserviceConnectionPoint = new ADServiceConnectionPoint();
                    adserviceConnectionPoint.SetId(childId);
                    if (!base.Fields.IsModified("AutoDiscoverServiceInternalUri"))
                    {
                        string text = ComputerInformation.DnsFullyQualifiedDomainName;
                        if (string.IsNullOrEmpty(text))
                        {
                            text = ComputerInformation.DnsPhysicalHostName;
                        }
                        adserviceConnectionPoint.ServiceBindingInformation.Add("https://" + text + "/Autodiscover/Autodiscover.xml");
                    }
                    if (!base.Fields.IsModified("AutoDiscoverSiteScope"))
                    {
                        adserviceConnectionPoint.Keywords.Add("77378F46-2C66-4aa9-A6A6-3E7A48B19596");
                        string siteName = NativeHelpers.GetSiteName(false);
                        if (!string.IsNullOrEmpty(siteName))
                        {
                            adserviceConnectionPoint.Keywords.Add("Site=" + siteName);
                        }
                    }
                    adserviceConnectionPoint.ServiceDnsName   = ComputerInformation.DnsPhysicalHostName;
                    adserviceConnectionPoint.ServiceClassName = "ms-Exchange-AutoDiscover-Service";
                    flag = true;
                }
                if (base.Fields.IsModified("AutoDiscoverServiceInternalUri"))
                {
                    adserviceConnectionPoint.ServiceBindingInformation.Clear();
                    if (this.AutoDiscoverServiceInternalUri != null)
                    {
                        adserviceConnectionPoint.ServiceBindingInformation.Add(this.AutoDiscoverServiceInternalUri.ToString());
                    }
                    flag = true;
                }
                if (base.Fields.IsModified("AutoDiscoverSiteScope"))
                {
                    adserviceConnectionPoint.Keywords.Clear();
                    adserviceConnectionPoint.Keywords.Add("77378F46-2C66-4aa9-A6A6-3E7A48B19596");
                    if (this.AutoDiscoverSiteScope != null)
                    {
                        foreach (string str in this.AutoDiscoverSiteScope)
                        {
                            adserviceConnectionPoint.Keywords.Add("Site=" + str);
                        }
                    }
                    flag = true;
                }
                if (flag)
                {
                    ADObjectId parent2 = adserviceConnectionPoint.Id.Parent;
                    if (((IConfigurationSession)base.DataSession).Read <ADContainer>(parent2) == null)
                    {
                        ADContainer adcontainer2 = new ADContainer();
                        adcontainer2.SetId(parent2);
                        base.DataSession.Save(adcontainer2);
                    }
                    base.DataSession.Save(adserviceConnectionPoint);
                }
            }
            bool flag2 = false;

            if (this.CleanUpInvalidAlternateServiceAccountCredentials.ToBool() && this.alternateServiceAccountCredentialsToRemove.Count > 0)
            {
                foreach (AlternateServiceAccountCredential credential in this.alternateServiceAccountCredentialsToRemove)
                {
                    this.alternateServiceAccountConfiguration.RemoveCredential(credential);
                }
                flag2 = true;
            }
            if (this.RemoveAlternateServiceAccountCredentials.ToBool())
            {
                flag2 = this.alternateServiceAccountConfiguration.RemoveAllCredentials();
                flag2 = true;
            }
            if (this.AlternateServiceAccountCredential != null)
            {
                for (int i = this.AlternateServiceAccountCredential.Length - 1; i >= 0; i--)
                {
                    this.alternateServiceAccountConfiguration.AddCredential(this.AlternateServiceAccountCredential[i]);
                    flag2 = true;
                }
            }
            if (this.DataObject.ObjectState != ObjectState.Unchanged)
            {
                base.InternalProcessRecord();
            }
            else if (!flag && !flag2)
            {
                this.WriteWarning(Strings.WarningForceMessage);
            }
            TaskLogger.LogExit();
        }
예제 #16
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter(new object[]
     {
         this.DataObject
     });
     if (this.PublicFolder)
     {
         MailboxTaskHelper.RemoveOrDisablePublicFolderMailbox(this.DataObject, this.exchangeGuid, this.TenantLocalConfigurationSession, new Task.ErrorLoggerDelegate(base.WriteError), true, false);
     }
     base.InternalProcessRecord();
     if ("Archive" == base.ParameterSetName || "RemoteArchive" == base.ParameterSetName)
     {
         TaskLogger.Trace("DisableMailbox -Archive or -RemoteArchive skipping InternalProcessRecord", new object[0]);
         TaskLogger.LogExit();
         return;
     }
     try
     {
         MailboxDatabase mailboxDatabase = null;
         if (this.mdbId != null)
         {
             mailboxDatabase = (MailboxDatabase)base.GetDataObject <MailboxDatabase>(new DatabaseIdParameter(this.mdbId)
             {
                 AllowLegacy = true
             }, base.GlobalConfigSession, null, new LocalizedString?(Strings.ErrorDatabaseNotFound(this.mdbId.ToString())), new LocalizedString?(Strings.ErrorDatabaseNotUnique(this.mdbId.ToString())));
         }
         if (mailboxDatabase != null && this.exchangeGuid != Guid.Empty)
         {
             Server server = mailboxDatabase.GetServer();
             if (server == null)
             {
                 this.WriteWarning(Strings.ErrorDBOwningServerNotFound(mailboxDatabase.Identity.ToString()));
             }
             else if (string.IsNullOrEmpty(server.ExchangeLegacyDN))
             {
                 this.WriteWarning(Strings.ErrorInvalidObjectMissingCriticalProperty(typeof(Server).Name, server.Identity.ToString(), ServerSchema.ExchangeLegacyDN.Name));
             }
             else if (string.IsNullOrEmpty(server.Fqdn))
             {
                 this.WriteWarning(Strings.ErrorInvalidObjectMissingCriticalProperty(typeof(Server).Name, server.Identity.ToString(), ServerSchema.Fqdn.Name));
             }
             else
             {
                 base.WriteVerbose(Strings.VerboseConnectionAdminRpcInterface(server.Fqdn));
                 using (MapiAdministrationSession mapiAdministrationSession = new MapiAdministrationSession(server.ExchangeLegacyDN, Fqdn.Parse(server.Fqdn)))
                 {
                     base.WriteVerbose(Strings.VerboseSyncMailboxWithDS(this.Identity.ToString(), this.mdbId.ToString(), server.Fqdn));
                     mapiAdministrationSession.SyncMailboxWithDS(new MailboxId(MapiTaskHelper.ConvertDatabaseADObjectIdToDatabaseId(this.mdbId), this.exchangeGuid));
                 }
             }
         }
     }
     catch (Microsoft.Exchange.Data.Mapi.Common.MailboxNotFoundException ex)
     {
         TaskLogger.Trace("Swallowing exception {0} from mapi.net", new object[]
         {
             ex
         });
         base.WriteVerbose(ex.LocalizedString);
     }
     catch (DataSourceTransientException ex2)
     {
         TaskLogger.Trace("Swallowing exception {0} from mapi.net", new object[]
         {
             ex2
         });
         this.WriteWarning(ex2.LocalizedString);
     }
     catch (DataSourceOperationException ex3)
     {
         TaskLogger.Trace("Swallowing exception {0} from mapi.net", new object[]
         {
             ex3
         });
         this.WriteWarning(ex3.LocalizedString);
     }
     TaskLogger.LogExit();
 }
 protected override void InternalValidate()
 {
     TaskLogger.LogEnter();
     try
     {
         string     empty      = string.Empty;
         string     empty2     = string.Empty;
         int        num        = 0;
         ADObjectId adobjectId = null;
         if (base.ParameterSetName.Equals("MigrationOutlookAnywherePublicFolder"))
         {
             IConfigurationSession session = RequestTaskHelper.CreateOrganizationFindingSession(base.CurrentOrganizationId, base.ExecutingUserOrganizationId);
             if (this.Organization == null)
             {
                 this.Organization = new OrganizationIdParameter(base.CurrentOrganizationId.OrganizationalUnit);
             }
             ADOrganizationalUnit adorganizationalUnit = (ADOrganizationalUnit)base.GetDataObject <ADOrganizationalUnit>(this.Organization, session, null, new LocalizedString?(Strings.ErrorOrganizationNotFound(this.Organization.ToString())), new LocalizedString?(Strings.ErrorOrganizationNotUnique(this.Organization.ToString())));
             base.RescopeToOrgId(adorganizationalUnit.OrganizationId);
             base.Flags = (RequestFlags.CrossOrg | RequestFlags.Pull);
         }
         else if (base.ParameterSetName.Equals("MigrationLocalPublicFolder"))
         {
             base.OrganizationId = OrganizationId.ForestWideOrgId;
             base.Flags          = (RequestFlags.IntraOrg | RequestFlags.Pull);
             PublicFolderDatabase publicFolderDatabase = base.CheckDatabase <PublicFolderDatabase>(this.SourceDatabase, NewRequest <PublicFolderMigrationRequest> .DatabaseSide.Source, this.SourceDatabase, out empty, out empty2, out adobjectId, out num);
             this.sourceDatabase = publicFolderDatabase.Id;
         }
         if (base.WorkloadType == RequestWorkloadType.None)
         {
             base.WorkloadType = (((base.Flags & RequestFlags.IntraOrg) == RequestFlags.IntraOrg) ? RequestWorkloadType.Local : RequestWorkloadType.Onboarding);
         }
         if (!string.IsNullOrEmpty(this.Name))
         {
             base.ValidateName();
             base.RequestName = this.Name;
         }
         else
         {
             base.RequestName = "PublicFolderMigration";
         }
         ADObjectId          adObjectId          = this.AutoSelectRequestQueueForPFRequest(base.OrganizationId);
         DatabaseIdParameter databaseIdParameter = new DatabaseIdParameter(adObjectId);
         ADObjectId          mdbServerSite       = null;
         MailboxDatabase     mailboxDatabase     = base.CheckDatabase <MailboxDatabase>(databaseIdParameter, NewRequest <PublicFolderMigrationRequest> .DatabaseSide.RequestStorage, this.Organization, out empty, out empty2, out mdbServerSite, out num);
         MailboxTaskHelper.VerifyDatabaseIsWithinScopeForRecipientCmdlets(base.CurrentOrgConfigSession.SessionSettings, mailboxDatabase, new Task.ErrorLoggerDelegate(base.WriteError));
         base.MdbId         = mailboxDatabase.Id;
         base.MdbServerSite = mdbServerSite;
         this.CheckRequestNameAvailability(null, null, false, MRSRequestType.PublicFolderMigration, this.Organization, false);
         if (base.CheckRequestOfTypeExists(MRSRequestType.PublicFolderMailboxMigration))
         {
             base.WriteError(new MultiplePublicFolderMigrationTypesNotAllowedException(), ExchangeErrorCategory.Client, this.Organization);
         }
         this.publicFolderConfiguration = TenantPublicFolderConfigurationCache.Instance.GetValue(base.OrganizationId);
         if (this.publicFolderConfiguration.HeuristicsFlags.HasFlag(HeuristicsFlags.PublicFolderMigrationComplete))
         {
             base.WriteError(new RecipientTaskException(Strings.ErrorPublicFolderMigrationCompletedPreviously), ExchangeErrorCategory.Client, null);
         }
         this.ValidateCSV();
         base.InternalValidate();
     }
     finally
     {
         TaskLogger.LogExit();
     }
 }
예제 #18
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     base.DisasterRecoveryAtom(this.AtomName);
     TaskLogger.LogExit();
 }
예제 #19
0
        protected override void InternalValidate()
        {
            TaskLogger.LogEnter();
            if (!base.Fields.Contains("Mailbox"))
            {
                SharedConfigurationTaskHelper.VerifyIsNotTinyTenant(base.CurrentOrgState, new Task.ErrorLoggerDelegate(base.WriteError));
            }
            if (base.ParameterSetName == "ParameterSetMailboxTask")
            {
                return;
            }
            if (base.Fields.IsModified("LegacyManagedFolder"))
            {
                if (this.LegacyManagedFolder != null)
                {
                    ELCFolder elcfolder = (ELCFolder)base.GetDataObject <ELCFolder>(this.LegacyManagedFolder, base.DataSession, null, new LocalizedString?(Strings.ErrorElcFolderNotFound(this.LegacyManagedFolder.ToString())), new LocalizedString?(Strings.ErrorAmbiguousElcFolderId(this.LegacyManagedFolder.ToString())));
                    this.DataObject.LegacyManagedFolder = elcfolder.Id;
                }
                else
                {
                    this.DataObject.LegacyManagedFolder = null;
                }
            }
            base.InternalValidate();
            if (this.contentSettingsObject.IsChanged(ElcContentSettingsSchema.RetentionAction))
            {
                RetentionActionType[] source = new RetentionActionType[]
                {
                    RetentionActionType.MoveToFolder
                };
                if (source.Any((RetentionActionType x) => x == this.contentSettingsObject.RetentionAction))
                {
                    base.WriteError(new RetentionPolicyTagTaskException(Strings.ErrorRetentionActionNowAllowed), ErrorCategory.InvalidOperation, null);
                }
                if (this.DataObject.Type == ElcFolderType.RecoverableItems && !this.contentSettingsObject.RetentionAction.Equals(RetentionActionType.MoveToArchive))
                {
                    base.WriteError(new ArgumentException(Strings.ErrorDumpsterTagWrongRetentionAction), ErrorCategory.InvalidArgument, this);
                }
                if (this.DataObject.Type != ElcFolderType.All && this.DataObject.Type != ElcFolderType.Personal && this.DataObject.Type != ElcFolderType.RecoverableItems && this.RetentionAction == RetentionActionType.MoveToArchive)
                {
                    base.WriteError(new RetentionPolicyTagTaskException(Strings.ErrorMoveToArchiveAppliedToSystemFolder), ErrorCategory.InvalidArgument, null);
                }
            }
            if (this.contentSettingsObject.IsChanged(ElcContentSettingsSchema.MessageClass) && this.DataObject.Type != ElcFolderType.All && !this.contentSettingsObject.MessageClass.Equals(ElcMessageClass.AllMailboxContent))
            {
                base.WriteError(new RetentionPolicyTagTaskException(Strings.ErrorOnlyDefaultTagAllowCustomizedMessageClass), ErrorCategory.InvalidOperation, this.DataObject);
            }
            string tagName;

            if (this.DataObject.IsChanged(RetentionPolicyTagSchema.RetentionId) && !(base.DataSession as IConfigurationSession).CheckForRetentionTagWithConflictingRetentionId(this.DataObject.RetentionId, this.DataObject.Identity.ToString(), out tagName))
            {
                base.WriteError(new RetentionPolicyTagTaskException(Strings.ErrorRetentionIdConflictsWithRetentionTag(this.DataObject.RetentionId.ToString(), tagName)), ErrorCategory.InvalidOperation, this.DataObject);
            }
            if (this.contentSettingsObject.IsChanged(ElcContentSettingsSchema.RetentionAction) || this.contentSettingsObject.IsChanged(ElcContentSettingsSchema.RetentionEnabled) || this.contentSettingsObject.IsChanged(ElcContentSettingsSchema.MessageClass))
            {
                this.ValidateRetentionPolicy();
            }
            if (base.Fields.IsModified("AddressForJournaling"))
            {
                if (this.AddressForJournaling != null)
                {
                    ADRecipient adrecipient = (ADRecipient)base.GetDataObject <ADRecipient>(this.AddressForJournaling, base.TenantGlobalCatalogSession, null, new LocalizedString?(Strings.ErrorMailboxAddressNotFound(this.AddressForJournaling.ToString())), new LocalizedString?(Strings.ErrorMailboxAddressNotUnique(this.AddressForJournaling.ToString())));
                    if (!this.DataObject.OrganizationId.Equals(OrganizationId.ForestWideOrgId))
                    {
                        RecipientTaskHelper.CheckRecipientInSameOrganizationWithDataObject(this.DataObject, adrecipient, new Task.ErrorLoggerDelegate(base.WriteError));
                    }
                    if (adrecipient.EmailAddresses == null || adrecipient.EmailAddresses.FindPrimary(ProxyAddressPrefix.Smtp) == null)
                    {
                        base.WriteError(new ArgumentException(Strings.SmtpAddressMissingForAutocopy(this.AddressForJournaling.ToString()), "AddressForJournaling"), ErrorCategory.InvalidData, this);
                    }
                    this.contentSettingsObject.AddressForJournaling = adrecipient.Id;
                }
                else
                {
                    this.contentSettingsObject.AddressForJournaling = null;
                }
            }
            ValidationError[] array = this.contentSettingsObject.Validate();
            if (array.Length > 0)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    this.WriteError(new DataValidationException(array[i]), (ErrorCategory)1003, this.contentSettingsObject.Identity, array.Length - 1 == i);
                }
            }
            if (base.HasErrors)
            {
                return;
            }
            TaskLogger.LogExit();
        }
예제 #20
0
 internal override void ProcessRecordWorker(ReplayConfiguration replayConfiguration)
 {
     ExTraceGlobals.CmdletsTracer.TraceDebug <ObjectId, string>((long)this.GetHashCode(), "Suspend-DBC: ProcessRecordWorker: {0}, {1}", this.DataObject.Identity, this.SuspendComment);
     ExTraceGlobals.PFDTracer.TracePfd <int, ObjectId, string>((long)this.GetHashCode(), "PFD CRS {0} Suspend-DBC Initiated for : ProcessRecordWorker: {1}, {2}", 25051, this.DataObject.Identity, this.SuspendComment);
     if (this.EnableReplayLag)
     {
         Database database = this.DataObject.GetDatabase <Database>();
         ReplayRpcClientHelper.RpccEnableReplayLag(base.Server.Name, database.Guid, ActionInitiatorType.Administrator);
         return;
     }
     if (this.SuspendComment != null && this.SuspendComment.Length > 512)
     {
         ExTraceGlobals.CmdletsTracer.TraceDebug((long)this.GetHashCode(), "Suspend-DBC {0}: ProcessRecordWorker: SuspendComment length (length={1}, max length={2}) is too long: {3}", new object[]
         {
             this.DataObject.Identity,
             this.SuspendComment.Length,
             512,
             this.SuspendComment
         });
         base.WriteError(new SuspendCommentTooLongException(this.SuspendComment.Length, 512), ErrorCategory.InvalidOperation, this.Identity);
     }
     if (!base.Stopping)
     {
         if (!base.UseRpc)
         {
             this.m_suspendThread = this.BeginSuspendUsingState(replayConfiguration);
         }
         else
         {
             this.m_suspendThread = base.BeginRpcOperation();
         }
         try
         {
             TimeSpan timeSpan = base.UseRpc ? DatabaseCopyStateAction.TimeoutRpc : SuspendDatabaseCopy.Timeout;
             if (!this.m_suspendThread.Join(timeSpan))
             {
                 ExTraceGlobals.CmdletsTracer.TraceDebug <TimeSpan>((long)this.GetHashCode(), "Suspend-DBC: suspend is being slow: timeout={0}", timeSpan);
                 this.WriteWarning(Strings.SuspendSgcTimeout);
                 if (!base.UseRpc)
                 {
                     this.m_suspendThread.Join();
                 }
                 else
                 {
                     this.m_event.WaitOne();
                 }
             }
         }
         finally
         {
             if (this.m_Exception != null)
             {
                 if (this.m_Terminating)
                 {
                     base.ThrowTerminatingError(this.m_Exception, ErrorCategory.NotSpecified, null);
                 }
                 else
                 {
                     ErrorCategory category;
                     this.TranslateException(ref this.m_Exception, out category);
                     if (this.m_Exception is ReplayServiceSuspendWantedSetException)
                     {
                         base.WriteWarning(this.m_Exception.Message);
                         this.m_fSuccess = true;
                     }
                     else if (this.m_Exception is ReplayServiceSuspendRpcPartialSuccessCatalogFailedException)
                     {
                         base.WriteWarning(this.m_Exception.Message);
                         this.m_fSuccess = true;
                     }
                     else if (!this.m_fFallbackToState)
                     {
                         this.WriteError(this.m_Exception, category, null, false);
                     }
                     else if (!base.Stopping)
                     {
                         ExTraceGlobals.CmdletsTracer.TraceDebug <ObjectId>((long)this.GetHashCode(), "ProcessRecordWorker: There was an RPC connection error, so now falling back to Suspend through the State, for {0}.", this.DataObject.Identity);
                         this.WriteWarning(Strings.SuspendSgcFallbackToState(this.DataObject.Identity.ToString(), this.m_Exception.Message));
                     }
                 }
             }
         }
     }
     if (!this.m_fSuccess && base.Stopping)
     {
         ExTraceGlobals.CmdletsTracer.TraceDebug <ObjectId>((long)this.GetHashCode(), "Suspend was cancelled for {0}", this.DataObject.Identity);
         return;
     }
     if (!base.UseRpc && this.m_Exception == null && this.m_fSuccess)
     {
         replayConfiguration.ReplayState.SuspendMessage = this.SuspendComment;
     }
     else if (base.UseRpc && this.m_fFallbackToState)
     {
         ReplayConfiguration replayConfiguration2 = base.ConstructReplayConfiguration(this.DataObject.GetDatabase <Database>());
         replayConfiguration2.ReplayState.SuspendLockRemote.EnterSuspend();
         replayConfiguration2.ReplayState.SuspendMessage = this.SuspendComment;
         this.m_fSuccess = true;
     }
     if (this.m_fSuccess)
     {
         ExTraceGlobals.CmdletsTracer.TraceDebug <string, ObjectId>((long)this.GetHashCode(), "Suspended ({0}) for {1}", this.SuspendComment, this.DataObject.Identity);
         ExTraceGlobals.PFDTracer.TracePfd <int, string, ObjectId>((long)this.GetHashCode(), "PFD CRS {0} Sucessfully Suspended ({1}) for {2}", 20955, this.SuspendComment, this.DataObject.Identity);
         if (this.m_fFallbackToState)
         {
             ReplayEventLogConstants.Tuple_SuspendMarkedForDatabaseCopy.LogEvent(null, new object[]
             {
                 this.DataObject.Identity
             });
         }
     }
     TaskLogger.LogExit();
 }
 public void CancelAsync(TaskMessage taskMessage, TaskLogger taskLogger, CancellationToken cancellationToken)
 {
 }
예제 #22
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            bool flag = false;
            ADEcpVirtualDirectory adecpVirtualDirectory = WebAppVirtualDirectoryHelper.FindWebAppVirtualDirectoryInSameWebSite <ADEcpVirtualDirectory>(this.DataObject, base.DataSession);

            if (adecpVirtualDirectory != null)
            {
                if (this.DataObject.IsChanged(ExchangeWebAppVirtualDirectorySchema.DefaultDomain))
                {
                    adecpVirtualDirectory.DefaultDomain = this.DataObject.DefaultDomain;
                    flag = true;
                }
                WebAppVirtualDirectoryHelper.CheckTwoWebAppVirtualDirectories(this.DataObject, adecpVirtualDirectory, new Action <string>(base.WriteWarning), Strings.OwaAuthenticationNotMatchEcpWarning, Strings.OwaUrlNotMatchEcpWarning);
            }
            else
            {
                this.WriteWarning(Strings.CreateEcpForOwaWarning);
            }
            if (this.DataObject.IsChanged(ADOwaVirtualDirectorySchema.AnonymousFeaturesEnabled))
            {
                this.UpdateCalendarMetabase(this.DataObject);
            }
            if (this.DataObject.IsChanged(ADOwaVirtualDirectorySchema.IntegratedFeaturesEnabled))
            {
                this.UpdateIntegratedMetabase(this.DataObject);
            }
            if (this.DataObject.IsChanged(ExchangeWebAppVirtualDirectorySchema.LiveIdAuthentication))
            {
                this.UpdateOmaMetabase(this.DataObject);
            }
            base.InternalProcessRecord();
            ADOwaVirtualDirectory dataObject = this.DataObject;
            bool flag2 = ExchangeServiceVDirHelper.IsBackEndVirtualDirectory(this.DataObject);

            if (dataObject.LiveIdAuthentication)
            {
                WebAppVirtualDirectoryHelper.UpdateMetabase(dataObject, dataObject.MetabasePath, true);
            }
            else
            {
                WebAppVirtualDirectoryHelper.UpdateMetabase(dataObject, dataObject.MetabasePath, flag2);
            }
            if (flag)
            {
                WebAppVirtualDirectoryHelper.UpdateMetabase(adecpVirtualDirectory, adecpVirtualDirectory.MetabasePath, true);
            }
            if (flag2)
            {
                ExchangeServiceVDirHelper.EwsAutodiscMWA.OnSetManageWCFEndpoints(this, ExchangeServiceVDirHelper.EwsAutodiscMWA.EndpointProtocol.OwaEws, false, this.DataObject);
            }
            else if (base.Fields.Contains("FormsAuthentication"))
            {
                ExchangeServiceVDirHelper.UpdateFrontEndHttpModule(this.DataObject, this.FormsAuthentication);
            }
            if (base.Fields.Contains("OAuthAuthentication"))
            {
                ExchangeServiceVDirHelper.SetOAuthAuthenticationModule(this.DataObject.OAuthAuthentication, false, this.DataObject);
            }
            if (base.Fields.Contains("AdfsAuthentication"))
            {
                ExchangeServiceVDirHelper.SetAdfsAuthenticationModule(this.DataObject.AdfsAuthentication, false, this.DataObject);
            }
            TaskLogger.LogExit();
        }
예제 #23
0
        protected override IConfigurable PrepareDataObject()
        {
            TaskLogger.LogEnter();
            ADRecipient adrecipient = (ADRecipient)base.PrepareDataObject();

            if (base.IsProvisioningLayerAvailable)
            {
                Fqdn value = (Fqdn)base.UserSpecifiedParameters["DomainController"];
                try
                {
                    base.UserSpecifiedParameters["DomainController"] = this.globalCatalog;
                    ProvisioningLayer.UpdateAffectedIConfigurable(this, RecipientTaskHelper.ConvertRecipientToPresentationObject(adrecipient), false);
                    goto IL_82;
                }
                finally
                {
                    base.UserSpecifiedParameters["DomainController"] = value;
                }
            }
            base.WriteError(new InvalidOperationException(Strings.ErrorNoProvisioningHandlerAvailable), (ErrorCategory)1012, null);
IL_82:
            if (RecipientType.UserMailbox == adrecipient.RecipientType)
            {
                ADUser aduser = (ADUser)adrecipient;
                if (string.IsNullOrEmpty(aduser.ServerLegacyDN))
                {
                    base.WriteError(new InvalidOperationException(Strings.ErrorInvalidObjectMissingCriticalProperty(typeof(Mailbox).Name, adrecipient.Identity.ToString(), MailEnabledRecipientSchema.LegacyExchangeDN.Name)), (ErrorCategory)1009, this.Identity);
                }
                Server server = this.configurationSession.FindServerByLegacyDN(aduser.ServerLegacyDN);
                if (server != null)
                {
                    if (!server.IsExchange2007OrLater)
                    {
                        base.WriteError(new InvalidOperationException(Strings.ErrorCannotUpdateLegacyMailbox(this.Identity.ToString())), (ErrorCategory)1010, this.Identity);
                    }
                    else if (RecipientTaskHelper.IsE15OrLater(server.VersionNumber))
                    {
                        if (adrecipient.ExchangeVersion.IsOlderThan(ExchangeObjectVersion.Exchange2012))
                        {
                            adrecipient.SetExchangeVersion(ExchangeObjectVersion.Exchange2012);
                        }
                    }
                    else if (server.IsE14OrLater)
                    {
                        if (adrecipient.ExchangeVersion.IsOlderThan(ExchangeObjectVersion.Exchange2010))
                        {
                            adrecipient.SetExchangeVersion(ExchangeObjectVersion.Exchange2010);
                        }
                    }
                    else if (adrecipient.ExchangeVersion.IsOlderThan(ExchangeObjectVersion.Exchange2007))
                    {
                        adrecipient.SetExchangeVersion(ExchangeObjectVersion.Exchange2007);
                    }
                }
                SetMailboxBase <MailboxIdParameter, Mailbox> .StampMailboxTypeDetails(adrecipient, true);

                MailboxTaskHelper.StampMailboxRecipientDisplayType(adrecipient);
                if (server != null && server.IsE14OrLater)
                {
                    NetID netID = aduser.NetID;
                    if (netID != null)
                    {
                        aduser.NetID = netID;
                    }
                }
                if (aduser.RoleAssignmentPolicy == null && RecipientTypeDetails.None == (aduser.RecipientTypeDetails & (RecipientTypeDetails.PublicFolder | RecipientTypeDetails.SystemMailbox | RecipientTypeDetails.ArbitrationMailbox | RecipientTypeDetails.DiscoveryMailbox | RecipientTypeDetails.AuditLogMailbox)))
                {
                    RoleAssignmentPolicy roleAssignmentPolicy = RecipientTaskHelper.FindDefaultRoleAssignmentPolicy(RecipientTaskHelper.GetTenantLocalConfigSession(base.CurrentOrganizationId, base.ExecutingUserOrganizationId, base.RootOrgContainerId), new Task.ErrorLoggerDelegate(base.WriteError), Strings.ErrorDefaultRoleAssignmentPolicyNotUnique, Strings.ErrorDefaultRoleAssignmentPolicyNotFound);
                    if (roleAssignmentPolicy != null)
                    {
                        aduser.RoleAssignmentPolicy = (ADObjectId)roleAssignmentPolicy.Identity;
                    }
                }
            }
            TaskLogger.LogExit();
            return(adrecipient);
        }
예제 #24
0
        protected override void InternalValidate()
        {
            TaskLogger.LogEnter();
            base.InternalValidate();
            if (base.HasErrors)
            {
                return;
            }
            if (base.Name.Length > 64)
            {
                base.WriteError(new InvalidAutoAttendantException(Strings.AANameTooLong), ErrorCategory.NotSpecified, null);
            }
            LocalizedException ex = ValidationHelper.ValidateDialedNumbers(this.DataObject.PilotIdentifierList, this.dialPlan);

            if (ex != null)
            {
                base.WriteError(ex, ErrorCategory.NotSpecified, this.DataObject);
            }
            foreach (string text in this.DataObject.PilotIdentifierList)
            {
                UMAutoAttendant umautoAttendant = UMAutoAttendant.FindAutoAttendantByPilotIdentifierAndDialPlan(text, this.DataObject.UMDialPlan);
                if (umautoAttendant != null)
                {
                    base.WriteError(new AutoAttendantExistsException(text, this.DataObject.UMDialPlan.Name), ErrorCategory.NotSpecified, null);
                }
            }
            if (this.dialPlan.URIType == UMUriType.SipName && this.DataObject.PilotIdentifierList != null)
            {
                Utility.CheckForPilotIdentifierDuplicates(this.DataObject, this.ConfigurationSession, this.DataObject.PilotIdentifierList, new Task.TaskErrorLoggingDelegate(base.WriteError));
            }
            if (this.DataObject.DTMFFallbackAutoAttendant != null)
            {
                ValidationHelper.ValidateDtmfFallbackAA(this.DataObject, this.dialPlan, this.fallbackAA);
            }
            StatusEnum status = StatusEnum.Disabled;

            if (base.Fields["Status"] != null)
            {
                status = (StatusEnum)base.Fields["Status"];
            }
            this.DataObject.SetStatus(status);
            if (base.Fields["SpeechEnabled"] != null && this.SpeechEnabled)
            {
                this.DataObject.SpeechEnabled = true;
            }
            else
            {
                this.DataObject.SpeechEnabled = false;
            }
            this.DataObject.NameLookupEnabled        = true;
            this.DataObject.OperatorExtension        = null;
            this.DataObject.InfoAnnouncementEnabled  = InfoAnnouncementEnabledEnum.False;
            this.DataObject.InfoAnnouncementFilename = null;
            this.DataObject.CallSomeoneEnabled       = true;
            this.DataObject.SendVoiceMsgEnabled      = false;
            if (this.dialPlan.SubscriberType == UMSubscriberType.Consumer)
            {
                this.DataObject.ContactScope             = DialScopeEnum.GlobalAddressList;
                this.DataObject.AllowDialPlanSubscribers = false;
                this.DataObject.AllowExtensions          = false;
            }
            else
            {
                this.DataObject.ContactScope             = DialScopeEnum.DialPlan;
                this.DataObject.AllowDialPlanSubscribers = true;
                this.DataObject.AllowExtensions          = true;
            }
            this.DataObject.BusinessHoursWelcomeGreetingEnabled       = false;
            this.DataObject.BusinessHoursWelcomeGreetingFilename      = null;
            this.DataObject.BusinessHoursMainMenuCustomPromptEnabled  = false;
            this.DataObject.BusinessHoursMainMenuCustomPromptFilename = null;
            this.DataObject.BusinessHoursTransferToOperatorEnabled    = false;
            this.DataObject.AfterHoursWelcomeGreetingEnabled          = false;
            this.DataObject.AfterHoursWelcomeGreetingFilename         = null;
            this.DataObject.AfterHoursMainMenuCustomPromptEnabled     = false;
            this.DataObject.AfterHoursMainMenuCustomPromptFilename    = null;
            this.DataObject.AfterHoursTransferToOperatorEnabled       = false;
            this.DataObject.TimeZone = ExTimeZone.CurrentTimeZone.Id;
            this.DataObject.Language = UMLanguage.DefaultLanguage;
            TaskLogger.LogExit();
        }
예제 #25
0
        protected override IConfigurable PrepareDataObject()
        {
            TaskLogger.LogEnter();
            ExchangeOrganizationalUnit exchangeOrganizationalUnit = null;

            ((IConfigurationSession)base.DataSession).SessionSettings.IsSharedConfigChecked = true;
            this.ConfigurationSession.SessionSettings.IsSharedConfigChecked = true;
            this.DataObject = (ExchangeRoleAssignment)base.PrepareDataObject();
            if (base.HasErrors)
            {
                return(null);
            }
            if (!this.IgnoreDehydratedFlag)
            {
                SharedConfigurationTaskHelper.VerifyIsNotTinyTenant(base.CurrentOrgState, new Task.ErrorLoggerDelegate(base.WriteError));
            }
            this.role = (ExchangeRole)base.GetDataObject <ExchangeRole>(this.Role, base.DataSession, null, new LocalizedString?(Strings.ErrorRoleNotFound(this.Role.ToString())), new LocalizedString?(Strings.ErrorRoleNotUnique(this.Role.ToString())));
            RoleHelper.VerifyNoScopeForUnScopedRole(base.Fields, this.role, new Task.TaskErrorLoggingDelegate(base.WriteError));
            if (this.role != null && this.role.IsDeprecated)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorCannotCreateRoleAssignmentToADeprecatedRole(this.role.ToString())), ErrorCategory.InvalidOperation, null);
            }
            RoleAssigneeType roleAssigneeType;
            ADObject         adobject;

            if (this.Policy != null)
            {
                RoleAssignmentPolicy roleAssignmentPolicy = (RoleAssignmentPolicy)base.GetDataObject <RoleAssignmentPolicy>(this.Policy, RecipientTaskHelper.GetTenantLocalConfigSession(base.CurrentOrganizationId, base.ExecutingUserOrganizationId, base.RootOrgContainerId), null, new LocalizedString?(Strings.ErrorRBACPolicyNotFound(this.Policy.ToString())), new LocalizedString?(Strings.ErrorRBACPolicyNotUnique(this.Policy.ToString())));
                if (!this.role.IsEndUserRole)
                {
                    base.WriteError(new InvalidOperationException(Strings.ErrorNonEndUserRoleCannoBeAssignedToPolicy(this.role.Name)), ErrorCategory.InvalidOperation, roleAssignmentPolicy.Id);
                }
                OrganizationId organizationId = OrganizationId.ForestWideOrgId;
                if (this.ConfigurationSession is ITenantConfigurationSession)
                {
                    organizationId = TaskHelper.ResolveOrganizationId(this.role.Id, ExchangeRole.RdnContainer, (ITenantConfigurationSession)this.ConfigurationSession);
                }
                ADObjectId adobjectId;
                if (OrganizationId.ForestWideOrgId.Equals(organizationId))
                {
                    adobjectId = this.ConfigurationSession.GetOrgContainerId();
                }
                else
                {
                    adobjectId = organizationId.ConfigurationUnit;
                }
                if (!roleAssignmentPolicy.Id.IsDescendantOf(adobjectId))
                {
                    base.WriteError(new InvalidOperationException(Strings.ErrorPolicyOutOfRoleScope(roleAssignmentPolicy.Id.ToString(), adobjectId.Name)), ErrorCategory.InvalidOperation, null);
                }
                roleAssigneeType = RoleAssigneeType.RoleAssignmentPolicy;
                adobject         = roleAssignmentPolicy;
            }
            else
            {
                ADRecipient adrecipient = null;
                if (this.User != null)
                {
                    adrecipient = (ADUser)base.GetDataObject <ADUser>(this.User, base.TenantGlobalCatalogSession, null, new LocalizedString?(Strings.ErrorAssigneeUserNotFound(this.User.ToString())), new LocalizedString?(Strings.ErrorAssigneeUserNotUnique(this.User.ToString())));
                }
                else if (this.SecurityGroup != null)
                {
                    adrecipient = (ADGroup)base.GetDataObject <ADGroup>(this.SecurityGroup, base.TenantGlobalCatalogSession, null, new LocalizedString?(Strings.ErrorAssigneeSecurityGroupNotFound(this.SecurityGroup.ToString())), new LocalizedString?(Strings.ErrorAssigneeSecurityGroupNotUnique(this.SecurityGroup.ToString())));
                }
                else if (this.Computer != null)
                {
                    adrecipient = (ADComputerRecipient)base.GetDataObject <ADComputerRecipient>(this.Computer, base.TenantGlobalCatalogSession, null, new LocalizedString?(Strings.ErrorAssigneeComputerNotFound(this.Computer.ToString())), new LocalizedString?(Strings.ErrorAssigneeComputerNotUnique(this.Computer.ToString())));
                }
                RoleHelper.ValidateRoleAssignmentUser(adrecipient, new Task.TaskErrorLoggingDelegate(base.WriteError), false);
                roleAssigneeType = ExchangeRoleAssignment.RoleAssigneeTypeFromADRecipient(adrecipient);
                adobject         = adrecipient;
            }
            ((IDirectorySession)base.DataSession).LinkResolutionServer = adobject.OriginatingServer;
            RoleHelper.PrepareNewRoleAssignmentWithUniqueNameAndDefaultScopes(this.Name, this.DataObject, this.role, adobject.Id, adobject.OrganizationId, roleAssigneeType, this.Delegating.IsPresent ? RoleAssignmentDelegationType.Delegating : RoleAssignmentDelegationType.Regular, this.ConfigurationSession, new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), new Task.TaskErrorLoggingDelegate(base.WriteError));
            if (this.role.IsUnscopedTopLevel && this.UnScopedTopLevel)
            {
                this.skipHRoleCheck = true;
                if (this.Delegating)
                {
                    this.DataObject.RoleAssignmentDelegationType = RoleAssignmentDelegationType.DelegatingOrgWide;
                }
            }
            else
            {
                RoleHelper.AnalyzeAndStampCustomizedWriteScopes(this, this.DataObject, this.role, this.ConfigurationSession, new DataAccessHelper.GetDataObjectDelegate(base.GetDataObject <ExchangeOrganizationalUnit>), new DataAccessHelper.GetDataObjectDelegate(base.GetDataObject <ManagementScope>), ref this.skipHRoleCheck, ref exchangeOrganizationalUnit, ref this.customRecipientScope, ref this.customConfigScope);
            }
            TaskLogger.LogExit();
            return(this.DataObject);
        }
 internal static void ReloadProvisioningParameters()
 {
     if (AcceptedDomainUtility.lastReadTime + AcceptedDomainUtility.reloadTimeSpan > DateTime.UtcNow)
     {
         return;
     }
     lock (AcceptedDomainUtility.LockObject)
     {
         if (!(AcceptedDomainUtility.lastReadTime + AcceptedDomainUtility.reloadTimeSpan > DateTime.UtcNow))
         {
             ServiceEndpoint serviceEndpoint  = null;
             ServiceEndpoint serviceEndpoint2 = null;
             ServiceEndpoint serviceEndpoint3 = null;
             ServiceEndpoint serviceEndpoint4 = null;
             ServiceEndpoint serviceEndpoint5 = null;
             try
             {
                 ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.FullyConsistent, ADSessionSettings.FromRootOrgScopeSet(), 138, "ReloadProvisioningParameters", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\MessageSecurity\\AcceptedDomain\\AcceptedDomainUtility.cs");
                 ServiceEndpointContainer      endpointContainer            = topologyConfigurationSession.GetEndpointContainer();
                 serviceEndpoint  = endpointContainer.GetEndpoint(ServiceEndpointId.CoexistenceParentDomain);
                 serviceEndpoint2 = endpointContainer.GetEndpoint(ServiceEndpointId.CoexistenceDnsEndpoint);
                 serviceEndpoint3 = endpointContainer.GetEndpoint(ServiceEndpointId.CoexistenceMailDomainFfo15);
                 serviceEndpoint4 = endpointContainer.GetEndpoint(ServiceEndpointId.CoexistenceDnsCname);
                 serviceEndpoint5 = endpointContainer.GetEndpoint(ServiceEndpointId.CoexistenceDnsText);
             }
             catch (EndpointContainerNotFoundException)
             {
                 TaskLogger.Trace("EndpointContainer was not found.", new object[0]);
             }
             catch (ServiceEndpointNotFoundException)
             {
                 TaskLogger.Trace("At least one Coexistence Endpoint was not found.", new object[0]);
             }
             if (serviceEndpoint2 != null)
             {
                 AcceptedDomainUtility.dnsRegistrationEndpoint = serviceEndpoint2.Uri;
                 if (string.IsNullOrEmpty(serviceEndpoint2.CertificateSubject))
                 {
                     throw new Exception("Unable to find the certificate.");
                 }
                 AcceptedDomainUtility.dnsRegistrationCertificateSubject = serviceEndpoint2.CertificateSubject;
                 TaskLogger.Trace("Dns Registration Endpoint set to '{0}'", new object[]
                 {
                     AcceptedDomainUtility.dnsRegistrationEndpoint.ToString()
                 });
                 TaskLogger.Trace("Dns Registration Subject set to '{0}'", new object[]
                 {
                     AcceptedDomainUtility.dnsRegistrationCertificateSubject
                 });
             }
             AcceptedDomainUtility.coexistenceMailDomainFfo15 = ((serviceEndpoint3 != null) ? serviceEndpoint3.Uri.Host : string.Empty);
             TaskLogger.Trace("Coexistence Mail Domain with FFO 15 set to '{0}'", new object[]
             {
                 AcceptedDomainUtility.coexistenceMailDomainFfo15
             });
             AcceptedDomainUtility.coexistenceDnsCnameValue = ((serviceEndpoint4 != null) ? serviceEndpoint4.Uri.Host : "autodiscover.outlook.com");
             TaskLogger.Trace("Coexistence DNS CNAME value set to '{0}'", new object[]
             {
                 AcceptedDomainUtility.coexistenceDnsCnameValue
             });
             AcceptedDomainUtility.coexistenceDnsTextValue = string.Format("v=spf1 include:{0} -all", (serviceEndpoint5 != null) ? serviceEndpoint5.Uri.Host : "outlook.com");
             TaskLogger.Trace("Coexistence DNS TEXT value set to '{0}'", new object[]
             {
                 AcceptedDomainUtility.coexistenceDnsTextValue
             });
             AcceptedDomainUtility.lastReadTime = DateTime.UtcNow;
             string text = (serviceEndpoint != null) ? serviceEndpoint.Uri.Host : string.Empty;
             if (text != null && !text.StartsWith("."))
             {
                 text = "." + text;
             }
             AcceptedDomainUtility.coexistenceParentDomain = ((text != null) ? text : string.Empty);
             TaskLogger.Trace("Coexistence Parent Domain set to '{0}'", new object[]
             {
                 AcceptedDomainUtility.coexistenceParentDomain
             });
         }
     }
 }
예제 #27
0
        private bool InternalExecuteScript(string script, bool handleError, int subSteps, LocalizedString statusDescription)
        {
            bool     result   = false;
            WorkUnit workUnit = new WorkUnit();
            bool     newSubProgressReceived = false;
            int      completedSubSteps      = 0;

            try
            {
                script.TrimEnd(new char[]
                {
                    '\n'
                });
                string script2 = script.Replace("\n", "\r\n");
                if (handleError)
                {
                    base.WriteVerbose(Strings.ExecutingScriptNonFatal(script2));
                }
                else
                {
                    base.WriteVerbose(Strings.ExecutingScript(script2));
                }
                script = string.Format("$error.Clear(); {0}", script);
                MonadCommand monadCommand = new MonadCommand(script, this.monadConnection);
                monadCommand.CommandType     = CommandType.Text;
                monadCommand.ProgressReport += delegate(object sender, ProgressReportEventArgs e)
                {
                    if (subSteps == 0)
                    {
                        return;
                    }
                    completedSubSteps      = subSteps * e.ProgressRecord.PercentComplete / 100;
                    newSubProgressReceived = true;
                };
                bool flag = false;
                try
                {
                    TaskLogger.IncreaseIndentation();
                    TaskLogger.LogErrorAsWarning = handleError;
                    MonadAsyncResult monadAsyncResult = monadCommand.BeginExecute(new WorkUnit[]
                    {
                        workUnit
                    });
                    while (!flag)
                    {
                        flag = monadAsyncResult.AsyncWaitHandle.WaitOne(200, false);
                        if (newSubProgressReceived)
                        {
                            base.WriteProgress(this.Description, statusDescription, (this.completedSteps + completedSubSteps) * 100 / this.totalSteps);
                            newSubProgressReceived = false;
                        }
                        if (base.Stopping)
                        {
                            break;
                        }
                    }
                    if (base.Stopping)
                    {
                        monadCommand.Cancel();
                    }
                    else
                    {
                        monadCommand.EndExecute(monadAsyncResult);
                    }
                }
                catch (CommandExecutionException ex)
                {
                    if (ex.InnerException != null)
                    {
                        throw new ScriptExecutionException(Strings.ErrorCommandExecutionException(script, ex.InnerException.ToString()), ex.InnerException);
                    }
                    throw;
                }
                finally
                {
                    TaskLogger.DecreaseIndentation();
                }
                this.completedSteps += subSteps;
                result = true;
            }
            catch (CmdletInvocationException ex2)
            {
                result = false;
                if (!handleError)
                {
                    throw;
                }
                base.WriteVerbose(Strings.IgnoringException(ex2.ToString()));
                base.WriteVerbose(Strings.WillContinueProcessing);
            }
            if (workUnit.Errors.Count > 0)
            {
                result = false;
                int count = workUnit.Errors.Count;
                base.WriteVerbose(Strings.ErrorDuringTaskExecution(count));
                for (int i = 0; i < count; i++)
                {
                    ErrorRecord errorRecord = workUnit.Errors[i];
                    base.WriteVerbose(Strings.ErrorRecordReport(errorRecord.ToString(), i));
                    if (!handleError)
                    {
                        base.WriteVerbose(Strings.ErrorRecordReport(errorRecord.Exception.ToString(), i));
                        ScriptExecutionException exception = new ScriptExecutionException(Strings.ErrorCommandExecutionException(script, errorRecord.Exception.ToString()), errorRecord.Exception);
                        this.WriteError(exception, errorRecord.CategoryInfo.Category, errorRecord.TargetObject, false);
                    }
                }
                if (handleError)
                {
                    base.WriteVerbose(Strings.WillIgnoreNoncriticalErrors);
                    base.WriteVerbose(Strings.WillContinueProcessing);
                }
            }
            return(result);
        }
예제 #28
0
        public static async Task CreateContainer(TaskLogger taskLogger, MyAppParameters myAppParameters)
        {
            // Get credentials
            var credentials = SdkContext.AzureCredentialsFactory
                              .FromServicePrincipal(myAppParameters.AzureSubscriptionClientId,
                                                    myAppParameters.AzureSubscriptionClientSecret,
                                                    myAppParameters.TenantId,
                                                    AzureEnvironment.AzureGlobalCloud);

            // Authenticate with Azure
            var azure = Azure.Configure()
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            var message = $"Authenticated with azure";
            await taskLogger.Log(message).ConfigureAwait(false);

            message = $"Getting resource group '{myAppParameters.ResourceGroupName}' details.";
            await taskLogger.Log(message).ConfigureAwait(false);

            // Check resource group exist or not.
            IResourceGroup resourceGroup = azure.ResourceGroups.GetByName(myAppParameters.ResourceGroupName);

            if (resourceGroup == null)
            {
                message = $"Resource group '{myAppParameters.ResourceGroupName}' not found.";
                throw new Exception(message);
            }

            // Check container group exist or not.
            IContainerGroup containerGroup = azure.ContainerGroups.GetByResourceGroup(myAppParameters.ResourceGroupName, myAppParameters.AgentName);

            if (containerGroup != null)
            {
                message = $"Already container group with name '{myAppParameters.AgentName}' exist in resource group '{myAppParameters.ResourceGroupName}'.";
                throw new Exception(message);
            }

            message = $"Creating container group '{myAppParameters.AgentName}' in resource group '{myAppParameters.ResourceGroupName}' with container image 'microsoft/vsts-agent:latest' ...";
            await taskLogger.Log(message).ConfigureAwait(false);

            message = $"This will take more than 15 mins... You can check container creating logs in Azure portal.";
            await taskLogger.Log(message).ConfigureAwait(false);

            var azureRegion = resourceGroup.Region;
            var env         = new Dictionary <string, string>
            {
                { "VSTS_ACCOUNT", myAppParameters.PipelineAccountName },
                { "VSTS_TOKEN", myAppParameters.PATToken },       // This PAT token used to configure the agent. This PAT token should have permission to configure the agent else container moves to running state without configuring the agent
                { "VSTS_AGENT", myAppParameters.AgentName },
                { "VSTS_POOL", myAppParameters.AgentPoolName }
            };

            // Create container group with image.
            await CreateContainerWithAsync(taskLogger, azure, resourceGroup.RegionName, myAppParameters, env);

            // You can use below function to CreateContainerGroup With Polling
            // await CreateContainerGroupWithPolling(taskLogger, azure, resourceGroup.RegionName, myAppParameters, env);

            message = $"Azure pipeline agent container running..";
            await taskLogger.Log(message).ConfigureAwait(false);
        }
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     base.Install();
     TaskLogger.LogExit();
 }
예제 #30
0
 internal void InstallPackageFile(string packagePath)
 {
     TaskLogger.LogEnter();
     try
     {
         Guid productCode = MsiUtility.GetProductCode(this.PackagePath);
         base.SetLogging();
         MsiUtility.PushExternalUI(base.UIHandler, (InstallLogMode)10115);
         try
         {
             base.WriteVerbose(Strings.InstallingPackage(packagePath));
             List <MsiNativeMethods.PatchSequenceInfo> list = new List <MsiNativeMethods.PatchSequenceInfo>();
             uint num;
             if (this.UpdatesDir != null)
             {
                 try
                 {
                     string[] files = Directory.GetFiles(this.UpdatesDir.PathName, "*.msp");
                     foreach (string patchData in files)
                     {
                         MsiNativeMethods.PatchSequenceInfo item = new MsiNativeMethods.PatchSequenceInfo
                         {
                             patchData     = patchData,
                             patchDataType = PatchDataType.PatchFile,
                             order         = -1,
                             status        = 0U
                         };
                         list.Add(item);
                         base.WriteVerbose(Strings.PatchFileFound(item.patchData));
                     }
                 }
                 catch (DirectoryNotFoundException)
                 {
                     base.WriteVerbose(Strings.UpdatesDirectoryNotFound(this.UpdatesDir.PathName));
                 }
                 catch (IOException exception)
                 {
                     base.WriteError(exception, ErrorCategory.InvalidOperation, null);
                 }
                 if (list.Count > 0)
                 {
                     MsiNativeMethods.PatchSequenceInfo[] array2 = list.ToArray();
                     num = MsiNativeMethods.DetermineApplicablePatches(this.PackagePath, array2.Length, array2);
                     if (num != 0U)
                     {
                         base.WriteError(new TaskException(Strings.FailedToSortPatches(num)), ErrorCategory.InvalidOperation, null);
                     }
                     else
                     {
                         base.WriteVerbose(Strings.SortedAvailablePatches);
                         List <MsiNativeMethods.PatchSequenceInfo> list2 = new List <MsiNativeMethods.PatchSequenceInfo>();
                         foreach (MsiNativeMethods.PatchSequenceInfo item2 in array2)
                         {
                             base.WriteVerbose(Strings.PrintPatchOrderInfo(item2.patchData, item2.order, item2.status));
                             if (item2.order >= 0)
                             {
                                 list2.Add(item2);
                             }
                         }
                         if (list2.Count > 0)
                         {
                             list2.Sort(new Comparison <MsiNativeMethods.PatchSequenceInfo>(MsiNativeMethods.ComparePatchSequence));
                             StringBuilder stringBuilder = new StringBuilder();
                             foreach (MsiNativeMethods.PatchSequenceInfo patchSequenceInfo in list2)
                             {
                                 base.WriteVerbose(Strings.ValidPatch(patchSequenceInfo.patchData, patchSequenceInfo.order));
                                 stringBuilder.Append(patchSequenceInfo.patchData);
                                 stringBuilder.Append(";");
                             }
                             base.WriteVerbose(Strings.PatchAttributeValue(stringBuilder.ToString()));
                             base.PropertyValues = string.Format("PATCH=\"{0}\" {1}", stringBuilder.ToString(), base.PropertyValues);
                         }
                     }
                 }
             }
             else
             {
                 base.WriteVerbose(Strings.NoUpdatesDirectorySpecified);
             }
             if (this.newProduct)
             {
                 base.WriteVerbose(Strings.NewProductInstallation(packagePath, base.PropertyValues));
                 num = MsiNativeMethods.InstallProduct(packagePath, base.PropertyValues);
             }
             else
             {
                 string productCodeString = productCode.ToString("B").ToUpper(CultureInfo.InvariantCulture);
                 base.WriteVerbose(Strings.ExistingProductConfiguration(productCodeString, base.PropertyValues));
                 num = MsiNativeMethods.ConfigureProduct(productCodeString, InstallLevel.Default, InstallState.Default, base.PropertyValues);
             }
             if (num != 0U)
             {
                 Win32Exception ex = new Win32Exception((int)num);
                 if (num == 3010U)
                 {
                     throw new TaskException(Strings.MsiRebootRequiredToContinue(packagePath), ex);
                 }
                 if (string.IsNullOrEmpty(base.LastMsiError))
                 {
                     base.WriteError(new TaskException(Strings.MsiInstallFailed(packagePath, ex.Message, (int)num), ex), ErrorCategory.InvalidOperation, null);
                 }
                 else
                 {
                     base.WriteError(new TaskException(Strings.MsiInstallFailedDetailed(packagePath, ex.Message, (int)num, base.LastMsiError), ex), ErrorCategory.InvalidOperation, null);
                 }
             }
         }
         finally
         {
             MsiUtility.PopExternalUI();
         }
     }
     catch (ArgumentOutOfRangeException exception2)
     {
         base.WriteError(exception2, ErrorCategory.InvalidArgument, null);
     }
     catch (TaskException exception3)
     {
         base.WriteError(exception3, ErrorCategory.InvalidOperation, null);
     }
     TaskLogger.LogExit();
 }
예제 #31
0
 protected override void InternalBeginProcessing()
 {
     TaskLogger.LogEnter();
     base.InternalBeginProcessing();
     try
     {
         this.newProduct = !MsiUtility.IsInstalled(this.PackagePath);
     }
     catch (ArgumentNullException exception)
     {
         base.WriteError(exception, ErrorCategory.InvalidArgument, null);
     }
     catch (ArgumentOutOfRangeException exception2)
     {
         base.WriteError(exception2, ErrorCategory.InvalidArgument, null);
     }
     catch (TaskException exception3)
     {
         base.WriteError(exception3, ErrorCategory.InvalidOperation, null);
     }
     if (!this.NoActionIfInstalled || this.newProduct)
     {
         if (!this.Reinstall)
         {
             if (this.newProduct && this.TargetDirectory != null && this.TargetDirectory.ToString() != string.Empty)
             {
                 base.PropertyValues = string.Format("{0} TARGETDIR=\"{1}\"", base.PropertyValues, this.TargetDirectory);
             }
             if (base.Features != null && base.Features.Length != 0)
             {
                 List <string> list = new List <string>(base.Features);
                 bool          flag = string.Equals("ExchangeServer.MSI", Path.GetFileName(this.PackagePath), StringComparison.OrdinalIgnoreCase);
                 if (flag)
                 {
                     bool flag2 = false;
                     bool flag3 = false;
                     foreach (string b in list)
                     {
                         if (string.Equals("Gateway", b, StringComparison.OrdinalIgnoreCase))
                         {
                             flag2 = true;
                         }
                         else if (string.Equals("AdminTools", b, StringComparison.OrdinalIgnoreCase))
                         {
                             flag3 = true;
                         }
                     }
                     if (flag2 && !flag3)
                     {
                         base.PropertyValues = string.Format("{0} REMOVE={1}", base.PropertyValues, "AdminToolsNonGateway");
                     }
                     if (!flag2 && flag3)
                     {
                         list.Add("AdminToolsNonGateway");
                     }
                 }
                 base.PropertyValues = string.Format("{0} ADDLOCAL={1}", base.PropertyValues, string.Join(",", list.ToArray()));
             }
         }
         else
         {
             base.PropertyValues = string.Format("{0} REINSTALL=ALL REINSTALLMODE={1}", base.PropertyValues, this.ReinstallMode);
         }
         if (!base.Fields.IsChanged("LogFile"))
         {
             base.LogFile = Path.Combine(ConfigurationContext.Setup.SetupLoggingPath, Path.ChangeExtension(Path.GetFileName(this.PackagePath), ".msilog"));
         }
         string fullPath = Path.GetFullPath(this.PackagePath);
         base.WriteVerbose(Strings.MsiFullPackagePath(this.PackagePath, fullPath));
         this.PackagePath = fullPath;
     }
     else
     {
         base.WriteVerbose(Strings.MsiPackageAlreadyInstalled(this.PackagePath));
     }
     TaskLogger.LogExit();
 }
예제 #32
0
        protected override void InternalValidate()
        {
            TaskLogger.LogEnter();
            base.InternalValidate();
            if (base.HasErrors)
            {
                return;
            }
            TDataObject dataObject = this.DataObject;

            if (dataObject.ExchangeVersion.IsOlderThan(PopImapAdConfiguration.MinimumSupportedExchangeObjectVersion))
            {
                TDataObject dataObject2 = this.DataObject;
                string      identity    = dataObject2.Identity.ToString();
                TDataObject dataObject3 = this.DataObject;
                base.WriteError(new TaskException(Strings.ErrorSetOlderVirtualDirectory(identity, dataObject3.ExchangeVersion.ToString(), PopImapAdConfiguration.MinimumSupportedExchangeObjectVersion.ToString())), ErrorCategory.InvalidArgument, null);
            }
            this.ValidateSetServerRoleSpecificParameters();
            HashSet <int> hashSet     = new HashSet <int>();
            TDataObject   dataObject4 = this.DataObject;

            foreach (IPBinding ipbinding in dataObject4.UnencryptedOrTLSBindings)
            {
                hashSet.Add(ipbinding.Port);
            }
            HashSet <int> hashSet2    = new HashSet <int>();
            TDataObject   dataObject5 = this.DataObject;

            foreach (IPBinding ipbinding2 in dataObject5.SSLBindings)
            {
                hashSet2.Add(ipbinding2.Port);
            }
            object[]    customAttributes = base.GetType().GetCustomAttributes(typeof(CmdletAttribute), false);
            string      noun             = (customAttributes.Length > 0) ? ((CmdletAttribute)customAttributes[0]).NounName : string.Empty;
            TDataObject dataObject6      = this.DataObject;

            foreach (ProtocolConnectionSettings protocolConnectionSettings in dataObject6.InternalConnectionSettings)
            {
                if (((protocolConnectionSettings.EncryptionType == null || protocolConnectionSettings.EncryptionType == EncryptionType.TLS) && !hashSet.Contains(protocolConnectionSettings.Port)) || (protocolConnectionSettings.EncryptionType == EncryptionType.SSL && !hashSet2.Contains(protocolConnectionSettings.Port)))
                {
                    string      name        = PopImapAdConfigurationSchema.InternalConnectionSettings.Name;
                    TDataObject dataObject7 = this.DataObject;
                    this.WriteWarning(Strings.PopImapSettingsPortMismatch(name, dataObject7.ProtocolName, noun));
                    break;
                }
            }
            TDataObject dataObject8 = this.DataObject;

            foreach (ProtocolConnectionSettings protocolConnectionSettings2 in dataObject8.ExternalConnectionSettings)
            {
                if (((protocolConnectionSettings2.EncryptionType == null || protocolConnectionSettings2.EncryptionType == EncryptionType.TLS) && !hashSet.Contains(protocolConnectionSettings2.Port)) || (protocolConnectionSettings2.EncryptionType == EncryptionType.SSL && !hashSet2.Contains(protocolConnectionSettings2.Port)))
                {
                    string      name2       = PopImapAdConfigurationSchema.ExternalConnectionSettings.Name;
                    TDataObject dataObject9 = this.DataObject;
                    this.WriteWarning(Strings.PopImapSettingsPortMismatch(name2, dataObject9.ProtocolName, noun));
                    break;
                }
            }
            if (this.DataObject.propertyBag.Changed)
            {
                TDataObject dataObject10 = this.DataObject;
                string      protocol     = dataObject10.ProtocolName;
                TDataObject dataObject11 = this.DataObject;
                this.WriteWarning(Strings.ChangesTakeEffectAfterRestartingPopImapService(protocol, dataObject11.ProtocolName, this.ServerObject.Name));
            }
            TaskLogger.LogExit();
        }