private void LogRemoveMailboxDetails(ADUser recipient)
        {
            Guid uniqueId = base.CurrentTaskContext.UniqueId;

            CmdletLogger.SafeAppendGenericInfo(uniqueId, "ExchangeGuid", recipient.ExchangeGuid.ToString());
            CmdletLogger.SafeAppendGenericInfo(uniqueId, "HomeMBD", (recipient.Database == null) ? string.Empty : recipient.Database.ToString());
        }
Exemple #2
0
        // Token: 0x06001673 RID: 5747 RVA: 0x00054EB4 File Offset: 0x000530B4
        private void MarkDcDownIfNecessary(GenericEventArg <TaskErrorEventArg> e)
        {
            if (e.Data.ExceptionHandled)
            {
                return;
            }
            ADDriverContext  threadADContext  = ADSessionSettings.GetThreadADContext();
            ADServerSettings adserverSettings = (threadADContext != null) ? threadADContext.ServerSettings : null;

            if (this.context == null || adserverSettings == null)
            {
                return;
            }
            string text = null;

            for (Exception ex = e.Data.Exception; ex != null; ex = ex.InnerException)
            {
                if (ex is SuitabilityDirectoryException)
                {
                    text = ((SuitabilityDirectoryException)ex).Fqdn;
                    break;
                }
                if (ex is ServerInMMException)
                {
                    text = ((ServerInMMException)ex).Fqdn;
                    break;
                }
                if (ex is ADServerSettingsChangedException)
                {
                    ADServerSettings serverSettings = ((ADServerSettingsChangedException)ex).ServerSettings;
                    this.PersistNewServerSettings(serverSettings);
                    break;
                }
                if (ex == ex.InnerException)
                {
                    break;
                }
            }
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }
            Fqdn fqdn;

            if (Fqdn.TryParse(text, out fqdn))
            {
                try
                {
                    adserverSettings.MarkDcDown(fqdn);
                    CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "MarkDcDown", fqdn);
                    return;
                }
                catch (NotSupportedException)
                {
                    CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "MarkDcDown-NotSupportedException", fqdn);
                    return;
                }
            }
            CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "MarkDcDown-InvalidFqdn", fqdn);
        }
Exemple #3
0
        protected void EnforceDelay()
        {
            if (this.context.ErrorInfo.TerminatePipeline)
            {
                return;
            }
            IPowerShellBudget psbudget = this.PSBudget;

            if (psbudget != null)
            {
                T t = (default(T) == null) ? Activator.CreateInstance <T>() : default(T);
                DelayEnforcementResults delayEnforcementResults = t.EnforceDelay(this, ThrottlingModule <T> .costTypesInEnforceDelay, ThrottlingModule <T> .CmdletMaxPreferredDelay);
                LocalizedString         localizedString         = this.GenerateDelayInfoLogString(this.PSBudget, delayEnforcementResults);
                if (!string.IsNullOrEmpty(localizedString))
                {
                    string          text           = string.Format("; PolicyDN: {0}; Snapshot: {1}", psbudget.ThrottlingPolicy.GetIdentityString(), psbudget);
                    LocalizedString warningMessage = new LocalizedString(localizedString + text);
                    this.context.Items["ThrottlingInfo"] = text;
                    this.context.Items["DelayedInfo"]    = localizedString;
                    Guid uniqueId = this.context.UniqueId;
                    CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.ThrottlingInfo, text);
                    CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.DelayInfo, CmdletLogHelper.NeedConvertLogMessageToUS ? localizedString.ToString(CmdletLogHelper.DefaultLoggingCulture) : localizedString);
                    this.WriteCmdletMicroDelayMessage(warningMessage, delayEnforcementResults.DelayInfo.Delay.TotalSeconds);
                }
                PowerShellBudgetWrapper powerShellBudgetWrapper = psbudget as PowerShellBudgetWrapper;
                WorkloadManagementLogger.SetBudgetBalance(powerShellBudgetWrapper.GetInnerBudget().CasTokenBucket.GetBalance().ToString(), null);
            }
        }
Exemple #4
0
 // Token: 0x060015BC RID: 5564 RVA: 0x00050BCF File Offset: 0x0004EDCF
 public override bool WriteObject(object input, out object output)
 {
     output = input;
     this.outputObjectCount++;
     CmdletLogger.SafeSetLogger(this.context.UniqueId, RpsCmdletMetadata.OutputObjectCount, this.outputObjectCount);
     return(true);
 }
Exemple #5
0
 internal void NewGroupMailbox(DatabaseLocationInfo databaseLocationInfo, out Exception exception, out ExchangeErrorCategory?errorCategory)
 {
     errorCategory = null;
     try
     {
         this.AddVerboseLog("Start: NewGroupMailbox");
         this.EnsureGroupIsInDirectoryCache("GroupMailboxContext.NewGroupMailbox");
         this.UpdateGroupMailbox(databaseLocationInfo, (GroupMailboxConfigurationActionType)0, this.GetValidGroupMembersFromFromRecipientIds(this.setMembers), null);
         if (this.invalidUsers.Length > 0)
         {
             CmdletLogger.SafeAppendGenericError("UsersWithoutSmtpAddress_New", this.invalidUsers.ToString(), false);
             this.invalidUsers.Clear();
         }
         exception = null;
     }
     catch (Exception ex)
     {
         exception     = ex;
         errorCategory = new ExchangeErrorCategory?(ExchangeErrorCategory.ServerTransient);
         if (this.IsWellKnownClientException(ex))
         {
             errorCategory = new ExchangeErrorCategory?(ExchangeErrorCategory.Client);
         }
     }
     finally
     {
         this.AddVerboseLog("End: NewGroupMailbox");
     }
 }
Exemple #6
0
 internal void SetGroupMailbox(GroupMailboxConfigurationActionType forceConfigurationActionMask, out Exception exception, out ExchangeErrorCategory?errorCategory)
 {
     errorCategory = null;
     try
     {
         this.AddVerboseLog("Start: SetGroupMailbox");
         if (this.addMembers != null || this.removeMembers != null || !this.groupMailbox.IsGroupMailboxConfigured || this.permissionsVersion != null || forceConfigurationActionMask != (GroupMailboxConfigurationActionType)0)
         {
             this.UpdateGroupMailbox(null, forceConfigurationActionMask, this.GetValidGroupMembersFromFromRecipientIds(this.addMembers), this.ResolveUsers(this.removeMembers, new Action <RecipientIdParameter, Exception>(this.ReportResolveUserWarning)));
             if (this.invalidUsers.Length > 0)
             {
                 CmdletLogger.SafeAppendGenericError("UsersWithoutSmtpAddress_Set", this.invalidUsers.ToString(), false);
                 this.invalidUsers.Clear();
             }
         }
         else
         {
             this.AddVerboseLog("No members to update on GroupMailbox or configuration action to execute.");
         }
         exception = null;
     }
     catch (LocalizedException ex)
     {
         exception     = ex;
         errorCategory = new ExchangeErrorCategory?(ExchangeErrorCategory.ServerTransient);
         if (this.IsWellKnownClientException(ex))
         {
             errorCategory = new ExchangeErrorCategory?(ExchangeErrorCategory.Client);
         }
     }
     finally
     {
         this.AddVerboseLog("End: SetGroupMailbox");
     }
 }
 internal static void Execute(this ICriticalFeature feature, Action action, TaskContext taskContext, string methodNameInLog)
 {
     try
     {
         action();
     }
     catch (Exception ex)
     {
         Guid      uniqueId = taskContext.UniqueId;
         bool      flag     = false;
         Exception ex2;
         bool      needReportException = !TaskHelper.IsTaskKnownException(ex2) && TaskHelper.ShouldReportException(ex2, out flag);
         if (!needReportException)
         {
             CmdletLogger.SafeAppendGenericError(uniqueId, methodNameInLog, ex2.ToString(), false);
         }
         else
         {
             CmdletLogger.SafeAppendGenericError(uniqueId, methodNameInLog, ex2.ToString(), true);
             CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.ErrorType, "UnHandled");
         }
         if (feature == null || feature.IsCriticalException(ex2))
         {
             throw;
         }
         if (!flag)
         {
             taskContext.CommandShell.WriteWarning(Strings.WarningTaskModuleSkipped(methodNameInLog, ex2.Message));
         }
         Diagnostics.ReportException(ex2, Constants.CoreEventLogger, TaskEventLogConstants.Tuple_UnhandledException, (object ex) => needReportException, null, ExTraceGlobals.InstrumentationTracer, "Exception from  " + methodNameInLog + ": {0}");
     }
 }
 // Token: 0x06001640 RID: 5696 RVA: 0x00053918 File Offset: 0x00051B18
 private void OnPreIterate(object sender, EventArgs eventArgs)
 {
     this.shouldProcessHasBeenPrompted = false;
     this.proxiedObjectCount           = 0;
     CmdletLogger.SafeSetLogger(this.context.UniqueId, RpsCmdletMetadata.ProxiedObjectCount, 0);
     this.context.Items["Log_ProxiedObjectCount"] = 0;
 }
Exemple #9
0
 // Token: 0x06001675 RID: 5749 RVA: 0x00055040 File Offset: 0x00053240
 private void PersistNewServerSettings(ADServerSettings newServerSettings)
 {
     if (newServerSettings != null)
     {
         ADSessionSettings.ClearThreadADContext();
         LocalizedString adserverSettings;
         if (CmdletLogHelper.NeedConvertLogMessageToUS)
         {
             adserverSettings = TaskVerboseStringHelper.GetADServerSettings(this.context.InvocationInfo.CommandName, newServerSettings, CmdletLogHelper.DefaultLoggingCulture);
         }
         else
         {
             adserverSettings = TaskVerboseStringHelper.GetADServerSettings(this.context.InvocationInfo.CommandName, newServerSettings);
         }
         if (this.context.SessionState != null)
         {
             CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "ADServerSettings-FailOver", adserverSettings);
             ExchangePropertyContainer.SetServerSettings(this.context.SessionState, newServerSettings);
         }
         else
         {
             CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "ADServerSettings-NOTFailOver-SessionStateNull", adserverSettings);
         }
         ADSessionSettings.SetThreadADContext(new ADDriverContext(newServerSettings, ContextMode.Cmdlet));
         this.context.ServerSettingsAfterFailOver = newServerSettings;
         this.context.CommandShell.WriteWarning(DirectoryStrings.RunspaceServerSettingsChanged);
         return;
     }
     CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "ADServerSettings-NOTFailOver-ServerSettingsNull", "NULL");
 }
 // Token: 0x06001642 RID: 5698 RVA: 0x000539C4 File Offset: 0x00051BC4
 private bool ProxyCmdlet(CmdletProxyInfo cmdletProxyInfo)
 {
     this.proxiedObjectCount++;
     CmdletLogger.SafeSetLogger(this.context.UniqueId, RpsCmdletMetadata.ProxiedObjectCount, this.proxiedObjectCount);
     this.context.Items["Log_ProxiedObjectCount"] = this.proxiedObjectCount;
     if (cmdletProxyInfo.ConfirmationMessage != LocalizedString.Empty)
     {
         if (!this.shouldProcessHasBeenPrompted && this.context.CommandShell != null && !this.context.CommandShell.ShouldProcess(cmdletProxyInfo.ConfirmationMessage))
         {
             CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "Proxy", "CancelAfterConfirm");
             CmdletLogger.SafeSetLogger(this.context.UniqueId, RpsCmdletMetadata.ExecutionResult, "Cancelled");
             this.context.WasCancelled = true;
             return(false);
         }
         SwitchParameter switchParameter = new SwitchParameter(false);
         if (this.ShouldRemoveConfirmParam() && this.context.InvocationInfo != null)
         {
             this.context.InvocationInfo.UserSpecifiedParameters.Remove("Confirm");
         }
         if (this.context.InvocationInfo != null)
         {
             this.context.InvocationInfo.UserSpecifiedParameters.Add("Confirm", switchParameter);
         }
     }
     using (new CmdletMonitoredScope(this.context.UniqueId, "CmdletProxyLatency", "CmdletProxyLatency", LoggerHelper.CmdletPerfMonitors))
     {
         this.ProxyCmdletExecution(cmdletProxyInfo);
     }
     this.context.Items["Log_CmdletProxyInfo"] = string.Format("Cmdlet proxied to remote server {0}, version {1}.", cmdletProxyInfo.RemoteServerFqdn, ProxyHelper.GetFriendlyVersionInformation(cmdletProxyInfo.RemoteServerVersion));
     return(true);
 }
Exemple #11
0
 internal void TriggerFailFast(OverBudgetException cmdletOverBudget)
 {
     if (this.context.UserInfo.ExecutingWindowsLiveId.IsValidAddress)
     {
         FailFastUserCache.Instance.AddUserToCache(this.context.UserInfo.ExecutingWindowsLiveId.ToString(), BlockedType.NewRequest, (cmdletOverBudget == null) ? TimeSpan.Zero : new TimeSpan(0, 0, 0, 0, cmdletOverBudget.BackoffTime));
         CmdletLogger.SafeAppendColumn(this.context.UniqueId, RpsCmdletMetadata.ContributeToFailFast, "Cmdlet", LoggerHelper.GetContributeToFailFastValue("User", this.context.UserInfo.ExecutingUserId.ToString(), "NewRequest", (double)((cmdletOverBudget == null) ? -1 : cmdletOverBudget.BackoffTime)));
     }
 }
 // Token: 0x06001603 RID: 5635 RVA: 0x00052250 File Offset: 0x00050450
 private void OnIterateCompleted(object sender, EventArgs eventArgs)
 {
     if (this.context.InvocationInfo != null)
     {
         Guid uniqueId = this.context.UniqueId;
         this.parametersSetInLog = true;
         CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.Cmdlet, this.context.InvocationInfo.CommandName);
         CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.Parameters, TaskVerboseStringHelper.FormatUserSpecifiedParameters(this.context.InvocationInfo.UserSpecifiedParameters ?? new PropertyBag()));
     }
 }
Exemple #13
0
        internal static void SetCmdletErrorType(Guid cmdletUniqueId, string errorType)
        {
            string a = CmdletStaticDataWithUniqueId <string> .Get(cmdletUniqueId);

            if (a == "UnHandled")
            {
                return;
            }
            CmdletStaticDataWithUniqueId <string> .Set(cmdletUniqueId, errorType);

            CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ErrorType, errorType);
        }
        // Token: 0x06001607 RID: 5639 RVA: 0x00052434 File Offset: 0x00050634
        private void StartLogging()
        {
            this.logPendingCommit   = true;
            this.parametersSetInLog = false;
            Guid uniqueId = this.context.UniqueId;

            CmdletThreadStaticData.RegisterCmdletUniqueId(uniqueId);
            CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.StartTime, DateTime.UtcNow);
            CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.ExecutionResult, "Success");
            CmdletLatencyTracker.StartLatencyTracker(uniqueId);
            CmdletLatencyTracker.StartInternalTracking(uniqueId, "Cmd", true);
        }
Exemple #15
0
        private LocalizedString GenerateDelayInfoLogString(IBudget budget, DelayEnforcementResults info)
        {
            LocalizedString result = LocalizedString.Empty;

            if (!string.Equals(info.NotEnforcedReason, "No Delay Necessary", StringComparison.OrdinalIgnoreCase))
            {
                CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "DelayInfo.Type", info.DelayInfo.GetType().Name);
                if (info.NotEnforcedReason != null)
                {
                    CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "NotEnforcedReason", info.NotEnforcedReason);
                }
                if (string.Equals(info.NotEnforcedReason, "Max Delayed Threads Exceeded", StringComparison.OrdinalIgnoreCase))
                {
                    BudgetTypeSetting budgetTypeSetting = BudgetTypeSettings.Get(budget.Owner.BudgetType);
                    if (info.DelayInfo is UserQuotaDelayInfo)
                    {
                        UserQuotaDelayInfo userQuotaDelayInfo = info.DelayInfo as UserQuotaDelayInfo;
                        result = Strings.UserQuotaDelayNotEnforcedMaxThreadsExceeded((int)info.DelayInfo.Delay.TotalMilliseconds, info.DelayInfo.Required, userQuotaDelayInfo.OverBudgetException.PolicyPart, budgetTypeSetting.MaxDelayedThreads);
                    }
                    else if (info.DelayInfo is ResourceLoadDelayInfo)
                    {
                        ResourceLoadDelayInfo resourceLoadDelayInfo = info.DelayInfo as ResourceLoadDelayInfo;
                        result = Strings.ResourceLoadDelayNotEnforcedMaxThreadsExceeded((int)info.DelayInfo.Delay.TotalMilliseconds, info.DelayInfo.Required, resourceLoadDelayInfo.ResourceKey.ToString(), resourceLoadDelayInfo.ResourceLoad.ToString(), budgetTypeSetting.MaxDelayedThreads);
                    }
                    else
                    {
                        result = Strings.MicroDelayNotEnforcedMaxThreadsExceeded((int)info.DelayInfo.Delay.TotalMilliseconds, info.DelayInfo.Required, budgetTypeSetting.MaxDelayedThreads);
                    }
                }
                else
                {
                    CmdletLogger.SafeSetLogger(this.context.UniqueId, RpsCmdletMetadata.ThrottlingDelay, info.DelayedAmount.TotalMilliseconds);
                    if (info.DelayInfo is UserQuotaDelayInfo)
                    {
                        UserQuotaDelayInfo userQuotaDelayInfo2 = info.DelayInfo as UserQuotaDelayInfo;
                        result = Strings.UserQuotaDelayInfo((int)info.DelayedAmount.TotalMilliseconds, info.Enforced, (int)info.DelayInfo.Delay.TotalMilliseconds, info.DelayInfo.Required, userQuotaDelayInfo2.OverBudgetException.PolicyPart, info.NotEnforcedReason);
                    }
                    else if (info.DelayInfo is ResourceLoadDelayInfo)
                    {
                        ResourceLoadDelayInfo resourceLoadDelayInfo2 = info.DelayInfo as ResourceLoadDelayInfo;
                        result = Strings.ResourceLoadDelayInfo((int)info.DelayedAmount.TotalMilliseconds, info.Enforced, (int)info.DelayInfo.Delay.TotalMilliseconds, info.DelayInfo.Required, resourceLoadDelayInfo2.ResourceKey.ToString(), resourceLoadDelayInfo2.ResourceLoad.ToString(), info.NotEnforcedReason);
                    }
                    else
                    {
                        result = Strings.MicroDelayInfo((int)info.DelayedAmount.TotalMilliseconds, info.Enforced, (int)info.DelayInfo.Delay.TotalMilliseconds, info.DelayInfo.Required, info.NotEnforcedReason);
                    }
                }
            }
            return(result);
        }
Exemple #16
0
        internal static void LogADServerSettingsAfterCmdExecuted(Guid cmdletUniqueId, ADServerSettings serverSettings)
        {
            string        key           = "ADServerSettingsInEnd";
            StringBuilder stringBuilder = new StringBuilder();
            string        format        = "{0}:{1} ";

            if (serverSettings == null)
            {
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, key, "null");
                return;
            }
            stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADViewEntireForest.ToString(), serverSettings.ViewEntireForest);
            if (serverSettings.RecipientViewRoot != null)
            {
                stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADRecipientViewRoot.ToString(), serverSettings.RecipientViewRoot.ToCanonicalName());
            }
            if (serverSettings.ConfigurationDomainControllers != null)
            {
                stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADConfigurationDomainControllers, string.Join <Fqdn>(",", serverSettings.ConfigurationDomainControllers.Values));
            }
            if (serverSettings.PreferredGlobalCatalogs != null)
            {
                stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADPreferredGlobalCatalogs.ToString(), string.Join <Fqdn>(",", serverSettings.PreferredGlobalCatalogs.Values));
            }
            if (serverSettings.PreferredDomainControllers != null)
            {
                stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADPreferredDomainControllers.ToString(), string.Join <Fqdn>(",", serverSettings.PreferredDomainControllers.ToArray()));
            }
            RunspaceServerSettings runspaceServerSettings = serverSettings as RunspaceServerSettings;

            if (runspaceServerSettings == null)
            {
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, key, stringBuilder.ToString());
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "RunspaceServerSettings", "null");
                return;
            }
            if (runspaceServerSettings.UserConfigurationDomainController != null)
            {
                stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADUserConfigurationDomainController.ToString(), runspaceServerSettings.UserConfigurationDomainController);
            }
            if (runspaceServerSettings.UserPreferredGlobalCatalog != null)
            {
                stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADUserPreferredGlobalCatalog.ToString(), runspaceServerSettings.UserConfigurationDomainController);
            }
            if (runspaceServerSettings.UserPreferredDomainControllers != null)
            {
                stringBuilder.AppendFormat(format, RpsCmdletMetadata.ADUserPreferredDomainControllers.ToString(), string.Join <Fqdn>(",", runspaceServerSettings.UserPreferredDomainControllers.ToArray()));
            }
            CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, key, stringBuilder.ToString());
        }
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     if (this.approvalRequired)
     {
         string text = this.SubmitApprovalRequest(this.ApprovalAction);
         this.WriteApprovalRequiredWarning(text);
         string text2 = string.Format("Approval Request Message ID: {0}", text);
         base.AdditionalLogData = text2;
         CmdletLogger.SafeAppendGenericInfo(base.CurrentTaskContext.UniqueId, "DGMemberTaskBase.Log", text2);
     }
     base.InternalProcessRecord();
     TaskLogger.LogExit();
 }
Exemple #18
0
        private void ExtractRbacDataFromRunspace(object sender, EventArgs e)
        {
            ADObjectId     adobjectId     = null;
            OrganizationId organizationId = null;

            ExchangePropertyContainer.InitializeExchangePropertyContainerIfNeeded(this.context.SessionState, out adobjectId, out organizationId);
            ExchangeRunspaceConfiguration exchangeRunspaceConfiguration = null;

            if (this.context.SessionState != null)
            {
                exchangeRunspaceConfiguration = ExchangePropertyContainer.GetExchangeRunspaceConfiguration(this.context.SessionState);
            }
            OrganizationId organizationId2;
            string         executingUserIdentityName;
            SmtpAddress    executingWindowsLiveId;

            if (exchangeRunspaceConfiguration == null)
            {
                if (this.context.SessionState != null)
                {
                    organizationId = (organizationId ?? ExchangePropertyContainer.GetExecutingUserOrganizationId(this.context.SessionState));
                    adobjectId     = (adobjectId ?? ExchangePropertyContainer.GetExecutingUserId(this.context.SessionState));
                }
                organizationId2           = organizationId;
                executingUserIdentityName = ((adobjectId == null) ? string.Empty : adobjectId.Name);
            }
            else
            {
                exchangeRunspaceConfiguration.TryGetExecutingUserId(out adobjectId);
                executingUserIdentityName = exchangeRunspaceConfiguration.IdentityName;
                exchangeRunspaceConfiguration.TryGetExecutingWindowsLiveId(out executingWindowsLiveId);
                organizationId  = (exchangeRunspaceConfiguration.PartnerMode ? OrganizationId.ForestWideOrgId : exchangeRunspaceConfiguration.OrganizationId);
                organizationId2 = exchangeRunspaceConfiguration.OrganizationId;
                SecurityIdentifier value;
                exchangeRunspaceConfiguration.TryGetExecutingUserSid(out value);
                CmdletLogger.SafeSetLogger(this.context.UniqueId, RpsCmdletMetadata.ExecutingUserSid, value);
            }
            if (this.context.InvocationInfo != null && this.context.InvocationInfo.IsVerboseOn && !TaskLogger.IsSetupLogging)
            {
                string executingUserId             = (adobjectId != null) ? adobjectId.ToCanonicalName() : string.Empty;
                string executingUserOrganizationId = (organizationId != null) ? organizationId.ToString() : string.Empty;
                string currentOrganizationId       = (organizationId2 != null) ? organizationId2.ToString() : string.Empty;
                if (this.context.CommandShell != null)
                {
                    this.context.CommandShell.WriteVerbose(Strings.VerboseExecutingUserContext(executingUserId, executingUserOrganizationId, currentOrganizationId, (exchangeRunspaceConfiguration == null) ? Strings.DisabledString : Strings.EnabledString));
                }
            }
            this.context.ExchangeRunspaceConfig = exchangeRunspaceConfiguration;
            this.context.UserInfo = new TaskUserInfo(organizationId, organizationId2, adobjectId, executingUserIdentityName, executingWindowsLiveId);
        }
Exemple #19
0
        private void StartBudgetProcess(object sender, EventArgs e)
        {
            string cmdLetName = null;

            if (this.context.InvocationInfo != null)
            {
                cmdLetName = this.context.InvocationInfo.CommandName;
            }
            this.DisposeCostHandle();
            this.SafeBudgetAction(delegate(BudgetInformation budgetInfo)
            {
                CmdletLogger.SafeSetLogger(this.context.UniqueId, RpsCmdletMetadata.UserBudgetOnStart, budgetInfo.Budget.GetCmdletBudgetUsage());
            });
            this.SafeBudgetAction(delegate(BudgetInformation budgetInfo)
            {
                budgetInfo.Budget.EndLocal();
            });
            this.SafeBudgetAction(delegate(BudgetInformation budgetInfo)
            {
                budgetInfo.Handle = budgetInfo.Budget.StartCmdlet(cmdLetName);
            });
            if (!this.casCostHandleDisabled)
            {
                this.SafeBudgetAction(delegate(BudgetInformation budgetInfo)
                {
                    try
                    {
                        budgetInfo.Budget.StartLocal(string.Format("Task.StartBudgetProcess.{0}", cmdLetName), default(TimeSpan));
                        budgetInfo.Budget.LocalCostHandle.MaxLiveTime = TimeSpan.FromHours(1.0);
                    }
                    catch (InvalidOperationException)
                    {
                        try
                        {
                            CmdletLogger.SafeAppendGenericError("StartLocalBudgetFailed", cmdLetName, false);
                            budgetInfo.Budget.EndLocal();
                        }
                        catch (Exception)
                        {
                        }
                    }
                });
                return;
            }
            ThrottlingModule <T> .LogInformationTrace("CasCostHandle is not enabled in cmdlet '{0}'", new object[]
            {
                cmdLetName
            });
        }
Exemple #20
0
        protected IDisposable CreatePiiSuppressionContext(IConfigurable outputObject)
        {
            ConfigurableObject configurableObject = outputObject as ConfigurableObject;

            if (configurableObject == null)
            {
                return(null);
            }
            if (configurableObject.SkipPiiRedaction || SuppressingPiiProperty.IsExcludedSchemaType(configurableObject.ObjectSchema.GetType()) || (VariantConfiguration.InvariantNoFlightingSnapshot.CmdletInfra.SkipPiiRedactionForForestWideObject.Enabled && TaskHelper.IsForestWideADObject(outputObject as ADObject)))
            {
                return(null);
            }
            CmdletLogger.SafeSetLogger(this.CurrentTaskContext.UniqueId, RpsCmdletMetadata.IsOutputObjectRedacted, true);
            return(SuppressingPiiContext.Create(true, this.CurrentPiiMap));
        }
Exemple #21
0
        // Token: 0x06001674 RID: 5748 RVA: 0x00054FE0 File Offset: 0x000531E0
        private void TryFailOver()
        {
            ADDriverContext  threadADContext  = ADSessionSettings.GetThreadADContext();
            ADServerSettings adserverSettings = (threadADContext != null) ? threadADContext.ServerSettings : null;

            if (adserverSettings != null && adserverSettings.IsFailoverRequired())
            {
                ADServerSettings newServerSettings;
                string           str;
                if (adserverSettings.TryFailover(out newServerSettings, out str, false))
                {
                    this.PersistNewServerSettings(newServerSettings);
                    return;
                }
                CmdletLogger.SafeAppendGenericInfo(this.context.UniqueId, "ADServerSettings-TryFailOver", "Failed - " + str);
            }
        }
Exemple #22
0
        internal static IEnumerable <PSObject> RPSProxyExecution(Guid cmdletUniqueId, PSCommand command, string serverFqn, ExchangeRunspaceConfiguration runspaceConfig, int serverVersion, bool asyncProxying, Task.TaskWarningLoggingDelegate writeWarning)
        {
            Uri uri = ProxyHelper.BuildCmdletProxyUri(serverFqn, runspaceConfig, serverVersion);
            IEnumerable <PSObject> result;

            try
            {
                RemoteConnectionInfo connectionInfo = ProxyHelper.BuildProxyWSManConnectionInfo(uri);
                ProxyPSCommand       proxyPSCommand = new ProxyPSCommand(connectionInfo, command, asyncProxying, writeWarning);
                result = proxyPSCommand.Invoke();
            }
            catch (Exception)
            {
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "TargetUri", uri.ToString());
                throw;
            }
            return(result);
        }
Exemple #23
0
        internal static void LogADServerSettings(Guid cmdletUniqueId, ADServerSettings serverSettings)
        {
            if (serverSettings == null)
            {
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "ADServerSettings", "null");
                return;
            }
            CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADViewEntireForest, serverSettings.ViewEntireForest);
            if (serverSettings.RecipientViewRoot != null)
            {
                CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADRecipientViewRoot, serverSettings.RecipientViewRoot.ToCanonicalName());
            }
            if (serverSettings.ConfigurationDomainControllers != null)
            {
                CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADConfigurationDomainControllers, string.Join <Fqdn>(",", serverSettings.ConfigurationDomainControllers.Values));
            }
            if (serverSettings.PreferredGlobalCatalogs != null)
            {
                CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADPreferredGlobalCatalogs, string.Join <Fqdn>(",", serverSettings.PreferredGlobalCatalogs.Values));
            }
            if (serverSettings.PreferredDomainControllers != null)
            {
                CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADPreferredDomainControllers, string.Join <Fqdn>(",", serverSettings.PreferredDomainControllers.ToArray()));
            }
            RunspaceServerSettings runspaceServerSettings = serverSettings as RunspaceServerSettings;

            if (runspaceServerSettings == null)
            {
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "RunspaceServerSettings", "null");
                return;
            }
            if (runspaceServerSettings.UserConfigurationDomainController != null)
            {
                CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADUserConfigurationDomainController, runspaceServerSettings.UserConfigurationDomainController);
            }
            if (runspaceServerSettings.UserPreferredGlobalCatalog != null)
            {
                CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADUserPreferredGlobalCatalog, runspaceServerSettings.UserConfigurationDomainController);
            }
            if (runspaceServerSettings.UserPreferredDomainControllers != null)
            {
                CmdletLogger.SafeSetLogger(cmdletUniqueId, RpsCmdletMetadata.ADUserPreferredDomainControllers, string.Join <Fqdn>(",", runspaceServerSettings.UserPreferredDomainControllers.ToArray()));
            }
        }
        internal static IEnumerable <PSObject> Invoke(Guid cmdletUniqueId, string pswsServiceUri, string cmdletCommand, NetworkCredential credential, NameValueCollection headersTobeAdd, TypeTable typeTable)
        {
            CommandInvocation.CheckArgumentNull("pswsServiceUri", pswsServiceUri);
            CommandInvocation.CheckArgumentNull("cmdletCommand", cmdletCommand);
            CommandInvocation.CheckArgumentNull("credential", credential);
            int             tickCount = Environment.TickCount;
            string          value;
            string          value2;
            ResponseContent responseContent = CommandInvocation.CreateRequest(pswsServiceUri, cmdletCommand, credential, headersTobeAdd, out value, out value2);

            while (responseContent.Status == ExecutionStatus.Executing)
            {
                int num = Environment.TickCount - tickCount;
                if (num > 600000)
                {
                    throw new PswsProxyException(Strings.PswsInvocationTimout(600000));
                }
                Thread.Sleep(1000);
                responseContent = CommandInvocation.ResumeRequest(pswsServiceUri, responseContent.Id, credential, headersTobeAdd, out value2);
            }
            CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "TicksElapsed", (Environment.TickCount - tickCount).ToString());
            if (responseContent.Status == ExecutionStatus.Error)
            {
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "RequestXml", value);
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "ResponseXml", value2);
                StringBuilder stringBuilder = new StringBuilder();
                if (headersTobeAdd != null)
                {
                    foreach (string text in headersTobeAdd.AllKeys)
                    {
                        stringBuilder.Append(text);
                        stringBuilder.Append(':');
                        stringBuilder.Append(headersTobeAdd[text]);
                        stringBuilder.Append(' ');
                    }
                }
                CmdletLogger.SafeAppendGenericInfo(cmdletUniqueId, "RequestHeaders", stringBuilder.ToString());
                throw new PswsProxyCmdletException(responseContent.Error.Exception);
            }
            return(ObjectTransfer.GetResultObjects(responseContent.OutputXml, typeTable));
        }
Exemple #25
0
        // Token: 0x06001613 RID: 5651 RVA: 0x00052AE4 File Offset: 0x00050CE4
        private static bool ShouldProxyCmdlet(TaskContext context, string remoteServerFqdn, int remoteServerVersion)
        {
            if (string.IsNullOrWhiteSpace(remoteServerFqdn))
            {
                return(false);
            }
            if (context.ExchangeRunspaceConfig == null)
            {
                return(false);
            }
            if (ExTraceGlobals.FaultInjectionTracer.IsTraceEnabled(TraceType.FaultInjection))
            {
                bool flag = false;
                ProxyHelper.FaultInjection_ShouldForcedlyProxyCmdlet(context.ExchangeRunspaceConfig.ConfigurationSettings.OriginalConnectionUri, remoteServerFqdn, ref flag);
                if (flag)
                {
                    return(true);
                }
            }
            string localServerFqdn = TaskHelper.GetLocalServerFqdn(null);

            if (string.IsNullOrEmpty(localServerFqdn))
            {
                CmdletLogger.SafeAppendGenericError(context.UniqueId, "ShouldProxyCmdlet", "GetLocalServerFqdn returns null/empty value", false);
                return(false);
            }
            if (string.Equals(remoteServerFqdn, localServerFqdn, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (CmdletProxy.CanServerBeProxiedTo(remoteServerVersion))
            {
                return(true);
            }
            CmdletLogger.SafeAppendGenericInfo(context.UniqueId, "ShouldProxyCmdlet", string.Format("Remote server version {0} doesn't support be proxied.", ProxyHelper.GetFriendlyVersionInformation(remoteServerVersion)));
            return(false);
        }
        // Token: 0x06001606 RID: 5638 RVA: 0x000522DC File Offset: 0x000504DC
        private void OnError(object sender, GenericEventArg <TaskErrorEventArg> genericEventArg)
        {
            if (genericEventArg.Data.ExceptionHandled)
            {
                return;
            }
            Exception exception = genericEventArg.Data.Exception;
            Guid      uniqueId  = this.context.UniqueId;
            Exception ex        = CmdletStaticDataWithUniqueId <Exception> .Get(uniqueId);

            if (ex != null && ex != exception)
            {
                CmdletLogger.SafeAppendGenericError(uniqueId, this.context.Stage.ToString() + ".FromWriteError", ex.ToString(), false);
            }
            bool isUnhandledException = (genericEventArg.Data.IsUnknownException != null) ? genericEventArg.Data.IsUnknownException.Value : TaskHelper.IsTaskUnhandledException(exception);

            CmdletLogger.SafeAppendGenericError(uniqueId, this.context.Stage.ToString(), exception.ToString(), isUnhandledException);
            if (exception is LocalizedException)
            {
                CmdletLogger.SafeAppendGenericError(uniqueId, "ExceptionStringId", ((LocalizedException)exception).LocalizedString.StringId, false);
                if (CmdletLogHelper.NeedConvertLogMessageToUS)
                {
                    LocalizedException ex2            = (LocalizedException)exception;
                    IFormatProvider    formatProvider = ex2.FormatProvider;
                    try
                    {
                        ex2.FormatProvider = CmdletLogHelper.DefaultLoggingCulture;
                        CmdletLogger.SafeAppendGenericError(uniqueId, this.context.Stage.ToString() + "(en-us)", ex2.ToString(), false);
                    }
                    finally
                    {
                        ex2.FormatProvider = formatProvider;
                    }
                }
            }
        }
        // Token: 0x06001644 RID: 5700 RVA: 0x00053BE8 File Offset: 0x00051DE8
        private void ProxyCmdletExecution(CmdletProxyInfo cmdletProxyInfo)
        {
            ExAssert.RetailAssert(this.context.ExchangeRunspaceConfig != null, "this.context.ExchangeRunspaceConfig should not be null.");
            string remoteServerFqdn           = cmdletProxyInfo.RemoteServerFqdn;
            int    remoteServerVersion        = cmdletProxyInfo.RemoteServerVersion;
            string friendlyVersionInformation = ProxyHelper.GetFriendlyVersionInformation(remoteServerVersion);

            CmdletProxyInfo.ChangeCmdletProxyParametersDelegate changeCmdletProxyParameters = cmdletProxyInfo.ChangeCmdletProxyParameters;
            if (Microsoft.Exchange.Diagnostics.Components.Tasks.ExTraceGlobals.FaultInjectionTracer.IsTraceEnabled(TraceType.FaultInjection))
            {
                Microsoft.Exchange.Diagnostics.Components.Tasks.ExTraceGlobals.FaultInjectionTracer.TraceTest <string>(3720752445U, ref remoteServerFqdn);
                UserToken userToken = this.context.ExchangeRunspaceConfig.ConfigurationSettings.UserToken;
                ProxyHelper.FaultInjection_UserSid(ref userToken);
                Microsoft.Exchange.Diagnostics.Components.Tasks.ExTraceGlobals.FaultInjectionTracer.TraceTest <int>(3452316989U, ref remoteServerVersion);
            }
            string text = this.GeneratePswsProxyCmdlet(changeCmdletProxyParameters);

            ExchangeRunspaceConfigurationSettings.ProxyMethod proxyMethod = this.DetermineProxyMethod(remoteServerVersion);
            if (this.context.CommandShell != null)
            {
                this.context.CommandShell.WriteVerbose(Strings.VerboseCmdletProxiedToAnotherServer(text, remoteServerFqdn, friendlyVersionInformation, proxyMethod.ToString()));
            }
            Guid uniqueId = this.context.UniqueId;

            CmdletLogger.SafeAppendColumn(uniqueId, RpsCmdletMetadata.CmdletProxyRemoteServer, this.proxiedObjectCount.ToString(), remoteServerFqdn);
            CmdletLogger.SafeAppendColumn(uniqueId, RpsCmdletMetadata.CmdletProxyRemoteServerVersion, this.proxiedObjectCount.ToString(), friendlyVersionInformation.ToString());
            CmdletLogger.SafeAppendColumn(uniqueId, RpsCmdletMetadata.CmdletProxyMethod, this.proxiedObjectCount.ToString(), proxyMethod.ToString());
            try
            {
                IEnumerable <PSObject> enumerable;
                if (proxyMethod == ExchangeRunspaceConfigurationSettings.ProxyMethod.RPS)
                {
                    PSCommand command = this.GenerateProxyCmdlet(changeCmdletProxyParameters);
                    Task.TaskWarningLoggingDelegate writeWarning = null;
                    if (this.context.CommandShell != null)
                    {
                        writeWarning = new Task.TaskWarningLoggingDelegate(this.context.CommandShell.WriteWarning);
                    }
                    enumerable = ProxyHelper.RPSProxyExecution(this.context.UniqueId, command, remoteServerFqdn, this.context.ExchangeRunspaceConfig, remoteServerVersion, cmdletProxyInfo.ShouldAsyncProxy, writeWarning);
                }
                else
                {
                    enumerable = CommandInvocation.Invoke(this.context.UniqueId, ProxyHelper.GetPSWSProxySiteUri(remoteServerFqdn), text, CredentialCache.DefaultNetworkCredentials, ProxyHelper.GetPSWSProxyRequestHeaders(this.context.ExchangeRunspaceConfig), this.context.ExchangeRunspaceConfig.TypeTable);
                }
                foreach (PSObject psobject in enumerable)
                {
                    object sendToPipeline = psobject;
                    if (psobject.BaseObject != null && !(psobject.BaseObject is PSCustomObject))
                    {
                        sendToPipeline = psobject.BaseObject;
                    }
                    else if (this.context.ExchangeRunspaceConfig != null)
                    {
                        if (this.context.ExchangeRunspaceConfig.ConfigurationSettings.ClientApplication != ExchangeRunspaceConfigurationSettings.ExchangeApplication.ECP)
                        {
                            if (this.context.ExchangeRunspaceConfig.ConfigurationSettings.ClientApplication != ExchangeRunspaceConfigurationSettings.ExchangeApplication.OSP)
                            {
                                goto IL_2CB;
                            }
                        }
                        try
                        {
                            Task.TaskVerboseLoggingDelegate writeVerbose = null;
                            if (this.context.CommandShell != null)
                            {
                                writeVerbose = new Task.TaskVerboseLoggingDelegate(this.context.CommandShell.WriteWarning);
                            }
                            sendToPipeline = ProxyHelper.ConvertPSObjectToOriginalType(psobject, remoteServerVersion, writeVerbose);
                        }
                        catch (Exception ex)
                        {
                            CmdletLogger.SafeAppendGenericError(uniqueId, "ConvertPSObjectToOriginalTyp", ex, new Func <Exception, bool>(TaskHelper.IsTaskUnhandledException));
                            Diagnostics.ReportException(ex, Constants.CoreEventLogger, TaskEventLogConstants.Tuple_UnhandledException, null, null, Microsoft.Exchange.Diagnostics.Components.Configuration.Core.ExTraceGlobals.InstrumentationTracer, "Exception from ProxyHelper.ConvertPSObjectToOriginalType : {0}");
                        }
                    }
IL_2CB:
                    if (this.context.CommandShell != null)
                    {
                        this.context.CommandShell.WriteObject(sendToPipeline);
                    }
                }
            }
            catch (Exception ex2)
            {
                CmdletLogger.SafeAppendGenericError(this.context.UniqueId, "ProxyCmdletExecution", ex2, new Func <Exception, bool>(TaskHelper.IsTaskUnhandledException));
                if (this.context.CommandShell != null)
                {
                    this.context.CommandShell.WriteError(new CmdletProxyException(text, remoteServerFqdn, friendlyVersionInformation, proxyMethod.ToString(), ex2.Message), ExchangeErrorCategory.ServerOperation, null);
                }
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var logger = new CmdletLogger(TreatWarningsAsErrors);

            try
            {
                logger.LogInfo("About to start importing data from Dynamics365");
                var manager = new Dynamics365DataManager();

                var cancellationTokenSource = new CancellationTokenSource();

                var importConfig = new CrmImportConfig();
                if (!string.IsNullOrWhiteSpace(ConfigFilePath))
                {
                    if (!File.Exists(ConfigFilePath))
                    {
                        WriteWarning($"Import config file path does not exist, will be ignored {ConfigFilePath}");
                    }
                    else
                    {
                        importConfig = CrmImportConfig.GetConfiguration(ConfigFilePath);
                    }
                }

                PopulateConfigFile(importConfig);

                if (!Directory.Exists(JsonFolderPath))
                {
                    WriteWarning($"JsonFolderPath {JsonFolderPath} does not exist, cannot continue!");
                    throw new DirectoryNotFoundException($"JsonFolderPath {JsonFolderPath} does not exist, cannot continue!");
                }

                CrmSchemaConfiguration schemaConfig = null;

                if (CsvImport)
                {
                    if (string.IsNullOrWhiteSpace(SchemaFilePath))
                    {
                        throw new ConfigurationException("Schema file is required for CSV Import!");
                    }

                    schemaConfig = CrmSchemaConfiguration.ReadFromFile(SchemaFilePath);
                    logger.LogInfo("Using Csv import");
                }
                else
                {
                    logger.LogInfo("Using JSon import");
                }

                if (MaxThreads > 1)
                {
                    var result = manager.StartImport(importConfig, logger, cancellationTokenSource, ConnectionString, MaxThreads, CsvImport, schemaConfig)
                                 .ContinueWith(a =>
                    {
                        logger.LogInfo("Dynamics365 data import completed successfully.");
                    },
                                               cancellationTokenSource.Token);

                    result.Wait(cancellationTokenSource.Token);
                }
                else
                {
                    manager.StartSingleThreadedImport(importConfig, new CmdletLoggerPS(this, TreatWarningsAsErrors), cancellationTokenSource, ConnectionString, CsvImport, schemaConfig);
                }
            }
            catch (Exception exception)
            {
                var errorMessage = $"Dynamics365 data import failed: {exception.Message}";
                logger.LogVerbose(errorMessage);
                logger.LogError(errorMessage);
                throw;
            }
        }
Exemple #29
0
        private void InitializeRunspaceServerSettings(object sender, EventArgs e)
        {
            ISessionState    sessionState     = this.CurrentTaskContext.SessionState;
            ADServerSettings adserverSettings = null;
            bool             flag             = false;
            bool             flag2            = false;
            string           value            = null;

            if (sessionState != null)
            {
                flag2 = ExchangePropertyContainer.IsContainerInitialized(sessionState);
                if (flag2)
                {
                    adserverSettings = ExchangePropertyContainer.GetServerSettings(sessionState);
                    if (adserverSettings != null)
                    {
                        value = "SessionState";
                    }
                }
            }
            if (adserverSettings == null)
            {
                adserverSettings = ADSessionSettings.GetProcessServerSettings();
                if (adserverSettings != null)
                {
                    value = "ProcessServerSettings";
                }
            }
            if (adserverSettings == null)
            {
                if (this.CurrentTaskContext.CommandShell != null)
                {
                    this.CurrentTaskContext.CommandShell.TryGetVariableValue <ADServerSettings>(ExchangePropertyContainer.ADServerSettingsVarName, out adserverSettings);
                }
                flag = (adserverSettings != null);
                if (adserverSettings != null)
                {
                    value = "CommandShell";
                }
            }
            if (TopologyProvider.CurrentTopologyMode == TopologyMode.ADTopologyService)
            {
                ADServerSettings cmdletADServerSettings = this.GetCmdletADServerSettings();
                if (cmdletADServerSettings != null)
                {
                    this.CurrentTaskContext.Items["CmdletServerSettings"] = cmdletADServerSettings;
                    value            = "ADTopologyService";
                    adserverSettings = cmdletADServerSettings;
                }
            }
            if (adserverSettings == null)
            {
                flag = true;
                if (TopologyProvider.CurrentTopologyMode == TopologyMode.Adam)
                {
                    if (this.CurrentTaskContext.InvocationInfo != null && this.CurrentTaskContext.InvocationInfo.IsVerboseOn)
                    {
                        this.CurrentTaskContext.CommandShell.WriteVerbose(Strings.VerboseInitializeRunspaceServerSettingsAdam);
                    }
                    if (Globals.InstanceType == InstanceType.NotInitialized)
                    {
                        Globals.InitializeSinglePerfCounterInstance();
                    }
                    value            = "Adam-SimpleServerSettings";
                    adserverSettings = new SimpleServerSettings();
                }
                else if (TopologyProvider.CurrentTopologyMode == TopologyMode.Ldap)
                {
                    if (this.CurrentTaskContext.InvocationInfo != null && this.CurrentTaskContext.CommandShell != null && this.CurrentTaskContext.InvocationInfo.IsVerboseOn)
                    {
                        this.CurrentTaskContext.CommandShell.WriteVerbose(Strings.VerboseInitializeRunspaceServerSettingsLocal);
                    }
                    Globals.InitializeMultiPerfCounterInstance("EMS");
                    value            = "Ldap-LocalCmdLineServerSettings";
                    adserverSettings = LocalCmdLineServerSettings.CreateLocalCmdLineServerSettings();
                }
                else
                {
                    if (this.CurrentTaskContext.InvocationInfo != null && this.CurrentTaskContext.InvocationInfo.IsVerboseOn)
                    {
                        this.CurrentTaskContext.CommandShell.WriteVerbose(Strings.VerboseInitializeRunspaceServerSettingsRemote);
                    }
                    adserverSettings = this.CreateADServerSettingsForOrganization(false);
                    if (adserverSettings == null)
                    {
                        value            = "GCRandomly";
                        adserverSettings = RunspaceServerSettings.CreateRunspaceServerSettings(false);
                    }
                }
            }
            if (flag)
            {
                if (flag2)
                {
                    ExchangePropertyContainer.SetServerSettings(sessionState, adserverSettings);
                }
                else
                {
                    sessionState.Variables[ExchangePropertyContainer.ADServerSettingsVarName] = adserverSettings;
                }
            }
            ADSessionSettings.SetThreadADContext(new ADDriverContext(adserverSettings, ContextMode.Cmdlet));
            LocalizedString localizedString = LocalizedString.Empty;

            if (this.CurrentTaskContext.InvocationInfo != null)
            {
                localizedString = TaskVerboseStringHelper.GetADServerSettings(this.CurrentTaskContext.InvocationInfo.CommandName, adserverSettings);
                if (this.CurrentTaskContext.InvocationInfo.IsVerboseOn && !string.Equals(this.CurrentTaskContext.InvocationInfo.CommandName, "Write-ExchangeSetupLog", StringComparison.OrdinalIgnoreCase) && this.CurrentTaskContext.CommandShell != null)
                {
                    this.CurrentTaskContext.CommandShell.WriteVerbose(localizedString);
                }
            }
            CmdletLogger.SafeSetLogger(this.CurrentTaskContext.UniqueId, RpsCmdletMetadata.RunspaceSettingsCreationHint, value);
            CmdletLogHelper.LogADServerSettings(this.CurrentTaskContext.UniqueId, adserverSettings);
            if (ExTraceGlobals.LogTracer.IsTraceEnabled(TraceType.InfoTrace))
            {
                ExTraceGlobals.LogTracer.Information <LocalizedString>(0L, "Cmdlet ADServerSettings {0}", localizedString);
            }
        }
Exemple #30
0
        private static PowerShellResults <O> InvokeCore <O>(PSCommand psCommand, RunspaceMediator runspaceMediator, IEnumerable pipelineInput, WebServiceParameters parameters, CmdletActivity activity, bool isGetListAsync)
        {
            Func <WarningRecord, string> func  = null;
            Func <Command, string>       func2 = null;

            PSCommandExtension.EnsureNoWriteTaskInGetRequest(psCommand, parameters);
            PowerShellResults <O> powerShellResults = new PowerShellResults <O>();

            ExTraceGlobals.EventLogTracer.TraceInformation <string, EcpTraceFormatter <PSCommand> >(0, 0L, "{0} tries to invoke {1}. For more details, refer to task trace", RbacPrincipal.Current.NameForEventLog, psCommand.GetTraceFormatter());
            using (RunspaceProxy runspaceProxy = new RunspaceProxy(runspaceMediator))
            {
                runspaceProxy.SetVariable("ConfirmPreference", "None");
                if (parameters != null)
                {
                    psCommand.AddParameters(parameters);
                }
                using (PowerShell powerShell = runspaceProxy.CreatePowerShell(psCommand))
                {
                    List <PSObject> list = null;
                    if (activity != null)
                    {
                        AsyncServiceManager.RegisterPowerShellToActivity(powerShell, activity, pipelineInput, out list, isGetListAsync);
                    }
                    else
                    {
                        AsyncServiceManager.RegisterPowerShell(powerShell);
                    }
                    int      requestLatency = 0;
                    DateTime utcNow         = DateTime.UtcNow;
                    try
                    {
                        TaskPerformanceRecord taskPerformanceRecord = new TaskPerformanceRecord(psCommand.GetCmdletName(), PSCommandExtension.powerShellLatencyDetectionContextFactory, EcpEventLogConstants.Tuple_EcpPowerShellInvoked, EcpEventLogConstants.Tuple_EcpPowerShellCompleted, EcpEventLogExtensions.EventLog, new IPerformanceDataProvider[]
                        {
                            PerformanceContext.Current,
                            RpcDataProvider.Instance,
                            TaskPerformanceData.CmdletInvoked,
                            TaskPerformanceData.BeginProcessingInvoked,
                            TaskPerformanceData.ProcessRecordInvoked,
                            TaskPerformanceData.EndProcessingInvoked,
                            EcpPerformanceData.PowerShellInvoke
                        });
                        try
                        {
                            using (EcpPerformanceData.PowerShellInvoke.StartRequestTimer())
                            {
                                if (list == null)
                                {
                                    powerShellResults.Output = powerShell.Invoke <O>(pipelineInput).ToArray <O>();
                                }
                                else
                                {
                                    powerShell.Invoke <PSObject>(pipelineInput, list);
                                    powerShellResults.Output = Array <O> .Empty;
                                }
                            }
                        }
                        finally
                        {
                            requestLatency = (int)taskPerformanceRecord.Stop().TotalMilliseconds;
                            IDisposable disposable2 = taskPerformanceRecord;
                            if (disposable2 != null)
                            {
                                disposable2.Dispose();
                            }
                        }
                        List <ErrorRecord> list2 = new List <ErrorRecord>();
                        bool flag = false;
                        foreach (ErrorRecord errorRecord in powerShell.Streams.Error)
                        {
                            if (!flag)
                            {
                                flag = PSCommandExtension.TryPatchShouldContinueException(errorRecord, psCommand, parameters);
                            }
                            list2.Add(new ErrorRecord(errorRecord));
                        }
                        powerShellResults.ErrorRecords = list2.ToArray();
                        PowerShellResults           powerShellResults2 = powerShellResults;
                        IEnumerable <WarningRecord> warning            = powerShell.Streams.Warning;
                        if (func == null)
                        {
                            func = ((WarningRecord warningRecord) => warningRecord.Message);
                        }
                        powerShellResults2.Warnings = warning.Select(func).ToArray <string>();
                    }
                    catch (RuntimeException ex)
                    {
                        PSCommandExtension.TryPatchShouldContinueException(ex.ErrorRecord, psCommand, parameters);
                        ErrorRecord errorRecord2;
                        if (ex.ErrorRecord != null && !(ex is ParameterBindingException))
                        {
                            errorRecord2 = new ErrorRecord(ex.ErrorRecord);
                        }
                        else
                        {
                            errorRecord2 = new ErrorRecord(ex);
                        }
                        powerShellResults.ErrorRecords = new ErrorRecord[]
                        {
                            errorRecord2
                        };
                    }
                    finally
                    {
                        string         text     = HttpContext.Current.Request.QueryString["reqId"];
                        ServerLogEvent logEvent = new ServerLogEvent(psCommand, pipelineInput, requestLatency, string.IsNullOrEmpty(text) ? string.Empty : text, (powerShellResults.ErrorRecords != null && powerShellResults.ErrorRecords.Length > 0) ? powerShellResults.ErrorRecords.ToLogString() : string.Empty, (powerShellResults.Output != null) ? powerShellResults.Output.Length : 0);
                        ServerLogger.Instance.LogEvent(logEvent);
                    }
                    PowerShellResults     powerShellResults3 = powerShellResults;
                    IEnumerable <Command> commands           = psCommand.Commands;
                    if (func2 == null)
                    {
                        func2 = ((Command cmd) => cmd.CommandText);
                    }
                    powerShellResults3.Cmdlets = commands.Select(func2).ToArray <string>();
                    if (powerShellResults.ErrorRecords.Length > 0)
                    {
                        ExTraceGlobals.EventLogTracer.TraceError <string, EcpTraceFormatter <PSCommand>, EcpTraceFormatter <ErrorRecord[]> >(0, 0L, "{0} invoked {1} and encountered errors: {2}", RbacPrincipal.Current.NameForEventLog, psCommand.GetTraceFormatter(), powerShellResults.ErrorRecords.GetTraceFormatter());
                    }
                    CmdExecuteInfo cmdExecuteInfo = CmdletLogger.CaculateLogAndSaveToContext(powerShell, utcNow, powerShellResults.ErrorRecords);
                    if (cmdExecuteInfo != null)
                    {
                        powerShellResults.CmdletLogInfo = new CmdExecuteInfo[]
                        {
                            cmdExecuteInfo
                        };
                    }
                }
            }
            return(powerShellResults);
        }