Beispiel #1
0
        protected override void InternalValidate()
        {
            if (base.OptionalIdentityData != null)
            {
                base.OptionalIdentityData.ConfigurationContainerRdn = ClassificationDefinitionConstants.ClassificationDefinitionsRdn;
            }
            base.InternalValidate();
            if (base.HasErrors)
            {
                return;
            }
            ExAssert.RetailAssert(base.DataObject != null, "DataObject must not be null at this point as it should have been resolved by the base class.");
            if (!ClassificationDefinitionUtils.IsAdObjectAClassificationRuleCollection(base.DataObject))
            {
                base.WriteError(new ClassificationRuleCollectionInvalidObjectException(Strings.ClassificationRuleCollectionInvalidObject), ErrorCategory.InvalidOperation, null);
            }
            if (VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).Global.MultiTenancy.Enabled&& OrganizationId.ForestWideOrgId.Equals(((IDirectorySession)base.DataSession).SessionSettings.CurrentOrganizationId) && !this.Identity.IsHierarchical)
            {
                base.WriteError(new ClassificationRuleCollectionIllegalScopeException(Strings.ClassificationRuleCollectionIllegalScopedRemoveOperation), ErrorCategory.InvalidOperation, null);
            }
            SortedSet <string> sortedSet     = new SortedSet <string>();
            IList <string>     allRulesInUse = this.GetAllRulesInUse(base.DataObject, sortedSet);

            if (allRulesInUse.Count > 0)
            {
                LocalizedString message = Strings.ClassificationRuleCollectionSharingViolationRemoveOperationVerbose(this.Identity.ToString(), string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, allRulesInUse), string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, sortedSet));
                ClassificationRuleCollectionSharingViolationException exception = ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionSharingViolationException, IList <string> >(new ClassificationRuleCollectionSharingViolationException(message), allRulesInUse);
                base.WriteError(exception, ErrorCategory.InvalidOperation, null);
            }
        }
        protected override IConfigurable PrepareDataObject()
        {
            TaskLogger.LogEnter();
            TransportRule transportRule;

            if (this.InstallDefaultCollection && this.existingRulePack != null)
            {
                transportRule = this.existingRulePack;
            }
            else
            {
                transportRule = (TransportRule)base.PrepareDataObject();
                transportRule.SetId(ClassificationDefinitionUtils.GetClassificationRuleCollectionContainerId(base.DataSession).GetChildId(this.rulePackageIdentifier));
                transportRule.OrganizationId = base.CurrentOrganizationId;
            }
            byte[] replicationSignature = null;
            try
            {
                replicationSignature = ClassificationRuleCollectionValidationUtils.PackAndValidateCompressedRulePackage(this.FileData, this.validationContext);
            }
            catch (LocalizedException exception)
            {
                base.WriteError(exception, ErrorCategory.InvalidData, null);
            }
            transportRule.AdminDisplayName = this.defaultName;
            transportRule.Xml = null;
            transportRule.ReplicationSignature = replicationSignature;
            TaskLogger.LogExit();
            return(transportRule);
        }
        private static IEnumerable <QueryMatchResult> ExecuteQueryMatching(IEnumerable <QueryMatchResult> mainQuery, Func <Dictionary <string, QueryMatchResult>, IEnumerable <KeyValuePair <string, XElement> > > queryForResolvingRuleAssociation, Action <Dictionary <string, QueryMatchResult>, KeyValuePair <string, XElement> > setAssociationData, Func <string, LocalizedString> createErrorMessageForMissingAssociation)
        {
            Dictionary <string, QueryMatchResult> queryMatchResults;

            try
            {
                queryMatchResults = mainQuery.ToDictionary((QueryMatchResult queryMatchResult) => queryMatchResult.MatchingRuleId, ClassificationDefinitionConstants.RuleIdComparer);
                if (queryMatchResults.Count == 0)
                {
                    return(Enumerable.Empty <QueryMatchResult>());
                }
                Dictionary <string, XElement> matchingAssociatedElements = queryForResolvingRuleAssociation(queryMatchResults).ToDictionary((KeyValuePair <string, XElement> ruleIdRefAndResourceElement) => ruleIdRefAndResourceElement.Key, (KeyValuePair <string, XElement> ruleIdRefAndResourceElement) => ruleIdRefAndResourceElement.Value, ClassificationDefinitionConstants.RuleIdComparer);
                if (queryMatchResults.Count != matchingAssociatedElements.Count)
                {
                    List <string> list = (from ruleId in queryMatchResults.Keys
                                          where !matchingAssociatedElements.ContainsKey(ruleId)
                                          select ruleId).ToList <string>();
                    LocalizedString value = createErrorMessageForMissingAssociation(string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list));
                    throw ClassificationDefinitionUtils.PopulateExceptionSource <XmlException, List <string> >(new XmlException(value), list);
                }
                Parallel.ForEach <KeyValuePair <string, XElement> >(matchingAssociatedElements, delegate(KeyValuePair <string, XElement> matchingAssociation)
                {
                    setAssociationData(queryMatchResults, matchingAssociation);
                });
            }
            catch (AggregateException ex)
            {
                throw new XmlException(Strings.ClassificationRuleCollectionUnexpectedContents, ex.Flatten());
            }
            return(queryMatchResults.Values);
        }
Beispiel #4
0
        private XDocument TryGetRuleCollectionDocumentFromTransportRule(TransportRule transportRule)
        {
            XDocument result = null;

            try
            {
                result = ClassificationDefinitionUtils.GetRuleCollectionDocumentFromTransportRule(transportRule);
            }
            catch (InvalidOperationException)
            {
                ClassificationDefinitionsDiagnosticsReporter.Instance.WriteInvalidObjectInformation(this.GetHashCode(), transportRule.OrganizationId, transportRule.DistinguishedName);
            }
            catch (ArgumentException underlyingException)
            {
                ClassificationDefinitionsDiagnosticsReporter.Instance.WriteCorruptRulePackageDiagnosticsInformation(this.GetHashCode(), transportRule.OrganizationId, transportRule.DistinguishedName, underlyingException);
            }
            catch (AggregateException ex)
            {
                ClassificationDefinitionsDiagnosticsReporter.Instance.WriteCorruptRulePackageDiagnosticsInformation(this.GetHashCode(), transportRule.OrganizationId, transportRule.DistinguishedName, ex.Flatten());
            }
            catch (XmlException ex2)
            {
                ClassificationDefinitionsDiagnosticsReporter.Instance.WriteCorruptRulePackageDiagnosticsInformation(this.GetHashCode(), transportRule.OrganizationId, transportRule.DistinguishedName, new AggregateException(new Exception[]
                {
                    ex2
                }).Flatten());
            }
            return(result);
        }
        private bool TryParseADRulePack(TransportRule adRulePack, out XDocument rulePackXDocument)
        {
            ArgumentValidator.ThrowIfNull("adRulePack", adRulePack);
            rulePackXDocument = null;
            Exception ex = null;

            try
            {
                rulePackXDocument = ClassificationDefinitionUtils.GetRuleCollectionDocumentFromTransportRule(adRulePack);
            }
            catch (ArgumentException ex2)
            {
                ex = ex2;
            }
            catch (AggregateException ex3)
            {
                ex = ex3;
            }
            catch (XmlException ex4)
            {
                ex = ex4;
            }
            if (ex != null)
            {
                this.task.WriteWarning(Strings.WarningInvalidRuleCollectionADObject(adRulePack.Identity.ToString(), ex.Message));
            }
            return(rulePackXDocument != null);
        }
Beispiel #6
0
        protected virtual void Initialize()
        {
            ExAssert.RetailAssert(this.StoredRuleCollection != null, "The stored transport rule instance for classification rule collection presentation object must not be null");
            XDocument ruleCollectionDocumentFromTransportRule = ClassificationDefinitionUtils.GetRuleCollectionDocumentFromTransportRule(this.StoredRuleCollection);

            this.Initialize(ruleCollectionDocumentFromTransportRule);
        }
        protected override void WriteResult(IConfigurable dataObject)
        {
            TaskLogger.LogEnter();
            TransportRule transportRule = dataObject as TransportRule;

            if (transportRule != null)
            {
                XDocument ruleCollectionDocumentFromTransportRule = ClassificationDefinitionUtils.GetRuleCollectionDocumentFromTransportRule(transportRule);
                if (ruleCollectionDocumentFromTransportRule != null)
                {
                    string[] ruleIdQueries = new string[]
                    {
                        ((DataClassificationObjectId)this.implementation.DataClassificationPresentationObject.Identity).Name
                    };
                    List <QueryMatchResult> list = XmlProcessingUtils.GetMatchingRulesById(ruleCollectionDocumentFromTransportRule, ruleIdQueries).ToList <QueryMatchResult>();
                    if (list.Count > 0)
                    {
                        ClassificationRuleCollectionPresentationObject rulePackPresentationObject = ClassificationRuleCollectionPresentationObject.Create(transportRule);
                        DataClassificationPresentationObject           result = DataClassificationPresentationObject.Create(list[0].MatchingRuleId, list[0].MatchingRuleXElement, list[0].MatchingResourceXElement, rulePackPresentationObject);
                        this.WriteResult(result);
                    }
                }
            }
            else
            {
                base.WriteResult(dataObject);
            }
            TaskLogger.LogExit();
        }
        internal static XDocument CreateRuleCollectionDocumentFromTemplate(string rulePackId, string organizationId, string organizationName)
        {
            ArgumentValidator.ThrowIfNullOrEmpty("rulePackId", rulePackId);
            ArgumentValidator.ThrowIfNullOrEmpty("organizationId", organizationId);
            ArgumentValidator.ThrowIfNullOrEmpty("organizationName", organizationName);
            string text = string.Empty;

            using (Stream stream = ClassificationDefinitionUtils.LoadStreamFromEmbeddedResource("FingerprintRulePackTemplate.xml"))
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    text = streamReader.ReadToEnd();
                }
            }
            if (string.IsNullOrEmpty(text))
            {
                throw new FingerprintRulePackTemplateCorruptedException("FingerprintRulePackTemplate.xml");
            }
            XDocument xdocument = XDocument.Parse(text);
            XElement  xelement  = xdocument.Root.Element(XmlProcessingUtils.GetMceNsQualifiedNodeName("RulePack"));

            xelement.SetAttributeValue("id", rulePackId);
            XElement xelement2 = xelement.Element(XmlProcessingUtils.GetMceNsQualifiedNodeName("Publisher"));

            xelement2.SetAttributeValue("id", organizationId);
            foreach (XElement xelement3 in xelement.Descendants(XmlProcessingUtils.GetMceNsQualifiedNodeName("PublisherName")))
            {
                xelement3.SetValue(organizationName);
            }
            XmlProcessingUtils.SetRulePackVersionFromAssemblyFileVersion(xdocument);
            return(xdocument);
        }
        private static bool HandleClassificationEngineValidatorException(Exception exception, OrganizationId currentOrganizationId)
        {
            COMException ex = exception as COMException;

            if (ex == null)
            {
                return(false);
            }
            int errorCode = ex.ErrorCode;

            if (errorCode == -2147220981)
            {
                throw new ClassificationRuleCollectionValidationException(Strings.ClassificationRuleCollectionEngineValidationFailure, ex);
            }
            if (errorCode == -2147220978)
            {
                List <string> list  = (List <string>)ex.Data[ClassificationEngineValidator.BadRegexesKey];
                string        names = string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list);
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionRegexValidationException, List <string> >(new ClassificationRuleCollectionRegexValidationException(Strings.ClassificationRuleCollectionRegexValidationFailure(names), ex), list);
            }
            int errorCode2 = ex.ErrorCode;

            ClassificationDefinitionsDiagnosticsReporter.Instance.WriteClassificationEngineUnexpectedFailureInValidation(0, currentOrganizationId, errorCode2);
            throw new ClassificationRuleCollectionInternalValidationException(errorCode2, ex);
        }
Beispiel #10
0
 public override string ToString()
 {
     if (!string.IsNullOrEmpty(this.organizationHierarchy))
     {
         return(ClassificationDefinitionUtils.CreateHierarchicalIdentityString(this.organizationHierarchy, this.ruleId));
     }
     return(this.ruleId);
 }
        private static XmlSchema LoadSchemaFromEmbeddedResource(string schemaName)
        {
            XmlSchema result;

            using (Stream stream = ClassificationDefinitionUtils.LoadStreamFromEmbeddedResource(schemaName))
            {
                result = XmlSchema.Read(stream, null);
            }
            return(result);
        }
 internal static IEnumerable <DataClassificationPresentationObject> FilterHigherVersionRules(IEnumerable <DataClassificationPresentationObject> unfilteredRules)
 {
     if (unfilteredRules == null)
     {
         throw new ArgumentNullException("unfilteredRules");
     }
     return(from rule in unfilteredRules
            where rule.MinEngineVersion <= ClassificationDefinitionUtils.GetCurrentAssemblyVersion()
            select rule);
 }
        internal static string GetLocalMachineMceConfigDirectory(bool shouldHandleException = false)
        {
            string mceForAdminToolInstallBase = ClassificationDefinitionUtils.GetMceForAdminToolInstallBase(shouldHandleException);

            if (mceForAdminToolInstallBase != null)
            {
                return(Path.Combine(mceForAdminToolInstallBase, ClassificationDefinitionConstants.OnDiskMceConfigurationDirName));
            }
            return(null);
        }
        internal static string GetMceExecutablePath(bool shouldHandleException = false)
        {
            string mceForAdminToolInstallBase = ClassificationDefinitionUtils.GetMceForAdminToolInstallBase(shouldHandleException);

            if (mceForAdminToolInstallBase != null)
            {
                return(Path.Combine(mceForAdminToolInstallBase, ClassificationDefinitionConstants.MceExecutableFileName));
            }
            return(null);
        }
        private static string ReadRegexTestTemplate()
        {
            string result;

            using (Stream stream = ClassificationDefinitionUtils.LoadStreamFromEmbeddedResource("RegexTestTemplate.xml"))
            {
                StreamReader streamReader = new StreamReader(stream);
                result = streamReader.ReadToEnd();
            }
            return(result);
        }
Beispiel #16
0
        private static void ValidateKeywordProcessorsPerformance(XDocument rulePackXDocument, int keywordLengthLimit)
        {
            List <string> list = (from keywordProcessorDefinition in KeywordProcessorsValidator.GetKeywordProcessorsTerms(rulePackXDocument).AsParallel <KeyValuePair <string, List <string> > >()
                                  where keywordProcessorDefinition.Value.Any((string term) => term.Length > keywordLengthLimit)
                                  select keywordProcessorDefinition.Key).ToList <string>();

            if (list.Count > 0)
            {
                LocalizedString message = Strings.ClassificationRuleCollectionKeywordTooLong(keywordLengthLimit, string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list));
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionKeywordValidationException, List <string> >(new ClassificationRuleCollectionKeywordValidationException(message), list);
            }
        }
Beispiel #17
0
        private static void ValidateRuleComplexity(IEnumerable <KeyValuePair <string, RuleComplexityData> > rulePackComplexityData, IDataClassificationComplexityValidator complexityValidator)
        {
            List <string> list = (from ruleComplexityData in rulePackComplexityData
                                  where complexityValidator.IsRuleComplexityLimitExceeded(ruleComplexityData.Value)
                                  select ruleComplexityData.Key).ToList <string>();

            if (list.Count > 0)
            {
                LocalizedString message = complexityValidator.CreateExceptionMessage(list);
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionComplexityValidationException, List <string> >(new ClassificationRuleCollectionComplexityValidationException(message), list);
            }
        }
Beispiel #18
0
        public override string ToString()
        {
            string result;

            if (this.dataClassificationIdentityFilter != null)
            {
                result = (base.IsHierarchical ? ClassificationDefinitionUtils.CreateHierarchicalIdentityString(base.OrganizationName, this.dataClassificationIdentityFilter) : this.dataClassificationIdentityFilter);
            }
            else
            {
                result = base.ToString();
            }
            return(result);
        }
Beispiel #19
0
        private static void ValidateDefaultValueLangCodesConsistency(XDocument rulePackXDocument)
        {
            List <string> list = (from ruleResourceElement in rulePackXDocument.Descendants(XmlProcessingUtils.GetMceNsQualifiedNodeName("Resource")).AsParallel <XElement>()
                                  let defaultNameLangCode = ruleResourceElement.Elements(XmlProcessingUtils.GetMceNsQualifiedNodeName("Name")).Single((XElement nameElement) => nameElement.Attribute("default") != null && (bool)nameElement.Attribute("default")).Attribute("langcode").Value
                                                            let defaultDescriptionLangCode = ruleResourceElement.Elements(XmlProcessingUtils.GetMceNsQualifiedNodeName("Description")).Single((XElement descriptionElement) => descriptionElement.Attribute("default") != null && (bool)descriptionElement.Attribute("default")).Attribute("langcode").Value
                                                                                             where !new CultureInfo(defaultNameLangCode).Equals(new CultureInfo(defaultDescriptionLangCode))
                                                                                             select ruleResourceElement.Attribute("idRef").Value).ToList <string>();

            if (list.Count > 0)
            {
                LocalizedString message = Strings.ClassificationRuleCollectionInconsistentDefaultInRuleResource(string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list));
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionLocalizationInfoValidationException, List <string> >(new ClassificationRuleCollectionLocalizationInfoValidationException(message), list);
            }
        }
Beispiel #20
0
        private static void ValidateUpdatedOobRulePackIsSuperSet(IEnumerable <string> existingOobRuleIds, IEnumerable <string> updatedOobRuleIds)
        {
            if (existingOobRuleIds == null)
            {
                return;
            }
            List <string> list = existingOobRuleIds.Except(updatedOobRuleIds, ClassificationDefinitionConstants.RuleIdComparer).ToList <string>();

            if (list.Count > 0)
            {
                LocalizedString message = Strings.ClassificationRuleCollectionOobRulesRemoved(string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list));
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionIdentifierValidationException, List <string> >(new ClassificationRuleCollectionIdentifierValidationException(message), list);
            }
        }
Beispiel #21
0
        internal static IEnumerable <Tuple <TransportRule, XDocument> > AggregateOobAndCustomClassificationDefinitions(OrganizationId organizationId, IConfigurationSession openedDataSession = null, Func <TransportRule, bool> inclusiveFilter = null, QueryFilter additionalFilter = null, IClassificationDefinitionsDataReader dataReader = null, IClassificationDefinitionsDiagnosticsReporter classificationDefinitionsDiagnosticsReporter = null)
        {
            IClassificationDefinitionsDataReader          dataReaderToUse = dataReader ?? ClassificationDefinitionsDataReader.DefaultInstance;
            IClassificationDefinitionsDiagnosticsReporter classificationDefinitionsDiagnosticsReporterToUse = classificationDefinitionsDiagnosticsReporter ?? ClassificationDefinitionsDiagnosticsReporter.Instance;

            foreach (TransportRule transportRule in dataReaderToUse.GetAllClassificationRuleCollection(organizationId, openedDataSession, additionalFilter))
            {
                if (inclusiveFilter != null)
                {
                    if (!inclusiveFilter(transportRule))
                    {
                        continue;
                    }
                }
                XDocument rulePackXDoc;
                try
                {
                    rulePackXDoc = ClassificationDefinitionUtils.GetRuleCollectionDocumentFromTransportRule(transportRule);
                }
                catch (InvalidOperationException)
                {
                    classificationDefinitionsDiagnosticsReporterToUse.WriteInvalidObjectInformation(0, organizationId, transportRule.DistinguishedName);
                    continue;
                }
                catch (ArgumentException underlyingException)
                {
                    classificationDefinitionsDiagnosticsReporterToUse.WriteCorruptRulePackageDiagnosticsInformation(0, organizationId, transportRule.DistinguishedName, underlyingException);
                    continue;
                }
                catch (AggregateException ex)
                {
                    classificationDefinitionsDiagnosticsReporterToUse.WriteCorruptRulePackageDiagnosticsInformation(0, organizationId, transportRule.DistinguishedName, ex.Flatten());
                    continue;
                }
                catch (XmlException ex2)
                {
                    classificationDefinitionsDiagnosticsReporterToUse.WriteCorruptRulePackageDiagnosticsInformation(0, organizationId, transportRule.DistinguishedName, new AggregateException(new Exception[]
                    {
                        ex2
                    }).Flatten());
                    continue;
                }
                yield return(new Tuple <TransportRule, XDocument>(transportRule, rulePackXDoc));
            }
            yield break;
        }
            private XDocument DeserializeMceConfig()
            {
                XmlReaderSettings xmlReaderSettings = ClassificationDefinitionUtils.CreateSafeXmlReaderSettings();

                xmlReaderSettings.IgnoreComments = true;
                xmlReaderSettings.ValidationType = ValidationType.None;
                XDocument result;

                using (Stream stream = this.OpenSourceStream())
                {
                    using (XmlReader xmlReader = XmlReader.Create(stream, xmlReaderSettings))
                    {
                        result = XDocument.Load(xmlReader);
                    }
                }
                return(result);
            }
        protected override void InternalValidate()
        {
            TaskLogger.LogEnter();
            if (this.InstallDefaultCollection)
            {
                using (Stream stream = ClassificationDefinitionUtils.LoadStreamFromEmbeddedResource("DefaultClassificationDefinitions.xml"))
                {
                    byte[] array = new byte[stream.Length];
                    stream.Read(array, 0, Convert.ToInt32(stream.Length));
                    this.FileData = array;
                    goto IL_71;
                }
            }
            if (VariantConfiguration.InvariantNoFlightingSnapshot.Global.MultiTenancy.Enabled)
            {
                this.ValidateOperationScope();
            }
IL_71:
            byte[] rulePackageRawData = null;
            byte[] array2             = null;
            try
            {
                this.isEncrypted = RulePackageDecrypter.DecryptRulePackage(this.FileData, out rulePackageRawData, out array2);
            }
            catch (Exception innerException)
            {
                base.WriteError(new ClassificationRuleCollectionDecryptionException(innerException), ErrorCategory.InvalidData, null);
            }
            if (this.isEncrypted)
            {
                ExAssert.RetailAssert(!this.InstallDefaultCollection, "Installation of encrypted default OOB rule pack is not supported due to versioning!");
                string text = this.ValidateAndReadMetadata(rulePackageRawData);
                this.FileData = ((text == null) ? null : array2);
            }
            else
            {
                string text2 = this.ValidateAndReadMetadata(this.FileData);
                this.FileData = ((text2 == null) ? null : Encoding.Unicode.GetBytes(text2));
            }
            if (this.FileData != null)
            {
                base.InternalValidate();
            }
            TaskLogger.LogExit();
        }
Beispiel #24
0
 protected override void WriteResult <T>(IEnumerable <T> dataObjects)
 {
     TaskLogger.LogEnter();
     if (dataObjects is IEnumerable <DataClassificationPresentationObject> )
     {
         IEnumerable <DataClassificationPresentationObject> enumerable = ClassificationDefinitionUtils.FilterHigherVersionRules((IEnumerable <DataClassificationPresentationObject>)dataObjects);
         if (this.Identity != null)
         {
             enumerable = this.Identity.FilterResults(enumerable);
         }
         base.WriteResult <DataClassificationPresentationObject>(enumerable);
     }
     else
     {
         base.WriteResult <T>(dataObjects);
     }
     TaskLogger.LogExit();
 }
Beispiel #25
0
        private static void ValidateDefaultValueCount(XDocument rulePackXDocument)
        {
            List <string> list = (from ruleResourceElement in rulePackXDocument.Descendants(XmlProcessingUtils.GetMceNsQualifiedNodeName("Resource")).AsParallel <XElement>().Where(delegate(XElement ruleResourceElement)
            {
                if (ruleResourceElement.Elements(XmlProcessingUtils.GetMceNsQualifiedNodeName("Name")).Count((XElement nameElement) => nameElement.Attribute("default") != null && (bool)nameElement.Attribute("default")) == 1)
                {
                    return(ruleResourceElement.Elements(XmlProcessingUtils.GetMceNsQualifiedNodeName("Description")).Count((XElement descriptionElement) => descriptionElement.Attribute("default") != null && (bool)descriptionElement.Attribute("default")) != 1);
                }
                return(true);
            })
                                  select ruleResourceElement.Attribute("idRef").Value).ToList <string>();

            if (list.Count > 0)
            {
                LocalizedString message = Strings.ClassificationRuleCollectionIncorrectNumberOfDefaultInRuleResources(string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list));
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionLocalizationInfoValidationException, List <string> >(new ClassificationRuleCollectionLocalizationInfoValidationException(message), list);
            }
        }
        internal static void ValidateRulePackage(XDocument rulePackXDoc, string rulePackContents)
        {
            string mceExecutablePath = ClassificationDefinitionUtils.GetMceExecutablePath(true);

            if (mceExecutablePath == null || !File.Exists(mceExecutablePath))
            {
                throw new COMException("Unable to locate the Microsoft Classification Engine", -2147287038);
            }
            try
            {
                using (ActivationContextActivator.FromInternalManifest(mceExecutablePath, Path.GetDirectoryName(mceExecutablePath)))
                {
                    MicrosoftClassificationEngine microsoftClassificationEngine = new MicrosoftClassificationEngine();
                    PropertyBag       propertyBag       = new PropertyBag();
                    RulePackageLoader rulePackageLoader = new RulePackageLoader();
                    microsoftClassificationEngine.Init(propertyBag, rulePackageLoader);
                    RULE_PACKAGE_DETAILS rule_PACKAGE_DETAILS = default(RULE_PACKAGE_DETAILS);
                    rule_PACKAGE_DETAILS.RulePackageSetID = "not-used-here";
                    rule_PACKAGE_DETAILS.RulePackageID    = "test-rule-pack";
                    rule_PACKAGE_DETAILS.RuleIDs          = null;
                    RULE_PACKAGE_DETAILS rule_PACKAGE_DETAILS2 = rule_PACKAGE_DETAILS;
                    rulePackageLoader.SetRulePackage(rule_PACKAGE_DETAILS2.RulePackageID, rulePackContents);
                    try
                    {
                        MicrosoftClassificationEngine microsoftClassificationEngine2 = microsoftClassificationEngine;
                        RULE_PACKAGE_DETAILS          rule_PACKAGE_DETAILS3          = rule_PACKAGE_DETAILS2;
                        microsoftClassificationEngine2.GetClassificationDefinitions(ref rule_PACKAGE_DETAILS3);
                    }
                    catch (COMException ex)
                    {
                        if (ex.ErrorCode == -2147220978)
                        {
                            List <string> value = ClassificationEngineValidator.GetInvalidRegexes(microsoftClassificationEngine, rulePackageLoader, rulePackXDoc).ToList <string>();
                            ex.Data[ClassificationEngineValidator.BadRegexesKey] = value;
                        }
                        throw ex;
                    }
                }
            }
            catch (ActivationContextActivatorException)
            {
                throw new COMException("Unable to instantiate the Microsoft Classification Engine", -2147164127);
            }
        }
        protected override IConfigurable PrepareDataObject()
        {
            TaskLogger.LogEnter();
            TransportRule transportRule = null;

            try
            {
                transportRule = this.TryGetDataObject();
                XDocument rulePackXDoc;
                if (transportRule == null)
                {
                    transportRule = (TransportRule)base.PrepareDataObject();
                    string rawIdentity = this.ClassificationRuleCollectionIdentity.RawIdentity;
                    transportRule.SetId(ClassificationDefinitionUtils.GetClassificationRuleCollectionContainerId(base.DataSession).GetChildId(rawIdentity));
                    transportRule.OrganizationId = base.CurrentOrganizationId;
                    transportRule.Xml            = null;
                    string organizationId;
                    string name;
                    if (base.CurrentOrganizationId != null && base.CurrentOrganizationId.OrganizationalUnit != null)
                    {
                        organizationId = base.CurrentOrganizationId.OrganizationalUnit.ObjectGuid.ToString();
                        name           = base.CurrentOrganizationId.OrganizationalUnit.Name;
                    }
                    else
                    {
                        organizationId = base.CurrentOrgContainerId.ObjectGuid.ToString();
                        name           = base.CurrentOrgContainerId.DomainId.Name;
                    }
                    rulePackXDoc = ClassificationDefinitionUtils.CreateRuleCollectionDocumentFromTemplate(rawIdentity, organizationId, name);
                }
                else
                {
                    rulePackXDoc = ClassificationDefinitionUtils.GetRuleCollectionDocumentFromTransportRule(transportRule);
                }
                this.implementation = new DataClassificationCmdletsImplementation(this);
                this.implementation.Initialize(transportRule, rulePackXDoc);
            }
            catch (LocalizedException exception)
            {
                base.WriteError(exception, ErrorCategory.InvalidOperation, null);
            }
            TaskLogger.LogExit();
            return(transportRule);
        }
Beispiel #28
0
        private void ValidateProcessorIdAndMatchReferences(XDocument rulePackXDocument)
        {
            ExAssert.RetailAssert(rulePackXDocument != null, "Extra rule package validation must take place after XML schema validation passed!");
            IDictionary <string, ExchangeBuild> textProcessorsFromTextProcessorGrouping = TextProcessorUtils.GetTextProcessorsFromTextProcessorGrouping(this.cannedOobTextProcessorsGroupedByType, null);
            ICollection <string> keys = textProcessorsFromTextProcessorGrouping.Keys;
            Dictionary <TextProcessorType, TextProcessorGrouping> textProcessorsGroupings = TextProcessorUtils.GetRulePackScopedTextProcessorsGroupedByType(rulePackXDocument).ToDictionary((TextProcessorGrouping textProcessorGroup) => textProcessorGroup.Key);
            IDictionary <string, ExchangeBuild> textProcessorsFromTextProcessorGrouping2  = TextProcessorUtils.GetTextProcessorsFromTextProcessorGrouping(textProcessorsGroupings, null);
            ICollection <string> keys2 = textProcessorsFromTextProcessorGrouping2.Keys;
            List <string>        list  = keys.AsParallel <string>().Union(keys2.AsParallel <string>(), ClassificationDefinitionConstants.TextProcessorIdComparer).ToList <string>();

            if (list.Count != keys.Count + keys2.Count)
            {
                List <string>   list2   = keys.AsParallel <string>().Intersect(keys2.AsParallel <string>(), ClassificationDefinitionConstants.TextProcessorIdComparer).ToList <string>();
                LocalizedString message = Strings.ClassificationRuleCollectionReservedProcessorIdViolation(string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list2));
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionIdentifierValidationException, List <string> >(new ClassificationRuleCollectionIdentifierValidationException(message), list2);
            }
            HashSet <string> hashSet = new HashSet <string>(ClassificationDefinitionConstants.TextProcessorIdComparer);
            IEnumerable <KeyValuePair <string, ExchangeBuild> > textProcessorReferences = TextProcessorUtils.GetTextProcessorReferences(rulePackXDocument.Root);

            foreach (KeyValuePair <string, ExchangeBuild> keyValuePair in textProcessorReferences)
            {
                ExchangeBuild objB;
                if ((!textProcessorsFromTextProcessorGrouping2.TryGetValue(keyValuePair.Key, out objB) && !textProcessorsFromTextProcessorGrouping.TryGetValue(keyValuePair.Key, out objB)) || !(keyValuePair.Value >= objB))
                {
                    hashSet.Add(keyValuePair.Key);
                }
            }
            IDictionary <string, ExchangeBuild> textProcessorsFromTextProcessorGrouping3 = TextProcessorUtils.GetTextProcessorsFromTextProcessorGrouping(this.cannedOobTextProcessorsGroupedByType, (TextProcessorType textProcessorType) => textProcessorType == TextProcessorType.Fingerprint);
            IDictionary <string, ExchangeBuild> textProcessorsFromTextProcessorGrouping4 = TextProcessorUtils.GetTextProcessorsFromTextProcessorGrouping(textProcessorsGroupings, (TextProcessorType textProcessorType) => textProcessorType == TextProcessorType.Fingerprint);
            IEnumerable <KeyValuePair <string, ExchangeBuild> > textProcessorReferences2 = TextProcessorUtils.GetTextProcessorReferences(rulePackXDocument.Root, ClassificationDefinitionConstants.MceIdMatchElementNames);

            foreach (KeyValuePair <string, ExchangeBuild> keyValuePair2 in textProcessorReferences2)
            {
                if (textProcessorsFromTextProcessorGrouping4.ContainsKey(keyValuePair2.Key) || textProcessorsFromTextProcessorGrouping3.ContainsKey(keyValuePair2.Key))
                {
                    hashSet.Add(keyValuePair2.Key);
                }
            }
            if (hashSet.Count > 0)
            {
                LocalizedString message2 = Strings.ClassificationRuleCollectionInvalidProcessorReferenceViolation(string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, hashSet));
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionProcessorReferenceValidationException, HashSet <string> >(new ClassificationRuleCollectionProcessorReferenceValidationException(message2), hashSet);
            }
        }
Beispiel #29
0
        private string ValidateAgainstBusinessRulesAndReadMetadata(XDocument rulePackXDoc)
        {
            ExAssert.RetailAssert(this.rulePackageIdentifier != null && this.DataObject != null, "Business rules validation in Set-ClassificationRuleCollection must take place after the DataObject resolution");
            string result = string.Empty;

            try
            {
                this.validationContext = new ValidationContext(ClassificationRuleCollectionOperationType.Update, base.CurrentOrganizationId, VariantConfiguration.InvariantNoFlightingSnapshot.Global.MultiTenancy.Enabled && this.OutOfBoxCollection, false, (IConfigurationSession)base.DataSession, this.DataObject, null, null);
                result = ClassificationRuleCollectionValidationUtils.ValidateRulePackageContents(this.validationContext, rulePackXDoc);
                ClassificationRuleCollectionLocalizableDetails classificationRuleCollectionLocalizableDetails = XmlProcessingUtils.ReadDefaultRulePackageMetadata(rulePackXDoc);
                this.defaultName = classificationRuleCollectionLocalizableDetails.Name;
                ClassificationRuleCollectionLocalizableDetails classificationRuleCollectionLocalizableDetails2 = XmlProcessingUtils.ReadRulePackageMetadata(rulePackXDoc, CultureInfo.CurrentCulture);
                this.localizedName = ((classificationRuleCollectionLocalizableDetails2 != null && classificationRuleCollectionLocalizableDetails2.Name != null) ? classificationRuleCollectionLocalizableDetails2.Name : this.defaultName);
                if (VariantConfiguration.InvariantNoFlightingSnapshot.Global.MultiTenancy.Enabled && OrganizationId.ForestWideOrgId.Equals(((IDirectorySession)base.DataSession).SessionSettings.CurrentOrganizationId))
                {
                    this.WriteWarning(Strings.ClassificationRuleCollectionIneffectiveSharingViolationCheck);
                }
                SortedSet <string> sortedSet         = new SortedSet <string>();
                IList <string>     deletedRulesInUse = ClassificationRuleCollectionValidationUtils.GetDeletedRulesInUse(base.DataSession, this.DataObject, sortedSet, rulePackXDoc);
                if (deletedRulesInUse.Count > 0)
                {
                    LocalizedString message = Strings.ClassificationRuleCollectionSharingViolationSetOperationVerbose(this.localizedName ?? this.rulePackageIdentifier, string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, deletedRulesInUse), string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, sortedSet));
                    throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionSharingViolationException, IList <string> >(new ClassificationRuleCollectionSharingViolationException(message), deletedRulesInUse);
                }
            }
            catch (ClassificationRuleCollectionSharingViolationException exception)
            {
                base.WriteError(exception, ErrorCategory.InvalidOperation, null);
            }
            catch (ClassificationRuleCollectionInternalValidationException ex)
            {
                base.WriteError(ex, (-2147287038 == ex.Error) ? ErrorCategory.ObjectNotFound : ErrorCategory.InvalidResult, null);
            }
            catch (ClassificationRuleCollectionTimeoutException exception2)
            {
                base.WriteError(exception2, ErrorCategory.OperationTimeout, null);
            }
            catch (LocalizedException exception3)
            {
                base.WriteError(exception3, ErrorCategory.InvalidData, null);
            }
            return(result);
        }
Beispiel #30
0
        private static void ValidateNoRuleIdentifiersConflicts(Dictionary <string, HashSet <string> > existingClassificationIdentifiers, IList <string> ruleIdentifiersToValidate)
        {
            ExAssert.RetailAssert(ruleIdentifiersToValidate != null, "Classification rule identifiers to be checked for conflicts with existing classification rule identifiers must not be null");
            if (existingClassificationIdentifiers == null || existingClassificationIdentifiers.Count == 0 || ruleIdentifiersToValidate.Count == 0)
            {
                return;
            }
            List <string> list = new List <string>();

            foreach (HashSet <string> @object in existingClassificationIdentifiers.Values)
            {
                list.AddRange(ruleIdentifiersToValidate.Where(new Func <string, bool>(@object.Contains)));
            }
            if (list.Count > 0)
            {
                LocalizedString message = Strings.ClassificationRuleCollectionExistingRuleIdViolation(string.Join(Strings.ClassificationRuleCollectionOffendingListSeparator, list));
                throw ClassificationDefinitionUtils.PopulateExceptionSource <ClassificationRuleCollectionIdentifierValidationException, List <string> >(new ClassificationRuleCollectionIdentifierValidationException(message), list);
            }
        }