Beispiel #1
0
        public void Temp()
        {
            var productService = ObjectFactoryBase.Resolve <IProductService>();
            var article        = productService.GetProductById(2166354);

            XamlConfigurationParser.Save(article);
        }
Beispiel #2
0
 public static T GetXaml <T>(string path)
 {
     using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
     {
         return((T)XamlConfigurationParser.LoadFrom(stream));
     }
 }
Beispiel #3
0
        public override IEnumerable <object[]> GetData(MethodInfo testMethod)
        {
            if (testMethod == null)
            {
                throw new ArgumentNullException(nameof(testMethod));
            }

            var result = new List <object> {
                XamlConfigurationParser.CreateFrom(File.ReadAllText(GetFullFilename(_fileName)))
            };

            if (!string.IsNullOrWhiteSpace(_expression))
            {
                result.Insert(0, _expression);
            }

            if (_expectedCount.HasValue)
            {
                result.Add(_expectedCount);
            }

            return(new[]
            {
                result.ToArray()
            });
        }
Beispiel #4
0
        public void TestEvaluatorRootFilter()
        {
            var xaml       = File.ReadAllText("TestData\\ReferenceDto.xaml");
            var productDto = (Article)XamlConfigurationParser.CreateFrom(xaml);
            var res        = DPathProcessor.Process("[Type='305']", productDto);

            Assert.IsTrue(res.Length > 0);
        }
Beispiel #5
0
        public void TestEvaluatorExtensionField()
        {
            var xaml       = File.ReadAllText("TestData\\ReferenceDto.xaml");
            var productDto = (Article)XamlConfigurationParser.CreateFrom(xaml);
            var res        = DPathProcessor.Process("MarketingProduct[ProductType='289']", productDto);

            Assert.IsTrue(res.Length > 0);
        }
 public string Serialize(Content product)
 {
     using (var stream = new MemoryStream())
     {
         XamlConfigurationParser.SaveTo(stream, product);
         return(new StreamReader(stream).ReadToEnd());
     }
 }
 private static UIElement Read(string path)
 {
     using (var stream = File.OpenRead(path))
     {
         Throws.IfNot(stream != null, "The requested file is not exist.");
         // создаем экземпляр
         return((UIElement)XamlConfigurationParser.LoadFrom(stream));
     }
 }
Beispiel #8
0
        protected virtual T GetOrAdd <T>(string key, Func <T> func)
        {
            var paths = new List <string>()
            {
                Path.Combine(DataDirectory, key)
            };

            if (ArchiveFiles)
            {
                paths.Insert(0, Path.Combine(DataDirectory, $"{key}.zip"));
            }
            foreach (var path in paths)
            {
                if (File.Exists(path))
                {
                    if (path.EndsWith("zip"))
                    {
                        using (var archive = ZipFile.OpenRead(path))
                        {
                            var entry = archive.Entries.FirstOrDefault();
                            using (var stream = entry.Open())
                            {
                                return((T)XamlConfigurationParser.LoadFrom(stream));
                            }
                        }
                    }
                    else
                    {
                        return((T)XamlConfigurationParser.LoadFrom(path));
                    }
                }
            }

            var data = func();

            if (data != null)
            {
                var path = paths[0];
                if (path.EndsWith("zip"))
                {
                    using (var memoryStream = File.Create(path))
                    {
                        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create))
                        {
                            var entry = archive.CreateEntry(key);

                            using (var stream = entry.Open())
                            {
                                XamlConfigurationParser.SaveTo(stream, data);
                            }
                        }
                    }
                }
            }

            return(data);
        }
Beispiel #9
0
 protected T GetXaml <T>(string path)
 {
     using (var stream = Assembly.GetExecutingAssembly()
                         .GetManifestResourceStream(path))
     {
         Throws.IfNot(stream != null, "The requested file is not found in embedded resource.");
         // создаем экземпляр
         return((T)XamlConfigurationParser.LoadFrom(stream));
     }
 }
Beispiel #10
0
        public void TextJsonDeserialization()
        {
            var jsonProductService = ObjectFactoryBase.Resolve <IJsonProductService>();
            var defStr             = File.ReadAllText("TestData\\ProductDefinition.xaml");
            var json          = File.ReadAllText("TestData\\ProductJson.js");
            var resultArticle = jsonProductService.DeserializeProduct(json, (Content)XamlConfigurationParser.CreateFrom(defStr));
            var resultXaml    = XamlConfigurationParser.Save(resultArticle);
            var referenceXaml = File.ReadAllText("TestData\\ReferenceDto.xaml");

            Assert.AreEqual(resultXaml, referenceXaml);
        }
        public UIElement GetControlForProduct(Article product)
        {
            var text = GetString(product);

            if (!string.IsNullOrEmpty(text))
            {
                return((UIElement)XamlConfigurationParser.CreateFrom(text));
            }

            return(null);
        }
Beispiel #12
0
        public ActionResult GetDefinitionLevel(DefinitionPathInfo defInfo)
        {
            var content = (Content)XamlConfigurationParser.CreateFrom(defInfo.Xml);
            var objects = DefinitionTreeNode.GetObjectsFromPath(content, defInfo.Path, _fieldService,
                                                                _definitionEditorService, _contentService);

            return(new ContentResult()
            {
                ContentType = "application/json", Content = JsonConvert.SerializeObject(objects)
            });
        }
Beispiel #13
0
        public ActionResult GetInitialNodeUrl(int?contentId)
        {
            var xml = XamlConfigurationParser.Save(new Content {
                ContentId = contentId.Value
            });

            return(new ContentResult()
            {
                ContentType = "application/json", Content = JsonConvert.SerializeObject(xml)
            });
        }
Beispiel #14
0
        public ActionResult Edit(DefinitionPathInfo defInfo)
        {
            var rootContent = (Content)XamlConfigurationParser.CreateFrom(defInfo.Xml);

            var objectToEdit = _definitionEditorService.GetObjectFromPath(rootContent, defInfo.Path, out var notFoundInDef);

            if (objectToEdit is Field edit)
            {
                return new ContentResult()
                       {
                           ContentType = "application/json", Content = JsonConvert.SerializeObject(new DefinitionFieldInfo(edit)
                    {
                        InDefinition = !notFoundInDef,
                        Path         = defInfo.Path,
                        Xml          = defInfo.Xml
                    }
                                                                                                   )
                       }
            }
            ;

            var isFromDictionaries = false;

            if (!Equals(rootContent, objectToEdit))
            {
                isFromDictionaries = _definitionEditorService.GetParentObjectFromPath(rootContent, defInfo.Path) is Dictionaries;
            }

            var contentToEdit = (Content)objectToEdit;

            return(new ContentResult()
            {
                ContentType = "application/json", Content = JsonConvert.SerializeObject(new DefinitionContentInfo
                {
                    ContentName = contentToEdit.ContentName,
                    IsReadOnly = contentToEdit.IsReadOnly,
                    PublishingMode = contentToEdit.PublishingMode,
                    ContentId = contentToEdit.ContentId,
                    LoadAllPlainFields = contentToEdit.LoadAllPlainFields,
                    CacheEnabled = contentToEdit.CachePeriod.HasValue,
                    CachePeriod = contentToEdit.CachePeriod ?? new TimeSpan(1, 45, 0),
                    Path = defInfo.Path,
                    Xml = defInfo.Xml,
                    InDefinition = !notFoundInDef,
                    IsFromDictionaries = isFromDictionaries,
                })
            });
        }
Beispiel #15
0
        public void TestXmlDeserialization()
        {
            var xmlProductService = ObjectFactoryBase.Resolve <IXmlProductService>();
            var xDoc          = XDocument.Load("TestData\\Product.xml");
            var defStr        = File.ReadAllText("TestData\\ProductDefinition.xaml");
            var resultArticle = xmlProductService.DeserializeProductXml(xDoc, (Content)XamlConfigurationParser.CreateFrom(defStr));
            var st            = new Stopwatch();

            st.Start();
            xmlProductService.DeserializeProductXml(xDoc, (Content)XamlConfigurationParser.CreateFrom(defStr));
            st.Stop();

            Debug.WriteLine(st.Elapsed);
            XamlConfigurationParser.Save(resultArticle);
            File.ReadAllText("TestData\\ReferenceDto.xaml");
        }
Beispiel #16
0
        public ActionResult Index([Bind("content_item_id")] int?contentItemId, int?contentId)
        {
            _cacheItemWatcher.TrackChanges();

            var definitionXml = contentItemId.HasValue
                                ? _contentDefinitionService.GetDefinitionXml(contentItemId.Value)
                                : contentId.HasValue
                                        ? XamlConfigurationParser.Save(new Content {
                ContentId = contentId.Value
            })
                                        : string.Empty;

            return(View(new DefinitionEditor {
                ContentItemId = contentItemId, Xml = definitionXml
            }));
        }
Beispiel #17
0
        public ActionResult GetSingleNode(DefinitionPathInfo defInfo)
        {
            var content = (Content)XamlConfigurationParser.CreateFrom(defInfo.Xml);

            var objFromDef = _definitionEditorService.GetObjectFromPath(content, defInfo.Path, out var notFoundInDef);

            if (objFromDef == null)
            {
                return(Json(new { MissingFieldToDeleteId = defInfo.Path }));
            }

            DefinitionTreeNode resultObj = null;

            switch (objFromDef)
            {
            case Content def:
            {
                var isFromDictionaries = _definitionEditorService.GetParentObjectFromPath(content, defInfo.Path) is Dictionaries;

                resultObj = new DefinitionTreeNode(def, null, defInfo.Path, isFromDictionaries, notFoundInDef, _contentService);
                break;
            }

            case Field field:
            {
                var existsInQp = true;

                if (!(field is BaseVirtualField))
                {
                    existsInQp = _fieldService.Read(field.FieldId) != null;
                }

                resultObj = new DefinitionTreeNode(field, null, defInfo.Path, !existsInQp, notFoundInDef);
                break;
            }
            }

            return(new ContentResult()
            {
                ContentType = "application/json", Content = JsonConvert.SerializeObject(resultObj)
            });
        }
        public Content[] GetDefinitions(bool isLive = false)
        {
            int prodDefContentId = int.Parse(_settingsService.GetSetting(SettingsTitles.PRODUCT_DEFINITIONS_CONTENT_ID));

            using (_articleService.CreateQpConnectionScope())
            {
                _articleService.IsLive = isLive;

                var definitions = _articleService.List(prodDefContentId, null).Where(x => !x.Archived && x.Visible);

                return(definitions
                       .Select(x => x.FieldValues
                               .Where(a => a.Field.Name == FIELD_NAME_XML_DEF)
                               .Select(a => a.Value)
                               .FirstOrDefault())
                       .Where(x => !string.IsNullOrEmpty(x))
                       .Select(x => (Content)XamlConfigurationParser.CreateFrom(x))
                       .ToArray());
            }
        }
        public EditorDefinition GetEditorDefinition(int productTypeId, int contentId, bool isLive = false)
        {
            int xamlContentId = int.Parse(_settingsService.GetSetting(SettingsTitles.PRODUCT_DEFINITIONS_CONTENT_ID));

            var fieldsByName = GetDefinitionFields(xamlContentId, contentId, productTypeId, isLive, forEditor: true);

            if (fieldsByName != null &&
                fieldsByName.TryGetValue(FIELD_NAME_XML_DEF, out string xmlDefinition) &&
                fieldsByName.TryGetValue(nameof(Article.Id), out string productDefinitionId) &&
                fieldsByName.TryGetValue(FIELD_NAME_EDITOR_VIEW_PATH, out string editorViewPath))
            {
                return(new EditorDefinition
                {
                    Content = (Content)XamlConfigurationParser.CreateFrom(xmlDefinition),
                    ProductDefinitionId = Int32.Parse(productDefinitionId),
                    EditorViewPath = editorViewPath
                });
            }

            return(null);
        }
Beispiel #20
0
        public ActionResult SaveField(DefinitionFieldInfo defInfo)
        {
            var rootContent = (Content)XamlConfigurationParser.CreateFrom(defInfo.Xml);

            var savedField = _definitionEditorService.UpdateOrDeleteField(rootContent, defInfo.GetField(), defInfo.Path, !defInfo.InDefinition);

            string resultXml = XamlConfigurationParser.Save(rootContent);

            ModelState.Clear();

            Field fieldForEditView = savedField ?? (Field)_definitionEditorService.GetObjectFromPath(rootContent, defInfo.Path, out _);

            return(new ContentResult()
            {
                ContentType = "application/json",
                Content = JsonConvert.SerializeObject(new DefinitionFieldInfo(fieldForEditView)
                {
                    InDefinition = defInfo.InDefinition,
                    Path = defInfo.Path,
                    Xml = resultXml
                })
            });
        }
 public string Serialize(Article product)
 {
     return(XamlConfigurationParser.Save(product));
 }
 public Task Write(Stream stream, Article product)
 {
     return(Task.Run(() => XamlConfigurationParser.SaveTo(stream, product)));
 }
 public Task <Article> Read(Stream stream)
 {
     return(Task.Run <Article>(() => (Article)XamlConfigurationParser.LoadFrom(stream)));
 }
 public Task <Content> Read(Stream stream)
 {
     return(Task.Run <Content>(() => (Content)XamlConfigurationParser.LoadFrom(stream)));
 }
        /// <returns><see cref="Content"/> or null</returns>
        public Content TryGetDefinitionForContent(int productTypeId, int contentId, bool isLive = false)
        {
            string xml = GetDefinitionXml(productTypeId, contentId, isLive);

            return(xml != null ? (Content)XamlConfigurationParser.CreateFrom(xml) : null);
        }
 public Content GetDefinitionForContent(int productTypeId, int contentId, bool isLive = false)
 {
     return((Content)XamlConfigurationParser.CreateFrom(GetDefinitionXml(productTypeId, contentId, isLive)));
 }
 public Content GetDefinitionById(int productDefinitionId, bool isLive = false)
 {
     return((Content)XamlConfigurationParser.CreateFrom(GetDefinitionXml(productDefinitionId, isLive)));
 }
        public ServiceDefinition GetServiceDefinition(string slug, string version, bool clearExtensions)
        {
            int productServicesContentId = int.Parse(_settingsService.GetSetting(SettingsTitles.PRODUCT_SERVICES_CONTENT_ID));

            int prodDefContentId = int.Parse(_settingsService.GetSetting(SettingsTitles.PRODUCT_DEFINITIONS_CONTENT_ID));

            string cacheKey = $"KEY_GET_DEFINITION_BY_SLUG:{slug.ToLower()}_{version.ToLower()}";

            return(_cacheProvider.GetOrAdd(
                       cacheKey,
                       new[] { productServicesContentId.ToString(), prodDefContentId.ToString() },
                       _cachePeriod, () =>
            {
                using (_articleService.CreateQpConnectionScope())
                {
                    var dbConnector = new DBConnector(_customer.ConnectionString, _customer.DatabaseType);

                    string wherePart =
                        $@"(lower({FIELD_NAME_SLUG})='{slug.Replace("'", "").ToLower()}'
						AND lower({FIELD_NAME_VERSION})='{version.Replace("'", "").ToLower()}')"                        ;

                    var dtdefinitionArticles = dbConnector.GetContentData(new ContentDataQueryObject(
                                                                              dbConnector,
                                                                              productServicesContentId,
                                                                              FIELD_NAME_DEFINITION + "," + FIELD_NAME_TYPE + "," + FIELD_NAME_FILTER,
                                                                              wherePart, null, 0, 1));

                    if (dtdefinitionArticles.Rows.Count == 0)
                    {
                        throw new Exception($"Slug '{slug}' with version '{version}' not found");
                    }

                    int definitionArticleId = (int)(decimal)dtdefinitionArticles.Rows[0][FIELD_NAME_DEFINITION];

                    object productTypeArticleId = dtdefinitionArticles.Rows[0][FIELD_NAME_TYPE];
                    int[] exstensionContentIds = new int[0];

                    var content = (Content)XamlConfigurationParser.CreateFrom(
                        _articleService.GetFieldValues(new[] { definitionArticleId }, prodDefContentId, FIELD_NAME_XML_DEF)[0]);

                    if (productTypeArticleId is decimal)
                    {
                        var productTypeArticle = _articleService.Read((int)(decimal)productTypeArticleId);
                        exstensionContentIds = productTypeArticle.FieldValues
                                               .Where(fv => fv.Field.Name.EndsWith("content", StringComparison.CurrentCultureIgnoreCase) &&
                                                      fv.RelatedItems.Any())
                                               .SelectMany(fv => fv.RelatedItems)
                                               .Distinct()
                                               .ToArray();
                    }

                    if (clearExtensions)
                    {
                        ClearExstensions(content, exstensionContentIds, null);
                    }

                    return new ServiceDefinition
                    {
                        Content = content,
                        Filter = dtdefinitionArticles.Rows[0][FIELD_NAME_FILTER].ToString(),
                        ExstensionContentIds = exstensionContentIds
                    };
                }
            }));
        }
        public RemoteValidationResult Validate(RemoteValidationContext context, RemoteValidationResult result)
        {
            var xmlDefinition = context.Definitions.FirstOrDefault(x => x.Alias == FieldXmlDefinition);

            if (xmlDefinition == null)
            {
                var message = new ActionTaskResultMessage()
                {
                    ResourceClass = ValidationHelper.ResourceClass,
                    ResourceName  = nameof(RemoteValidationMessages.FieldNotFound),
                    Parameters    = new object[] { FieldXmlDefinition }
                };
                result.Messages.Add(ValidationHelper.ToString(context, message));
            }

            var xaml = context.ProvideValueExact <string>(xmlDefinition);

            if (!string.IsNullOrWhiteSpace(xaml))
            {
                Content definition;
                try
                {
                    definition = (Content)XamlConfigurationParser.CreateFrom(xaml);
                }
                catch (Exception ex)
                {
                    var message = new ActionTaskResultMessage()
                    {
                        ResourceClass = ValidationHelper.ResourceClass,
                        ResourceName  = nameof(RemoteValidationMessages.NotValidXamlDefinition),
                        Parameters    = new object[] { ex.Message }
                    };
                    result.Messages.Add(ValidationHelper.ToString(context, message));
                    return(result);
                }

                var jsonDefinition = context.Definitions.FirstOrDefault(x => x.Alias == FieldJsonDefinition);
                if (jsonDefinition != null)
                {
                    using (var stream = new MemoryStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            try
                            {
                                _formatter.Write(stream, definition);
                                stream.Position = 0;
                                context.SetValue(result, jsonDefinition, reader.ReadToEnd());
                            }
                            catch (Exception ex)
                            {
                                var message = new ActionTaskResultMessage()
                                {
                                    ResourceClass = ValidationHelper.ResourceClass,
                                    ResourceName  = nameof(RemoteValidationMessages.JsonDefinitionError),
                                    Parameters    = new object[] { ex.Message }
                                };
                                result.Messages.Add(ValidationHelper.ToString(context, message));
                                return(result);
                            }
                        }
                    }
                }
            }

            return(result);
        }
Beispiel #30
0
 public static void SaveXaml(string path, object data)
 {
     XamlConfigurationParser.Save(data);
 }