// initialize a PublishedContentCache instance with
        // an XmlStore containing the master xml
        // an IAppCache that should be at request-level
        // a RoutesCache - need to cleanup that one
        // a preview token string (or null if not previewing)
        public PublishedContentCache(
            XmlStore xmlStore,        // an XmlStore containing the master xml
            IDomainCache domainCache, // an IDomainCache implementation
            IAppCache appCache,       // an IAppCache that should be at request-level
            IGlobalSettings globalSettings,
            ISiteDomainHelper siteDomainHelper,
            IUmbracoContextAccessor umbracoContextAccessor,
            PublishedContentTypeCache contentTypeCache, // a PublishedContentType cache
            RoutesCache routesCache,                    // a RoutesCache
            string previewToken)                        // a preview token string (or null if not previewing)
            : base(previewToken.IsNullOrWhiteSpace() == false)
        {
            _appCache               = appCache;
            _globalSettings         = globalSettings;
            _umbracoContextAccessor = umbracoContextAccessor;
            _routesCache            = routesCache; // may be null for unit-testing
            _contentTypeCache       = contentTypeCache;
            _domainCache            = domainCache;
            _domainHelper           = new DomainHelper(_domainCache, siteDomainHelper);

            _xmlStore = xmlStore;
            _xml      = _xmlStore.Xml; // capture - because the cache has to remain consistent

            if (previewToken.IsNullOrWhiteSpace() == false)
            {
                _previewContent = new PreviewContent(_xmlStore, previewToken);
            }
        }
        public void TestReadConditionsSecondLevel()
        {
            string policyCatalogueFilename = m_testPath + "SamplePolicyCatalogue.xml";
            string policyLanguageFilename = m_testPath + "SampleLanguageBase.xml";
            string policyFilename = m_testPath + "SamplePolicy.xml";

            XmlPolicyLanguageStore.Instance.AddLanguage(System.IO.File.ReadAllText(policyLanguageFilename));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(policyCatalogueFilename));

            XmlStore store = new XmlStore(System.IO.File.ReadAllText(policyFilename));

            XmlPolicyReader xmlPolicyReader = store.Reader as XmlPolicyReader;
            string policyId = "{8FC9EB93-C376-4E96-B22E-71FAA848393D}";
            string ruleId = "{56C991B8-953D-46AD-B9E9-0CFB08F52C23}";
            string conditionGroupId = "{D64056E5-A19D-4B29-8F4A-A70337B42A19}";
            string childConditionGroupId = "{661EDD6F-D750-493A-9932-E56C8C22E2CF}";
            string conditionsXpath = string.Format(@"/PolicySetStore/PolicySets/PolicySet[@id='{0}']/Policies/Policy[@id='{1}']/Conditions/ConditionGroup[@id='{2}']/ConditionGroup[@id='{3}']",
                policyId, ruleId, conditionGroupId, childConditionGroupId);

            PolicyObjectCollection<IPolicyObject> conditions = new PolicyObjectCollection<IPolicyObject>();

            XmlConditionGroupReader conditionReader = new XmlConditionGroupReader(xmlPolicyReader, conditions, conditionsXpath);
            conditionReader.Read();

            Assert.AreEqual(1, conditions.Count);

            ICondition condition = conditions[0] as ICondition;
            Assert.IsNotNull(condition);
            Assert.AreEqual(new Guid("{6B7F6B0C-747A-4BD0-A65D-A1FB9E44FE7C}"), condition.Identifier);
            Assert.AreEqual("IDataComparer", condition.Class);
            Assert.AreEqual(OperatorType.GreaterThan, condition.Operator);
        }
示例#3
0
		public void TestLoadPolicy()
		{
            PolicyCataloguesCache.Instance().Reset();

            string testCatalogue = m_testPath + "TestRealPolicyCatalogue.xml";
            string languageFilename = m_testPath + "TestRealPolicyLanguage.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            string languageName;
            languageStore.AddLanguage(System.IO.File.ReadAllText(languageFilename), out languageName);

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();

            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            string filename = m_testPath + "TestRealPolicySet.xml";
            XmlStore store = new XmlStore(System.IO.File.ReadAllText(filename));
            XmlPolicyReader xmlPolicyReader = store.Reader as XmlPolicyReader;

            IPolicyObjectCollection<IPolicySet> policySets = xmlPolicyReader.PolicySets;
            Assert.IsNotNull(policySets);

            Assert.AreEqual(1, policySets.Count, "Expected one policy set");
            IPolicySet policySet = policySets[0];

			Assert.AreEqual(3, policySet.Policies.Count, "Expected two rules to exist");

			int ruleIndex = 0;
            ValidateRule1(policySet.Policies[ruleIndex++]);
            ValidateRule2(policySet.Policies[ruleIndex++]);
            ValidateRule3(policySet.Policies[ruleIndex++]);
		}
 public PublishedMemberCache(XmlStore xmlStore, ICacheProvider requestCacheProvider, IMemberService memberService, PublishedContentTypeCache contentTypeCache)
 {
     _requestCache     = requestCacheProvider;
     _memberService    = memberService;
     _xmlStore         = xmlStore;
     _contentTypeCache = contentTypeCache;
 }
        static Worker()
        {
            try
            {
                config = XmlStore <MpfConfig> .Import("C:\\Windows\\System32\\MpfConfig.xml");
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Could not open 'C:\\Windows\\System32\\MpfConfig.xml', the error was: {0}", ex.Message));
                config = new MpfConfig
                {
                    IsEnabled       = true,
                    ResultIfFailure = true
                };
                config.PasswordPolicy.MinLength = 12;
                config.PasswordPolicy.MinScore  = 4;
                config.PasswordPolicy.MaxConsecutiveRepeatingCharacters = 5;
            }

            try
            {
                rootDse = new DirectoryEntry("LDAP://RootDSE");
            }
            catch
            {
                Console.WriteLine("Could not read RootDse object, AD Tests will be skipped.");
            }
        }
        private XmlStore ReadRuleAttributesHelper()
        {
            string policyCatalogueFilename = m_testPath + "ExpectedWriteRuleAttributesCatalogue.xml";
            string policyFilename = m_testPath + "ExpectedWriteRuleAttributes.xml";
            
            string policyLanguageFilename = m_testPath + "ExpectedWriteRuleAttributesLanguage.xml";
            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            languageStore.AddLanguage(System.IO.File.ReadAllText(policyLanguageFilename));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(policyCatalogueFilename));

            XmlStore store = new XmlStore(System.IO.File.ReadAllText(policyFilename));

            IPolicyObjectCollection<IPolicySet> policySet = store.Reader.PolicySets;
            Assert.IsNotNull(policySet);
            Assert.AreEqual(1, policySet.Count, "Expected one policy set");
            IPolicyObjectCollection<IPolicy> policies = store.Reader.Policies(policySet[0]);
            Assert.AreEqual(1, policies.Count);
            IPolicy policy = policies[0];
            Assert.IsNotNull(policy, "Expected a valid rule");

            Assert.AreEqual("This is my first custom property", policy["custom1"].Value);
            Assert.AreEqual("This is my second custom property", policy["custom2"].Value);

            return store;
        }
示例#7
0
        public void TestReadPolicySetPolicies()
        {
            string testCatalogue = m_testPath + "TestRealPolicyCatalogue.xml";
            string languageFilename = m_testPath + "TestRealPolicyLanguage.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            languageStore.AddLanguage(System.IO.File.ReadAllText(languageFilename));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            string filename = m_testPath + "TestRealPolicySet.xml";
            XmlStore store = new XmlStore(System.IO.File.ReadAllText(filename));
            XmlPolicyReader xmlPolicyReader = store.Reader as XmlPolicyReader;

            IPolicyObjectCollection<IPolicySet> policySets = xmlPolicyReader.PolicySets;
            Assert.IsNotNull(policySets);
            Assert.AreEqual(1, policySets.Count, "Expected one policy");
            IPolicyObjectCollection<IPolicy> policies = xmlPolicyReader.Policies(policySets[0]);
            Assert.AreEqual(3, policies.Count);

            int index = 0;
            IPolicy policy = policies[index++];
            Assert.AreEqual("Privacy", policy.Name.Value);

            policy = policies[index++];
            Assert.AreEqual("Global", policy.Name.Value);

            policy = policies[index++];
            Assert.AreEqual("Financial Disclosure", policy.Name.Value);
        }
        public PasswordRulesBase()
        {
            try
            {
                config = XmlStore <Config> .Import(configFilePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Could not open '{0}', the error was: {1}", configFilePath, ex.Message));
                config = new Config
                {
                    IsEnabled       = true,
                    ResultIfFailure = true
                };
                config.PasswordPolicy.MinLength = 12;
                config.PasswordPolicy.MaxLength = 256;
                config.PasswordPolicy.MinScore  = 4;
                config.PasswordPolicy.MaxConsecutiveRepeatingCharacters = 5;
                config.PasswordPolicy.AllowedBlackListQuotaPercent      = 20;
                config.PasswordPolicy.DenySettings = PasswordSettings.DenyName;
            }

            try
            {
                rootDse = new DirectoryEntry("LDAP://RootDSE");
                var temp = rootDse.Name;
                IsConnectedToAd = true;
            }
            catch
            {
                //No connection to AD
            }
        }
示例#9
0
 private IPolicySet CreatePolicySet()
 {
     IPolicyStore policyStore = new XmlStore();
     PolicyCatalogue policyCatalogue = new PolicyCatalogue(Guid.NewGuid(), language.Identifier, new TranslateableLanguageItem(""), catalogueStore);
     catalogueStore.AddPolicyCatalogue(policyCatalogue);
     return new PolicySet(Guid.NewGuid(), new TranslateableLanguageItem(""), policyStore, policyCatalogue, false);
 }
示例#10
0
        private void RefreshEditor()
        {
            XmlEditorService es = GetService(typeof(XmlEditorService)) as XmlEditorService;

            _store             = es.CreateXmlStore();
            _store.UndoManager = _undoManager;

            _model = _store.OpenXmlModel(new Uri(_fileName));
            _textBuffer.Reload(1);

            if (ManifestEditorFactory.ExcuteToCheckXmlRule(_fileName))
            {
                _ManifestDesignerControl.IsEnabled = true;
                try
                {
                    _ManifestDesignerControl.Refresh(new ViewModelTizen(_store, _model, this, _textBuffer));
                    var vsRunningDocumentTable = GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
                    var hr = vsRunningDocumentTable.NotifyDocumentChanged(_documentCookie, (uint)__VSRDTATTRIB.RDTA_DocDataReloaded);
                    ErrorHandler.ThrowOnFailure(hr);
                }
                catch
                {
                }
            }
            else
            {
                _ManifestDesignerControl.IsEnabled = false;
            }
        }
示例#11
0
        public void TestReadChannel()
        {
            string policyCatalogueFilename = m_testPath + "SamplePolicyCatalogue.xml";
            string policyLanguageFilename = m_testPath + "SampleLanguageBase.xml";
            string policyFilename = m_testPath + "SamplePolicy.xml";

            XmlPolicyLanguageStore.Instance.AddLanguage(System.IO.File.ReadAllText(policyLanguageFilename));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(policyCatalogueFilename));

            XmlStore store = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            XmlPolicyReader xmlPolicyReader = store.Reader as XmlPolicyReader;
            string policySetId = "{8FC9EB93-C376-4E96-B22E-71FAA848393D}";
            string policyId = "{F067B5B0-431A-4A34-BDD8-307C83DD8F7C}";
            string xpath = string.Format(@"/PolicySetStore/PolicySets/PolicySet[@id='{0}']/Policies/Policy[@id='{1}']/Channels",
                policySetId, policyId);

            Assert.AreEqual(1, xmlPolicyReader.PolicySets.Count);
            IPolicySet policySet = xmlPolicyReader.PolicySets[0];
            Assert.IsNotNull(policySet);

            IPolicy policy = policySet.Policies[new Guid(policyId)];
            Assert.IsNotNull(policy);

            PolicyObjectCollection<IPolicyChannel> channels = new PolicyObjectCollection<IPolicyChannel>();
            XmlChannelsReader reader = new XmlChannelsReader(xmlPolicyReader, channels, policy, xpath);
            reader.Read();

            Assert.AreEqual(2, channels.Count, "Expected two channels");

            int channelIndex = 0;
            ValidateChannel1(channels[channelIndex++]);
            ValidateChannel2(channels[channelIndex++]);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PreviewContent"/> with a preview token.
        /// </summary>
        /// <param name="xmlStore">The underlying Xml store.</param>
        /// <param name="token">The preview token.</param>
        public PreviewContent(XmlStore xmlStore, string token)
        {
            if (xmlStore == null)
            {
                throw new ArgumentNullException(nameof(xmlStore));
            }
            _xmlStore = xmlStore;

            if (token.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("Null or empty token.", nameof(token));
            }
            var parts = token.Split(':');

            if (parts.Length != 2)
            {
                throw new ArgumentException("Invalid token.", nameof(token));
            }

            if (int.TryParse(parts[0], out _userId) == false)
            {
                throw new ArgumentException("Invalid token.", nameof(token));
            }
            if (Guid.TryParse(parts[1], out _previewSet) == false)
            {
                throw new ArgumentException("Invalid token.", nameof(token));
            }

            _previewSetPath = GetPreviewSetPath(_userId, _previewSet);
        }
        protected override void Initialize()
        {
            base.Initialize();

            _httpContextFactory = new FakeHttpContextFactory("~/Home");

            var umbracoSettings = Factory.GetInstance <IUmbracoSettingsSection>();
            var globalSettings  = Factory.GetInstance <IGlobalSettings>();

            _xml = new XmlDocument();
            _xml.LoadXml(GetXml());
            var xmlStore          = new XmlStore(() => _xml, null, null, null);
            var cacheProvider     = new StaticCacheProvider();
            var domainCache       = new DomainCache(ServiceContext.DomainService, DefaultCultureAccessor);
            var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedSnapshot(
                new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null),
                new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, cacheProvider, ContentTypesCache),
                new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache),
                domainCache);
            var publishedSnapshotService = new Mock <IPublishedSnapshotService>();

            publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(publishedShapshot);

            _umbracoContext = new UmbracoContext(
                _httpContextFactory.HttpContext,
                publishedSnapshotService.Object,
                new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService, globalSettings),
                umbracoSettings,
                Enumerable.Empty <IUrlProvider>(),
                globalSettings,
                new TestVariationContextAccessor());

            _cache = _umbracoContext.ContentCache;
        }
        private PublishedSnapshotService(ServiceContext serviceContext,
                                         IPublishedContentTypeFactory publishedContentTypeFactory,
                                         IScopeProvider scopeProvider,
                                         ICacheProvider requestCache,
                                         IEnumerable <IUrlSegmentProvider> segmentProviders,
                                         IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor,
                                         IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository,
                                         IDefaultCultureAccessor defaultCultureAccessor,
                                         ILogger logger,
                                         IGlobalSettings globalSettings,
                                         ISiteDomainHelper siteDomainHelper,
                                         PublishedContentTypeCache contentTypeCache,
                                         MainDom mainDom,
                                         bool testing, bool enableRepositoryEvents)
            : base(publishedSnapshotAccessor, variationContextAccessor)
        {
            _routesCache = new RoutesCache();
            _publishedContentTypeFactory = publishedContentTypeFactory;
            _contentTypeCache            = contentTypeCache
                                           ?? new PublishedContentTypeCache(serviceContext.ContentTypeService, serviceContext.MediaTypeService, serviceContext.MemberTypeService, publishedContentTypeFactory, logger);

            _xmlStore = new XmlStore(serviceContext, scopeProvider, _routesCache,
                                     _contentTypeCache, segmentProviders, publishedSnapshotAccessor, mainDom, testing, enableRepositoryEvents,
                                     documentRepository, mediaRepository, memberRepository, globalSettings);

            _domainService          = serviceContext.DomainService;
            _memberService          = serviceContext.MemberService;
            _mediaService           = serviceContext.MediaService;
            _userService            = serviceContext.UserService;
            _defaultCultureAccessor = defaultCultureAccessor;

            _requestCache     = requestCache;
            _globalSettings   = globalSettings;
            _siteDomainHelper = siteDomainHelper;
        }
示例#15
0
        // initialize further instances, which are active (touched)
        private XmlStoreFilePersister(IBackgroundTaskRunner <XmlStoreFilePersister> runner, XmlStore store, ILogger logger, bool touched)
        {
            _runner = runner;
            _store  = store;
            _logger = logger;

            if (_runner.TryAdd(this) == false)
            {
                _runner   = null; // runner's down
                _released = true; // don't mess with timer
                return;
            }

            // runner could decide to run it anytime now

            if (touched == false)
            {
                return;
            }

            _logger.Debug <XmlStoreFilePersister>("Created, save in {WaitMilliseconds}ms.", WaitMilliseconds);
            _initialTouch = DateTime.Now;
            _timer        = new Timer(_ => TimerRelease());
            _timer.Change(WaitMilliseconds, 0);
        }
        public void TestAddPolicySetWindow()
        {
            //setup
            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            IPolicyLanguage language = new PolicyLanguage(new Guid("{E8B22533-98EB-4D00-BDE4-406DC3E1858B}"), "en");
            languageStore.AddLanguage(language);
            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            PolicyCatalogue policyCatalogue = new PolicyCatalogue(new Guid("{AB5E2A43-01FB-4AA6-98FC-8F74BB0621CA}"), language.Identifier, new TranslateableLanguageItem("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), catalogueStore);
            catalogueStore.AddPolicyCatalogue(policyCatalogue);
            IPolicyStore policyStore = new XmlStore();

            //try to add two policy sets with the same GUID. Should create two nodes in the tree, each with
            //unique GUIDs, and with the tree node GUIDs unequal to the policy set GUIDs. This proves we can load two .policy files
            //each with the same GUID without things screwing up.
            Guid policySetGuid = new Guid("{8D6C9D98-0B49-4dbe-9AE8-CEE5DC6535BF}");
            IPolicySet policySet1 = new PolicySet(policySetGuid, new TranslateableLanguageItem("PolicySet1"), policyStore, policyCatalogue, false);
            IPolicySet policySet2 = new PolicySet(policySetGuid, new TranslateableLanguageItem("PolicySet2"), policyStore, policyCatalogue, false);

            PolicySetExplorerForm policySetExplorerForm = new PolicySetExplorerForm();
            policySetExplorerForm.AddPolicySetWindow(policySet1, Workshare.Policy.Interfaces.PolicySetVersionStatus.Disabled, "1.0");
            policySetExplorerForm.AddPolicySetWindow(policySet2, Workshare.Policy.Interfaces.PolicySetVersionStatus.Disabled, "1.0");

            Assert.AreEqual(2, policySetExplorerForm.TreeView.Nodes.Count, "unexpected number of nodes in tree");
            Assert.AreNotEqual(((TreeObject)policySetExplorerForm.TreeView.Nodes[0]).Guid, ((TreeObject)policySetExplorerForm.TreeView.Nodes[1]).Guid, ("Treeview node GIUDs match"));
            Assert.AreNotEqual(policySetGuid, ((TreeObject)policySetExplorerForm.TreeView.Nodes[0]).Guid, ("Treeview node GIUD matches policy set GUID"));
            Assert.AreNotEqual(policySetGuid, ((TreeObject)policySetExplorerForm.TreeView.Nodes[1]).Guid, ("Treeview node GIUD matches policy set GUID"));
        }
        public void TestWriteRuleAttributes()
        {
            Guid languageId = new Guid("{CBEB31FA-7FE8-4E27-A01A-1D19AFCA604C}");
            PolicyLanguage language = new PolicyLanguage(languageId, "en");
            language[new Guid("{B067FF7F-2DA0-4AA1-A69F-DEFCD8B4CE90}")] = "Test rule";
            language[new Guid("{305F5FFD-9C46-4BE7-896E-2ACE709E5D7E}")] = "Test policy";
            language[new Guid("{EBF8443B-4912-44F2-89BE-A0A055332D1B}")] = "This is my first custom property";
            language[new Guid("{8053E60C-EED7-464D-84EA-ECB51C291237}")] = "This is my second custom property";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.AddLanguage(language);

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            Guid catalogueGuid = new Guid("{BC626464-1524-407C-8CD4-2B2B9C5BFE87}");
            PolicyCatalogue policyCatalogue = new PolicyCatalogue(catalogueGuid, languageId, catalogueStore);
            XmlStore store = new XmlStore();

            ObjectModel.PolicySet policySet = new ObjectModel.PolicySet(new Guid("{8FC9EB93-C376-4E96-B22E-71FAA848393D}"), new TranslateableLanguageItem("{305F5FFD-9C46-4BE7-896E-2ACE709E5D7E}"), store, policyCatalogue, false);
            P5Policy policy = new P5Policy(policySet, new Guid("{8E915159-5F01-41B3-9FFF-20731544ADFA}"), new TranslateableLanguageItem("{B067FF7F-2DA0-4AA1-A69F-DEFCD8B4CE90}"), PolicyStatus.Active);
            policy["custom1"] = new TranslateableLanguageItem("{EBF8443B-4912-44F2-89BE-A0A055332D1B}");
            policy["custom2"] = new TranslateableLanguageItem("{8053E60C-EED7-464D-84EA-ECB51C291237}");

            IPolicyStoreWriter writer = store.Writer;
            writer.WritePolicySet(policySet);
            writer.WritePolicy(policySet, policy);
            writer.Close();

            TestHelpers.CompareXml(m_testPath + "ExpectedWriteRuleAttributes.xml", store.StoreXML);
        }
示例#18
0
        public ViewModel(XmlStore xmlStore, XmlModel xmlModel, IServiceProvider provider, IVsTextLines buffer)
        {
            if (xmlModel == null)
                throw new ArgumentNullException("xmlModel");
            if (xmlStore == null)
                throw new ArgumentNullException("xmlStore");
            if (provider == null)
                throw new ArgumentNullException("provider");
            if (buffer == null)
                throw new ArgumentNullException("buffer");

            this.BufferDirty = false;
            this.DesignerDirty = false;

            this._serviceProvider = provider;
            this._buffer = buffer;

            this._xmlStore = xmlStore;
            // OnUnderlyingEditCompleted
            _editingScopeCompletedHandler = new EventHandler<XmlEditingScopeEventArgs>(OnUnderlyingEditCompleted);
            this._xmlStore.EditingScopeCompleted += _editingScopeCompletedHandler;
            // OnUndoRedoCompleted
            _undoRedoCompletedHandler = new EventHandler<XmlEditingScopeEventArgs>(OnUndoRedoCompleted);
            this._xmlStore.UndoRedoCompleted += _undoRedoCompletedHandler;

            this._xmlModel = xmlModel;
            // BufferReloaded
            _bufferReloadedHandler += new EventHandler(BufferReloaded);
            this._xmlModel.BufferReloaded += _bufferReloadedHandler;

            LoadModelFromXmlModel();
        }
示例#19
0
        public void TestCreatePreRoutingSetWithInternalExternalSmptRoutingTable()
        {
            string testCatalogue = m_testPath + "TestRealPolicyCatalogue.xml";
            string testLanguage = m_testPath + "TestRealPolicyLanguage.xml";

            XmlPolicyLanguageStore.Instance.AddLanguage(System.IO.File.ReadAllText(testLanguage));
            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            PolicyCatalogue policyCatalogue = catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));
            PolicyChannel channel = new PolicyChannel(new Guid("{390F589A-24B0-4DF0-B750-D47EDD1FF0BE}"), new TranslateableLanguageItem("{463A0FAF-CE8C-470E-8077-A093B9350719}"), ChannelType.SMTP);

            XmlStore store = new XmlStore();
            ObjectModel.PolicySet policySet = new ObjectModel.PolicySet(new Guid("{8FC9EB93-C376-4E96-B22E-71FAA848393D}"), new TranslateableLanguageItem("{D803727B-5C81-44CC-8BFC-9B68797AC6EB}"), store, policyCatalogue, false);
            P5Policy policy = new P5Policy(store, policySet, new Guid("{C0F6D4BB-CBF1-41FC-8A28-616D6FC1DC73}"), new TranslateableLanguageItem("{F0DD86A0-5D21-4784-88AF-C5321B5998F6}"), PolicyStatus.Active);

            channel.Routing = BuildInternalExternalSmtpRouting();
            channel.Actions = BuildActionMatrix(policy, false);
            NxPreRoutingSet nxprs = new NxPreRoutingSet(channel, policy, Guid.NewGuid(), Guid.NewGuid());
            XmlNode xml = nxprs.Create();

            XmlNodeList nodes = xml.SelectNodes("ObjectLookup");

            XmlNode objLookup = nodes[0];
            Assert.AreEqual("LDAPAnalyzer", objLookup.Attributes["objectId"].Value);
            Assert.AreEqual("IsLdapEnabled", objLookup.Attributes["member"].Value);
        }
示例#20
0
        public void TestExportChannels()
        {           
            string policyCatalogueFilename = m_testPath + "SamplePolicyCatalogue.xml";
            string policyLanguageFilename = m_testPath + "SampleLanguageBase.xml";
            string policyFilename = m_testPath + "SamplePolicy.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.AddLanguage(System.IO.File.ReadAllText(policyLanguageFilename));
            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(policyCatalogueFilename));

            XmlStore store = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            IPolicyObjectCollection<IPolicySet> policySet = store.Reader.PolicySets;
            IPolicyObjectCollection<IPolicy> policies = store.Reader.Policies(policySet[0]);
            IPolicy policy = policies[0];
            IPolicySet ps = policySet[0];

            NxPolicyStore policyStore = new NxPolicyStore();
            policyStore.ResourceManager = ResourcesCache.GetResources();
            ps.Export(policyStore);

            string nxstore = policyStore.XMLRepresentation;
            CompiledPolicySetExtractor pse = new CompiledPolicySetExtractor(nxstore);
            List<string> channelNames = pse.GetChannelNames();
            foreach (string channel in channelNames)
            {
                Assert.AreNotEqual("", pse.GetRules(channel));
                Assert.AreNotEqual("", pse.GetObjects(channel));
            }
        }
示例#21
0
 void CreateXmlDatabase()
 {
     databasePath = GetFreeDatabase("TestDatabase{0}.xml");
     DeleteFileWithRetries(databasePath, 1);
     createNewDatabaseDialog.CreateXmlDatabase(databasePath);
     isLoaded = true;
     createNewDatabaseDialog = null;
     Database = new XmlStore(databasePath, null);
 }
示例#22
0
        public static XmlStore CreateXmlStore(Boolean lazyLoading, Boolean embeddedImages, Boolean automaticBackup)
        {
            XmlStore result = CreateXmlStore();

            result.LazyLoading          = lazyLoading;
            result.BackupGenerationMode = automaticBackup ? XmlStore.BackupFileGenerationMode.BakFile : XmlStore.BackupFileGenerationMode.None;
            result.ImageLocation        = embeddedImages ? XmlStore.ImageFileLocation.Embedded : XmlStore.ImageFileLocation.Directory;
            return(result);
        }
 public PublishedMemberCache(XmlStore xmlStore, IAppCache requestCache, IMemberService memberService,
                             PublishedContentTypeCache contentTypeCache, IUmbracoContextAccessor umbracoContextAccessor)
 {
     _requestCache           = requestCache;
     _memberService          = memberService;
     _xmlStore               = xmlStore;
     _contentTypeCache       = contentTypeCache;
     _umbracoContextAccessor = umbracoContextAccessor;
 }
        public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache)
            : base(false)
        {
            _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService));
            _userService  = userService ?? throw new ArgumentNullException(nameof(userService));

            _cacheProvider    = cacheProvider;
            _xmlStore         = xmlStore;
            _contentTypeCache = contentTypeCache;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PreviewContent"/> class for a user.
        /// </summary>
        /// <param name="xmlStore">The underlying Xml store.</param>
        /// <param name="userId">The user identifier.</param>
        public PreviewContent(XmlStore xmlStore, int userId)
        {
            if (xmlStore == null)
            {
                throw new ArgumentNullException(nameof(xmlStore));
            }
            _xmlStore = xmlStore;

            _userId         = userId;
            _previewSet     = Guid.NewGuid();
            _previewSetPath = GetPreviewSetPath(_userId, _previewSet);
        }
示例#26
0
		public XmlPolicyWriter(XmlStore store)
		{
			m_store = store;

			m_xmlDocument = new XmlDocument();
			XmlProcessingInstruction processingInstruction = m_xmlDocument.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
			m_xmlDocument.AppendChild(processingInstruction);
			m_xmlRootNode = m_xmlDocument.CreateElement("PolicySetStore");
			m_xmlDocument.AppendChild(m_xmlRootNode);

			m_policieSetsNode = m_xmlDocument.CreateElement("PolicySets");
			m_xmlRootNode.AppendChild(m_policieSetsNode);
		}
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_txDictionary != null)
                {
                    try
                    {
                        foreach (var tx in _txDictionary.Values)
                        {
                            tx.Dispose();
                        }
                    }
                    finally
                    {
                        _txDictionary = null;
                    }
                }

                if (_xmlModels != null)
                {
                    try
                    {
                        foreach (var vsXmlModel in _xmlModels.Values)
                        {
                            vsXmlModel.Dispose();
                        }
                    }
                    finally
                    {
                        _xmlModels = null;
                    }
                }

                if (_xmlStore != null)
                {
                    try
                    {
                        _xmlStore.EditingScopeCompleted -= OnXmlModelTransactionCompleted;
                        _xmlStore.UndoRedoCompleted     -= OnXmlModelUndoRedoCompleted;
                        _xmlStore.Dispose();
                    }
                    finally
                    {
                        _xmlStore = null;
                    }
                }
            }

            base.Dispose(disposing);
        }
        public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService,
                                   IAppCache appCache, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer,
                                   IUmbracoContextAccessor umbracoContextAccessor)
            : base(false)
        {
            _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService));
            _userService  = userService ?? throw new ArgumentNullException(nameof(userService));

            _appCache               = appCache;
            _xmlStore               = xmlStore;
            _contentTypeCache       = contentTypeCache;
            _entitySerializer       = entitySerializer;
            _umbracoContextAccessor = umbracoContextAccessor;
        }
示例#29
0
		public XmlPolicyReader(XmlStore policyStore)
		{
			if (policyStore == null)
				return;

			m_policyStore = policyStore;

			m_policyDocument = new XmlDocument();
			string policyXML = policyStore.StoreXML;
			if (policyXML.Length > 0)
			{
				m_policyDocument.LoadXml(policyXML);
				PolicyValidator.ValidatePolicy(this.GetType(), m_policyDocument);
			}
		}
        public void XmlStore_Save_Stress()
        {
            var store = new XmlStore <People>(Path);

            for (int i = 0; i < 100; i++)
            {
                store.Value.Persons.Add(new Person
                {
                    ID        = i,
                    FirstName = "User",
                    LastName  = "#" + 1
                });
                store.Save();
            }
        }
 /// <summary>
 ///     Create a new XML model provider.
 /// </summary>
 public VSXmlModelProvider(IServiceProvider services, IXmlDesignerPackage xmlDesignerPackage)
 {
     Debug.Assert(services != null);
     Debug.Assert(xmlDesignerPackage != null);
     _xmlDesignerPackage = xmlDesignerPackage;
     _services           = services;
     if (_xmlStore == null)
     {
         var xmlEditorService = (XmlEditorService)services.GetService(
             typeof(XmlEditorService));
         _xmlStore = xmlEditorService.CreateXmlStore();
         _xmlStore.EditingScopeCompleted += OnXmlModelTransactionCompleted;
         _xmlStore.UndoRedoCompleted     += OnXmlModelUndoRedoCompleted;
     }
 }
 /// <summary>
 ///     Create a new XML model provider.
 /// </summary>
 public VSXmlModelProvider(IServiceProvider services, IXmlDesignerPackage xmlDesignerPackage)
 {
     Debug.Assert(services != null);
     Debug.Assert(xmlDesignerPackage != null);
     _xmlDesignerPackage = xmlDesignerPackage;
     _services = services;
     if (_xmlStore == null)
     {
         var xmlEditorService = (XmlEditorService)services.GetService(
             typeof(XmlEditorService));
         _xmlStore = xmlEditorService.CreateXmlStore();
         _xmlStore.EditingScopeCompleted += OnXmlModelTransactionCompleted;
         _xmlStore.UndoRedoCompleted += OnXmlModelUndoRedoCompleted;
     }
 }
示例#33
0
        public void TestReadPolicyChannels()
        {
            string testCatalogue = m_testPath + "TestRealPolicyCatalogue.xml";
            string languageFilename = m_testPath + "TestRealPolicyLanguage.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            languageStore.AddLanguage(System.IO.File.ReadAllText(languageFilename));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            string filename = m_testPath + "TestRealPolicySet.xml";
            XmlStore store = new XmlStore(System.IO.File.ReadAllText(filename));

            XmlPolicyReader xmlPolicyReader = store.Reader as XmlPolicyReader;
            IPolicyObjectCollection<IPolicySet> policySets = xmlPolicyReader.PolicySets;
            Assert.IsNotNull(policySets);
            Assert.AreEqual(1, policySets.Count, "Expected one policy");
            IPolicyObjectCollection<IPolicy> policies = xmlPolicyReader.Policies(policySets[0]);
            Assert.AreEqual(3, policies.Count);

            int index = 0;
            IPolicy policy = policies[index++];
            Assert.IsFalse(policy.ReadOnly);
            //assert that the conditions object is unchanged after accessing policy channels
            //important - must access policy.Channels AFTER the first access of policy.Conditions, otherwise the test will always pass!
            ICondition condition1 = ((ICondition)((IConditionGroup)policy.Conditions[0]).Conditions[0]);
            IPolicyObjectCollection<IPolicyChannel> channels = policy.Channels;
            ICondition condition2 = ((ICondition)((IConditionGroup)policy.Conditions[0]).Conditions[0]);
            Assert.IsTrue(Object.ReferenceEquals(condition1, condition2), "Expected to get same condition object");
            Assert.IsTrue(Object.ReferenceEquals(condition1, condition1.Parent.Conditions[0]), "Expected to get same condition object");
            Assert.AreEqual(1, channels.Count);

            policy = policies[index++];
            channels = policy.Channels;
            Assert.IsFalse(policy.ReadOnly);
            Assert.AreEqual("Global", policy.Name.Value);
            Assert.AreEqual(2, channels.Count);

            policy = policies[index++];
            channels = policy.Channels;
            Assert.IsFalse(policy.ReadOnly);
            Assert.AreEqual("Financial Disclosure", policy.Name.Value);
            Assert.AreEqual(2, channels.Count);
            Assert.AreSame(channels, policy.Channels, "Expected to get same object");
        }
示例#34
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="xmlStore">THe XML Store</param>
        /// <param name="xmlModel">The XML Model</param>
        /// <param name="provider">The Service Provider</param>
        /// <param name="buffer">The buffer</param>
        public ViewModel(XmlStore xmlStore, XmlModel xmlModel, IServiceProvider provider, IVsTextLines buffer, string fileName, XmlModel defaultTables)
        {
            if (defaultTables == null)
            {
                throw new ArgumentNullException("defaultTables");
            }
            if (xmlModel == null)
            {
                throw new ArgumentNullException("xmlModel");
            }
            if (xmlStore == null)
            {
                throw new ArgumentNullException("xmlStore");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            BufferDirty   = false;
            DesignerDirty = false;

            ServiceProvider = provider;
            _buffer         = buffer;

            _xmlStore = xmlStore;
            // OnUnderlyingEditCompleted
            _editingScopeCompletedHandler    = new EventHandler <XmlEditingScopeEventArgs>(OnUnderlyingEditCompleted);
            _xmlStore.EditingScopeCompleted += _editingScopeCompletedHandler;
            // OnUndoRedoCompleted
            _undoRedoCompletedHandler    = new EventHandler <XmlEditingScopeEventArgs>(OnUndoRedoCompleted);
            _xmlStore.UndoRedoCompleted += _undoRedoCompletedHandler;

            _defaultTables = defaultTables;
            _xmlModel      = xmlModel;

            // BufferReloaded
            _bufferReloadedHandler   += new EventHandler(BufferReloaded);
            _xmlModel.BufferReloaded += _bufferReloadedHandler;

            m_FileName = fileName;

            LoadModelFromXmlModel();
        }
示例#35
0
        // Returns false, if the save should be retried with another project name.
        private bool SaveProjectAs()
        {
            bool result = false;

            if (((CachedRepository)project.Repository).Store is XmlStore)
            {
                XmlStore xmlStore = (XmlStore)((CachedRepository)project.Repository).Store;

                // Select a file name
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.CreatePrompt    = false;                         // Do not ask wether to create the file
                saveFileDialog.CheckFileExists = false;                         // Do not check wether the file does NOT exist
                saveFileDialog.CheckPathExists = true;                          // Ask wether to overwrite existing file
                saveFileDialog.Filter          = "NShape XML Repositories|*.nspj;*.xml|All Files|*.*";
                if (Directory.Exists(xmlStore.DirectoryName))
                {
                    saveFileDialog.InitialDirectory = xmlStore.DirectoryName;
                }
                else
                {
                    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                }
                saveFileDialog.FileName = Path.GetFileName(xmlStore.ProjectFilePath);

                // Try to save repository to file...
                if (saveFileDialog.ShowDialog().GetValueOrDefault(false))
                {
                    // Set the selected project name (file name) and the location (directory)
                    xmlStore.DirectoryName = Path.GetDirectoryName(saveFileDialog.FileName);
                    project.Name           = Path.GetFileNameWithoutExtension(saveFileDialog.FileName);
                    Title = string.Format("{0} - {1}", appTitle, project.Name);
                    // Delete file if it exists, because the user was prompted wether to overwrite it before (SaveFileDialog.CheckPathExists).
                    if (project.Repository.Exists())
                    {
                        project.Repository.Erase();
                    }
                    saveProjectMenuItem.IsEnabled = true;
                    // Save the project (with error handling and wait cursor)
                    result = SaveProject();
                }
            }
            else
            {
                MessageBox.Show(this, "'Save as...' is not supported for database repositories.", "Not supported", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return(result);
        }
示例#36
0
        public void TestExportChannel()
        {
            string policyCatalogueFilename = m_testPath + "SamplePolicyCatalogueWithSingleChannel.xml";
            string policyLanguageFilename = m_testPath + "SampleLanguageBase.xml";
            string policyFilename = m_testPath + "SamplePolicyWithSingleChannel.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            Guid languageId = languageStore.AddLanguage(System.IO.File.ReadAllText(policyLanguageFilename));
            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();

            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(policyCatalogueFilename));

            XmlStore store = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            IPolicyObjectCollection<IPolicySet> policySet = store.Reader.PolicySets;
            IPolicyObjectCollection<IPolicy> policies = store.Reader.Policies(policySet[0]);
            IPolicy policy = policies[0];
            IPolicySet ps = policySet[0];

            NxPolicyStore policyStore = new NxPolicyStore();
            policyStore.ResourceManager = ResourcesCache.GetResources();
            ps.Export(policyStore);

            string nxstore = policyStore.XMLRepresentation;
            string emailrules = System.IO.Path.GetTempFileName();
            string emailobjects = System.IO.Path.GetTempFileName();

            CompiledPolicySetExtractor pse = new CompiledPolicySetExtractor(nxstore);
            System.IO.File.WriteAllText(emailrules, pse.GetRules("SMTP"));
            System.IO.File.WriteAllText(emailobjects, pse.GetObjects("SMTP"));

            pse.GetLanguages();
      
            XmlDocument rulesXml = new XmlDocument();
            rulesXml.Load(emailrules);

            string xpath = string.Format("/xBusinessRules/Set");
            XmlNodeList nodes = rulesXml.SelectNodes(xpath);

            Assert.AreEqual("Policies", nodes[0].Attributes["id"].Value);
            Assert.AreEqual("w-C1C0D5EA-5B82-4607-AE41-D52739AA6AB1", nodes[1].Attributes["id"].Value);
            Assert.AreEqual("w-c7d62e10-d889-4ef5-af3d-823c82c230ca", nodes[2].Attributes["id"].Value);
            Assert.AreEqual("w-af6e5d89-0c6f-4b10-9a6c-658d13cd3ea8", nodes[4].Attributes["id"].Value);

            System.IO.File.Delete(emailrules);
            System.IO.File.Delete(emailobjects);
        }
示例#37
0
 public override bool EnsureEnvironment(out IEnumerable <string> errors)
 {
     // Test creating/saving/deleting a file in the same location as the content xml file
     // NOTE: We cannot modify the xml file directly because a background thread is responsible for
     // that and we might get lock issues.
     try
     {
         XmlStore.EnsureFilePermission();
         errors = Enumerable.Empty <string>();
         return(true);
     }
     catch
     {
         errors = new[] { SystemFiles.GetContentCacheXml(_globalSettings) };
         return(false);
     }
 }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                RegisterIndependentView(false);

                using (_model)
                {
                    _model = null;
                }
                using (_store)
                {
                    _store = null;
                }
            }
            base.Dispose(disposing);
        }
示例#39
0
        public void SetUpTest()
        {

            m_stateMachine = new DynamicMock(typeof(IStateMachine));

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            IPolicyLanguage language = new PolicyLanguage(new Guid("{E8B22533-98EB-4D00-BDE4-406DC3E1858B}"), "en");
            languageStore.AddLanguage(language);
            PolicyLanguageCache.Instance.ActiveLanguageId = language.Identifier;
            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            PolicyCatalogue policyCatalogue = new PolicyCatalogue(new Guid("{AB5E2A43-01FB-4AA6-98FC-8F74BB0621CA}"), language.Identifier, new TranslateableLanguageItem("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), catalogueStore);
            catalogueStore.AddPolicyCatalogue(policyCatalogue);
            IPolicyStore policyStore = new XmlStore();
            m_policySet = new PolicySet(Guid.NewGuid(), new TranslateableLanguageItem("TestPolicySet"), policyStore, policyCatalogue, false);
        }
示例#40
0
        /// <summary>
        /// Reads the data from file.
        /// </summary>
        protected virtual void ReadDataFromFile()
        {
            if (File.Exists(FILE_PATH))
            {
                using (FileStream file = new FileStream(FILE_PATH, FileMode.OpenOrCreate)) {
                    if (file.Length > 0)
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(XmlStore));
                        _XML_STORE = (XmlStore)serializer.Deserialize(file);
                    }
                }
            }

            if (null == _XML_STORE)
            {
                _XML_STORE = new XmlStore();
            }
        }
        public void XmlStore_Save_DirectBatch()
        {
            var store = new XmlStore <People>(Path)
            {
                DirectWrite = true
            };

            for (int i = 0; i < 1000; i++)
            {
                store.Value.Persons.Add(new Person
                {
                    ID        = i,
                    FirstName = "User",
                    LastName  = "#" + 1
                });
            }

            store.Save();
        }
        // used in some tests
        internal XmlPublishedSnapshotService(
            ServiceContext serviceContext,
            IPublishedContentTypeFactory publishedContentTypeFactory,
            IScopeProvider scopeProvider,
            IAppCache requestCache,
            IPublishedSnapshotAccessor publishedSnapshotAccessor,
            IVariationContextAccessor variationContextAccessor,
            IUmbracoContextAccessor umbracoContextAccessor,
            IDocumentRepository documentRepository,
            IMediaRepository mediaRepository,
            IMemberRepository memberRepository,
            IDefaultCultureAccessor defaultCultureAccessor,
            ILoggerFactory loggerFactory,
            GlobalSettings globalSettings,
            IHostingEnvironment hostingEnvironment,
            IApplicationShutdownRegistry hostingLifetime,
            IShortStringHelper shortStringHelper,
            IEntityXmlSerializer entitySerializer,
            PublishedContentTypeCache contentTypeCache,
            MainDom mainDom,
            bool testing,
            bool enableRepositoryEvents)
        {
            _routesCache = new RoutesCache();
            _publishedContentTypeFactory = publishedContentTypeFactory;
            _contentTypeCache            = contentTypeCache
                                           ?? new PublishedContentTypeCache(serviceContext.ContentTypeService, serviceContext.MediaTypeService, serviceContext.MemberTypeService, publishedContentTypeFactory, loggerFactory.CreateLogger <PublishedContentTypeCache>());

            _xmlStore = new XmlStore(serviceContext.ContentTypeService, serviceContext.ContentService, scopeProvider, _routesCache,
                                     _contentTypeCache, publishedSnapshotAccessor, mainDom, testing, enableRepositoryEvents,
                                     documentRepository, mediaRepository, memberRepository, entitySerializer, hostingEnvironment, hostingLifetime, shortStringHelper);

            _domainService            = serviceContext.DomainService;
            _mediaService             = serviceContext.MediaService;
            _userService              = serviceContext.UserService;
            _defaultCultureAccessor   = defaultCultureAccessor;
            _variationContextAccessor = variationContextAccessor;
            _requestCache             = requestCache;
            _umbracoContextAccessor   = umbracoContextAccessor;
            _globalSettings           = globalSettings;
            _entitySerializer         = entitySerializer;
        }
示例#43
0
        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;

                //string policyXML = System.IO.File.ReadAllText(@"P:\Projects\Hygiene\src\PolicyDesigner\SamplePolicy.xml");
                string policyXML = System.IO.File.ReadAllText(FileName);

                IPolicyStore store = new XmlStore(policyXML);

                MDIChild form = new MDIChild(store, FileName);
                form.MdiParent = this;
                form.Show();
                form.WindowState = FormWindowState.Maximized;
                
            }
        }
        public ViewModel(XmlStore xmlStore, XmlModel xmlModel, IServiceProvider provider, IVsTextLines buffer)
        {
            if (xmlModel == null)
            {
                throw new ArgumentNullException("xmlModel");
            }
            if (xmlStore == null)
            {
                throw new ArgumentNullException("xmlStore");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            this.BufferDirty   = false;
            this.DesignerDirty = false;

            this._serviceProvider = provider;
            this._buffer          = buffer;

            this._xmlStore = xmlStore;
            // OnUnderlyingEditCompleted
            _editingScopeCompletedHandler         = new EventHandler <XmlEditingScopeEventArgs>(OnUnderlyingEditCompleted);
            this._xmlStore.EditingScopeCompleted += _editingScopeCompletedHandler;
            // OnUndoRedoCompleted
            _undoRedoCompletedHandler         = new EventHandler <XmlEditingScopeEventArgs>(OnUndoRedoCompleted);
            this._xmlStore.UndoRedoCompleted += _undoRedoCompletedHandler;

            this._xmlModel = xmlModel;
            // BufferReloaded
            _bufferReloadedHandler        += new EventHandler(BufferReloaded);
            this._xmlModel.BufferReloaded += _bufferReloadedHandler;

            LoadModelFromXmlModel();
        }
        protected override void Initialize()
        {
            base.Initialize();

            _httpContextFactory = new FakeHttpContextFactory("~/Home");

            var globalSettings         = new GlobalSettings();
            var umbracoContextAccessor = Factory.GetRequiredService <IUmbracoContextAccessor>();

            _xml = new XmlDocument();
            _xml.LoadXml(GetXml());
            var xmlStore          = new XmlStore(() => _xml, null, null, null, HostingEnvironment);
            var appCache          = new DictionaryAppCache();
            var domainCache       = new DomainCache(Mock.Of <IDomainService>(), DefaultCultureAccessor);
            var publishedShapshot = new PublishedSnapshot(
                new PublishedContentCache(xmlStore, domainCache, appCache, globalSettings, ContentTypesCache, null, VariationContextAccessor, null),
                new PublishedMediaCache(xmlStore, Mock.Of <IMediaService>(), Mock.Of <IUserService>(), appCache, ContentTypesCache, Factory.GetRequiredService <IEntityXmlSerializer>(), umbracoContextAccessor, VariationContextAccessor),
                new PublishedMemberCache(ContentTypesCache, VariationContextAccessor),
                domainCache);
            var publishedSnapshotService = new Mock <IPublishedSnapshotService>();

            publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(publishedShapshot);

            var httpContext         = _httpContextFactory.HttpContext;
            var httpContextAccessor = TestHelper.GetHttpContextAccessor(httpContext);

            _umbracoContext = new UmbracoContext(
                httpContextAccessor,
                publishedSnapshotService.Object,
                Mock.Of <IBackOfficeSecurity>(),
                globalSettings,
                HostingEnvironment,
                new TestVariationContextAccessor(),
                UriUtility,
                new AspNetCookieManager(httpContextAccessor));

            _cache = _umbracoContext.Content;
        }
示例#46
0
        /// <summary>
        /// Called after the WindowPane has been sited with an IServiceProvider from the environment
        /// 
        protected override void Initialize()
        {
            base.Initialize();

            // Create and initialize the editor
            #region Register with IOleComponentManager
            IOleComponentManager componentManager = (IOleComponentManager)GetService(typeof(SOleComponentManager));
            if (this._componentId == 0 && componentManager != null)
            {
                OLECRINFO[] crinfo = new OLECRINFO[1];
                crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime | (uint)_OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 100;
                int hr = componentManager.FRegisterComponent(this, crinfo, out this._componentId);
                ErrorHandler.Succeeded(hr);
            }
            #endregion

            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditorPane));

            #region Hook Undo Manager
            // Attach an IOleUndoManager to our WindowFrame. Merely calling QueryService
            // for the IOleUndoManager on the site of our IVsWindowPane causes an IOleUndoManager
            // to be created and attached to the IVsWindowFrame. The WindowFrame automaticall
            // manages to route the undo related commands to the IOleUndoManager object.
            // Thus, our only responsibilty after this point is to add IOleUndoUnits to the
            // IOleUndoManager (aka undo stack).
            _undoManager = (IOleUndoManager)GetService(typeof(SOleUndoManager));

            // In order to use the IVsLinkedUndoTransactionManager, it is required that you
            // advise for IVsLinkedUndoClient notifications. This gives you a callback at
            // a point when there are intervening undos that are blocking a linked undo.
            // You are expected to activate your document window that has the intervening undos.
            if (_undoManager != null)
            {
                IVsLinkCapableUndoManager linkCapableUndoMgr = (IVsLinkCapableUndoManager)_undoManager;
                if (linkCapableUndoMgr != null)
                {
                    linkCapableUndoMgr.AdviseLinkedUndoClient(this);
                }
            }
            #endregion

            // hook up our
            XmlEditorService es = GetService(typeof(XmlEditorService)) as XmlEditorService;
            _store = es.CreateXmlStore();
            _store.UndoManager = _undoManager;

            _model = _store.OpenXmlModel(new Uri(_fileName));

            // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
            // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
            // the object returned by the Content property.
            _vsDesignerControl = new VsDesignerControl(_service, new ViewModel(_store, _model, this, _textBuffer));
            base.Content = _vsDesignerControl;

            RegisterIndependentView(true);

            IMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as IMenuCommandService;
            if (null != mcs)
            {
                // Now create one object derived from MenuCommnad for each command defined in
                // the CTC file and add it to the command service.

                // For each command we have to define its id that is a unique Guid/integer pair, then
                // create the OleMenuCommand object for this command. The EventHandler object is the
                // function that will be called when the user will select the command. Then we add the
                // OleMenuCommand to the menu service.  The addCommand helper function does all this for us.
                AddCommand(mcs, VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.NewWindow,
                                new EventHandler(OnNewWindow), new EventHandler(OnQueryNewWindow));
                AddCommand(mcs, VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.ViewCode,
                                new EventHandler(OnViewCode), new EventHandler(OnQueryViewCode));
            }
        }
示例#47
0
        public void TestAddPolicyToExistingPolicySet()
        {
            string testCatalogue = m_testPath + "TestRealPolicyCatalogue.xml";
            string languageFilename = m_testPath + "TestRealPolicyLanguage.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            string languageName;
            Guid languageId = languageStore.AddLanguage(System.IO.File.ReadAllText(languageFilename), out languageName);

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            PolicyCatalogue policyCatalogue = catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            string policyFilename = m_testPath + "TestAddPolicyToExistingPolicySet.xml";
            XmlStore policyStore = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            XmlPolicyReader xmlPolicyReader = policyStore.Reader as XmlPolicyReader;
            IPolicySet policySet = xmlPolicyReader.PolicySets[0];

            // Add a new policy to the policy set
            PolicyLanguageCache.Instance.SetLanguageItemText(languageId, new Guid("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), "New policy");

            IPolicy newPolicy = new P5Policy(policySet, new Guid("{D257D4DC-4A12-438F-A32A-CF1CE4474441}"), new TranslateableLanguageItem("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), PolicyStatus.Active);
            policySet.Policies.Add(newPolicy);
            // Save everything

            IPolicyCatalogueWriter catalogueWriter = catalogueStore.GetWriter(policyCatalogue.Identifier, languageId);
            catalogueWriter.WriteCatalogue(policyCatalogue);
            catalogueWriter.Close();

            policySet.Save();

            TestHelpers.CompareXml(m_testPath + "TestRealPolicyCatalogue.Modified.xml", catalogueStore.GetStoreXML(policyCatalogue.Identifier));
            TestHelpers.CompareXml(m_testPath + "TestAddPolicyToExistingPolicySet.Modified.xml", policyStore.XMLRepresentation);
            TestHelpers.CompareXml(m_testPath + "TestAddPolicyToExistingPolicySet.Language.Modified.xml", languageStore.GetXMLRepresentation(languageId, languageName));
        }
示例#48
0
        /// <summary>
        /// Called after the WindowPane has been sited with an IServiceProvider from the environment
        ///
        protected override void Initialize()
        {
            base.Initialize();

            // Create and initialize the editor
            #region Register with IOleComponentManager
            IOleComponentManager componentManager = (IOleComponentManager)GetService(typeof(SOleComponentManager));
            if (this._componentId == 0 && componentManager != null)
            {
                OLECRINFO[] crinfo = new OLECRINFO[1];
                crinfo[0].cbSize            = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf            = (uint)_OLECRF.olecrfNeedIdleTime | (uint)_OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf          = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 100;
                int hr = componentManager.FRegisterComponent(this, crinfo, out this._componentId);
                ErrorHandler.Succeeded(hr);
            }
            #endregion

            ComponentResourceManager resources = new ComponentResourceManager(typeof(ManifestEditorPane));

            #region Hook Undo Manager
            // Attach an IOleUndoManager to our WindowFrame. Merely calling QueryService
            // for the IOleUndoManager on the site of our IVsWindowPane causes an IOleUndoManager
            // to be created and attached to the IVsWindowFrame. The WindowFrame automaticall
            // manages to route the undo related commands to the IOleUndoManager object.
            // Thus, our only responsibilty after this point is to add IOleUndoUnits to the
            // IOleUndoManager (aka undo stack).
            _undoManager = (IOleUndoManager)GetService(typeof(SOleUndoManager));

            // In order to use the IVsLinkedUndoTransactionManager, it is required that you
            // advise for IVsLinkedUndoClient notifications. This gives you a callback at
            // a point when there are intervening undos that are blocking a linked undo.
            // You are expected to activate your document window that has the intervening undos.
            if (_undoManager != null)
            {
                IVsLinkCapableUndoManager linkCapableUndoMgr = (IVsLinkCapableUndoManager)_undoManager;
                if (linkCapableUndoMgr != null)
                {
                    linkCapableUndoMgr.AdviseLinkedUndoClient(this);
                }
            }
            #endregion

            // hook up our
            XmlEditorService es = GetService(typeof(XmlEditorService)) as XmlEditorService;
            _store             = es.CreateXmlStore();
            _store.UndoManager = _undoManager;

            _model = _store.OpenXmlModel(new Uri(_fileName));

            // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
            // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
            // the object returned by the Content property.
            //_vsDesignerControl = new VsDesignerControl(new ViewModel(_store, _model, this, _textBuffer));
            EnvDTE.DTE dte = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
            _ManifestDesignerControl = new TizenManifestDesignerControl(new ViewModelTizen(_store, _model, this, _textBuffer), dte);
            Content = _ManifestDesignerControl;

            _ManifestDesignerControl.IsEnabledChanged += _ManifestDesignerControl_IsEnabledChanged;

            RegisterIndependentView(true);

            if (GetService(typeof(IMenuCommandService)) is IMenuCommandService mcs)
            {
                // Now create one object derived from MenuCommnad for each command defined in
                // the CTC file and add it to the command service.

                // For each command we have to define its id that is a unique Guid/integer pair, then
                // create the OleMenuCommand object for this command. The EventHandler object is the
                // function that will be called when the user will select the command. Then we add the
                // OleMenuCommand to the menu service.  The addCommand helper function does all this for us.
                AddCommand(mcs, VSConstants.GUID_VSStandardCommandSet97, (int)VSStd97CmdID.NewWindow, new EventHandler(OnNewWindow), new EventHandler(OnQueryNewWindow));
                AddCommand(mcs, VSConstants.GUID_VSStandardCommandSet97, (int)VSStd97CmdID.ViewCode, new EventHandler(OnViewCode), new EventHandler(OnQueryViewCode));
            }
        }
示例#49
0
        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                RegisterIndependentView(false);

                using (_model)
                {
                    _model = null;
                }
                using (_store)
                {
                    _store = null;
                }
            }
            base.Dispose(disposing);
        }
示例#50
0
        public void TestActionExceptionHandlerWithOffline()
        {
            string testCatalogue = m_testPath + "TestActionExceptionHandlerWithOffline.Catalogue.xml";
            string testLanguage = m_testPath + "TestActionExceptionHandlerWithOffline.Language.xml";

            Guid languageId = XmlPolicyLanguageStore.Instance.AddLanguage(System.IO.File.ReadAllText(testLanguage));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            PolicyCatalogue policyCatalogue = catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            XmlStore store = new XmlStore();

            ObjectModel.PolicySet policySet = new ObjectModel.PolicySet(new Guid("{8FC9EB93-C376-4E96-B22E-71FAA848393D}"), new TranslateableLanguageItem("{D803727B-5C81-44CC-8BFC-9B68797AC6EB}"), store, policyCatalogue, false);
            P5Policy policy = new P5Policy(store, policySet, new Guid("{C0F6D4BB-CBF1-41FC-8A28-616D6FC1DC73}"), new TranslateableLanguageItem("{F0DD86A0-5D21-4784-88AF-C5321B5998F6}"), PolicyStatus.Active);

            IPolicyObjectCollection<IPolicyChannel> channels = new PolicyObjectCollection<IPolicyChannel>();
            PolicyChannel channel = new PolicyChannel(new Guid("{390F589A-24B0-4DF0-B750-D47EDD1FF0BE}"), new TranslateableLanguageItem("{463A0FAF-CE8C-470E-8077-A093B9350719}"), ChannelType.SMTP);

            // Build the ActionException cell for the action matrix.
            IActionMatrix actions = new ObjectModel.ActionMatrix();

            ActionExceptionCell actionExceptionCell = actions.ActionExceptionHandler as ObjectModel.ActionExceptionCell;
            Assert.IsNotNull(actionExceptionCell);

            OfflineActionMatrixCell offlineCell = actions.Offline as OfflineActionMatrixCell;

            ConditionGroup conditionGroup = new ConditionGroup(new Guid("{661EDD6F-D750-493A-9932-E56C8C22E2CF}"), new TranslateableLanguageItem("Test condition group"), ConditionLogic.AND, false);
            ICondition subCondition = new Condition(new Guid("{6B7F6B0C-747A-4BD0-A65D-A1FB9E44FE7C}"), "ITestOne", OperatorType.GreaterThan);

            DataMethod dataMethod = new DataMethod("Test method");
            dataMethod.Parameters.Add(new Parameter("FindSomething", new DataElement(new TranslateableLanguageItem("string value"), new TranslateableLanguageItem(""), DataType.String, "missing")));
            dataMethod.Parameters.Add(new Parameter("RunSomething", new DataElement(new TranslateableLanguageItem("string value"), new TranslateableLanguageItem(""), DataType.String, "just do it!")));
            DataSource dataSource = new DataSource("Testme.dll", "TestMe", dataMethod);
            subCondition.DataLeft = new DataElement(new Guid("{4E2F50C5-D310-47A1-AE3A-621F5C77FA68}"), new TranslateableLanguageItem("Do testing stuff"), new TranslateableLanguageItem(""), DataType.Object, dataSource);
            IDataItem dataItem = DataItem.CreateDataItem(new TranslateableLanguageItem("Test data item"), DataType.Long, "10");
            subCondition.DataRight = new DataElement(new Guid("{EB56B397-954D-45C2-ADBA-263372A8B59F}"), new TranslateableLanguageItem("Test data item stored in data element"), new TranslateableLanguageItem(""), DataType.Long, dataItem);
            conditionGroup.Conditions.Add(subCondition);

            policy.Conditions.Add(conditionGroup);
            actionExceptionCell.AddActionCondition(conditionGroup, BuildActionGroup(), false);

            channel.Actions = actions;
            channels.Add(channel);
            policy.Channels = channels;

            Store.IPolicyStoreWriter writer = store.Writer;
            Assert.IsNotNull(writer, "Expected a valid [IPolicyStoreWriter] writer");
            writer.WritePolicySet(policySet);
            writer.WritePolicy(policySet, policy);
            writer.WriteChildCollection(policySet, policy, policy.Name.Value, policy.Conditions);
            writer.WriteChildCollection(policySet, policy, policy.Name.Value, CollectionConverter.Convert<IPolicyChannel, IPolicyObject>(channels));
            writer.Close();

            string expectedPolicySetFile = m_testPath + "TestActionExceptionHandlerWithOffline.PolicySet.xml";
            TestHelpers.CompareXml(expectedPolicySetFile, store.StoreXML);
        }
示例#51
0
        public void TestWriteHttpOfflineNoActions()
        {
            string testCatalogue = m_testPath + "TestHttpOfflineRouting.Catalogue.xml";
            string testLanguage = m_testPath + "TestHttpOfflineRouting.Language.xml";

            Guid languageId = XmlPolicyLanguageStore.Instance.AddLanguage(System.IO.File.ReadAllText(testLanguage));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            PolicyCatalogue policyCatalogue = catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            XmlStore store = new XmlStore();

            ObjectModel.PolicySet policySet = new ObjectModel.PolicySet(new Guid("{8FC9EB93-C376-4E96-B22E-71FAA848393D}"), new TranslateableLanguageItem("{D803727B-5C81-44CC-8BFC-9B68797AC6EB}"), store, policyCatalogue, false);
            P5Policy policy = new P5Policy(store, policySet, new Guid("{C0F6D4BB-CBF1-41FC-8A28-616D6FC1DC73}"), new TranslateableLanguageItem("{F0DD86A0-5D21-4784-88AF-C5321B5998F6}"), PolicyStatus.Active);

            IPolicyObjectCollection<IPolicyChannel> channels = new PolicyObjectCollection<IPolicyChannel>();
            PolicyChannel channel = new PolicyChannel(new Guid("{390F589A-24B0-4DF0-B750-D47EDD1FF0BE}"), new TranslateableLanguageItem("{463A0FAF-CE8C-470E-8077-A093B9350719}"), ChannelType.HTTP);

            // Build the offline cell for the action matrix.
            IActionMatrix actions = new ObjectModel.ActionMatrix();

            OfflineActionMatrixCell offlineCell = actions.Offline as OfflineActionMatrixCell;
            Assert.IsNotNull(offlineCell);

            ConditionGroup conditionGroup = new ConditionGroup(new Guid("{661EDD6F-D750-493A-9932-E56C8C22E2CF}"), new NonTranslateableLanguageItem("Test condition group"), ConditionLogic.AND, false);
            policy.Conditions.Add(conditionGroup);
            offlineCell.AddActionCondition(conditionGroup, BuildActionGroupNoActions(), false);

            channel.Actions = actions;
            channels.Add(channel);
            policy.Channels = channels;

            Store.IPolicyStoreWriter writer = store.Writer;
            Assert.IsNotNull(writer, "Expected a valid [IPolicyStoreWriter] writer");
            writer.WritePolicySet(policySet);
            writer.WritePolicy(policySet, policy);
            writer.WriteChildCollection(policySet, policy, policy.Name.Value, CollectionConverter.Convert<IPolicyChannel, IPolicyObject>(channels));
            writer.Close();

            string expectedPolicySetFile = m_testPath + "TestHttpOfflineNoActions.PolicySet.xml";
            TestHelpers.CompareXml(expectedPolicySetFile, store.StoreXML);

            IPolicyCatalogueWriter catalogueWriter = catalogueStore.GetWriter(policyCatalogue.Identifier, languageId);
            catalogueWriter.WriteCatalogue(policySet.MasterCatalogue);
            catalogueWriter.Close();

            string expectedCatalogueFile = m_testPath + "TestHttpOfflineNoActions.Catalogue.xml";
            TestHelpers.CompareXml(expectedCatalogueFile, catalogueStore.GetStoreXML(policyCatalogue.Identifier));
        }
示例#52
0
        public void TestReadChannelActionMatrix()
        {
            string policyCatalogueFilename = m_testPath + "SamplePolicyCatalogue.xml";
            string policyLanguageFilename = m_testPath + "SampleLanguageBase.xml";
            string policyFilename = m_testPath + "SamplePolicy.xml";

            XmlPolicyLanguageStore.Instance.AddLanguage(System.IO.File.ReadAllText(policyLanguageFilename));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(policyCatalogueFilename));

            XmlStore store = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            XmlPolicyReader xmlPolicyReader = store.Reader as XmlPolicyReader;
            string policySetId = "{8FC9EB93-C376-4E96-B22E-71FAA848393D}";
            string policyId = "{C7D62E10-D889-4EF5-AF3D-823C82C230CA}";
            string xpath = string.Format(@"/PolicySetStore/PolicySets/PolicySet[@id='{0}']/Policies/Policy[@id='{1}']/Channels",
                policySetId, policyId);

            Assert.AreEqual(1, xmlPolicyReader.PolicySets.Count);
            IPolicySet policySet = xmlPolicyReader.PolicySets[0];
            Assert.IsNotNull(policySet);

            IPolicy policy = policySet.Policies[new Guid(policyId)];
            Assert.IsNotNull(policy);

            PolicyObjectCollection<IPolicyChannel> channels = new PolicyObjectCollection<IPolicyChannel>();
            XmlChannelsReader reader = new XmlChannelsReader(xmlPolicyReader, channels, policy, xpath);
            reader.Read();

            Assert.AreEqual(1, channels.Count, "Expected one channel");
            IPolicyChannel channel = channels[0];
            Assert.IsNotNull(channel);
            Assert.IsNotNull(channel.Actions, "Expected a valid instance of the channel actions collection");
            IActionMatrix actionMatrix = channel.Actions;
            Assert.IsNotNull(actionMatrix);
            Assert.AreEqual("", actionMatrix.Name.Value);

            Dictionary<KeyValuePair<Guid, Guid>, IActionMatrixCell>.Enumerator enumerator = actionMatrix.GetEnumerator();
            Assert.IsTrue(enumerator.MoveNext(), "Expectd the enumerator to move to the first item");
            IActionMatrixCell actionMatrixCell = enumerator.Current.Value;
            Assert.IsNotNull(actionMatrixCell, "Expected a valid action matrix cell");
            IPolicyObjectCollection<IActionConditionGroup> actionConditiongroups = actionMatrixCell.ActionConditionGroups;
            Assert.IsNotNull(actionConditiongroups, "Expected a valid action condition group collection");
            Assert.AreEqual(1, actionConditiongroups.Count, "Expected one action condition group collection");
            IActionConditionGroup actionConditionGroup = actionConditiongroups[0];
            Assert.IsNotNull(actionConditionGroup, "Expected a valid action condition group");

            IActionGroup actionGroup = actionConditionGroup.ActionGroup;

            Assert.IsNotNull(actionGroup, "Expected a valid action group");
            Assert.AreEqual(new Guid("{987B7C8B-5ADD-4696-8456-DDE11D95CE0B}"), actionGroup.Identifier);
            Assert.AreEqual("Protect us please", actionGroup.Name.Value);
            Assert.AreEqual(1, actionGroup.ActionGroups.Count);
            IActionGroup subActionGroup = actionGroup.ActionGroups[0];
            Assert.IsNotNull(subActionGroup, "Expected a valid sub-action group");
            Assert.AreEqual(new Guid("{BBEF6879-6D10-455d-A5D9-86D9B8B725A6}"), subActionGroup.Identifier);
            Assert.AreEqual("Email us please", subActionGroup.Name.Value);
            Assert.IsNotNull(subActionGroup.ActionGroups, "Expected the sub-ActionGroup's ActionGroup to be valid");
            Assert.AreEqual(0, subActionGroup.ActionGroups.Count);
            Assert.IsNotNull(subActionGroup.Actions, "Expected the sub-ActionGroup's Actions to be valid");
            Assert.AreEqual(1, subActionGroup.Actions.Count);
            IAction action = subActionGroup.Actions[0];
            Assert.IsNotNull(action, "Expected a valid action");
            Assert.AreEqual(new Guid("{72551FD1-D46D-4af6-8DA3-76B5BCE01FD8}"), action.Identifier);
            Assert.AreEqual("CustomAction2.dll", action.Assembly);
            Assert.IsNotNull(action.DataElements, "Expected the data elements to be valid for the action");
            Assert.AreEqual(1, action.DataElements.Count);
            IDataElement dataElement = action.DataElements[0];
            Assert.IsNotNull(dataElement, "Expected a valid data element");
            Assert.AreEqual(new Guid("{4E2F50C5-D310-47A1-AE3A-621F5C77FA68}"), dataElement.Identifier);
            Assert.AreEqual("Profanity lookup", dataElement.Name.Value);

            Assert.AreEqual(1, actionGroup.Actions.Count);
            action = actionGroup.Actions[0];
            Assert.IsNotNull(action, "Expected a valid action");
            Assert.AreEqual(new Guid("{26BCFA7E-3605-4ee7-ACC6-0AFB4D5EBB71}"), action.Identifier);
            Assert.AreEqual("CustomAction.dll", action.Assembly);
            Assert.IsNotNull(action.DataElements, "Expected the data elements to be valid for the action");
            Assert.AreEqual(1, action.DataElements.Count);
            dataElement = action.DataElements[0];
            Assert.IsNotNull(dataElement, "Expected a valid data element");
            Assert.AreEqual(new Guid("{7CED5561-FD8C-423C-838F-9440EDFE6758}"), dataElement.Identifier);
            Assert.AreEqual("Discrimination lookup", dataElement.Name.Value);
        }
示例#53
0
        static void Main(string[] args)
        {
            //SerializationTest1();
            var labName = "failover";

            var labPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "AutomatedLab-Labs", labName, "Lab.xml");
            var ltest1  = XmlStore <Lab> .Import(labPath);

            var machines2 = ListXmlStore <Machine> .Import(labPath.Replace("Lab.xml", "Machines.xml"));

            var x2 = machines2.SelectMany(m => m.NetworkAdapters).Select(na => na.Ipv4DnsServers);

            XmlValidatorArgs.XmlPath = labPath;
            LabValidatorArgs.XmlPath = labPath;

            var summaryMessageContainer = new ValidationMessageContainer();

            var a = Assembly.GetAssembly(typeof(ValidatorBase));

            foreach (Type t in a.GetTypes())
            {
                if (t.IsSubclassOf(typeof(ValidatorBase)))
                {
                    var validator = (ValidatorBase)Activator.CreateInstance(t);
                    summaryMessageContainer += validator.MessageContainer;

                    Console.WriteLine(t);
                }
            }

            summaryMessageContainer.AddSummary();
            var dasda = summaryMessageContainer.GetFilteredMessages();

            Console.ReadKey();

            var isov = new PathValidator();

            //var messages2 = isov.Validate().ToList();
            var labsDirectory         = new DirectoryInfo(@"C:\Users\randr\Documents\AutomatedLab-Labs");
            var sampleScriptDirectory = new DirectoryInfo(@"C:\Users\randr\Documents\AutomatedLab Sample Scripts");
            var sampleScriptFiles     = sampleScriptDirectory.EnumerateFiles("*.ps1", SearchOption.AllDirectories);

            foreach (var file in sampleScriptFiles)
            {
                var id = Guid.NewGuid();
                IEnumerable <ErrorRecord> errors;
                var scriptContent = File.ReadAllText(file.FullName)
                                    .Replace("Install-Lab", "Export-LabDefinition");

                var labNameStart = scriptContent.IndexOf("'") + 1;
                var labNameEnd   = scriptContent.IndexOf("'", labNameStart);
                scriptContent = scriptContent.Remove(labNameStart, labNameEnd - labNameStart);
                scriptContent = scriptContent.Insert(labNameStart, id.ToString());

                try
                {
                    var result = PowerShellHelper.InvokeCommand(scriptContent, out errors);

                    var labXmlPath = System.IO.Path.Combine(labsDirectory.FullName, id.ToString(), "Lab.xml");
                    var labPaths   = new List <string>()
                    {
                        System.IO.Path.Combine(labsDirectory.FullName, id.ToString(), "Machines.xml")
                    };
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();

            SerializationTest1();
            var l1 = XmlStore <Lab> .Import(@"D:\POSH\Lab.xml");

            //var l1 = XmlStore<Lab>.Import(@"C:\Users\randr_000\Documents\AutomatedLab-Labs\Small1\Lab.xml");

            //var w2012r2 = new AutomatedLab.OperatingSystem("Windows Server 2012 R2 SERVERDATACENTER");
            //var w2012 = new AutomatedLab.OperatingSystem("Windows Server 2012 SERVERDATACENTER");
            //var w2008r2 = new AutomatedLab.OperatingSystem("Windows Server 2008 R2 SERVERSTANDARD");
            //var w2008 = new AutomatedLab.OperatingSystem("Windows Server 2008 SERVERSTANDARD");
            //var w10 = new AutomatedLab.OperatingSystem("Windows Technical Preview");
            //var w7 = new AutomatedLab.OperatingSystem("Windows 7 ENTERPRISE");
            //var w8 = new AutomatedLab.OperatingSystem("Windows 8 Pro");
            //var w81 = new AutomatedLab.OperatingSystem("Windows 8.1 Pro");

            //var w2012r2 = new AutomatedLab.OperatingSystem("2012 R2");
            //var w2012 = new AutomatedLab.OperatingSystem("2012");
            //var w2008r2 = new AutomatedLab.OperatingSystem("2008 R2 SERVERSTANDARD");
            //var w2008 = new AutomatedLab.OperatingSystem("Windows Server 2008 SERVERSTANDARD");
            //var w10 = new AutomatedLab.OperatingSystem("Windows Technical Preview");
            var w7  = new AutomatedLab.OperatingSystem("Windows 7 ENTERPRISE");
            var w8  = new AutomatedLab.OperatingSystem("Windows 8 Pro");
            var w81 = new AutomatedLab.OperatingSystem("Windows 8.1 Pro");
            //var xx1 = w2012.Version;
            var xx2 = w7.Version;

            var ll = new Lab();

            var labPath2 = @"C:\Users\randr_000\Documents\AutomatedLab-Labs\POSH";
            var paths    = new List <string>()
            {
                string.Format(@"{0}\Machines.xml", labPath2)
            };
            //AutomatedLab.LabXmlValidator lv = new AutomatedLab.LabXmlValidator(string.Format(@"{0}\Lab.xml", labPath2), paths.ToArray());
            //lv.RunTests();

            //var results = lv.GetMessages().ToList();

            var lab      = Lab.Import(System.IO.Path.Combine(labPath2, "Lab.xml"));
            var machines = ListXmlStore <Machine> .Import(System.IO.Path.Combine(labPath2, "Machines.xml"));

            var m1 = machines.Where(m => m.Name == "xAZDC1").FirstOrDefault();
            var c1 = m1.GetLocalCredential();

            var x = 5;
        }
示例#54
0
        public void TestReadPolicyAddSecondActionToCell()
        {
            string testCatalogue = m_testPath + "TestRealPolicyCatalogue.xml";
            string languageFilename = m_testPath + "TestRealPolicyLanguage.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            string languageName;
            Guid languageId = languageStore.AddLanguage(System.IO.File.ReadAllText(languageFilename), out languageName);

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            PolicyCatalogue policyCatalogue = catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            string policyFilename = m_testPath + "TestReadPolicyRulesReadAndSave.xml";
            XmlStore policyStore = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            XmlPolicyReader xmlPolicyReader = policyStore.Reader as XmlPolicyReader;
            
            IPolicySet policySet = xmlPolicyReader.PolicySets[0];
            IPolicy policy = policySet.Policies[0];
            Assert.AreEqual(1, policy.Channels.Count, "Expected one channel");

            IPolicyChannel channel = policy.Channels[0];
            IActionMatrix actionMatrix = channel.Actions;

            IRoutingItemCollection senders = policyCatalogue.LocationsCollection[new Guid("{A81631A6-6AA3-45F7-AADD-4853447E5BD6}")];
            Assert.IsNotNull(senders, "Expected a valid sources collection");

            IRoutingItemCollection recipients = policyCatalogue.LocationsCollection[new Guid("{D23F36C4-953F-4ED9-B1EB-8921BD50562B}")];
            Assert.IsNotNull(recipients, "Expected a valid destinations collection");

            // Create a new action matrix cell
            IActionMatrixCell actionMatrixCell = actionMatrix[senders, recipients];

            PolicyLanguageCache policyLanguageCache = PolicyLanguageCache.Instance;
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{5B486305-A84C-4DF0-B29C-94FCB0053761}"), "This is a test action");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{4182414A-C775-4EFB-89FF-54FBAC334D71}"), "This is a test data element");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{25D5679E-B4B5-4C9E-8E85-5A922399B291}"), "This is a test data element description");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{6C94A67C-F43E-4761-89B4-EB0AD75CB29B}"), "This is a test data item");

            ObjectModel.Action action = new ObjectModel.Action(new Guid("{707303BD-3EBB-48FD-93F3-CB72C6AAFF47}"), new TranslateableLanguageItem("{5B486305-A84C-4DF0-B29C-94FCB0053761}"), "TestAssembly.dll", "DoThis.Now", RunAt.Client, false, 1); //TODO JE
            IDataItem dataItem = DataItem.CreateDataItem(new TranslateableLanguageItem("{6C94A67C-F43E-4761-89B4-EB0AD75CB29B}"), DataType.String, "This is a test item");
            action.DataElements.Add(new DataElement(new Guid("{B10BEEC4-E851-4E25-A6AE-C6CEC3F767EB}"), new TranslateableLanguageItem("{4182414A-C775-4EFB-89FF-54FBAC334D71}"), new TranslateableLanguageItem("{25D5679E-B4B5-4C9E-8E85-5A922399B291}"), DataType.String, dataItem));
            IActionConditionGroup actionConditionGroup = actionMatrixCell.ActionConditionGroups[0];
            Assert.IsNotNull(actionConditionGroup, "Expected a valid action condition group");
            actionConditionGroup.ActionGroup.Actions.Add(action);

            // Save everthing
            IPolicyCatalogueWriter catalogueWriter = catalogueStore.GetWriter(policyCatalogue.Identifier, languageId);
            catalogueWriter.WriteCatalogue(policyCatalogue);
            catalogueWriter.Close();

            policySet.Save();

            TestHelpers.CompareXml(m_testPath + "TestReadPolicyAddSecondActionToCell.Catalogue.xml", catalogueStore.GetStoreXML(policyCatalogue.Identifier));
            TestHelpers.CompareXml(m_testPath + "TestReadPolicyAddSecondActionToCell.PolicySet.xml", policyStore.XMLRepresentation);
            TestHelpers.CompareXml(m_testPath + "TestReadPolicyAddSecondActionToCell.Language.xml", languageStore.GetXMLRepresentation(languageId, languageName));
        }
示例#55
0
        public void TestReadChannelRoutingMatrix()
        {
            string policyCatalogueFilename = m_testPath + "SamplePolicyCatalogue.xml";
            string policyLanguageFilename = m_testPath + "SampleLanguageBase.xml";
            string policyFilename = m_testPath + "SamplePolicy.xml";

            XmlPolicyLanguageStore.Instance.AddLanguage(System.IO.File.ReadAllText(policyLanguageFilename));

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(policyCatalogueFilename));

            XmlStore store = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            XmlPolicyReader xmlPolicyReader = store.Reader as XmlPolicyReader;
            string policySetId = "{8FC9EB93-C376-4E96-B22E-71FAA848393D}";
            string policyId = "{C7D62E10-D889-4EF5-AF3D-823C82C230CA}";
            string xpath = string.Format(@"/PolicySetStore/PolicySets/PolicySet[@id='{0}']/Policies/Policy[@id='{1}']/Channels",
                policySetId, policyId);

            Assert.AreEqual(1, xmlPolicyReader.PolicySets.Count);
            IPolicySet policySet = xmlPolicyReader.PolicySets[0];
            Assert.IsNotNull(policySet);

            IPolicy policy = policySet.Policies[new Guid(policyId)];
            Assert.IsNotNull(policy);

            PolicyObjectCollection<IPolicyChannel> channels = new PolicyObjectCollection<IPolicyChannel>();
            XmlChannelsReader reader = new XmlChannelsReader(xmlPolicyReader, channels, policy, xpath);
            reader.Read();

            Assert.AreEqual(1, channels.Count, "Expected one channel");
            IPolicyChannel channel = channels[0];
            Assert.IsNotNull(channel);
            Assert.IsNotNull(channel.Routing, "Expected a valid instance of the channel routing collection");
            IRoutingTable smtpRouting = channel.Routing;
            Assert.IsNotNull(smtpRouting, "Expected the routing table type to be SMTP");
            Assert.IsTrue(smtpRouting.CellCount > 0, "Expected a routing matrix with cells inserted");
        }
示例#56
0
 // initialize the first instance, which is inactive (not touched yet)
 public XmlStoreFilePersister(IBackgroundTaskRunner <XmlStoreFilePersister> runner, XmlStore store, ILogger logger)
     : this(runner, store, logger, false)
 {
 }
示例#57
0
        public void TestReadPolicyRulesReadAndSave()
        {
            string testCatalogue = m_testPath + "TestRealPolicyCatalogue.xml";
            string languageFilename = m_testPath + "TestRealPolicyLanguage.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            string languageName;
            Guid languageId = languageStore.AddLanguage(System.IO.File.ReadAllText(languageFilename), out languageName);

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            PolicyCatalogue policyCatalogue = catalogueStore.AddPolicyCatalogue(System.IO.File.ReadAllText(testCatalogue));

            string policyFilename = m_testPath + "TestReadPolicyRulesReadAndSave.xml";
            XmlStore policyStore = new XmlStore(System.IO.File.ReadAllText(policyFilename));
            XmlPolicyReader xmlPolicyReader = policyStore.Reader as XmlPolicyReader;

            IPolicyCatalogueWriter catalogueWriter = catalogueStore.GetWriter(policyCatalogue.Identifier, languageId);
            catalogueWriter.WriteCatalogue(policyCatalogue);
            catalogueWriter.Close();

            IPolicySet policySet = xmlPolicyReader.PolicySets[0];

            policySet.Save();

            TestHelpers.CompareXml(testCatalogue, catalogueStore.GetStoreXML(policyCatalogue.Identifier));
            TestHelpers.CompareXml(policyFilename, policyStore.XMLRepresentation);
            TestHelpers.CompareXml(languageFilename, languageStore.GetXMLRepresentation(languageId, languageName));
        }
示例#58
0
        public void TestCreatePolicySetChannelsMasterCataloguePrepopulateRouting()
        {
            string testCatalogue = m_testPath + "TestCreatePolicySetChannelsMasterCatalogue.xml";
            string languageFilename = m_testPath + "TestCreatePolicySetChannelsMasterCatalogueLanguage.xml";
            string policySetFilename = m_testPath + "TestCreatePolicySetChannelsMasterCataloguePolicySet.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();

            Guid languageId = new Guid("{E8B22533-98EB-4D00-BDE4-406DC3E1858B}");
            PolicyLanguageCache.Instance.ActiveLanguageId = languageId;
            IPolicyLanguage language = new PolicyLanguage(languageId, "en");
            language.DefaultLanguage = true;
            languageStore.AddLanguage(language);

            PolicyLanguageCache policyLanguageCache = PolicyLanguageCache.Instance;
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), "New catalogue");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{9465CA41-A0A1-40BD-BE26-E83E17D83148}"), "New policy set");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), "New policy");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{39C06E29-074C-46C8-BE3D-F1CD92BB8D66}"), "Test channel");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{03005F4E-04FC-4287-B2A6-25F877D9C31B}"), "Test sources");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{3BF2C1D6-0F40-4A32-A311-6F65A5D271BD}"), "Test destinations");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{A8CEBEDF-92EA-4DCC-8053-08E5245ED84D}"), "Test routing table");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{86D8056D-BA38-44FA-B9BD-100CFB7113F8}"), "Test condition group");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{040C4E16-EE88-4B91-833F-8F30A536DAC6}"), "Test action group");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{F03E6CD1-98C0-4590-B789-907ECF90BEBF}"), "Test data element");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{6197CDBE-9F42-4A61-9369-238355BAB404}"), "Test data element display");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{E5C29C65-9600-42D9-8CD6-6638F40F9341}"), "Test data item");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{463295F1-A5A2-4BB1-B029-7917AC75E9E6}"), "Test action");

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            PolicyCatalogue policyCatalogue = new PolicyCatalogue(new Guid("{AB5E2A43-01FB-4AA6-98FC-8F74BB0621CA}"), language.Identifier, new TranslateableLanguageItem("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), catalogueStore);
            catalogueStore.AddPolicyCatalogue(policyCatalogue);

            IPolicyStore policyStore = new XmlStore();
            IPolicySet policySet = new PolicySet(new Guid("{29EC30A5-1271-4306-89C8-5811172D901A}"), new TranslateableLanguageItem("{9465CA41-A0A1-40BD-BE26-E83E17D83148}"), policyStore, policyCatalogue, false);
            IPolicy newPolicy = new P5Policy(policySet, new Guid("{D257D4DC-4A12-438F-A32A-CF1CE4474441}"), new TranslateableLanguageItem("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), PolicyStatus.Active);
            policySet.Policies.Add(newPolicy);

            // Create policy set channel
            PolicyChannel channel = new PolicyChannel(new Guid("{0FE26539-7AAD-46DC-8D5B-9651CC00B9E4}"), new TranslateableLanguageItem("{39C06E29-074C-46C8-BE3D-F1CD92BB8D66}"), ChannelType.SMTP);           

            // Create routing table
            RoutingTable routingTable = new RoutingTable(new Guid("{CDF0252C-3D5D-4AFB-98C2-89CF00FE2175}"), new TranslateableLanguageItem("{A8CEBEDF-92EA-4DCC-8053-08E5245ED84D}"), ChannelType.SMTP);
            
            IRoutingItemCollection senders = new RoutingItemCollection(new Guid("{441FDCBF-B606-4325-8CD5-E829AD5303B9}"), "{03005F4E-04FC-4287-B2A6-25F877D9C31B}");
            senders.Add(new RoutingItem(new Guid("{D41A47E2-CC13-46FF-BE83-829625792576}"), "James Brown", "*****@*****.**"));
            senders.Add(new RoutingItem(new Guid("{B031DFE9-54E7-482B-8955-18CFB8F06A40}"), "Nat King Cole", "*****@*****.**"));
            IRoutingItemCollection recipients = new RoutingItemCollection(new Guid("{29C44E5C-5405-409F-8513-A99AE246536F}"), "{3BF2C1D6-0F40-4A32-A311-6F65A5D271BD}");
            recipients.Add(new RoutingItem(new Guid("{9E26C6A2-ABE2-427D-9D78-5B8547ADA8D2}"), "Jet Li", "*****@*****.**"));
            
            routingTable.Sources.Add(senders);
            routingTable.Destinations.Add(recipients);

            // Assign routing table to channel
            channel.Routing = routingTable;

            // Create action matrix
            ActionMatrix actionMatrix = new ObjectModel.ActionMatrix(false);

            // Create an action matrix cell
            ActionMatrixCell actionMatrixCell = new ObjectModel.ActionMatrixCell(senders, recipients);

            // Populate the action matrix cell
            ConditionGroup conditionGroup = new ConditionGroup(new Guid("{661EDD6F-D750-493A-9932-E56C8C22E2CF}"), new TranslateableLanguageItem("{86D8056D-BA38-44FA-B9BD-100CFB7113F8}"), ConditionLogic.AND, false);
            ActionGroup actionGroup = new ObjectModel.ActionGroup(new Guid("{32D97853-2680-4B02-A391-22CAEE87B017}"), new TranslateableLanguageItem("{040C4E16-EE88-4B91-833F-8F30A536DAC6}"), 1);
            IActionConditionGroup actionConditionGroup = new ObjectModel.ActionConditionGroup(conditionGroup, actionGroup, false);

            ObjectModel.Action action = new ObjectModel.Action(new Guid("{5153B00E-7D30-4D37-90F9-75E55AA1B32B}"), new TranslateableLanguageItem("{463295F1-A5A2-4BB1-B029-7917AC75E9E6}"), "TestAction.dll", "Test.Action", RunAt.Client, false, 1); //TODO JE

            DataItem dataItem = DataItem.CreateDataItem(new TranslateableLanguageItem("{E5C29C65-9600-42D9-8CD6-6638F40F9341}"), DataType.String, "Not again, when will it ever end!");
            DataElement dataElement = new DataElement(new Guid("{39500989-0B41-4C4E-85DF-CCB4FBD5BEB8}"), new TranslateableLanguageItem("{F03E6CD1-98C0-4590-B789-907ECF90BEBF}"), new TranslateableLanguageItem("{6197CDBE-9F42-4A61-9369-238355BAB404}"), DataType.String, dataItem);
            action.DataElements.Add(dataElement);
            actionConditionGroup.ActionGroup.Actions.Add(action);

            // Assign the action condition group to the matrix cell
            actionMatrixCell.ActionConditionGroups.Add(actionConditionGroup);

            // Assign the action matrix cell to the action matrix
            actionMatrix[senders, recipients] = actionMatrixCell;

            // Assign action matrix to channel
            channel.Actions = actionMatrix;

            // Assign channel to policy
            newPolicy.Channels.Add(channel);

            // Save everything
            IPolicyCatalogueWriter catalogueWriter = catalogueStore.GetWriter(policyCatalogue.Identifier, language.Identifier);
            catalogueWriter.WriteCatalogue(policyCatalogue);
            catalogueWriter.Close();

            policySet.Save();

            TestHelpers.CompareXml(policySetFilename, policyStore.XMLRepresentation);

            IRoutingMatrixCell routingMatrixCell = routingTable[senders, recipients];

            string expectedCatalogueXml = System.IO.File.ReadAllText(testCatalogue);
            expectedCatalogueXml = expectedCatalogueXml.Replace("{0}", routingMatrixCell.Name.Identifier.ToString("B").ToUpper());
            expectedCatalogueXml = expectedCatalogueXml.Replace("{1}", routingMatrixCell.Description.Identifier.ToString("B").ToUpper());
            testCatalogue += ".tmp";

            System.IO.File.WriteAllText(testCatalogue, expectedCatalogueXml);

            TestHelpers.CompareXml(testCatalogue, catalogueStore.GetStoreXML(policySet.MasterCatalogue.Identifier));

            string expectedLanguageXml = System.IO.File.ReadAllText(languageFilename);
            expectedLanguageXml = expectedLanguageXml.Replace("{0}", routingMatrixCell.Name.Identifier.ToString("B").ToUpper());
            expectedLanguageXml = expectedLanguageXml.Replace("{1}", routingMatrixCell.Description.Identifier.ToString("B").ToUpper());
            languageFilename += ".tmp";
            System.IO.File.WriteAllText(languageFilename, expectedLanguageXml);

            TestHelpers.CompareXml(languageFilename, languageStore.GetXMLRepresentation(language.Identifier, language.Name.Value));
        }
示例#59
0
        public void TestCreatePolicySetConditionsMasterCatalogue()
        {
            string testCatalogue = m_testPath + "TestCreatePolicySetConditionsMasterCatalogue.xml";
            string languageFilename = m_testPath + "TestCreatePolicySetConditionsMasterCatalogueLanguage.xml";
            string policySetFilename = m_testPath + "TestCreatePolicySetConditionsMasterCataloguePolicySet.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();

            Guid languageId = new Guid("{E8B22533-98EB-4D00-BDE4-406DC3E1858B}");
            IPolicyLanguage language = new PolicyLanguage(languageId, "en");
            language.DefaultLanguage = true;
            languageStore.AddLanguage(language);

            PolicyLanguageCache policyLanguageCache = PolicyLanguageCache.Instance;
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), "New catalogue");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{9465CA41-A0A1-40BD-BE26-E83E17D83148}"), "New policy set");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), "New policy");

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            PolicyCatalogue policyCatalogue = new PolicyCatalogue(new Guid("{AB5E2A43-01FB-4AA6-98FC-8F74BB0621CA}"), language.Identifier, new TranslateableLanguageItem("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), catalogueStore);
            catalogueStore.AddPolicyCatalogue(policyCatalogue);

            IPolicyStore policyStore = new XmlStore();
            IPolicySet policySet = new PolicySet(new Guid("{29EC30A5-1271-4306-89C8-5811172D901A}"), new TranslateableLanguageItem("{9465CA41-A0A1-40BD-BE26-E83E17D83148}"), policyStore, policyCatalogue, false);
            IPolicy newPolicy = new P5Policy(policySet, new Guid("{D257D4DC-4A12-438F-A32A-CF1CE4474441}"), new TranslateableLanguageItem("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), PolicyStatus.Active);
            policySet.Policies.Add(newPolicy);

            // Create a condition group for the policy.
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{8EB7FF08-1DC8-4F11-9D55-AF47F83F843A}"), "Test condition group");
            IConditionGroup conditionGroup = new ConditionGroup(new Guid("{B87DF614-2400-4C1F-BEA8-3C2EB3964EAE}"), new TranslateableLanguageItem("{8EB7FF08-1DC8-4F11-9D55-AF47F83F843A}"), ConditionLogic.AND, false);
            newPolicy.Conditions.Add(conditionGroup);

            // Create a condition for the condition group.
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{EC8E1E63-7097-4330-8130-5776D4FDF1ED}"), "Test condition");
            ICondition condition = new Condition(new Guid("{98C73BC3-3E20-403C-8023-C91E2818355F}"), "TestClass", new TranslateableLanguageItem("{EC8E1E63-7097-4330-8130-5776D4FDF1ED}"), OperatorType.Equals);
            conditionGroup.Conditions.Add(condition);

            // Create the data left for the condition data.
            DataMethod dataMethod = new DataMethod("ThisIsATest");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{BA56AB4C-43D0-465A-BE67-D8A569A1894C}"), "Test data item to the left");

            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{AB454A4B-1A0F-4864-9F46-3AAC8A34ACA5}"), "Test parameter data element");
            DataElement parameterDataElement = new DataElement(new Guid("{015035B7-1793-464D-AF69-030E9DC7151E}"), new TranslateableLanguageItem("{AB454A4B-1A0F-4864-9F46-3AAC8A34ACA5}"), new NonTranslateableLanguageItem(""), DataType.String, "Lets go dynamo");
            dataMethod.Parameters.Add(new Parameter("somethingTerrible", parameterDataElement));
            IDataSource dataSource = new DataSource("ThisIsADodgyAssembly.dll", "ItWantsToTakeOverYourComputer", dataMethod);

            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{79784B11-5FCC-47A8-A35E-C8399BE71C05}"), "Test data left");
            condition.DataLeft = new DataElement(new Guid("{454672AC-BCED-4DAB-813F-6CF14E6289C5}"), new TranslateableLanguageItem("{79784B11-5FCC-47A8-A35E-C8399BE71C05}"), new NonTranslateableLanguageItem(""), DataType.Object, dataSource);

            // Create the data right for the condition data.
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{BD40DDEE-B045-4D3B-8092-D596329230FE}"), "Test data item to the right");
            IDataItem dataRightDataItem = DataItem.CreateDataItem(new TranslateableLanguageItem("{BD40DDEE-B045-4D3B-8092-D596329230FE}"), DataType.String, "This is a test");

            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{8549333F-0A4D-4939-8A36-36FB0FF1C89A}"), "Test data right");
            condition.DataRight = new DataElement(new Guid("{4E2F50C5-D310-47A1-AE3A-621F5C77FA68}"), new TranslateableLanguageItem("{8549333F-0A4D-4939-8A36-36FB0FF1C89A}"), new NonTranslateableLanguageItem(""), DataType.String, dataRightDataItem);

            // Save everything
            IPolicyCatalogueWriter catalogueWriter = catalogueStore.GetWriter(policyCatalogue.Identifier, language.Identifier);
            catalogueWriter.WriteCatalogue(policyCatalogue);
            catalogueWriter.Close();

            policySet.Save();

            TestHelpers.CompareXml(policySetFilename, policyStore.XMLRepresentation);
            TestHelpers.CompareXml(testCatalogue, catalogueStore.GetStoreXML(policySet.MasterCatalogue.Identifier));
            TestHelpers.CompareXml(languageFilename, languageStore.GetXMLRepresentation(language.Identifier, language.Name.Value));
        }
示例#60
0
        public void TestCreateNewPolicySet()
        {
            string testCatalogue = m_testPath + "TestCreateNewPolicyCatalogue.xml";
            string languageFilename = m_testPath + "TestCreateNewPolicySetLanguage.xml";
            string policySetFilename = m_testPath + "TestCreateNewPolicySet.xml";

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();

            Guid languageId = new Guid("{E8B22533-98EB-4D00-BDE4-406DC3E1858B}");
            IPolicyLanguage language = new PolicyLanguage(languageId, "en");
            language.DefaultLanguage = true;
            languageStore.AddLanguage(language);

            PolicyLanguageCache policyLanguageCache = PolicyLanguageCache.Instance;
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), "New catalogue");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{9465CA41-A0A1-40BD-BE26-E83E17D83148}"), "New policy set");
            policyLanguageCache.SetLanguageItemText(languageId, new Guid("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), "New policy");

            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            PolicyCatalogue policyCatalogue = new PolicyCatalogue(new Guid("{AB5E2A43-01FB-4AA6-98FC-8F74BB0621CA}"), language.Identifier, new TranslateableLanguageItem("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), catalogueStore);
            catalogueStore.AddPolicyCatalogue(policyCatalogue);

            IPolicyStore policyStore = new XmlStore();
            IPolicySet policySet = new PolicySet(new Guid("{29EC30A5-1271-4306-89C8-5811172D901A}"), new TranslateableLanguageItem("{9465CA41-A0A1-40BD-BE26-E83E17D83148}"), policyStore, policyCatalogue, false);
            IPolicy newPolicy = new P5Policy(policySet, new Guid("{D257D4DC-4A12-438F-A32A-CF1CE4474441}"), new TranslateableLanguageItem("{08BC5764-4879-42ED-9AD8-15040C4ADEDE}"), PolicyStatus.Active);
            policySet.Policies.Add(newPolicy);

            // Save everything
            IPolicyCatalogueWriter catalogueWriter = catalogueStore.GetWriter(policyCatalogue.Identifier, language.Identifier);
            catalogueWriter.WriteCatalogue(policyCatalogue);
            catalogueWriter.Close();

            policySet.Save();

            TestHelpers.CompareXml(testCatalogue, catalogueStore.GetStoreXML(policyCatalogue.Identifier));
            TestHelpers.CompareXml(policySetFilename, policyStore.XMLRepresentation);
            TestHelpers.CompareXml(languageFilename, languageStore.GetXMLRepresentation(language.Identifier, language.Name.Value));

            policySet.Save();

            TestHelpers.CompareXml(testCatalogue, catalogueStore.GetStoreXML(policyCatalogue.Identifier));
            TestHelpers.CompareXml(policySetFilename, policyStore.XMLRepresentation);
            TestHelpers.CompareXml(languageFilename, languageStore.GetXMLRepresentation(language.Identifier, language.Name.Value));
        }