Example #1
0
        public override void Uninstall()
        {
            foreach (var kvp in _packageToRestore.Reverse())
            {
                if (this.InstalledPackages.ContainsKey(kvp.Key))
                {
                    XDocument doc = XDocumentUtils.Load(this.InstalledPackages[kvp.Key]);

                    XElement element = doc.Root;
                    if (element == null)
                    {
                        continue;
                    }

                    XAttribute attribute = element.Attribute(PackageSystemSettings.VersionAttributeName);
                    if (attribute == null)
                    {
                        continue;
                    }

                    attribute.Value = kvp.Value;

                    doc.SaveToFile(this.InstalledPackages[kvp.Key]);
                }
            }
        }
        /// <exclude />
        protected override void OnInitialize()
        {
            if ((this.OwnerNode is DataElementsTreeNode) == false)
            {
                AddValidationError("TreeValidationError.GenericEditDataAction.OwnerIsNotDataNode");
            }

            if (string.IsNullOrEmpty(this.CustomFormMarkupPath) == false)
            {
                try
                {
                    string path = PathUtil.Resolve(this.CustomFormMarkupPath);
                    if (C1File.Exists(path) == false)
                    {
                        AddValidationError("TreeValidationError.GenericEditDataAction.MissingMarkupFile", path);
                    }

                    XDocument document = XDocumentUtils.Load(path);

                    this.CustomFormMarkupPath = path;
                }
                catch
                {
                    AddValidationError("TreeValidationError.GenericEditDataAction.BadMarkupPath", this.CustomFormMarkupPath);
                }
            }
        }
Example #3
0
        public IUrlFormatter Assemble(IBuilderContext context, UrlFormatterData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            var data = (StringReplaceUrlFormatterData)objectConfiguration;

            string rulesFile = data.RulesFile;

            if (!rulesFile.IsNullOrEmpty())
            {
                string fullPath = HostingEnvironment.MapPath(rulesFile);
                Verify.That(C1File.Exists(fullPath), "Cannot find file '{0}'", rulesFile);

                try
                {
                    XDocument xDoc = XDocumentUtils.Load(fullPath);

                    return(new StringReplaceUrlFormatter(
                               xDoc.Root.Elements()
                               .Select(e => new Pair <string, string>(GetAttributeNotNull(e, "oldValue"), GetAttributeNotNull(e, "newValue"))).ToList()));
                }
                catch (Exception e)
                {
                    throw new ConfigurationErrorsException("Failed to process file '{0}'".FormatWith(rulesFile), e);
                }
            }

            var replacements = data.Replace.Cast <ReplacementRuleConfigurationElement>();

            return(new StringReplaceUrlFormatter(replacements.Select(r => new Pair <string, string>(r.OldValue, r.NewValue)).ToList()));
        }
Example #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var xsdFiles = C1Directory.GetFiles(this.MapPath(""), "*.xsd");

        XElement xsdFilesTable = new XElement("table",
                                              new XElement("tr",
                                                           new XElement("td", "Namespace"),
                                                           new XElement("td", "Last generated")));

        foreach (string xsdFile in xsdFiles)
        {
            DateTime lastWrite = C1File.GetLastWriteTime(xsdFile);

            XDocument schemaDocument  = XDocumentUtils.Load(xsdFile);
            string    targetNamespace = schemaDocument.Root.Attribute("targetNamespace").Value;

            xsdFilesTable.Add(
                new XElement("tr",
                             new XElement("td",
                                          new XElement("a",
                                                       new XAttribute("href", Path.GetFileName(xsdFile)),
                                                       targetNamespace)),
                             new XElement("td", lastWrite)));
        }

        XsdTable.Controls.Add(new LiteralControl(xsdFilesTable.ToString()));

        GenerateButton.Click += new EventHandler(GenerateButton_Click);
    }
        private static void LoadC1ConsoleAccessConfig()
        {
            // defaults - keeping these if config file is missing or f****d up somehow
            _forceHttps            = false;
            _allowFallbackToHttp   = true;
            _customHttpsPortNumber = null;

            string c1ConsoleAccessConfigPath = HostingEnvironment.MapPath(c1ConsoleAccessRelativeConfigPath);

            if (C1File.Exists(c1ConsoleAccessConfigPath))
            {
                try
                {
                    XDocument accessDoc = XDocumentUtils.Load(c1ConsoleAccessConfigPath);
                    _allowC1ConsoleRequests = _allowC1ConsoleRequests && (bool)accessDoc.Root.Attribute("enabled");

                    XElement protocolElement = accessDoc.Root.Element("ClientProtocol");
                    _forceHttps          = (bool)protocolElement.Attribute("forceHttps");
                    _allowFallbackToHttp = (bool)protocolElement.Attribute("allowFallbackToHttp");

                    var customHttpsPortNumberAttrib = protocolElement.Attribute("customHttpsPortNumber");

                    if (customHttpsPortNumberAttrib != null && customHttpsPortNumberAttrib.Value.Length > 0)
                    {
                        _customHttpsPortNumber = (int)customHttpsPortNumberAttrib;
                    }
                }
                catch (Exception ex)
                {
                    Log.LogError("Authorization", "Problem parsing '{0}'. Will use defaults and allow normal access. Error was '{1}'", c1ConsoleAccessRelativeConfigPath, ex.Message);
                }
            }
        }
        private static void LoadAllowedPaths()
        {
            _allAllowedPaths.Clear();

            string webauthorizationConfigPath = HostingEnvironment.MapPath(webauthorizationRelativeConfigPath);

            if (!C1File.Exists(webauthorizationConfigPath))
            {
                Log.LogInformation("AdministrativeAuthorizationHttpModule ", "File '{0}' not found - all access to the ~/Composite folder will be blocked", webauthorizationConfigPath);
                return;
            }

            XDocument webauthorizationConfigDocument = XDocumentUtils.Load(webauthorizationConfigPath);

            XAttribute loginPagePathAttribute = Verify.ResultNotNull(webauthorizationConfigDocument.Root.Attribute("loginPagePath"), "Missing '{0}' attribute on '{1}' root element", loginPagePathAttributeName, webauthorizationRelativeConfigPath);
            string     relativeLoginPagePath  = Verify.StringNotIsNullOrWhiteSpace(loginPagePathAttribute.Value, "Unexpected empty '{0}' attribute on '{1}' root element", loginPagePathAttributeName, webauthorizationRelativeConfigPath);

            _loginPagePath = UrlUtils.ResolveAdminUrl(relativeLoginPagePath);

            foreach (XElement allowElement in webauthorizationConfigDocument.Root.Elements(allowElementName))
            {
                XAttribute relativePathAttribute = Verify.ResultNotNull(allowElement.Attribute(allow_pathAttributeName), "Missing '{0}' attribute on '{1}' element in '{2}'.", allow_pathAttributeName, allowElement, webauthorizationRelativeConfigPath);
                string     relativePath          = Verify.StringNotIsNullOrWhiteSpace(relativePathAttribute.Value, "Empty '{0}' attribute on '{1}' element in '{2}'.", allow_pathAttributeName, allowElement, webauthorizationRelativeConfigPath);

                string fullPath = UrlUtils.ResolveAdminUrl(relativePath).ToLowerInvariant();
                _allAllowedPaths.Add(fullPath);
            }
        }
Example #7
0
        public static DateTime GetFirstTimeStart()
        {
            Verify.That(File.Exists(FirstTimeStartFilePath), "File '{0}' is missing", FirstTimeStartFilePath);

            var doc = XDocumentUtils.Load(FirstTimeStartFilePath);

            return((DateTime)doc.Element("Root").Attribute("time"));
        }
Example #8
0
        internal TagManager()
        {
            var doc = XDocumentUtils.Load(PathUtil.Resolve(TagConfigurationsRelativePath));

            _tagToTitleMap = (from element in doc.Root?.Elements()
                              select new { Name = element.GetAttributeValue("name"), Value = element.GetAttributeValue("title") })
                             .ToDictionary(o => o.Name, o => o.Value);
        }
Example #9
0
        /// <summary>
        /// Used for processing xml/sql data providers configuration build by C1 vesrion older than 3.0
        /// </summary>
        internal static Dictionary <string, Guid> GetTypeManagerTypeNameToTypeIdMap()
        {
            string metaDataFolderPath = PathUtil.Resolve(GlobalSettingsFacade.DataMetaDataDirectory);

            List <string> filepaths = C1Directory.GetFiles(metaDataFolderPath, "*.xml").ToList();

            var result = new Dictionary <string, Guid>();

            foreach (string filepath in filepaths)
            {
                try
                {
                    XDocument doc = XDocumentUtils.Load(filepath);

                    XAttribute dataTypeIdAttr          = doc.Root.Attribute("dataTypeId");
                    XAttribute typeManagerTypeNameAttr = doc.Root.Attribute("typeManagerTypeName");

                    if (dataTypeIdAttr == null || typeManagerTypeNameAttr == null)
                    {
                        continue;
                    }

                    string typeManagerTypeName = typeManagerTypeNameAttr.Value;
                    Guid   dataTypeId          = new Guid(dataTypeIdAttr.Value);

                    const string redundantSuffix = ",Composite.Generated";
                    if (typeManagerTypeName.EndsWith(redundantSuffix, StringComparison.OrdinalIgnoreCase))
                    {
                        typeManagerTypeName = typeManagerTypeName.Substring(0, typeManagerTypeName.Length - redundantSuffix.Length);
                    }

                    if (!result.ContainsKey(typeManagerTypeName))
                    {
                        result.Add(typeManagerTypeName, dataTypeId);
                    }

                    if (!typeManagerTypeName.Contains(",") && !typeManagerTypeName.StartsWith("DynamicType:"))
                    {
                        string fixedTypeManagerTypeName = "DynamicType:" + typeManagerTypeName;

                        if (!result.ContainsKey(fixedTypeManagerTypeName))
                        {
                            result.Add(fixedTypeManagerTypeName, dataTypeId);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.LogWarning(LogTitle, "Error while parsing meta data file '{0}'".FormatWith(filepath));
                    Log.LogWarning(LogTitle, ex);
                }
            }

            // Backward compatibility for configuraiton files. (Breaking change C1 3.2 -> C1 4.0)
            result["Composite.Data.Types.IPageTemplate,Composite"] = new Guid("7b54d7d2-6be6-48a6-9ae1-2e0373073d1d");

            return(result);
        }
Example #10
0
        private static bool ValidateMarkup(Tree tree, XDocument document)
        {
            try
            {
                if (document.Root == null)
                {
                    tree.AddValidationError("", "TreeValidationError.Markup.NoRootElement");
                    return(false);
                }

                bool schemaValidationResult = true;
                Action <object, ValidationEventArgs> onValidationError = (obj, args) =>
                {
                    tree.AddValidationError("", "TreeValidationError.Markup.SchemaError", args.Message, args.Exception.LineNumber, args.Exception.LinePosition);
                    schemaValidationResult = false;
                };

                XDocument schemaDocument        = XDocumentUtils.Load(Path.Combine(PathUtil.Resolve("~/Composite/schemas/Trees"), "Tree.xsd"));
                IEnumerable <XElement> elements = schemaDocument.Descendants((XNamespace)"http://www.w3.org/2001/XMLSchema" + "import").ToList();
                foreach (XElement element in elements)
                {
                    element.Remove();
                }

                XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
                xmlReaderSettings.ValidationType = ValidationType.Schema;
                using (XmlReader schemaReader = schemaDocument.CreateReader())
                {
                    xmlReaderSettings.Schemas.Add(null, schemaReader);
                }
                xmlReaderSettings.Schemas.AddFromPath(null, Path.Combine(PathUtil.Resolve("~/Composite/schemas/Functions"), "Function.xsd"));
                //xmlReaderSettings.Schemas.AddFromPath(null, Path.Combine(PathUtil.Resolve("~/Composite/schemas/Trees"), "Tree.xsd"));
                xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(onValidationError);
                xmlReaderSettings.ValidationFlags         = XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings;
                XmlReader xmlReader = XmlReader.Create(new StringReader(document.ToString()), xmlReaderSettings);

                while (xmlReader.Read())
                {
                    ;
                }

                if (schemaValidationResult == false)
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                tree.AddValidationError("", "TreeValidationError.Common.UnknownException", ex.Message);
                return(false);
            }

            return(true);
        }
Example #11
0
    void GenerateButton_Click(object sender, EventArgs e)
    {
        IEnumerable <SchemaInfo> schemaInfos = SchemaBuilder.GenerateAllDynamicSchemas();

        foreach (SchemaInfo schemaInfo in schemaInfos)
        {
            XDocumentUtils.Save(schemaInfo.Schema, this.MapPath(BuildFileName(schemaInfo)));
        }

        GenerateButton.Text = "Done";
    }
Example #12
0
        public static UrlMappings GetMappingsFromXml()
        {
            var result = new UrlMappings
            {
                RawLinks                 = new Dictionary <string, string>(),
                RelativeLinks            = new Dictionary <string, string>(),
                RelativeLinksPerHostname = new Dictionary <string, Dictionary <string, string> >()
            };

            if (C1File.Exists(XmlFileName))
            {
                var doc = XDocumentUtils.Load(XmlFileName).Descendants("Mapping");

                foreach (var m in doc)
                {
                    var oldPath = m.Attribute("OldPath").Value;
                    var newPath = m.Attribute("NewPath").Value;

                    if (!result.RawLinks.ContainsKey(oldPath))
                    {
                        result.RawLinks.Add(oldPath, newPath);
                    }

                    if (oldPath.StartsWith("http://") || oldPath.StartsWith("https://") || oldPath.StartsWith("//"))
                    {
                        int hostnameOffset    = oldPath.IndexOf("//") + 2;
                        int hostnameEndOffset = oldPath.IndexOf('/', hostnameOffset);

                        if (hostnameEndOffset > 0)
                        {
                            string hostname    = oldPath.Substring(hostnameOffset, hostnameEndOffset - hostnameOffset);
                            string relativeUrl = oldPath.Substring(hostnameEndOffset);

                            Dictionary <string, string> linksPerHostname;
                            if (!result.RelativeLinksPerHostname.TryGetValue(hostname, out linksPerHostname))
                            {
                                result.RelativeLinksPerHostname.Add(hostname, linksPerHostname = new Dictionary <string, string>());
                            }

                            if (!linksPerHostname.ContainsKey(relativeUrl))
                            {
                                linksPerHostname.Add(relativeUrl, newPath);
                            }
                        }
                    }
                    else
                    {
                        result.RelativeLinks.Add(oldPath, newPath);
                    }
                }
            }
            return(result);
        }
Example #13
0
 private static XDocument TryLoad(string uri)
 {
     try
     {
         return(XDocumentUtils.Load(uri));
     }
     catch
     {
         /* silent */
         return(null);
     }
 }
            public ElementInformationExtractor(string configurationFilePath)
            {
                this.configurationFilePath = configurationFilePath;
                configDoc = XDocumentUtils.Load(configurationFilePath);

                //Quick code for nameSpaces
                UiContolNs = (from c in GetUiControlDescriptors()
                              group c by c.NamespaceName into g
                              select g.Key).ToList();
                FunctionNs = (from c in GetFunctionDescriptors()
                              group c by c.NamespaceName into g
                              select g.Key).ToList();
            }
Example #15
0
        /// <summary>
        /// Returns custom form markup.
        /// </summary>
        /// <param name="dataTypeDescriptor">A data type descriptor</param>
        /// <returns></returns>
        public static XDocument GetCustomFormMarkup(DataTypeDescriptor dataTypeDescriptor)
        {
            var file = GetCustomFormMarkupFile(dataTypeDescriptor.Namespace, dataTypeDescriptor.Name);

            if (file == null)
            {
                return(null);
            }

            var markupFilePath = (file as FileSystemFile).SystemPath;

            return(XDocumentUtils.Load(markupFilePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo));
        }
Example #16
0
        private static DataTypeDescriptor LoadFromFile(string filePath)
        {
            XDocument doc;

            try
            {
                doc = XDocumentUtils.Load(filePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
            }
            catch (XmlException e)
            {
                throw new ConfigurationErrorsException("Error loading meta data file '{0}': {1}".FormatWith(filePath, e.Message), e, filePath, e.LineNumber);
            }

            return(DataTypeDescriptor.FromXml(doc.Root));
        }
Example #17
0
        static InstallationInformationFacade()
        {
            string filepath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.ConfigurationDirectory), "InstallationInformation.xml");

            if (C1File.Exists(filepath))
            {
                XDocument doc = XDocumentUtils.Load(filepath);

                XAttribute idAttribute = doc.Root.Attribute("installationId");

                _installationId = (Guid)idAttribute;
            }
            else
            {
                InitializeNewFile(filepath);
            }
        }
        /// <summary>
        /// Loads a Page Template Feature based on name.
        /// </summary>
        /// <param name="featureName">Name of the Page Template Feature to load.</param>
        /// <returns></returns>
        private static XhtmlDocument LoadPageTemplateFeature(string featureName)
        {
            string featurePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), featureName + ".xml");

            if (!C1File.Exists(featurePath))
            {
                featurePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), featureName + ".html");
            }

            if (!C1File.Exists(featurePath))
            {
                throw new InvalidOperationException("Unknown feature '" + featureName + "'");
            }

            var doc = XDocumentUtils.Load(featurePath);

            return(new XhtmlDocument(doc));
        }
Example #19
0
        internal static void CreateStore(string providerName, DataScopeConfigurationElement scopeElement)
        {
            string filename = ResolvePath(scopeElement.Filename, providerName);

            string directoryPath = Path.GetDirectoryName(filename);

            if (!C1Directory.Exists(directoryPath))
            {
                C1Directory.CreateDirectory(directoryPath);
            }

            bool   keepExistingFile        = false;
            string rootLocalName           = XmlDataProviderDocumentWriter.GetRootElementName(scopeElement.ElementName);
            string obsoleteRootElementName = scopeElement.ElementName + "s";

            if (C1File.Exists(filename))
            {
                try
                {
                    XDocument existingDocument = XDocumentUtils.Load(filename);
                    if (existingDocument.Root.Name.LocalName == rootLocalName ||
                        existingDocument.Root.Name.LocalName == obsoleteRootElementName)
                    {
                        keepExistingFile = true;
                    }
                }
                catch (Exception)
                {
                    keepExistingFile = false;
                }

                if (!keepExistingFile)
                {
                    C1File.Delete(filename);
                }
            }

            if (!keepExistingFile)
            {
                var document = new XDocument();
                document.Add(new XElement(rootLocalName));
                XDocumentUtils.Save(document, filename);
            }
        }
        private Tree LoadTreeFromFile(string treeId)
        {
            string filename = Path.Combine(TreeDefinitionsFolder, treeId);

            for (int i = 0; i < 10; i++)
            {
                try
                {
                    XDocument document = XDocumentUtils.Load(filename);
                    return(LoadTreeFromDom(treeId, document));
                }
                catch (IOException)
                {
                    Thread.Sleep(100);
                }
            }

            throw new InvalidOperationException("Could not load tree " + treeId);
        }
        private static Dictionary <string, string> AntonymContainerClassLoader()
        {
            XDocument document = null;

            try
            {
                document = XDocumentUtils.Load(PathUtil.Resolve(AntonymClassConfigurationsRelativePath));
            }
            catch (XmlException exception)
            {
                Log.LogWarning(nameof(AntonymContainerClassManager), $"error in parsing config file: {exception}");
                return(new Dictionary <string, string>());
            }


            return((from element in document.Root?.Elements()
                    select new { Name = element.GetAttributeValue("name"), Value = element.GetAttributeValue("antonym") })
                   .ToDictionary(o => o.Name, o => o.Value));
        }
Example #22
0
        private static IEnumerable <string> GetStrings(string type, string mode, string folderPath)
        {
            string filename = Path.Combine(folderPath, _compileScriptsFilename);

            XDocument doc = XDocumentUtils.Load(filename);

            if (mode == "compile")
            {
                mode = "develop";
            }

            XName name = "name";

            XElement topElement  = doc.Root.Elements().Single(f => f.Attribute(name).Value == type);
            XElement modeElement = topElement.Elements().Single(f => f.Attribute(name).Value == mode);

            return
                (from e in modeElement.Elements()
                 select e.Attribute("filename").Value);
        }
Example #23
0
        /// <exclude />
        public override IEnumerable <XElement> Install()
        {
            Verify.IsNotNull(_xmlFileMerges, "XmlFileMergePackageFragmentInstaller has not been validated");

            foreach (XmlFileMerge xmlFileMerge in _xmlFileMerges)
            {
                string targetXmlFile = PathUtil.Resolve(xmlFileMerge.TargetPath);

                using (Stream stream = this.InstallerContext.ZipFileSystem.GetFileStream(xmlFileMerge.ChangeFilePath))
                {
                    XElement  source = XElement.Load(stream);
                    XDocument target = XDocumentUtils.Load(targetXmlFile);

                    target.Root.ImportSubtree(source);
                    target.SaveToFile(targetXmlFile);
                }
            }

            return(new[] { this.Configuration.FirstOrDefault() });
        }
        /// <exclude />
        public override void Uninstall()
        {
            if (_xmlFileMerges == null)
            {
                throw new InvalidOperationException("XmlFileMergePackageFragmentUninstaller has not been validated");
            }

            foreach (XmlFileMerge xmlFileMerge in _xmlFileMerges)
            {
                string targetXml = PathUtil.Resolve(xmlFileMerge.TargetPath);

                using (Stream stream = this.UninstallerContext.ZipFileSystem.GetFileStream(xmlFileMerge.ChangeFilePath))
                {
                    XElement  source = XElement.Load(stream);
                    XDocument target = XDocumentUtils.Load(targetXml);

                    target.Root.RemoveMatches(source);
                    target.SaveToFile(targetXml);
                }
            }
        }
Example #25
0
        /// <exclude />
        public static void PersistMetaData(DataTypeDescriptor dataTypeDescriptor)
        {
            lock (_lock)
            {
                Initialize();

                string filepath = CreateFilename(dataTypeDescriptor);

                XElement  rootElement = dataTypeDescriptor.ToXml();
                XDocument doc         = new XDocument(rootElement);
                XDocumentUtils.Save(doc, filepath);

                _dataTypeDescriptorCache[dataTypeDescriptor.DataTypeId] = dataTypeDescriptor;

                if ((_dataTypeDescriptorFilesnamesCache.ContainsKey(dataTypeDescriptor.DataTypeId)) &&
                    (_dataTypeDescriptorFilesnamesCache[dataTypeDescriptor.DataTypeId] != filepath))
                {
                    FileUtils.Delete(_dataTypeDescriptorFilesnamesCache[dataTypeDescriptor.DataTypeId]);
                    _dataTypeDescriptorFilesnamesCache[dataTypeDescriptor.DataTypeId] = filepath;
                }
            }
        }
Example #26
0
        /// <exclude />
        public override IEnumerable <XElement> Install()
        {
            Verify.IsNotNull(_packagesToBumb, this.GetType().Name + " has not been validated");

            var installedElements = new List <XElement>();

            foreach (var kvp in _packagesToBumb)
            {
                if (this.InstalledPackages.ContainsKey(kvp.Key))
                {
                    XDocument doc = XDocumentUtils.Load(this.InstalledPackages[kvp.Key]);

                    XElement element = doc.Root;
                    if (element == null)
                    {
                        continue;
                    }

                    XAttribute attribute = element.Attribute(PackageSystemSettings.VersionAttributeName);
                    if (attribute == null)
                    {
                        continue;
                    }

                    installedElements.Add(
                        new XElement("PackageVersion",
                                     new XAttribute("packageId", kvp.Key),
                                     new XAttribute("oldVersion", attribute.Value))
                        );

                    attribute.Value = kvp.Value;

                    doc.SaveToFile(this.InstalledPackages[kvp.Key]);
                }
            }

            yield return(new XElement("PackageVersions", installedElements));
        }
        private void TryLoadPersistedFormData(string filename)
        {
            string guidString = Path.GetFileNameWithoutExtension(filename);

            Guid id;

            if (!Guid.TryParse(guidString ?? "", out id))
            {
                return;
            }

            try
            {
                var doc      = XDocumentUtils.Load(filename);
                var formData = FormData.Deserialize(doc.Root);

                if (!_resourceLocker.Resources.FormData.ContainsKey(id))
                {
                    _resourceLocker.Resources.FormData.TryAdd(id, formData);

                    FormsWorkflowBindingCache.Bindings.TryAdd(id, formData.Bindings);
                }
            }
            catch (DataSerilizationException ex)
            {
                Log.LogWarning(LogTitle, $"The workflow {id} contained one or more bindings where data was deleted or data type changed");
                Log.LogWarning(LogTitle, ex);

                //AbortWorkflow(id);
            }
            catch (Exception ex)
            {
                Log.LogCritical(LogTitle, $"Could not deserialize form data for the workflow {id}");
                Log.LogCritical(LogTitle, ex);
                AbortWorkflow(id);
            }
        }
        /// <exclude />
        public static void TransformConfiguration(Func <XDocument, bool> transformer)
        {
            using (GlobalInitializerFacade.CoreLockScope)
            {
                lock (_lock)
                {
                    XDocument document = XDocumentUtils.Load(ConfigurationServices.FileConfigurationSourcePath);

                    if (transformer(document))
                    {
                        ValidateConfigurationFile(document);

                        // Kill monitoring of file changes:
                        //                        FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false);
                        document.SaveToFile(ConfigurationServices.FileConfigurationSourcePath);
                        _configurationSource = new FileConfigurationSource(ConfigurationServices.FileConfigurationSourcePath);
                        // Kill monitoring of file changes:
                        //                        FileConfigurationSource.ResetImplementation(ConfigurationServices.FileConfigurationSourcePath, false);

                        GlobalEventSystemFacade.ShutDownTheSystem();
                    }
                }
            }
        }
Example #29
0
        private static PackageLicenseDefinition TryLoadLicenseFile(string filePath)
        {
            XDocument doc = XDocumentUtils.Load(filePath);

            var licenseDefinition = new PackageLicenseDefinition
            {
                ProductName     = doc.Descendants("Name").Single().Value,
                InstallationId  = (Guid)doc.Descendants("InstallationId").Single(),
                ProductId       = (Guid)doc.Descendants("ProductId").Single(),
                Permanent       = (bool)doc.Descendants("Permanent").Single(),
                Expires         = (DateTime?)doc.Descendants("Expires").SingleOrDefault() ?? DateTime.MaxValue,
                LicenseKey      = doc.Descendants("LicenseKey").Single().Value,
                PurchaseUrl     = doc.Descendants("PurchaseUrl").SingleOrDefault()?.Value ?? "",
                LicenseFileName = filePath
            };

            if (licenseDefinition.InstallationId != InstallationInformationFacade.InstallationId)
            {
                Log.LogError(LogTitle, $"The license for the product '{licenseDefinition.ProductId}' ({licenseDefinition.ProductName}) does not match the current installation");
                return(null);
            }

            return(licenseDefinition);
        }
Example #30
0
        private static void CopyData(string providerName, DataTypeChangeDescriptor dataTypeChangeDescriptor, DataScopeConfigurationElement oldDataScopeConfigurationElement, DataScopeConfigurationElement newDataScopeConfigurationElement, Dictionary <string, object> newFieldValues, bool deleteOldFile = true)
        {
            string oldFilename = ResolvePath(oldDataScopeConfigurationElement.Filename, providerName);
            string newFilename = ResolvePath(newDataScopeConfigurationElement.Filename, providerName);

            XDocument oldDocument = XDocumentUtils.Load(PathUtil.Resolve(oldFilename));

            List <XElement> newElements = new List <XElement>();

            bool addingVersionId = dataTypeChangeDescriptor.AddedFields.Any(f => f.Name == nameof(IVersioned.VersionId)) &&
                                   dataTypeChangeDescriptor.AlteredType.SuperInterfaces.Any(s => s == typeof(IVersioned));

            string versionIdSourceFieldName = null;

            if (addingVersionId)
            {
                if (dataTypeChangeDescriptor.AlteredType.DataTypeId == typeof(IPage).GetImmutableTypeId())
                {
                    versionIdSourceFieldName = nameof(IPage.Id);
                }
                else
                {
                    versionIdSourceFieldName = dataTypeChangeDescriptor.AlteredType.Fields
                                               .Where(f => f.InstanceType == typeof(Guid) &&
                                                      (f.ForeignKeyReferenceTypeName?.Contains(typeof(IPage).FullName) ?? false))
                                               .OrderByDescending(f => f.Name == nameof(IPageData.PageId))
                                               .Select(f => f.Name)
                                               .FirstOrDefault();
                }
            }


            foreach (XElement oldElement in oldDocument.Root.Elements())
            {
                List <XAttribute> newChildAttributes = new List <XAttribute>();

                foreach (XAttribute oldChildAttribute in oldElement.Attributes())
                {
                    var existingFieldInfo = GetExistingFieldInfo(dataTypeChangeDescriptor, oldChildAttribute.Name.LocalName);

                    if (existingFieldInfo != null)
                    {
                        if (existingFieldInfo.OriginalField.Name != existingFieldInfo.AlteredField.Name)
                        {
                            XAttribute newChildAttribute = new XAttribute(existingFieldInfo.AlteredField.Name, oldChildAttribute.Value);

                            newChildAttributes.Add(newChildAttribute);
                        }
                        else
                        {
                            newChildAttributes.Add(oldChildAttribute);
                        }
                    }
                    // It may happen that some data were added before data descriptors are updated, in the case of using
                    // [AutoUpdateable] attribute.
                    else if (dataTypeChangeDescriptor.AddedFields.Any(addedField => addedField.Name == oldChildAttribute.Name))
                    {
                        newChildAttributes.Add(oldChildAttribute);
                    }
                }

                // Adding default value for fields that are NULL and become required
                foreach (var existingFieldInfo in dataTypeChangeDescriptor.ExistingFields)
                {
                    bool fieldBecomeRequired = existingFieldInfo.OriginalField.IsNullable && !existingFieldInfo.AlteredField.IsNullable;

                    string fieldName = existingFieldInfo.AlteredField.Name;

                    if (fieldBecomeRequired && !newChildAttributes.Any(attr => attr.Name.LocalName == fieldName))
                    {
                        newChildAttributes.Add(new XAttribute(fieldName, GetDefaultValue(existingFieldInfo.AlteredField)));
                    }
                }

                foreach (DataFieldDescriptor fieldDescriptor in dataTypeChangeDescriptor.AddedFields)
                {
                    if (addingVersionId && fieldDescriptor.Name == nameof(IVersioned.VersionId) && versionIdSourceFieldName != null)
                    {
                        var existingField = (Guid)oldElement.Attribute(versionIdSourceFieldName);
                        if (existingField != null)
                        {
                            newChildAttributes.Add(new XAttribute(fieldDescriptor.Name, existingField));
                            continue;
                        }
                    }

                    if (!fieldDescriptor.IsNullable &&
                        !newChildAttributes.Any(attr => attr.Name == fieldDescriptor.Name))
                    {
                        object value;
                        if (!newFieldValues.TryGetValue(fieldDescriptor.Name, out value))
                        {
                            value = GetDefaultValue(fieldDescriptor);
                        }

                        newChildAttributes.Add(new XAttribute(fieldDescriptor.Name, value));
                    }
                    else if (newFieldValues.ContainsKey(fieldDescriptor.Name))
                    {
                        XAttribute attribute = newChildAttributes.SingleOrDefault(attr => attr.Name == fieldDescriptor.Name);

                        attribute?.SetValue(newFieldValues[fieldDescriptor.Name]);
                    }
                }

                XElement newElement = new XElement(newDataScopeConfigurationElement.ElementName, newChildAttributes);

                newElements.Add(newElement);
            }

            if (deleteOldFile)
            {
                C1File.Delete(oldFilename);
            }

            XElement newRoot = new XElement(XmlDataProviderDocumentWriter.GetRootElementName(newDataScopeConfigurationElement.ElementName));

            newRoot.Add(newElements);

            XDocument newDocument = new XDocument();

            newDocument.Add(newRoot);

            XDocumentUtils.Save(newDocument, newFilename);
        }