Exemplo n.º 1
0
        public void TestJsonPointerSpec()
        {
            var root = ConvertToObjectHelper.ConvertToDynamic(ConvertToObjectHelper.ConvertJObjectToObject(JsonUtility.FromJsonString <object>(@"
{
      ""foo"": [""bar"", ""baz""],
      """": 0,
      ""a/b"": 1,
      ""c%d"": 2,
      ""e^f"": 3,
      ""g|h"": 4,
      ""i\\j"": 5,
      ""k\""l"": 6,
      "" "": 7,
      ""m~n"": 8
   }
")));

            Assert.Equal(root, new JsonPointer("").GetValue(root));
            Assert.Equal(((dynamic)root).foo, new JsonPointer("/foo").GetValue(root));
            Assert.Equal("bar", new JsonPointer("/foo/0").GetValue(root));
            Assert.Equal(0L, new JsonPointer("/").GetValue(root));
            Assert.Equal(1L, new JsonPointer("/a~1b").GetValue(root));
            Assert.Equal(2L, new JsonPointer("/c%d").GetValue(root));
            Assert.Equal(3L, new JsonPointer("/e^f").GetValue(root));
            Assert.Equal(4L, new JsonPointer("/g|h").GetValue(root));
            Assert.Equal(5L, new JsonPointer("/i\\j").GetValue(root));
            Assert.Equal(6L, new JsonPointer("/k\"l").GetValue(root));
            Assert.Equal(7L, new JsonPointer("/ ").GetValue(root));
            Assert.Equal(8L, new JsonPointer("/m~0n").GetValue(root));
        }
Exemplo n.º 2
0
        public override FileModel Load(FileAndType file, ImmutableDictionary <string, object> metadata)
        {
            switch (file.Type)
            {
            case DocumentType.Article:
                // TODO: Support dynamic in YAML deserializer
                try
                {
                    // MUST be a dictionary
                    var obj = YamlUtility.Deserialize <Dictionary <string, object> >(file.File);

                    // Validate against the schema first
                    // Temporarily disable schema validation as Json.NET schema has limitation of 1000 calls per hour
                    // TODO: Reenable schema validation
                    // _schemaValidator.Validate(obj);

                    var content      = ConvertToObjectHelper.ConvertToDynamic(obj);
                    var pageMetadata = _schema.MetadataReference.GetValue(content) as IDictionary <string, object>;
                    if (pageMetadata == null)
                    {
                        pageMetadata = new ExpandoObject();
                        _schema.MetadataReference.SetValue(ref content, pageMetadata);
                    }
                    foreach (var pair in metadata)
                    {
                        if (!pageMetadata.ContainsKey(pair.Key))
                        {
                            pageMetadata[pair.Key] = pair.Value;
                        }
                    }

                    var localPathFromRoot = PathUtility.MakeRelativePath(EnvironmentContext.BaseDirectory, EnvironmentContext.FileAbstractLayer.GetPhysicalPath(file.File));

                    var fm = new FileModel(
                        file,
                        content,
                        serializer: new BinaryFormatter())
                    {
                        LocalPathFromRoot = localPathFromRoot,
                    };

                    fm.Properties.Schema   = _schema;
                    fm.Properties.Metadata = pageMetadata;
                    return(fm);
                }
                catch (YamlDotNet.Core.YamlException e)
                {
                    throw new DocumentException($"{file.File} is not in supported format: {e.Message}", e);
                }

            case DocumentType.Overwrite:
                return(OverwriteDocumentReader.Read(file));

            default:
                throw new NotSupportedException();
            }
        }
Exemplo n.º 3
0
        public string Render(object model)
        {
            model = ConvertToObjectHelper.ConvertJObjectToObject(model);
            model = ConvertToObjectHelper.ConvertExpandoObjectToObject(model);
            if (model is IDictionary <string, object> )
            {
                return(_template.Render(DotLiquid.Hash.FromDictionary((IDictionary <string, object>)model)));
            }

            return(_template.Render(DotLiquid.Hash.FromAnonymousObject(model)));
        }
Exemplo n.º 4
0
        public void ConvertComplexTypeToObjectShouldWork()
        {
            var complexType = new ComplexType
            {
                String        = "String",
                List          = new List <string>(),
                IntDictionary = new Dictionary <int, string>()
            };
            var result = ConvertToObjectHelper.ConvertStrongTypeToObject(complexType);

            Assert.Equal(typeof(Dictionary <string, object>), result.GetType());
            Assert.Equal(typeof(object[]), ((Dictionary <string, object>)result)["List"].GetType());
            Assert.Equal(typeof(Dictionary <string, object>), ((Dictionary <string, object>)result)["IntDictionary"].GetType());
        }
Exemplo n.º 5
0
        public void ConvertComplexTypeWithJsonAttributeToObjectShouldUseAttributeAsPropertyName()
        {
            var complexType = new ComplexTypeWithJson
            {
                String        = "String",
                List          = new List <string>(),
                IntDictionary = new Dictionary <int, string>()
            };
            var result = ConvertToObjectHelper.ConvertStrongTypeToObject(complexType);

            Assert.Equal(typeof(Dictionary <string, object>), result.GetType());
            Assert.Equal(typeof(object[]), ((Dictionary <string, object>)result)["list"].GetType());
            Assert.Equal(typeof(Dictionary <string, object>), ((Dictionary <string, object>)result)["dict"].GetType());
        }
Exemplo n.º 6
0
        private static IDictionary <string, object> ConvertObjectToDictionary(object model)
        {
            if (model is IDictionary <string, object> dictionary)
            {
                return(dictionary);
            }

            if (!(ConvertToObjectHelper.ConvertStrongTypeToObject(model) is IDictionary <string, object> objectModel))
            {
                throw new ArgumentException("Only object model is supported for template transformation.");
            }

            return(objectModel);
        }
Exemplo n.º 7
0
        public void TestJsonPointerWithComplexObject()
        {
            var root = ConvertToObjectHelper.ConvertToDynamic(ConvertToObjectHelper.ConvertJObjectToObject(JsonUtility.FromJsonString <object>(@"
{
      ""dict"": {
        ""key1"": ""value1"",
        ""key2"": [""arr1"", ""arr2""],
        ""key3"": {
            ""key1"": ""value1"",
            ""key2"": [""arr1"", ""arr2""],
            ""key3"": {
                ""key1"": ""value1"",
                ""key2"": [""arr1"", ""arr2""],
                ""key3"": {
                   ""key1"": ""value1""
                }
            }
        }
    },
      ""array"": [""bar"", ""baz""]
   }
")));

            Assert.Equal(root, new JsonPointer("").GetValue(root));
            Assert.Equal("value1", new JsonPointer("/dict/key1").GetValue(root));
            Assert.Equal("arr2", new JsonPointer("/dict/key2/1").GetValue(root));
            Assert.Equal("value1", new JsonPointer("/dict/key3/key3/key3/key1").GetValue(root));
            Assert.Null(new JsonPointer("/dict/key4").GetValue(root));
            Assert.Null(new JsonPointer("/dict/key4/key1").GetValue(root));
            Assert.Null(new JsonPointer("/dict/key2/2").GetValue(root));

            var jp = new JsonPointer("/dict/key1");

            jp.SetValue(ref root, 1);
            Assert.Equal(1, jp.GetValue(root));

            jp = new JsonPointer("/dict/key3/key2/1");
            jp.SetValue(ref root, 2);
            Assert.Equal(2, jp.GetValue(root));

            jp = new JsonPointer("");
            jp.SetValue(ref root, 3);
            Assert.Equal(3, root);
            Assert.Equal(3, jp.GetValue(root));

            Assert.Throws <InvalidJsonPointerException>(() => new JsonPointer("/dict/key2/2").SetValue(ref root, 1));
        }
Exemplo n.º 8
0
        private object BuildOverwriteWithSchema(FileModel owModel, OverwriteDocumentModel overwrite, IHostService host, BaseSchema schema)
        {
            dynamic overwriteObject = ConvertToObjectHelper.ConvertToDynamic(overwrite.Metadata);

            overwriteObject.uid = overwrite.Uid;
            var overwriteModel = new FileModel(owModel.FileAndType, overwriteObject, owModel.OriginalFileAndType);
            var context        = new ProcessContext(host, overwriteModel)
            {
                ContentAnchorParser = new ContentAnchorParser(overwrite.Conceptual)
            };

            var transformed = _overwriteProcessor.Process(overwriteObject, schema, context) as IDictionary <string, object>;

            if (!context.ContentAnchorParser.ContainsAnchor)
            {
                transformed["conceptual"] = context.ContentAnchorParser.Content;
            }

            // add SouceDetail back to transformed, in week type
            transformed[Constants.PropertyName.Documentation] = new Dictionary <string, object>
            {
                ["remote"] = overwrite.Documentation.Remote == null ? null : new Dictionary <string, object>
                {
                    ["path"]   = overwrite.Documentation.Remote.RelativePath,
                    ["branch"] = overwrite.Documentation.Remote.RemoteBranch,
                    ["repo"]   = overwrite.Documentation.Remote.RemoteRepositoryUrl,
                }
                ["path"]      = overwrite.Documentation?.Path,
                ["startLine"] = overwrite.Documentation?.StartLine ?? 0,
                ["endLine"]   = overwrite.Documentation?.EndLine ?? 0,
            };

            owModel.LinkToUids                   = owModel.LinkToUids.Union((context.UidLinkSources).Keys);
            owModel.LinkToFiles                  = owModel.LinkToFiles.Union((context.FileLinkSources).Keys);
            owModel.FileLinkSources              = owModel.FileLinkSources.Merge(context.FileLinkSources);
            owModel.UidLinkSources               = owModel.UidLinkSources.Merge(context.UidLinkSources);
            owModel.Uids                         = owModel.Uids.AddRange(context.Uids);
            owModel.Properties.XRefSpecs         = context.XRefSpecs;
            owModel.Properties.ExternalXRefSpecs = context.ExternalXRefSpecs;

            foreach (var d in context.Dependency)
            {
                host.ReportDependencyTo(owModel, d, DependencyTypeName.Include);
            }
            return(transformed);
        }
Exemplo n.º 9
0
        private void ApplySystemMetadata()
        {
            Logger.LogVerbose("Applying system metadata to manifest...");

            // Add system attributes
            var systemMetadataGenerator = new SystemMetadataGenerator(_context);

            var sharedObjects = new ConcurrentDictionary <string, object>();

            _manifestWithContext.RunAll(m =>
            {
                if (m.FileModel.Type == DocumentType.Resource)
                {
                    return;
                }
                using (new LoggerFileScope(m.FileModel.LocalPathFromRoot))
                {
                    Logger.LogDiagnostic("Generating system metadata...");

                    // TODO: use weak type for system attributes from the beginning
                    var systemAttrs = systemMetadataGenerator.Generate(m.Item);
                    var metadata    = (IDictionary <string, object>)ConvertToObjectHelper.ConvertStrongTypeToObject(systemAttrs);

                    var model = (IDictionary <string, object>)m.Item.Model.Content;

                    foreach (var pair in metadata)
                    {
                        if (!model.ContainsKey(pair.Key))
                        {
                            model[pair.Key] = pair.Value;
                        }
                    }

                    Logger.LogDiagnostic($"Load shared model from template for {m.Item.DocumentType}...");
                    if (m.Options?.IsShared == true)
                    {
                        // Take a snapshot of current model as shared object
                        sharedObjects[m.Item.Key] = new Dictionary <string, object>(model);
                    }
                }
            },
                                        _context.MaxParallelism);

            _globalMetadata["_shared"] = sharedObjects;
        }
Exemplo n.º 10
0
 private ImmutableArray <FileMetadataItem> GetFileMetadataItemArray(JToken value)
 {
     if (!(value is JArray arr))
     {
         throw new JsonReaderException($"Expect {value} to be JArray.");
     }
     return(arr.Select(e =>
     {
         if (!(e is JObject obj))
         {
             throw new JsonReaderException($"Expect {e} to be JObject.");
         }
         return new FileMetadataItem(
             new GlobMatcher((string)obj[Glob]),
             (string)obj[Key],
             ConvertToObjectHelper.ConvertJObjectToObject(obj[Value]));
     }).ToImmutableArray());
 }
Exemplo n.º 11
0
        private static IDictionary <string, object> ConvertObjectToDictionary(object model)
        {
            var dictionary = model as IDictionary <string, object>;

            if (dictionary != null)
            {
                return(dictionary);
            }

            var objectModel = ConvertToObjectHelper.ConvertStrongTypeToObject(model) as IDictionary <string, object>;

            if (objectModel == null)
            {
                throw new ArgumentException("Only object model is supported for template transformation.");
            }

            return(objectModel);
        }
Exemplo n.º 12
0
 public void TestJObjectConvertWithJToken()
 {
     var testData = ConvertToObjectHelper.ConvertStrongTypeToObject(new TestData());
     {
         var jsValue = JintProcessorHelper.ConvertObjectToJsValue(testData);
         Assert.True(jsValue.IsObject());
         dynamic value = jsValue.ToObject();
         Assert.Equal(2, value.ValueA);
         Assert.Equal("ValueB", value.ValueB);
         System.Dynamic.ExpandoObject valueDict = value.ValueDict;
         var dict = (IDictionary <string, object>)valueDict;
         Assert.Equal("Value1", dict["1"]);
         Assert.Equal(2.0, dict["key"]);
         object[] array = value.ValueList;
         Assert.Equal("ValueA", array[0]);
         Assert.Equal("ValueB", array[1]);
     }
 }
        public override FileModel Load(FileAndType file, ImmutableDictionary <string, object> metadata)
        {
            switch (file.Type)
            {
            case DocumentType.Article:
                // TODO: Support dynamic in YAML deserializer
                try
                {
                    // MUST be a dictionary
                    var obj = YamlUtility.Deserialize <Dictionary <string, object> >(file.File);
                    foreach (var pair in metadata)
                    {
                        if (!obj.ContainsKey(pair.Key))
                        {
                            obj[pair.Key] = pair.Value;
                        }
                    }
                    var content = ConvertToObjectHelper.ConvertToDynamic(obj);

                    var localPathFromRoot = PathUtility.MakeRelativePath(EnvironmentContext.BaseDirectory, EnvironmentContext.FileAbstractLayer.GetPhysicalPath(file.File));

                    var fm = new FileModel(
                        file,
                        content,
                        serializer: new BinaryFormatter())
                    {
                        LocalPathFromRoot = localPathFromRoot,
                    };

                    fm.Properties.Schema = _schema;
                    return(fm);
                }
                catch (YamlDotNet.Core.YamlException e)
                {
                    throw new DocumentException($"{file.File} is not in supported format: {e.Message}", e);
                }

            case DocumentType.Overwrite:
                return(OverwriteDocumentReader.Read(file));

            default:
                throw new NotSupportedException();
            }
        }
Exemplo n.º 14
0
        private void ApplySystemMetadata()
        {
            Logger.LogVerbose("Applying system metadata to manifest...");

            // Add system attributes
            var systemMetadataGenerator = new SystemMetadataGenerator(_context);

            _manifestWithContext.RunAll(m =>
            {
                if (m.FileModel.Type == DocumentType.Resource)
                {
                    return;
                }
                using (new LoggerFileScope(m.FileModel.LocalPathFromRoot))
                {
                    Logger.LogDiagnostic("Generating system metadata...");

                    // TODO: use weak type for system attributes from the beginning
                    var systemAttrs = systemMetadataGenerator.Generate(m.Item);
                    var metadata    = (JObject)ConvertToObjectHelper.ConvertStrongTypeToJObject(systemAttrs);
                    // Change file model to weak type
                    var model         = m.Item.Model.Content;
                    var modelAsObject = (JToken)ConvertToObjectHelper.ConvertStrongTypeToJObject(model);
                    if (modelAsObject is JObject)
                    {
                        foreach (var pair in (JObject)modelAsObject)
                        {
                            // Overwrites the existing system metadata if the same key is defined in document model
                            metadata[pair.Key] = pair.Value;
                        }
                    }
                    else
                    {
                        Logger.LogWarning("Input model is not an Object model, it will be wrapped into an Object model. Please use --exportRawModel to view the wrapped model");
                        metadata["model"] = modelAsObject;
                    }

                    // Append system metadata to model
                    m.Item.Model.Serializer = null;
                    m.Item.Model.Content    = metadata;
                }
            },
                                        _context.MaxParallelism);
        }
Exemplo n.º 15
0
        public void ConvertObjectWithCircularReferenceToDynamic()
        {
            var a = new Dictionary <string, object>
            {
                ["key"] = "value"
            };

            a["key1"] = a;

            dynamic converted = ConvertToObjectHelper.ConvertToDynamic(a);

            Assert.Equal(converted.key1, converted);
            Assert.Equal("value", converted.key1.key);

            Dictionary <string, object> obj = ConvertToObjectHelper.ConvertExpandoObjectToObject(converted);

            Assert.True(ReferenceEquals(obj["key1"], obj));
            Assert.Equal("value", ((Dictionary <string, object>)obj["key1"])["key"]);
        }
Exemplo n.º 16
0
        private void ApplySystemMetadata(List <ManifestItemWithContext> manifest, IDocumentBuildContext context)
        {
            Logger.LogVerbose($"Applying system metadata to manifest...");

            // Add system attributes
            var systemMetadataGenerator = new SystemMetadataGenerator(context);

            manifest.RunAll(m =>
            {
                using (new LoggerFileScope(m.FileModel.LocalPathFromRepoRoot))
                {
                    Logger.LogVerbose($"Generating system metadata...");

                    // TODO: use weak type for system attributes from the beginning
                    var systemAttrs = systemMetadataGenerator.Generate(m.Item);
                    var metadata    = (IDictionary <string, object>)ConvertToObjectHelper.ConvertStrongTypeToObject(systemAttrs);
                    // Change file model to weak type
                    var model         = m.Item.Model.Content;
                    var modelAsObject = ConvertToObjectHelper.ConvertStrongTypeToObject(model) as IDictionary <string, object>;
                    if (modelAsObject != null)
                    {
                        foreach (var token in modelAsObject)
                        {
                            // Overwrites the existing system metadata if the same key is defined in document model
                            metadata[token.Key] = token.Value;
                        }
                    }
                    else
                    {
                        Logger.LogWarning("Input model is not an Object model, it will be wrapped into an Object model. Please use --exportRawModel to view the wrapped model");
                        metadata["model"] = model;
                    }

                    // Append system metadata to model
                    m.Item.Model.Content = metadata;
                }
            });
        }
Exemplo n.º 17
0
 private object ConvertToObject(TocItemViewModel model)
 {
     return(ConvertToObjectHelper.ConvertStrongTypeToObject(model));
 }
Exemplo n.º 18
0
        private void NormalizeToObject()
        {
            Logger.LogVerbose("Normalizing all the object to week type");

            _manifestWithContext.RunAll(m =>
            {
                using (new LoggerFileScope(m.FileModel.LocalPathFromRoot))
                {
                    var model = m.Item.Model.Content;
                    // Change file model to weak type
                    // Go through the convert even if it is IDictionary as the inner object might be of strong type
                    var modelAsObject = model == null ? new Dictionary <string, object>() : ConvertToObjectHelper.ConvertStrongTypeToObject(model);
                    if (modelAsObject is IDictionary <string, object> )
                    {
                        m.Item.Model.Content = modelAsObject;
                    }
                    else
                    {
                        Logger.LogWarning("Input model is not an Object model, it will be wrapped into an Object model. Please use --exportRawModel to view the wrapped model");
                        m.Item.Model.Content = new Dictionary <string, object>
                        {
                            ["model"] = modelAsObject
                        };
                    }
                }
            },
                                        _context.MaxParallelism);
        }
Exemplo n.º 19
0
 public FileMetadataPairsItem(string pattern, object value)
 {
     Glob  = new GlobMatcher(pattern);
     Value = ConvertToObjectHelper.ConvertJObjectToObject(value);
 }
Exemplo n.º 20
0
        private TemplateManifestItem TransformItem(ManifestItem item, IDocumentBuildContext context, ApplyTemplateSettings settings)
        {
            if (settings.Options.HasFlag(ApplyTemplateOptions.ExportRawModel))
            {
                ExportModel(item.Model.Content, item.ModelFile, settings.RawModelExportSettings);
            }

            if (item.Model == null || item.Model.Content == null)
            {
                throw new ArgumentNullException("Content for item.Model should not be null!");
            }
            var manifestItem = new TemplateManifestItem
            {
                DocumentType = item.DocumentType,
                OriginalFile = item.LocalPathFromRepoRoot,
                OutputFiles  = new Dictionary <string, string>()
            };
            var outputDirectory = settings.OutputFolder ?? Environment.CurrentDirectory;

            if (!IsEmpty)
            {
                HashSet <string> missingUids = new HashSet <string>();

                // Must convert to JObject first as we leverage JsonProperty as the property name for the model
                var model     = ConvertToObjectHelper.ConvertStrongTypeToJObject(item.Model.Content);
                var templates = Templates[item.DocumentType];

                // 1. process model
                if (templates != null)
                {
                    var systemAttrs = new SystemAttributes(context, item, TemplateProcessor.Language);
                    foreach (var template in templates)
                    {
                        var    extension  = template.Extension;
                        string outputFile = Path.ChangeExtension(item.ModelFile, extension);
                        string outputPath = Path.Combine(outputDirectory, outputFile);
                        var    dir        = Path.GetDirectoryName(outputPath);
                        if (!string.IsNullOrEmpty(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        object viewModel = null;
                        try
                        {
                            viewModel = template.TransformModel(model, systemAttrs, _global);
                        }
                        catch (Exception e)
                        {
                            // save raw model for further investigation:
                            var exportSettings = ApplyTemplateSettings.RawModelExportSettingsForDebug;
                            var rawModelPath   = ExportModel(item.Model, item.ModelFile, exportSettings);
                            throw new DocumentException($"Error transforming model \"{rawModelPath}\" generated from \"{item.LocalPathFromRepoRoot}\" using \"{template.ScriptName}\": {e.Message}");
                        }

                        string result;
                        try
                        {
                            result = template.Transform(viewModel);
                        }
                        catch (Exception e)
                        {
                            // save view model for further investigation:
                            var exportSettings = ApplyTemplateSettings.ViewModelExportSettingsForDebug;
                            var viewModelPath  = ExportModel(viewModel, outputFile, exportSettings);
                            throw new DocumentException($"Error applying template \"{template.Name}\" to view model \"{viewModelPath}\" generated from \"{item.LocalPathFromRepoRoot}\": {e.Message}");
                        }

                        if (settings.Options.HasFlag(ApplyTemplateOptions.ExportViewModel))
                        {
                            ExportModel(viewModel, outputFile, settings.ViewModelExportSettings);
                        }

                        if (settings.Options.HasFlag(ApplyTemplateOptions.TransformDocument))
                        {
                            if (string.IsNullOrWhiteSpace(result))
                            {
                                // TODO: WHAT to do if is transformed to empty string? STILL creat empty file?
                                Logger.LogWarning($"Model \"{item.ModelFile}\" is transformed to empty string with template \"{template.Name}\"");
                                File.WriteAllText(outputPath, string.Empty);
                            }
                            else
                            {
                                TransformDocument(result, extension, context, outputPath, item.ModelFile, missingUids);
                                Logger.Log(LogLevel.Verbose, $"Transformed model \"{item.LocalPathFromRepoRoot}\" to \"{outputPath}\".");
                            }

                            manifestItem.OutputFiles.Add(extension, outputFile);
                        }
                    }
                }

                if (missingUids.Count > 0)
                {
                    var uids = string.Join(", ", missingUids.Select(s => $"\"{s}\""));
                    Logger.LogWarning($"Unable to resolve cross-reference {uids} for \"{manifestItem.OriginalFile.ToDisplayPath()}\"");
                }
            }

            // 2. process resource
            if (item.ResourceFile != null)
            {
                // Resource file has already been processed in its plugin
                manifestItem.OutputFiles.Add("resource", item.ResourceFile);
            }

            return(manifestItem);
        }
Exemplo n.º 21
0
        public object BuildOverwriteWithSchema(FileModel owModel, OverwriteDocumentModel overwrite, BaseSchema schema)
        {
            if (overwrite == null || owModel == null)
            {
                return(null);
            }

            if (schema == null)
            {
                throw new ArgumentNullException(nameof(schema));
            }

            dynamic overwriteObject = ConvertToObjectHelper.ConvertToDynamic(overwrite.Metadata);

            overwriteObject.uid = overwrite.Uid;
            var overwriteModel = new FileModel(owModel.FileAndType, overwriteObject, owModel.OriginalFileAndType);
            var context        = (((IDictionary <string, object>)(owModel.Properties)).TryGetValue("MarkdigMarkdownService", out var service))
                ? new ProcessContext(_host, overwriteModel, null, (MarkdigMarkdownService)service)
                : new ProcessContext(_host, overwriteModel);

            if (_overwriteModelType == OverwriteModelType.Classic)
            {
                context.ContentAnchorParser = new ContentAnchorParser(overwrite.Conceptual);
            }

            var transformed = _overwriteProcessor.Process(overwriteObject, schema, context) as IDictionary <string, object>;

            if (_overwriteModelType == OverwriteModelType.Classic && !context.ContentAnchorParser.ContainsAnchor)
            {
                transformed["conceptual"] = context.ContentAnchorParser.Content;
            }

            // add SouceDetail back to transformed, in week type
            if (overwrite.Documentation != null)
            {
                transformed[Constants.PropertyName.Documentation] = new Dictionary <string, object>
                {
                    ["remote"] = overwrite.Documentation.Remote == null ? null : new Dictionary <string, object>
                    {
                        ["path"]   = overwrite.Documentation.Remote.RelativePath,
                        ["branch"] = overwrite.Documentation.Remote.RemoteBranch,
                        ["repo"]   = overwrite.Documentation.Remote.RemoteRepositoryUrl,
                    }
                    ["path"]      = overwrite.Documentation?.Path,
                    ["startLine"] = overwrite.Documentation?.StartLine ?? 0,
                    ["endLine"]   = overwrite.Documentation?.EndLine ?? 0,
                };
            }

            owModel.LinkToUids                   = owModel.LinkToUids.Union((context.UidLinkSources).Keys);
            owModel.LinkToFiles                  = owModel.LinkToFiles.Union((context.FileLinkSources).Keys);
            owModel.FileLinkSources              = owModel.FileLinkSources.Merge(context.FileLinkSources);
            owModel.UidLinkSources               = owModel.UidLinkSources.Merge(context.UidLinkSources);
            owModel.Uids                         = owModel.Uids.AddRange(context.Uids);
            owModel.Properties.XRefSpecs         = context.XRefSpecs;
            owModel.Properties.ExternalXRefSpecs = context.ExternalXRefSpecs;

            foreach (var d in context.Dependency)
            {
                _host.ReportDependencyTo(owModel, d, DependencyTypeName.Include);
            }
            return(transformed);
        }
Exemplo n.º 22
0
        public override FileModel Load(FileAndType file, ImmutableDictionary <string, object> metadata)
        {
            switch (file.Type)
            {
            case DocumentType.Article:
                // TODO: Support dynamic in YAML deserializer
                try
                {
                    // MUST be a dictionary
                    var obj = YamlUtility.Deserialize <Dictionary <string, object> >(file.File);

                    // Validate against the schema first
                    _schemaValidator.Validate(obj);

                    // load overwrite segments
                    string markdownFragmentsContent = null;
                    var    markdownFragmentsFile    = file.File + ".md";
                    if (EnvironmentContext.FileAbstractLayer.Exists(markdownFragmentsFile))
                    {
                        markdownFragmentsContent = EnvironmentContext.FileAbstractLayer.ReadAllText(markdownFragmentsFile);
                    }

                    var content      = ConvertToObjectHelper.ConvertToDynamic(obj);
                    var pageMetadata = _schema.MetadataReference.GetValue(content) as IDictionary <string, object>;
                    if (pageMetadata == null)
                    {
                        pageMetadata = new ExpandoObject();
                        _schema.MetadataReference.SetValue(ref content, pageMetadata);
                    }
                    foreach (var pair in metadata)
                    {
                        if (!pageMetadata.ContainsKey(pair.Key))
                        {
                            pageMetadata[pair.Key] = pair.Value;
                        }
                    }

                    var localPathFromRoot = PathUtility.MakeRelativePath(EnvironmentContext.BaseDirectory, EnvironmentContext.FileAbstractLayer.GetPhysicalPath(file.File));

                    var fm = new FileModel(
                        file,
                        content,
                        serializer: new BinaryFormatter())
                    {
                        LocalPathFromRoot = localPathFromRoot,
                    };
                    if (markdownFragmentsContent != null)
                    {
                        fm.MarkdownFragmentsModel = new FileModel(
                            file,
                            markdownFragmentsContent,
                            new FileAndType(
                                file.BaseDir,
                                markdownFragmentsFile,
                                DocumentType.MarkdownFragments,
                                file.SourceDir,
                                file.DestinationDir),
                            new BinaryFormatter())
                        {
                            LocalPathFromRoot = PathUtility.MakeRelativePath(
                                EnvironmentContext.BaseDirectory,
                                EnvironmentContext.FileAbstractLayer.GetPhysicalPath(markdownFragmentsFile))
                        };
                        fm.MarkdownFragmentsModel.Properties.MarkdigMarkdownService = _markdigMarkdownService;
                    }

                    fm.Properties.Schema   = _schema;
                    fm.Properties.Metadata = pageMetadata;
                    return(fm);
                }
                catch (YamlDotNet.Core.YamlException e)
                {
                    throw new DocumentException($"{file.File} is not in supported format: {e.Message}", e);
                }

            case DocumentType.Overwrite:
                return(OverwriteDocumentReader.Read(file));

            default:
                throw new NotSupportedException();
            }
        }
Exemplo n.º 23
0
        public void ConvertSimpleTypeToObjectShouldWork(object value, Type expectedType)
        {
            var result = ConvertToObjectHelper.ConvertStrongTypeToObject(value);

            Assert.Equal(expectedType, result.GetType());
        }