示例#1
0
        protected bool ExecuteScript(string script, bool handleError, int subSteps, LocalizedString statusDescription)
        {
            bool flag = false;

            if (this.IsCmdletLogEntriesEnabled)
            {
                this.GetCmdletLogEntries().IncreaseIndentation();
            }
            try
            {
                flag = this.InternalExecuteScript(script, handleError, subSteps, statusDescription);
            }
            finally
            {
                if (this.IsCmdletLogEntriesEnabled)
                {
                    if (!flag)
                    {
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ScriptExecutionFailed, this.GetScriptEventParameters(this.GetVerboseInformation(this.GetCmdletLogEntries())));
                    }
                    else
                    {
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ScriptExecutionSuccessfully, this.GetScriptEventParameters(this.GetVerboseInformation(this.GetCmdletLogEntries())));
                    }
                    this.GetCmdletLogEntries().DecreaseIndentation();
                }
            }
            return(flag);
        }
        public object Process(object input)
        {
            object obj = null;

            if (input != null)
            {
                obj = Activator.CreateInstance(this.targetOutputType);
                foreach (Tuple <PropertyInfo, DalConversion> tuple in this.converters)
                {
                    DalConversion item  = tuple.Item2;
                    PropertyInfo  item2 = tuple.Item1;
                    try
                    {
                        item.SetOutput(obj, item2, input, this.parentInstance);
                    }
                    catch (NullReferenceException)
                    {
                        string arg  = (item2 != null) ? item2.Name : "Unknown";
                        string text = string.Format("Null dalObj {0} reportObj {1}", item.DalPropertyName, arg);
                        ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FfoReportingTaskFailure, new string[]
                        {
                            text
                        });
                    }
                }
                IPageableObject pageableObject = obj as IPageableObject;
                if (pageableObject != null && this.pagingIndex != null)
                {
                    pageableObject.Index = this.pagingIndex.Value;
                    this.pagingIndex++;
                }
            }
            return(obj);
        }
        public void WriteDuplicateRuleIdAcrossRulePacksDiagnosticsInformation(int traceSourceHashCode, OrganizationId currentOrganizationId, string offendingRulePackageObjectDn1, string offendingRulePackageObjectDn2, string duplicateRuleId)
        {
            string organizationId = currentOrganizationId.ToString();

            Task.Factory.StartNew(delegate()
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_DuplicateDataClassificationIdAcrossRulePack, new string[]
                {
                    organizationId,
                    duplicateRuleId,
                    offendingRulePackageObjectDn1,
                    offendingRulePackageObjectDn2
                });
            });
            string eventMessage = string.Format("A duplicate data classification identifier '{1}' has been identified in objects with DN '{2}' and '{3}' under organization '{0}'.", new object[]
            {
                organizationId,
                duplicateRuleId,
                offendingRulePackageObjectDn1,
                offendingRulePackageObjectDn2
            });

            Task.Factory.StartNew(delegate()
            {
                EventNotificationItem.Publish(ClassificationDefinitionsDiagnosticsReporter.ServiceName, "ClassificationManagement", "NonUniqueDataClassificationIdentifierFound", eventMessage, ResultSeverityLevel.Warning, false);
            });
            this.dlpTracer.TraceError((long)traceSourceHashCode, eventMessage);
        }
示例#4
0
        private static void WriteNoAdminAuditLogWarningAsNeed(IConfigurationSession configSession)
        {
            bool           flag = true;
            OrganizationId currentOrganizationId = configSession.SessionSettings.CurrentOrganizationId;

            if (currentOrganizationId.ConfigurationUnit != null)
            {
                ExchangeConfigurationUnit exchangeConfigurationUnit = configSession.Read <ExchangeConfigurationUnit>(currentOrganizationId.ConfigurationUnit);
                if (exchangeConfigurationUnit == null)
                {
                    AdminAuditLogHelper.Tracer.TraceDebug <OrganizationId>(0L, "AdminAuditLogHelper: ExchangeConfigurationUnit for org {0} is null", currentOrganizationId);
                }
                else
                {
                    AdminAuditLogHelper.Tracer.TraceDebug <OrganizationId, OrganizationStatus>(0L, "AdminAuditLogHelper: org {0}'s status is {1}", currentOrganizationId, exchangeConfigurationUnit.OrganizationStatus);
                    if (exchangeConfigurationUnit.OrganizationStatus == OrganizationStatus.PendingCompletion)
                    {
                        flag = false;
                    }
                }
            }
            else
            {
                AdminAuditLogHelper.Tracer.TraceDebug <OrganizationId>(0L, "AdminAuditLogHelper: ConfigurationUnit for org {0} is null", currentOrganizationId);
            }
            if (flag)
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_NoAdminAuditLogConfig, new string[]
                {
                    currentOrganizationId.ToString()
                });
            }
        }
示例#5
0
 public static void CheckForError(Task task, PswsCmdlet cmdlet)
 {
     ArgumentValidator.ThrowIfNull("task", task);
     ArgumentValidator.ThrowIfNull("cmdlet", cmdlet);
     if (!string.IsNullOrEmpty(cmdlet.Error))
     {
         string errMsg = cmdlet.Error.ToString();
         EOPRecipient.PublishErrorEvent(errMsg);
         string        text          = "<NULL>";
         Authenticator authenticator = cmdlet.Authenticator as Authenticator;
         if (authenticator != null)
         {
             text = text.ToString();
         }
         ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FfoReportingRecipientTaskFailure, new string[]
         {
             cmdlet.Organization ?? "<NULL>",
             cmdlet.HostServerName ?? "<NULL>",
             cmdlet.ToString() ?? "<NULL>",
             cmdlet.AdditionalHeaders.ToString() ?? "<NULL>",
             (cmdlet.RequestTimeout != null) ? cmdlet.RequestTimeout.Value.ToString() : "<NULL>",
             cmdlet.Exception.ToString() ?? "<NULL>"
         });
         task.WriteError(cmdlet.Exception, ErrorCategory.InvalidOperation, null);
     }
 }
示例#6
0
        internal static void RegisterMigrationBatch(Task task, MailboxSession mailboxSession, OrganizationId organizationId, bool failIfNotConnected, bool refresh = false)
        {
            string     serverFqdn           = mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn;
            Guid       mdbGuid              = mailboxSession.MdbGuid;
            string     mailboxOwnerLegacyDN = mailboxSession.MailboxOwnerLegacyDN;
            ADObjectId organizationName     = organizationId.OrganizationalUnit ?? new ADObjectId();
            int        num = 2;

            for (int i = 1; i <= num; i++)
            {
                try
                {
                    MigrationNotificationRpcStub migrationNotificationRpcStub = new MigrationNotificationRpcStub(serverFqdn);
                    migrationNotificationRpcStub.RegisterMigrationBatch(new RegisterMigrationBatchArgs(mdbGuid, mailboxOwnerLegacyDN, organizationName, refresh));
                    break;
                }
                catch (MigrationServiceRpcException ex)
                {
                    ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_MigrationServiceConnectionError, new string[]
                    {
                        serverFqdn,
                        ex.Message
                    });
                    if (i == num && failIfNotConnected)
                    {
                        MigrationLogger.Log(MigrationEventType.Warning, MigrationLogger.GetDiagnosticInfo(ex, null), new object[0]);
                        task.WriteError(new LocalizedException(Strings.MigrationOperationFailed, null), ExchangeErrorCategory.Client, null);
                    }
                }
            }
        }
 private void HandleInvalidSupportedToolsData(Exception e)
 {
     if (e is FileNotFoundException)
     {
         FileNotFoundException ex = e as FileNotFoundException;
         ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_SupportedToolsInformationFileMissing, new string[]
         {
             ex.FileName
         });
     }
     else if (e is InvalidDataException)
     {
         ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_SupportedToolsInformationDataFileInconsistent, new string[]
         {
             GetToolInformation.GetFilePath("SupportedTools.xml"),
             e.Message
         });
     }
     else
     {
         Exception ex2 = e.InnerException ?? e;
         ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_SupportedToolsInformationDataFileCorupted, new string[]
         {
             GetToolInformation.GetFilePath("SupportedTools.xml"),
             ex2.Message
         });
     }
     base.WriteError(new SupportedToolsDataException(Strings.SupportedToolsUnableToGetToolData), ErrorCategory.InvalidData, null);
 }
示例#8
0
 protected void ThrowAndLogTaskError(Exception e)
 {
     ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FfoReportingTaskFailure, new string[]
     {
         e.ToString()
     });
     this.ThrowTaskError(e);
 }
示例#9
0
 private void LogFailedToUploadPhotoEvent(Exception e)
 {
     ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FailedToUploadPhoto, new string[]
     {
         this.DataObject.ToString(),
         this.DataObject.UserPrincipalName,
         e.ToString()
     });
 }
示例#10
0
        protected override IConfigurable ConvertDataObjectToPresentationObject(IConfigurable dataObject)
        {
            if (dataObject == null)
            {
                return(null);
            }
            ADUser aduser = (ADUser)dataObject;
            UserPhotoConfiguration userPhotoConfiguration = new UserPhotoConfiguration(dataObject.Identity, Stream.Null, null);

            if (CmdletProxy.TryToProxyOutputObject(userPhotoConfiguration, base.CurrentTaskContext, aduser, this.Identity == null, this.ConfirmationMessage, CmdletProxy.AppendIdentityToProxyCmdlet(aduser)))
            {
                return(userPhotoConfiguration);
            }
            IConfigurable result;

            try
            {
                ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(aduser, null);
                using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=Get-UserPhoto"))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        PhotoManagementRetrievalPipeline photoManagementRetrievalPipeline = new PhotoManagementRetrievalPipeline(GetUserPhoto.PhotosConfiguration, mailboxSession, (IRecipientSession)base.DataSession, this.tracer);
                        PhotoResponse  photoResponse = photoManagementRetrievalPipeline.Retrieve(this.CreateRetrievePhotoRequest(exchangePrincipal), memoryStream);
                        HttpStatusCode status        = photoResponse.Status;
                        if (status != HttpStatusCode.OK && status == HttpStatusCode.NotFound)
                        {
                            this.WriteError(new UserPhotoNotFoundException(this.Preview), ExchangeErrorCategory.Client, this.Identity, true);
                            throw new InvalidOperationException();
                        }
                        memoryStream.Seek(0L, SeekOrigin.Begin);
                        result = new UserPhotoConfiguration(dataObject.Identity, memoryStream, photoResponse.Thumbprint);
                    }
                }
            }
            catch (UserPhotoNotFoundException)
            {
                throw;
            }
            catch (Exception ex)
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FailedToRetrievePhoto, new string[]
                {
                    dataObject.ToString(),
                    ((ADUser)dataObject).UserPrincipalName,
                    ex.ToString()
                });
                throw;
            }
            finally
            {
                this.tracer.Dump(new PhotoRequestLogWriter(GetUserPhoto.RequestLog, GetUserPhoto.GenerateRequestId()));
            }
            return(result);
        }
示例#11
0
        internal void TraceException(string msg, Exception exception)
        {
            string text = string.Format(string.Format("{0}\n{1}", msg, Schema.Utilities.GenerateDetailedError(exception)), new object[0]);

            ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FfoReportingTaskFailure, new string[]
            {
                text
            });
            string msg2 = string.Format("{0}:{1}", msg, exception.Message);

            this.Trace(SystemProbe.Status.Fail, msg2);
        }
        protected override void InternalValidate()
        {
            string cmdletName  = SystemConfigurationTasksHelper.GetCmdletName(typeof(GetTransportServer));
            string cmdletName2 = SystemConfigurationTasksHelper.GetCmdletName(typeof(GetTransportService));

            this.WriteWarning(Strings.TransportServerCmdletDeprecated(cmdletName, cmdletName2));
            ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_TransportServerCmdletsDeprecated, new string[]
            {
                cmdletName,
                cmdletName2
            });
            base.InternalValidate();
        }
示例#13
0
        private void HandleSqlConnectionError(IDbConnection connection, SqlException sqlException)
        {
            this.TraceSqlException(sqlException);
            ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_DataMartConnectionFailed, new string[]
            {
                connection.ConnectionString,
                sqlException.Number.ToString(CultureInfo.InvariantCulture),
                sqlException.Message
            });
            LocalizedException localizedException = SqlErrorHandler.TrasnlateConnectionError(sqlException);

            this.TaskContext.WriteError(localizedException, ExchangeErrorCategory.ServerOperation, null);
        }
 private void CheckServices(string[] requiredServices, ADPowerShellVirtualDirectory psVdir)
 {
     foreach (string text in requiredServices)
     {
         if (ManageServiceBase.GetServiceStatus(text) != ServiceControllerStatus.Running)
         {
             ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_RequiredServiceNotRunning, new string[]
             {
                 psVdir.Name,
                 text
             });
             base.WriteVerbose(Strings.CasHealthPowerShellServiceNotRunning(psVdir.Name, text));
             base.TraceInfo(Strings.CasHealthPowerShellServiceNotRunning(psVdir.Name, text));
         }
     }
 }
 private void CheckAppPool(string appPoolName)
 {
     using (ServerManager serverManager = new ServerManager())
     {
         ApplicationPool applicationPool = serverManager.ApplicationPools[appPoolName];
         if (applicationPool != null && applicationPool.State != 1)
         {
             ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_AppPoolNotRunning, new string[]
             {
                 applicationPool.Name
             });
             base.WriteVerbose(Strings.CasHealthPowerShellAppPoolNotRunning(applicationPool.Name));
             base.TraceInfo(Strings.CasHealthPowerShellAppPoolNotRunning(applicationPool.Name));
         }
     }
 }
示例#16
0
 private void HandleSqlConnectionFailOverWarning(IDbConnection connection, SqlException sqlException, IDbConnection backupConnection)
 {
     try
     {
         this.TraceSqlException(sqlException);
         ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_DataMartConnectionFailOverToBackupServer, new string[]
         {
             connection.ConnectionString,
             backupConnection.ConnectionString,
             sqlException.Number.ToString(CultureInfo.InvariantCulture),
             sqlException.Message
         });
     }
     catch (Exception)
     {
     }
 }
示例#17
0
 protected ComponentInfoBasedTask()
 {
     this.monadConnection = new MonadConnection("pooled=false");
     this.monadConnection.Open();
     if (ExManagementApplicationLogger.IsLowEventCategoryEnabled(4))
     {
         this.IsCmdletLogEntriesEnabled         = true;
         base.Fields["CmdletLogEntriesEnabled"] = new bool?(true);
     }
     base.Fields["InstallationMode"]      = InstallationModes.Unknown;
     base.Fields["IsDatacenter"]          = new SwitchParameter(false);
     base.Fields["IsDatacenterDedicated"] = new SwitchParameter(false);
     base.Fields["IsPartnerHosted"]       = new SwitchParameter(false);
     object[] customAttributes = base.GetType().GetCustomAttributes(typeof(CmdletAttribute), false);
     this.taskVerb         = ((CmdletAttribute)customAttributes[0]).VerbName;
     this.taskNoun         = ((CmdletAttribute)customAttributes[0]).NounName;
     this.implementsResume = true;
     this.isResuming       = false;
 }
        public void WriteClassificationEngineConfigurationErrorInformation(int traceSourceHashCode, Exception underlyingException)
        {
            string exceptionDetails = underlyingException.ToString();

            Task.Factory.StartNew(delegate()
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ClassificationEngineConfigurationError, new string[]
                {
                    exceptionDetails
                });
            });
            string eventMessage = string.Format("Unable to obtain information from Microsoft Classification Engine configuration for classification rule collection validation purpose. Error details: {0}", exceptionDetails);

            Task.Factory.StartNew(delegate()
            {
                EventNotificationItem.Publish(ClassificationDefinitionsDiagnosticsReporter.ServiceName, "ClassificationManagement", "MceConfigIssue", eventMessage, ResultSeverityLevel.Warning, false);
            });
            this.dlpTracer.TraceError((long)traceSourceHashCode, eventMessage);
        }
示例#19
0
        public static AdminAuditLogConfig GetAdminAuditLogConfig(IConfigurationSession configSession)
        {
            OrganizationId currentOrganizationId = configSession.SessionSettings.CurrentOrganizationId;

            AdminAuditLogHelper.Tracer.TraceDebug <OrganizationId>(0L, "AdminAuditLogHelper: Will retrieve config objects from AD for OrganizationId: {0}", currentOrganizationId);
            SharedConfiguration   sharedConfiguration  = SharedConfiguration.GetSharedConfiguration(currentOrganizationId);
            IConfigurationSession configurationSession = configSession;

            if (sharedConfiguration != null)
            {
                configurationSession = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(configSession.ConsistencyMode, sharedConfiguration.GetSharedConfigurationSessionSettings(), 160, "GetAdminAuditLogConfig", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\AdminAuditLog\\AdminAuditLogHelper.cs");
            }
            configurationSession.SessionSettings.IsSharedConfigChecked = true;
            bool includeCNFObject = configurationSession.SessionSettings.IncludeCNFObject;

            AdminAuditLogConfig[] array;
            try
            {
                configurationSession.SessionSettings.IncludeCNFObject = false;
                array = configurationSession.Find <AdminAuditLogConfig>(null, QueryScope.SubTree, null, null, 2);
            }
            finally
            {
                configurationSession.SessionSettings.IncludeCNFObject = includeCNFObject;
            }
            if (array.Length == 0)
            {
                AdminAuditLogHelper.Tracer.TraceDebug <OrganizationId>(0L, "AdminAuditLogHelper: No AdminAuditLogConfig was found in org {0}.", currentOrganizationId);
                AdminAuditLogHelper.WriteNoAdminAuditLogWarningAsNeed(configSession);
                return(null);
            }
            if (array.Length > 1)
            {
                AdminAuditLogHelper.Tracer.TraceDebug <OrganizationId>(0L, "AdminAuditLogHelper: More than one AdminAuditLogConfig was found in org {0}.", currentOrganizationId);
                ExManagementApplicationLogger.LogEvent(currentOrganizationId, ManagementEventLogConstants.Tuple_MultipleAdminAuditLogConfig, new string[]
                {
                    currentOrganizationId.ToString()
                });
                throw new MultipleAdminAuditLogConfigException(currentOrganizationId.ToString());
            }
            AdminAuditLogHelper.Tracer.TraceDebug <OrganizationId, bool>(0L, "AdminAuditLogHelper: One AdminAuditLogConfig was found in org {0}. Logging enabled is {1}.", currentOrganizationId, array[0].AdminAuditLogEnabled);
            return(array[0]);
        }
示例#20
0
        public static MailboxDatabase ChooseTargetMDB(IEnumerable <ADObjectId> excludedDatabaseIds, bool checkInitialProvisioningSetting, ADUser adUser, Fqdn domainController, ScopeSet scopeSet, Action <LocalizedString> writeVerbose, Action <LocalizedException, ExchangeErrorCategory, object> writeExchangeError, Action <Exception, ErrorCategory, object> writeError, object identity)
        {
            MailboxProvisioningConstraint   mailboxProvisioningConstraint   = (adUser == null) ? new MailboxProvisioningConstraint() : adUser.MailboxProvisioningConstraint;
            LoadBalancingReport             loadBalancingReport             = new LoadBalancingReport();
            MailboxDatabaseWithLocationInfo mailboxDatabaseWithLocationInfo = PhysicalResourceLoadBalancing.FindDatabaseAndLocation(domainController, delegate(string msg)
            {
                writeVerbose(new LocalizedString(msg));
            }, scopeSet, checkInitialProvisioningSetting, false, new int?(Server.E15MinVersion), mailboxProvisioningConstraint, excludedDatabaseIds, ref loadBalancingReport);

            if (mailboxDatabaseWithLocationInfo == null)
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_LoadBalancingFailedToFindDatabase, new string[]
                {
                    domainController,
                    loadBalancingReport.ToString()
                });
                writeExchangeError(new RecipientTaskException(Strings.ErrorAutomaticProvisioningFailedToFindDatabase("TargetDatabase")), ExchangeErrorCategory.ServerOperation, null);
            }
            return(mailboxDatabaseWithLocationInfo.MailboxDatabase);
        }
        public void WriteClassificationEngineUnexpectedFailureInValidation(int traceSourceHashCode, OrganizationId currentOrganizationId, int engineErrorCode)
        {
            string organizationId     = (!object.ReferenceEquals(currentOrganizationId, null)) ? currentOrganizationId.ToString() : string.Empty;
            string hexEngineErrorCode = engineErrorCode.ToString("X8");

            Task.Factory.StartNew(delegate()
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ClassificationEngineFailure, new string[]
                {
                    organizationId,
                    string.Format("0x{0}", hexEngineErrorCode)
                });
            });
            string eventMessage = string.Format("MCE returned an error when trying to validate a classification rule collection for organization '{0}'. Error code returned was 0x{1}.", organizationId, hexEngineErrorCode);

            Task.Factory.StartNew(delegate()
            {
                EventNotificationItem.Publish(ClassificationDefinitionsDiagnosticsReporter.ServiceName, "ClassificationManagement", "MceFailureIssue", eventMessage, ResultSeverityLevel.Error, false);
            });
            this.dlpTracer.TraceError((long)traceSourceHashCode, eventMessage);
        }
        public void WriteClassificationEngineTimeoutInValidation(int traceSourceHashCode, OrganizationId currentOrganizationId, int validationTimeout)
        {
            string organizationId = (!object.ReferenceEquals(currentOrganizationId, null)) ? currentOrganizationId.ToString() : string.Empty;
            string timeout        = validationTimeout.ToString(CultureInfo.InvariantCulture);

            Task.Factory.StartNew(delegate()
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_ClassificationEngineTimeout, new string[]
                {
                    organizationId,
                    timeout
                });
            });
            string eventMessage = string.Format("MCE timed-out when trying to validate a classification rule collection for organization '{0}'. The operation timeout was {1} ms.", organizationId, timeout);

            Task.Factory.StartNew(delegate()
            {
                EventNotificationItem.Publish(ClassificationDefinitionsDiagnosticsReporter.ServiceName, "ClassificationManagement", "MceTimeoutIssue", eventMessage, ResultSeverityLevel.Error, false);
            });
            this.dlpTracer.TraceError((long)traceSourceHashCode, eventMessage);
        }
        public void WriteCorruptRulePackageDiagnosticsInformation(int traceSourceHashCode, OrganizationId currentOrganizationId, string offendingRulePackageObjectDn, Exception underlyingException)
        {
            string organizationId   = currentOrganizationId.ToString();
            string exceptionDetails = underlyingException.ToString();

            Task.Factory.StartNew(delegate()
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_CorruptClassificationRuleCollection, new string[]
                {
                    organizationId,
                    offendingRulePackageObjectDn,
                    exceptionDetails
                });
            });
            string eventMessage = string.Format("A corrupted classification rule collection has been identified under organization: '{0}'. Source object DN: {1}. Error details: {2}", organizationId, offendingRulePackageObjectDn, exceptionDetails);

            Task.Factory.StartNew(delegate()
            {
                EventNotificationItem.Publish(ClassificationDefinitionsDiagnosticsReporter.ServiceName, "ClassificationManagement", "CorruptClassificationRuleCollection", eventMessage, ResultSeverityLevel.Warning, false);
            });
            this.dlpTracer.TraceError((long)traceSourceHashCode, eventMessage);
        }
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            this.InternalBeginProcessing();
            string text = this.rootDomain.Id.ToDNString();

            foreach (Tuple <string, List <SecurityIdentifier>, List <SecurityIdentifier> > tuple in InitializeDkmDatacenter.DkmContainersToCreate)
            {
                try
                {
                    DkmProxy dkmProxy = null;
                    try
                    {
                        this.CreateDkmContainer(tuple.Item1, string.Format("{0},{1}", "CN=Microsoft,CN=Program Data", text), out dkmProxy);
                    }
                    catch (ObjectAlreadyExistsException)
                    {
                        this.WriteWarning(Strings.DkmContainerAlreadyExists(tuple.Item1));
                    }
                    if (dkmProxy != null)
                    {
                        this.RemoveUnwantedDkmContainerAccessRules(tuple.Item1, tuple.Item2, tuple.Item3, text);
                        InitializeDkmDatacenter.SetDkmContainerAccessRules(dkmProxy, tuple.Item2, tuple.Item3);
                    }
                }
                catch (Exception ex)
                {
                    this.WriteWarning(Strings.DkmProvisioningException(tuple.Item1, ex));
                    ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_DkmProvisioningException, new string[]
                    {
                        ex.ToString()
                    });
                    throw;
                }
            }
            ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_DkmProvisioningSuccessful, new string[0]);
            TaskLogger.LogExit();
        }
示例#25
0
        private static void UpdateRecipients(EmailAddressPolicy eap, OrganizationId organizationId, string domainController, IRecipientSession globalCatalogSession, Task.TaskVerboseLoggingDelegate writeVerbose, Task.TaskWarningLoggingDelegate writeWarning, WriteProgress writeProgress, Task cmdlet, bool fixMissingAlias)
        {
            UpdateEmailAddressPolicy.AssertArgumentNotNull(eap, "eap");
            UpdateEmailAddressPolicy.AssertArgumentNotNull(writeVerbose, "writeVerbose");
            UpdateEmailAddressPolicy.AssertArgumentNotNull(writeWarning, "writeWarning");
            UpdateEmailAddressPolicy.AssertArgumentNotNull(writeProgress, "writeProgress");
            if (string.IsNullOrEmpty(eap.LdapRecipientFilter) && !fixMissingAlias)
            {
                return;
            }
            int num = 0;

            try
            {
                if (cmdlet != null && cmdlet.Stopping)
                {
                    return;
                }
                IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(false, ConsistencyMode.PartiallyConsistent, globalCatalogSession.SessionSettings, 409, "UpdateRecipients", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\RecipientPolicy\\UpdateEmailAddressPolicy.cs");
                tenantOrRootOrgRecipientSession.EnforceDefaultScope = false;
                IEnumerable <ADRecipient> enumerable = eap.FindMatchingRecipientsPaged(globalCatalogSession, organizationId, null, fixMissingAlias);
                string    text      = null;
                Hashtable hashtable = new Hashtable();
                foreach (ADRecipient adrecipient in enumerable)
                {
                    if (cmdlet != null && cmdlet.Stopping)
                    {
                        return;
                    }
                    if (!string.IsNullOrEmpty(domainController) && string.IsNullOrEmpty(text))
                    {
                        try
                        {
                            string configurationDomainControllerFqdn = SystemConfigurationTasksHelper.GetConfigurationDomainControllerFqdn(domainController);
                            int    num2 = configurationDomainControllerFqdn.IndexOf(".");
                            if (0 <= num2)
                            {
                                text = configurationDomainControllerFqdn.Substring(num2);
                            }
                        }
                        catch (SocketException ex)
                        {
                            writeWarning(Strings.ErrorResolveFqdnForDomainController(domainController, ex.Message));
                            return;
                        }
                    }
                    string text2 = adrecipient.Id.DomainId.DistinguishedName.ToLowerInvariant();
                    if (!hashtable.ContainsKey(text2))
                    {
                        SystemConfigurationTasksHelper.PrepareDomainControllerRecipientSessionForUpdate(tenantOrRootOrgRecipientSession, adrecipient.Id, domainController, text);
                        IEnumerable <ADRecipient> collection = eap.FindMatchingRecipientsPaged(tenantOrRootOrgRecipientSession, organizationId, adrecipient.Id, fixMissingAlias);
                        List <ADRecipient>        list       = new List <ADRecipient>();
                        Exception ex2 = null;
                        Exception ex3 = null;
                        try
                        {
                            list.AddRange(collection);
                        }
                        catch (DataSourceOperationException ex4)
                        {
                            TaskLogger.Trace("Exception caught when re-read recipient from DC : {0}", new object[]
                            {
                                ex4.ToString()
                            });
                            if (ex4.InnerException is ActiveDirectoryObjectNotFoundException || ex4.InnerException is AuthenticationException)
                            {
                                ex3 = ex4;
                            }
                            else
                            {
                                ex2 = ex4;
                            }
                        }
                        catch (DataSourceTransientException ex5)
                        {
                            TaskLogger.Trace("Exception caught when re-read recipient from DC : {0}", new object[]
                            {
                                ex5.ToString()
                            });
                            if (ex5.InnerException is ActiveDirectoryOperationException || ex5.InnerException is ActiveDirectoryServerDownException)
                            {
                                ex3 = ex5;
                            }
                            else
                            {
                                ex2 = ex5;
                            }
                        }
                        if (ex3 != null)
                        {
                            hashtable.Add(text2, null);
                            writeWarning(Strings.ErrorCannotUpdateRecipientOfDomain(DNConvertor.FqdnFromDomainDistinguishedName(text2), ex3.Message));
                        }
                        else if (ex2 != null)
                        {
                            writeWarning(Strings.ErrorFailedToReadRecipientForUpdate(adrecipient.Id.ToString(), ex2.Message));
                        }
                        else if (1 == list.Count)
                        {
                            ADRecipient adrecipient2 = list[0];
                            if (cmdlet != null && cmdlet.Stopping)
                            {
                                return;
                            }
                            num = num++ % 99 + 1;
                            writeProgress(Strings.ProgressActivityUpdateRecipient, Strings.ProgressStatusUpdateRecipient(adrecipient2.Id.ToString()), num);
                            writeVerbose(Strings.ProgressStatusUpdateRecipient(adrecipient2.Id.ToString()));
                            try
                            {
                                if (fixMissingAlias && string.IsNullOrEmpty(adrecipient2.Alias))
                                {
                                    if (adrecipient2 is ADMicrosoftExchangeRecipient)
                                    {
                                        adrecipient2.Alias = RecipientTaskHelper.GenerateUniqueAlias(globalCatalogSession, adrecipient2.OrganizationId, ADMicrosoftExchangeRecipient.DefaultName, writeVerbose);
                                    }
                                    else if (adrecipient2 is ADSystemAttendantMailbox)
                                    {
                                        adrecipient2.Alias = RecipientTaskHelper.GenerateUniqueAlias(globalCatalogSession, adrecipient2.OrganizationId, (adrecipient2 as ADSystemAttendantMailbox).ServerName + "-SA", writeVerbose);
                                    }
                                    else
                                    {
                                        adrecipient2.Alias = RecipientTaskHelper.GenerateUniqueAlias(globalCatalogSession, adrecipient2.OrganizationId, adrecipient2.Name, writeVerbose);
                                    }
                                    writeWarning(Strings.WarningGeneratingMissingAlias(adrecipient2.Identity.ToString(), adrecipient2.Alias));
                                }
                                if (!adrecipient2.IsReadOnly)
                                {
                                    ProvisioningLayer.UpdateAffectedIConfigurable(cmdlet, RecipientTaskHelper.ConvertRecipientToPresentationObject(adrecipient2), true);
                                }
                                if (!adrecipient2.IsValid || adrecipient2.IsReadOnly)
                                {
                                    writeWarning(Strings.ErrorCannotUpdateInvalidRecipient(adrecipient2.Id.ToString()));
                                }
                                else
                                {
                                    if (cmdlet.IsVerboseOn && adrecipient2.ObjectState != ObjectState.Unchanged)
                                    {
                                        writeVerbose(TaskVerboseStringHelper.GetConfigurableObjectChangedProperties(adrecipient2));
                                    }
                                    tenantOrRootOrgRecipientSession.Save(adrecipient2);
                                }
                            }
                            catch (DataSourceTransientException ex6)
                            {
                                writeWarning(Strings.ErrorUpdateRecipient(adrecipient2.Id.ToString(), ex6.Message));
                                TaskLogger.Trace("Exception is raised while updating recipient '{0}': {1}", new object[]
                                {
                                    adrecipient2.Id.ToString(),
                                    ex6.Message
                                });
                            }
                            catch (DataSourceOperationException ex7)
                            {
                                writeWarning(Strings.ErrorUpdateRecipient(adrecipient2.Id.ToString(), ex7.Message));
                                TaskLogger.Trace("Exception is raised while updating recipient '{0}': {1}", new object[]
                                {
                                    adrecipient2.Id.ToString(),
                                    ex7.Message
                                });
                            }
                            catch (DataValidationException ex8)
                            {
                                writeWarning(Strings.ErrorUpdateRecipient(adrecipient2.Id.ToString(), ex8.Message));
                                TaskLogger.Trace("Exception is raised while updating recipient '{0}': {1}", new object[]
                                {
                                    adrecipient2.Id.ToString(),
                                    ex8.Message
                                });
                            }
                        }
                    }
                }
            }
            finally
            {
                if (cmdlet != null && cmdlet.Stopping)
                {
                    ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_RecipientsUpdateForEmailAddressPolicyCancelled, new string[]
                    {
                        eap.Identity.ToString(),
                        eap.LdapRecipientFilter,
                        ADRecipientSchema.EmailAddresses.Name
                    });
                }
            }
            if (num != 0)
            {
                writeVerbose(Strings.ProgressStatusFinished);
                writeProgress(Strings.ProgressActivityUpdateRecipient, Strings.ProgressStatusFinished, 100);
            }
        }
示例#26
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);
        }
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            List <string> list          = new List <string>();
            StringBuilder stringBuilder = null;

            string[] instanceNames = MSExchangeTenantMonitoring.GetInstanceNames();
            if (instanceNames != null)
            {
                foreach (string text in instanceNames)
                {
                    if (!string.Equals("_total", text, StringComparison.OrdinalIgnoreCase) && this.CheckInstance(text))
                    {
                        MSExchangeTenantMonitoringInstance instance = MSExchangeTenantMonitoring.GetInstance(text);
                        double valueForCounter  = this.GetValueForCounter(instance, this.CounterNameForAttempts);
                        double valueForCounter2 = this.GetValueForCounter(instance, this.CounterNameForSuccesses);
                        if (valueForCounter != this.GetValueForCounter(instance, this.CounterNameForAttempts) || valueForCounter2 != this.GetValueForCounter(instance, this.CounterNameForSuccesses))
                        {
                            ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_IgnoringInstanceData, new string[]
                            {
                                text
                            });
                        }
                        else if (valueForCounter > 0.0 && valueForCounter >= this.MinimumCountForAlert && valueForCounter2 / valueForCounter * 100.0 < this.SuccessThresholdPercentage)
                        {
                            if (stringBuilder == null)
                            {
                                stringBuilder = new StringBuilder(text);
                            }
                            else if (list.Count < 10)
                            {
                                stringBuilder.AppendFormat(", {0}", text);
                            }
                            list.Add(text);
                            ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_InstanceAboveThreshold, new string[]
                            {
                                text,
                                valueForCounter.ToString(),
                                valueForCounter2.ToString()
                            });
                        }
                    }
                }
                if (list.Count > 0)
                {
                    stringBuilder.AppendFormat(", TotalFailingInstances={0}", list.Count);
                }
            }
            string text2 = (stringBuilder != null) ? stringBuilder.ToString() : string.Empty;

            if (!string.IsNullOrEmpty(text2))
            {
                if (TestTenantMonitoringPerfCounters.eventIdDictionary.ContainsKey(this.EventId))
                {
                    ExManagementApplicationLogger.LogEvent(TestTenantMonitoringPerfCounters.eventIdDictionary[this.EventId], new string[]
                    {
                        text2,
                        this.CounterNameForAttempts,
                        this.CounterNameForSuccesses,
                        this.MinimumCountForAlert.ToString(),
                        this.SuccessThresholdPercentage.ToString(),
                        this.GetFailureDetails(list, this.CounterNameForAttempts)
                    });
                }
            }
            else
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_TenantMonitoringSuccess, new string[]
                {
                    this.CounterNameForAttempts,
                    this.CounterNameForSuccesses
                });
            }
            base.InternalProcessRecord();
            TaskLogger.LogExit();
        }
        private string GetFailureDetails(List <string> instances, string counterNameForAttempts)
        {
            List <string> cmdletNamesFromAttemptsCounterName = this.GetCmdletNamesFromAttemptsCounterName(counterNameForAttempts);

            if (cmdletNamesFromAttemptsCounterName.Count == 0 || instances == null)
            {
                return(string.Empty);
            }
            string result;

            try
            {
                List <string> list = new List <string>();
                foreach (string instanceName in instances)
                {
                    string item = null;
                    if (ProvisioningMonitoringConfig.TryGetOrganizationNameFromInstanceName(instanceName, ref item))
                    {
                        list.Add(item);
                    }
                }
                if (list.Count == 0)
                {
                    result = string.Empty;
                }
                else
                {
                    TimeSpan      timeSpan      = IntervalCounterInstanceCache.UpdateInterval + IntervalCounterInstanceCache.UpdateInterval;
                    DateTime      t             = this.startTime.Add(timeSpan.Negate());
                    StringBuilder stringBuilder = new StringBuilder();
                    using (EventLog eventLog = new EventLog())
                    {
                        eventLog.Log = "MSExchange Management";
                        EventLogEntryCollection entries = eventLog.Entries;
                        int count = entries.Count;
                        for (int i = count - 1; i >= 0; i--)
                        {
                            EventLogEntry eventLogEntry = entries[i];
                            if (eventLogEntry.TimeGenerated < t)
                            {
                                break;
                            }
                            if (eventLogEntry.ReplacementStrings != null && eventLogEntry.ReplacementStrings.Length >= 14 && eventLogEntry.ReplacementStrings[0] != null && eventLogEntry.EntryType == EventLogEntryType.Error && cmdletNamesFromAttemptsCounterName.Contains(eventLogEntry.ReplacementStrings[0].ToLowerInvariant()))
                            {
                                foreach (string text in list.ToArray())
                                {
                                    if ((eventLogEntry.ReplacementStrings[1] != null && eventLogEntry.ReplacementStrings[1].IndexOf(text, StringComparison.OrdinalIgnoreCase) != -1) || (eventLogEntry.ReplacementStrings[7] != null && eventLogEntry.ReplacementStrings[7].IndexOf(text, StringComparison.OrdinalIgnoreCase) != -1))
                                    {
                                        stringBuilder.AppendLine("Invocation: ");
                                        foreach (string value in eventLogEntry.ReplacementStrings)
                                        {
                                            stringBuilder.AppendLine(value);
                                        }
                                        list.Remove(text);
                                        break;
                                    }
                                }
                                if (list.Count == 0 || stringBuilder.Length > 10000)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    if (stringBuilder.Length > 10000)
                    {
                        stringBuilder.Remove(10000, stringBuilder.Length - 10000);
                        stringBuilder.Append("...");
                    }
                    result = stringBuilder.ToString();
                }
            }
            catch (Exception ex)
            {
                if (instances.Count > 10)
                {
                    instances = instances.GetRange(0, 10);
                }
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FailToRetrieveErrorDetails, new string[]
                {
                    counterNameForAttempts,
                    string.Join(", ", instances.ToArray()),
                    ex.ToString()
                });
                result = string.Empty;
            }
            return(result);
        }
示例#29
0
        internal static void UpdateRecipients(AddressBookBase abb, ADObjectId[] removedAbbTreeIds, string domainController, IRecipientSession globalCatalogSession, Task.TaskWarningLoggingDelegate writeWarning, WriteProgress writeProgress, Cmdlet cmdlet)
        {
            if (abb == null)
            {
                throw new ArgumentNullException("abb");
            }
            if (Guid.Empty == abb.Guid)
            {
                throw new ArgumentNullException("abb.Guid");
            }
            if (writeWarning == null)
            {
                throw new ArgumentNullException("writeWarning");
            }
            if (writeProgress == null)
            {
                throw new ArgumentNullException("writeProgress");
            }
            int num = 0;

            try
            {
                if (cmdlet != null && cmdlet.Stopping)
                {
                    return;
                }
                string domainControllerFqdn = null;
                if (!string.IsNullOrEmpty(domainController))
                {
                    try
                    {
                        domainControllerFqdn = SystemConfigurationTasksHelper.GetConfigurationDomainControllerFqdn(domainController);
                    }
                    catch (SocketException ex)
                    {
                        writeWarning(Strings.ErrorResolveFqdnForDomainController(domainController, ex.Message));
                        return;
                    }
                }
                if (string.IsNullOrEmpty(abb.LdapRecipientFilter) || removedAbbTreeIds != null)
                {
                    List <Guid> list = new List <Guid>();
                    if (removedAbbTreeIds != null)
                    {
                        foreach (ADObjectId adobjectId in removedAbbTreeIds)
                        {
                            list.Add(adobjectId.ObjectGuid);
                        }
                        list.Sort();
                    }
                    else
                    {
                        list.Add(abb.Guid);
                    }
                    QueryFilter[] array = null;
                    int           num2  = LdapFilterBuilder.MaxCustomFilterTreeSize - 1;
                    for (int j = 0; j < list.Count; j += num2)
                    {
                        int num3 = Math.Min(num2, list.Count - j);
                        if (array == null || array.Length != num3)
                        {
                            array = new QueryFilter[num3];
                        }
                        for (int k = 0; k < num3; k++)
                        {
                            array[k] = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.AddressListMembership, new ADObjectId(list[k + j]));
                        }
                        QueryFilter queryFilter = new OrFilter(array);
                        ADPagedReader <ADRecipient> adpagedReader = globalCatalogSession.FindPaged(null, QueryScope.SubTree, queryFilter, null, 0);
                        using (IEnumerator <ADRecipient> enumerator = adpagedReader.GetEnumerator())
                        {
                            UpdateAddressBookBase <TIdParameter> .InternalUpdateRecipients(enumerator, null, queryFilter, list, domainControllerFqdn, globalCatalogSession, writeWarning, writeProgress, cmdlet, ref num);
                        }
                    }
                }
                else
                {
                    IEnumerator <ADRecipient> enumerator2 = abb.FindUpdatingRecipientsPaged(globalCatalogSession, null).GetEnumerator();
                    UpdateAddressBookBase <TIdParameter> .InternalUpdateRecipients(enumerator2, abb, null, null, domainControllerFqdn, globalCatalogSession, writeWarning, writeProgress, cmdlet, ref num);
                }
            }
            finally
            {
                if (cmdlet != null && cmdlet.Stopping)
                {
                    ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_RecipientsUpdateForAddressBookCancelled, new string[]
                    {
                        string.Format("{0} (objectGUID=<{1}>)", abb.DistinguishedName ?? string.Empty, abb.Guid.ToString()),
                        abb.LdapRecipientFilter,
                        ADRecipientSchema.AddressListMembership.Name
                    });
                }
            }
            if (num != 0)
            {
                writeProgress(Strings.ProgressActivityUpdateRecipient, Strings.ProgressStatusFinished, 100);
            }
        }
示例#30
0
        public string GetConnectionString(DataMartType dataMartType, bool backup = false)
        {
            string result;

            try
            {
                string text = this.dataMartKeyMapping[dataMartType];
                string key  = string.Format(CultureInfo.InvariantCulture, "{0}Server", new object[]
                {
                    text
                });
                string text2 = DataMart.GetConfiguration(dataMartType, this.dataMartServerMapping, key);
                if (backup)
                {
                    text2 = this.GetBackupServer(dataMartType);
                    if (string.IsNullOrEmpty(text2))
                    {
                        return(string.Empty);
                    }
                }
                else
                {
                    string text3 = Environment.MachineName.Substring(0, 3).ToUpper();
                    if (text2.ToUpper().StartsWith("CDM-TENANTDS."))
                    {
                        text2 = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.exmgmt.local", new object[]
                        {
                            "CDM-TENANTDS",
                            text3
                        });
                    }
                    else if (text2.ToUpper().StartsWith("CDM-TENANTDS-SCALED."))
                    {
                        text2 = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.exmgmt.local", new object[]
                        {
                            "CDM-TENANTDS-SCALED",
                            text3
                        });
                    }
                }
                string key2 = string.Format(CultureInfo.InvariantCulture, "{0}Database", new object[]
                {
                    text
                });
                string configuration = DataMart.GetConfiguration(dataMartType, this.dataMartDatabaseMapping, key2);
                if (DataMart.connectionTimeout == -1)
                {
                    DataMart.connectionTimeout = DataMart.LoadSettingFromRegistry <int>("SQLConnectionTimeout");
                    DataMart.ValidateIntegerInRange("SQLConnectionTimeout", DataMart.connectionTimeout, 1, 180);
                }
                string text4 = string.Format(CultureInfo.InvariantCulture, "Server={0};Database={1};Integrated Security=SSPI;Connection Timeout={2}", new object[]
                {
                    text2,
                    configuration,
                    DataMart.connectionTimeout
                });
                result = text4;
            }
            catch (DataMartConfigurationException ex)
            {
                ExTraceGlobals.LogTracer.TraceError <DataMartConfigurationException>(0L, "Load data mart configuration error: {0}", ex);
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_DataMartConfigurationError, new string[]
                {
                    ex.Message
                });
                throw;
            }
            return(result);
        }