예제 #1
0
        public async Task <ProjectBuildResult> BuildAsync(ProjectBuildArgs args)
        {
            var templateInfo = GetTemplateInfo(args);

            args.TemplateName = templateInfo.Name;

            if (args.DatabaseProvider == DatabaseProvider.NotSpecified)
            {
                if (templateInfo.DefaultDatabaseProvider != DatabaseProvider.NotSpecified)
                {
                    args.DatabaseProvider = templateInfo.DefaultDatabaseProvider;
                }
            }

            var templateFile = await TemplateStore.GetAsync(
                args.TemplateName,
                args.DatabaseProvider,
                args.SolutionName.FullName
                );

            var context = new ProjectBuildContext(
                templateInfo,
                templateFile,
                args
                );

            ProjectBuildPipelineBuilder.Build(context).Execute(context);

            if (!templateInfo.DocumentUrl.IsNullOrEmpty())
            {
                Logger.LogInformation("Check the documentation of this template: " + templateInfo.DocumentUrl);
            }

            return(new ProjectBuildResult(context.Result.ZipContent, args.SolutionName.ProjectName));
        }
예제 #2
0
        public async Task <ProjectBuildResult> BuildAsync(ProjectBuildArgs args)
        {
            var templateInfo = GetTemplateInfo(args);

            NormalizeArgs(args, templateInfo);

            var templateFile = await TemplateStore.GetAsync(
                args.TemplateName,
                args.Version
                );

            var apiKey = await ApiKeyService.GetApiKeyOrNullAsync();

            if (apiKey != null)
            {
                args.ExtraProperties["api-key"] = apiKey;
            }

            var context = new ProjectBuildContext(
                templateInfo,
                templateFile,
                args
                );

            ProjectBuildPipelineBuilder.Build(context).Execute();

            if (!templateInfo.DocumentUrl.IsNullOrEmpty())
            {
                Logger.LogInformation("Check the documentation of this template: " + templateInfo.DocumentUrl);
            }

            // Exclude unwanted or known options.
            var options = args.ExtraProperties
                          .Where(x => !x.Key.Equals(CliConsts.Command, StringComparison.InvariantCultureIgnoreCase))
                          .Where(x => !x.Key.Equals("tiered", StringComparison.InvariantCultureIgnoreCase))
                          .Where(x => !x.Key.Equals(NewCommand.Options.DatabaseProvider.Long, StringComparison.InvariantCultureIgnoreCase) &&
                                 !x.Key.Equals(NewCommand.Options.DatabaseProvider.Short, StringComparison.InvariantCultureIgnoreCase))
                          .Where(x => !x.Key.Equals(NewCommand.Options.OutputFolder.Long, StringComparison.InvariantCultureIgnoreCase) &&
                                 !x.Key.Equals(NewCommand.Options.OutputFolder.Short, StringComparison.InvariantCultureIgnoreCase))
                          .Where(x => !x.Key.Equals(NewCommand.Options.UiFramework.Long, StringComparison.InvariantCultureIgnoreCase) &&
                                 !x.Key.Equals(NewCommand.Options.UiFramework.Short, StringComparison.InvariantCultureIgnoreCase))
                          .Where(x => !x.Key.Equals(NewCommand.Options.Version.Long, StringComparison.InvariantCultureIgnoreCase) &&
                                 !x.Key.Equals(NewCommand.Options.Version.Short, StringComparison.InvariantCultureIgnoreCase))
                          .Select(x => x.Key).ToList();

            await CliAnalyticsCollect.CollectAsync(new CliAnalyticsCollectInputDto
            {
                Tool             = Options.ToolName,
                Command          = args.ExtraProperties.ContainsKey(CliConsts.Command) ? args.ExtraProperties[CliConsts.Command] : "",
                DatabaseProvider = args.DatabaseProvider.ToProviderName(),
                IsTiered         = args.ExtraProperties.ContainsKey("tiered"),
                UiFramework      = args.UiFramework.ToFrameworkName(),
                Options          = JsonSerializer.Serialize(options),
                ProjectName      = args.SolutionName.FullName,
                TemplateName     = args.TemplateName,
                TemplateVersion  = templateFile.Version
            });

            return(new ProjectBuildResult(context.Result.ZipContent, args.SolutionName.ProjectName));
        }
예제 #3
0
        static void Main(string[] args)
        {
            try
            {
                log.Write("Program Başladı");

                string        Subject;
                List <Person> personList = new List <Person>();

                using (PersonDB context = new PersonDB())
                {
                    personList = context.Person.Where(x => x.BirthDate.Day == DateTime.Now.Day && x.BirthDate.Month == DateTime.Now.Month).ToList();
                }

                ITemplate     BirthdayMail = new BirthdayTemp();
                TemplateStore tStore       = new TemplateStore(BirthdayMail);

                foreach (Person person in personList)
                {
                    log.Write("Kişi bulundu : " + person.Name + " " + person.SurName);
                    Subject = string.Format("İyi ki Doğdun {0} {1}", person.Name, person.SurName);
                    IMessenger Message = new SendMail(person.Mail, person.Name, person.SurName, Subject, tStore.GetTemplate());

                    Notification notification = new Notification(Message);
                    notification.Send();
                }
            }
            catch (Exception ex)
            {
                log.Write("Hata : " + ex.Message.ToString());
            }

            log.Write("Bitti");
            Console.ReadLine();
        }
예제 #4
0
        public async Task <ProjectBuildResult> BuildAsync(ProjectBuildArgs args)
        {
            var templateInfo = GetTemplateInfo(args);

            args.TemplateName = templateInfo.Name;

            if (args.DatabaseProvider == DatabaseProvider.NotSpecified)
            {
                if (templateInfo.DefaultDatabaseProvider != DatabaseProvider.NotSpecified)
                {
                    args.DatabaseProvider = templateInfo.DefaultDatabaseProvider;
                }
            }

            var templateFile = await TemplateStore.GetAsync(
                args.TemplateName,
                args.DatabaseProvider,
                args.SolutionName.FullName
                );

            var context = new ProjectBuildContext(
                templateInfo,
                templateFile,
                args
                );

            ProjectBuildPipelineBuilder.Build(context).Execute(context);

            return(new ProjectBuildResult(context.Result.ZipContent, args.SolutionName.ProjectName));
        }
        public static void AddCodeOnlyTemplates(TemplateStore templateStore, Dictionary <string, ControlTemplate> templates, AppType type)
        {
            templates.Add("appinfo", CreateAppInfoTemplate(type));
            if (!templateStore.TryGetTemplate("appinfo", out _))
            {
                templateStore.AddTemplate("appinfo", new CombinedTemplateState()
                {
                    Id      = "http://microsoft.com/appmagic/appinfo",
                    Name    = "appinfo",
                    Version = "1.0",
                    LastModifiedTimestamp = "0",
                    IsComponentTemplate   = false,
                    FirstParty            = true,
                });
            }

            templates.Add("screen", CreateScreenTemplate(type));
            if (!templateStore.TryGetTemplate("screen", out _))
            {
                templateStore.AddTemplate("screen", new CombinedTemplateState()
                {
                    Id      = "http://microsoft.com/appmagic/screen",
                    Name    = "screen",
                    Version = "1.0",
                    LastModifiedTimestamp = "0",
                    IsComponentTemplate   = false,
                    FirstParty            = true,
                });
            }
        }
예제 #6
0
 private ControlDiffVisitor(EditorStateStore childStateStore, TemplateStore parentTemplateStore, TemplateStore childTemplateStore)
 {
     _deltas              = new List <IDelta>();
     _childStateStore     = childStateStore;
     _parentTemplateStore = parentTemplateStore;
     _childTemplateStore  = childTemplateStore;
 }
        public void TestGalleryNestedTemplateParse()
        {
            var galleryTemplatePath = Path.Combine(Environment.CurrentDirectory, "Templates", "gallery_2.10.0.xml");

            Assert.IsTrue(File.Exists(galleryTemplatePath));

            using var galleryTemplateStream = File.OpenRead(galleryTemplatePath);
            using var galleryTemplateReader = new StreamReader(galleryTemplateStream);

            var galleryTemplateContents = galleryTemplateReader.ReadToEnd();

            var parsedTemplates = new Dictionary <string, ControlTemplate>();
            var templateStore   = new TemplateStore();

            Assert.IsTrue(ControlTemplateParser.TryParseTemplate(templateStore, galleryTemplateContents, AppType.DesktopOrTablet, parsedTemplates, out var topTemplate, out var name));

            Assert.AreEqual(2, parsedTemplates.Count);
            Assert.AreEqual("gallery", name);
            Assert.AreEqual("http://microsoft.com/appmagic/gallery", topTemplate.Id);

            Assert.IsTrue(templateStore.TryGetTemplate("gallery", out _));

            Assert.IsTrue(parsedTemplates.TryGetValue("galleryTemplate", out var innerTemplate));
            Assert.AreEqual("http://microsoft.com/appmagic/galleryTemplate", innerTemplate.Id);
            Assert.AreEqual("RGBA(0, 0, 0, 0)", innerTemplate.InputDefaults["TemplateFill"]);

            Assert.IsTrue(templateStore.TryGetTemplate("galleryTemplate", out _));
        }
예제 #8
0
        private IDictionary <string, object> Serialise(Template template)
        {
            var dictionary    = new Dictionary <string, object>();
            var serialisation = new SettingsSerialisation(dictionary);
            var store         = new TemplateStore(serialisation);

            store.AddTemplate(template);
            return(dictionary);
        }
        public SourceTransformer(ErrorContainer errors, Dictionary <string, ControlTemplate> defaultValueTemplates, Theme theme, ComponentInstanceTransform componentInstanceTransform,
                                 EditorStateStore stateStore, TemplateStore templateStore, Entropy entropy)
        {
            _templateTransforms = new List <IControlTemplateTransform>();
            _templateTransforms.Add(new GalleryTemplateTransform(defaultValueTemplates, stateStore));
            _templateTransforms.Add(new AppTestTransform(errors, templateStore, stateStore, entropy));
            _templateTransforms.Add(componentInstanceTransform);

            _defaultValTransform = new DefaultValuesTransform(defaultValueTemplates, theme, stateStore);
        }
예제 #10
0
        internal CanvasDocument(CanvasDocument other)
        {
            foreach (var kvp in other._unknownFiles)
            {
                _unknownFiles.Add(kvp.Key, new FileEntry(kvp.Value));
            }

            foreach (var kvp in other._assetFiles)
            {
                _assetFiles.Add(kvp.Key, new FileEntry(kvp.Value));
            }

            foreach (var kvp in other._screens)
            {
                _screens.Add(kvp.Key, kvp.Value.Clone());
            }

            foreach (var kvp in other._components)
            {
                _components.Add(kvp.Key, kvp.Value.Clone());
            }

            _editorStateStore = new EditorStateStore(other._editorStateStore);
            _templateStore    = new TemplateStore(other._templateStore);

            _dataSources = other._dataSources.JsonClone();
            _screenOrder = new List <string>(other._screenOrder);

            _header               = other._header.JsonClone();
            _properties           = other._properties.JsonClone();
            _parameterSchema      = other._parameterSchema.JsonClone();
            _publishInfo          = other._publishInfo.JsonClone();
            _templates            = other._templates.JsonClone();
            _themes               = other._themes.JsonClone();
            _resourcesJson        = other._resourcesJson.JsonClone();
            _appCheckerResultJson = other._appCheckerResultJson.JsonClone();
            _pcfControls          = other._pcfControls.JsonClone();

            _appInsights = other._appInsights.JsonClone();

            _connections = other._connections.JsonClone();

            _dataSourceReferences = other._dataSourceReferences.JsonClone();
            _libraryReferences    = other._libraryReferences.JsonClone();

            _logoFile = other._logoFile != null ? new FileEntry(other._logoFile) : null;
            _entropy  = other._entropy.JsonClone();
            _checksum = other._checksum.JsonClone();

            this._idRestorer = new UniqueIdRestorer(this._entropy);

            _localAssetInfoJson = other._localAssetInfoJson.JsonClone();
        }
        protected TemplateStore Run(Action<DirectoryInfo> init, bool deep)
        {
            var id = Guid.NewGuid();
            var path = Path.Combine(Directory.GetCurrentDirectory(), id.ToString());
            var dirInfo = Directory.CreateDirectory(path);

            init(dirInfo);

            var store = new TemplateStore(path, "*.htm*", deep);

            Directory.Delete(path, true);
            return store;
        }
예제 #12
0
        protected TemplateStore Run(Action <DirectoryInfo> init, bool deep)
        {
            var id      = Guid.NewGuid();
            var path    = Path.Combine(Directory.GetCurrentDirectory(), id.ToString());
            var dirInfo = Directory.CreateDirectory(path);

            init(dirInfo);

            var store = new TemplateStore(path, "*.htm*", deep);

            Directory.Delete(path, true);
            return(store);
        }
        public static void AddCodeOnlyTemplates(TemplateStore templateStore, Dictionary <string, ControlTemplate> templates, AppType type)
        {
            templates.Add("appinfo", CreateAppInfoTemplate(type));
            if (!templateStore.TryGetTemplate("appinfo", out _))
            {
                templateStore.AddTemplate("appinfo", new CombinedTemplateState()
                {
                    Id      = "http://microsoft.com/appmagic/appinfo",
                    Name    = "appinfo",
                    Version = "1.0",
                    LastModifiedTimestamp = "0",
                    IsComponentTemplate   = false,
                    FirstParty            = true,
                });
            }

            templates.Add("screen", CreateScreenTemplate(type));
            if (!templateStore.TryGetTemplate("screen", out _))
            {
                templateStore.AddTemplate("screen", new CombinedTemplateState()
                {
                    Id      = "http://microsoft.com/appmagic/screen",
                    Name    = "screen",
                    Version = "1.0",
                    LastModifiedTimestamp = "0",
                    IsComponentTemplate   = false,
                    FirstParty            = true,
                });
            }

            /*  Prior to PAC Document version 1.318, the groupContainer control was not version
             *  flexible, so we must check for its existence here. These can be removed from
             *  GlobalTemplates IFF all documents are upgraded to 1.318+ (unlikely) OR if support
             *  for documents 1.317 and lower is dropped. */
            if (!templates.ContainsKey("groupContainer"))
            {
                templates.Add("groupContainer", CreateGroupContainerTemplate(type));
            }
            if (!templateStore.TryGetTemplate("groupContainer", out _))
            {
                templateStore.AddTemplate("groupContainer", new CombinedTemplateState()
                {
                    Id      = "http://microsoft.com/appmagic/groupContainer",
                    Name    = "groupContainer",
                    Version = "1.0",
                    LastModifiedTimestamp = "0",
                    IsComponentTemplate   = false,
                    FirstParty            = true,
                });
            }
        }
        private static bool TryParseNestedWidgets(TemplateStore templateStore, XElement root, AppType type, Dictionary <string, ControlTemplate> loadedTemplates)
        {
            var nestedWidgets = root.Element(ControlMetadataXNames.NestedWidgets);

            if (nestedWidgets == null)
            {
                return(false);
            }

            foreach (var widget in nestedWidgets.Elements(ControlMetadataXNames.DataControlWidgetTag))
            {
                var name    = widget.Attribute(ControlMetadataXNames.NameAttribute).Value;
                var id      = widget.Attribute(ControlMetadataXNames.IdAttribute).Value;
                var version = widget.Attribute(ControlMetadataXNames.VersionAttribute).Value;

                var template = new ControlTemplate(name, version, id);

                var properties = widget.Element(ControlMetadataXNames.PropertiesTag);
                if (properties != null)
                {
                    foreach (var prop in properties.Elements(ControlMetadataXNames.PropertyTag))
                    {
                        if (prop.Attribute(ControlMetadataXNames.DirectionAttribute)?.Value == "out")
                        {
                            continue;
                        }

                        if (!AddPropertyDefault(prop, type, template))
                        {
                            return(false);
                        }
                    }
                }

                loadedTemplates.Add(name, template);
                if (!templateStore.TryGetTemplate(name, out _))
                {
                    templateStore.AddTemplate(name, new CombinedTemplateState()
                    {
                        Id      = template.Id,
                        Name    = template.Name,
                        Version = template.Version,
                        LastModifiedTimestamp = "0",
                        IsComponentTemplate   = false,
                        FirstParty            = true,
                    });
                }
            }
            return(true);
        }
예제 #15
0
        public AppTestTransform(CanvasDocument app, ErrorContainer errors, TemplateStore templateStore, EditorStateStore stateStore, Entropy entropy)
        {
            _testStepTemplateName = "TestStep";

            int i = 1;

            while (templateStore.TryGetTemplate(_testStepTemplateName, out _))
            {
                _testStepTemplateName = "TestStep" + i;
            }

            _screenIdToScreenName = app._screens
                                    .Select(screen => new KeyValuePair <string, string>(app._idRestorer.GetControlId(screen.Key).ToString(), screen.Key)).ToList();

            _errors = errors;
        }
예제 #16
0
        // To Load the fluidGrid template defaults
        private Dictionary <string, ControlTemplate> getTemplateStore()
        {
            var parsedTemplates       = new Dictionary <string, ControlTemplate>();
            var fluidGridTemplatePath = Path.Combine(Environment.CurrentDirectory, "Templates", "fluidGrid_2.2.0.xml");

            Assert.IsTrue(File.Exists(fluidGridTemplatePath));

            using var fluidGridTemplateStream = File.OpenRead(fluidGridTemplatePath);
            using var fluidGridTemplateReader = new StreamReader(fluidGridTemplateStream);
            var templateStore             = new TemplateStore();
            var fluidGridTemplateContents = fluidGridTemplateReader.ReadToEnd();

            ControlTemplateParser.TryParseTemplate(templateStore, fluidGridTemplateContents, AppType.DesktopOrTablet, parsedTemplates, out var topTemplate, out var name);

            return(parsedTemplates);
        }
        public AppTestTransform(ErrorContainer errors, TemplateStore templateStore, EditorStateStore stateStore, Entropy entropy)
        {
            _testStepTemplateName = "TestStep";

            int i = 1;

            while (templateStore.TryGetTemplate(_testStepTemplateName, out _))
            {
                _testStepTemplateName = "TestStep" + i;
            }

            var idRestorer = new UniqueIdRestorer(entropy);

            _screenIdToScreenName = stateStore.Contents
                                    .Where(state => state.TopParentName == state.Name)
                                    .Select(state => new KeyValuePair <string, string>(idRestorer.GetControlId(state.Name).ToString(), state.Name)).ToList();

            _errors = errors;
        }
        internal static bool TryParseTemplate(TemplateStore templateStore, string templateString, AppType type, Dictionary <string, ControlTemplate> loadedTemplates, out ControlTemplate template, out string name)
        {
            template = null;
            name     = string.Empty;
            try
            {
                var manifest = XDocument.Parse(templateString);
                if (manifest == null)
                {
                    return(false);
                }
                var widget = manifest.Root;
                if (widget.Name != ControlMetadataXNames.WidgetTag)
                {
                    return(false);
                }

                name = widget.Attribute(ControlMetadataXNames.NameAttribute).Value;
                var id      = widget.Attribute(ControlMetadataXNames.IdAttribute).Value;
                var version = widget.Attribute(ControlMetadataXNames.VersionAttribute).Value;

                template = new ControlTemplate(name, version, id);

                var properties = widget.Element(ControlMetadataXNames.PropertiesTag);
                if (properties != null)
                {
                    foreach (var prop in properties.Elements(ControlMetadataXNames.PropertyTag))
                    {
                        if (prop.Attribute(ControlMetadataXNames.DirectionAttribute)?.Value == "out")
                        {
                            continue;
                        }
                        if (!AddPropertyDefault(prop, type, template))
                        {
                            return(false);
                        }
                    }
                }

                // Parse the include properties and add them to control template
                var includeProperties = widget.Element(ControlMetadataXNames.IncludePropertiesTag);
                if (includeProperties != null)
                {
                    foreach (var includeProperty in includeProperties.Elements(ControlMetadataXNames.IncludePropertyTag))
                    {
                        if (includeProperty.Attribute(ControlMetadataXNames.DirectionAttribute)?.Value == "out")
                        {
                            continue;
                        }
                        AddIncludePropertyDefault(includeProperty, type, template);
                    }
                }

                if (template.Id == "http://microsoft.com/appmagic/gallery" && !TryParseNestedWidgets(templateStore, widget, type, loadedTemplates))
                {
                    return(false);
                }

                loadedTemplates.Add(name, template);
                if (!templateStore.TryGetTemplate(name, out _))
                {
                    templateStore.AddTemplate(name, new CombinedTemplateState()
                    {
                        Id      = template.Id,
                        Name    = template.Name,
                        Version = template.Version,
                        LastModifiedTimestamp = "0",
                        IsComponentTemplate   = false,
                        FirstParty            = true,
                    });
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
 internal static void Init(string templatePath, string fileMask, bool deep)
 {
     templateStore = new TemplateStore(templatePath, fileMask, deep);
 }
        // Returns pair of item and index (with respect to parent order)
        private static (ControlInfoJson.Item item, int index) CombineIRAndState(BlockNode blockNode, ErrorContainer errors, string parent, EditorStateStore stateStore, TemplateStore templateStore, UniqueIdRestorer uniqueIdRestorer)
        {
            var controlName = blockNode.Name.Identifier;

            // Bottom up, merge children first
            var children = new List <(ControlInfoJson.Item item, int index)>();

            foreach (var childBlock in blockNode.Children)
            {
                children.Add(CombineIRAndState(childBlock, errors, controlName, stateStore, templateStore, uniqueIdRestorer));
            }

            var orderedChildren = children.OrderBy(childPair => childPair.index).Select(pair => pair.item).ToArray();

            var templateIR   = blockNode.Name.Kind;
            var templateName = templateIR.TypeName;
            var variantName  = templateIR.OptionalVariant;

            ControlInfoJson.Template template;

            if (!templateStore.TryGetTemplate(templateName, out var templateState))
            {
                template = ControlInfoJson.Template.CreateDefaultTemplate(templateName, null);
            }
            else
            {
                template = templateState.ToControlInfoTemplate();
            }

            var uniqueId = uniqueIdRestorer.GetControlId(controlName);

            ControlInfoJson.Item resultControlInfo;
            if (stateStore.TryGetControlState(controlName, out var state))
            {
                var properties = new List <ControlInfoJson.RuleEntry>();
                foreach (var propIR in blockNode.Properties)
                {
                    properties.Add(CombinePropertyIRAndState(propIR, errors, state));
                }

                if (blockNode.Functions.Any())
                {
                    foreach (var func in blockNode.Functions)
                    {
                        var funcName          = func.Identifier;
                        var thisPropertyBlock = func.Metadata.FirstOrDefault(metadata => metadata.Identifier == PAConstants.ThisPropertyIdentifier);
                        if (thisPropertyBlock == default)
                        {
                            errors.ParseError(func.SourceSpan.GetValueOrDefault(), "Function definition missing ThisProperty block");
                            throw new DocumentException();
                        }
                        properties.Add(GetPropertyEntry(state, errors, funcName, thisPropertyBlock.Default.Expression));

                        foreach (var arg in func.Metadata)
                        {
                            if (arg.Identifier == PAConstants.ThisPropertyIdentifier)
                            {
                                continue;
                            }

                            properties.Add(GetPropertyEntry(state, errors, funcName + "_" + arg.Identifier, arg.Default.Expression));
                        }

                        RepopulateTemplateCustomProperties(func, templateState, errors);
                    }
                }
                else if (template.CustomProperties?.Any(prop => prop.IsFunctionProperty) ?? false)
                {
                    // For component uses, recreate the dummy props for function parameters
                    foreach (var hiddenScopeRule in template.CustomProperties.Where(prop => prop.IsFunctionProperty).SelectMany(prop => prop.PropertyScopeKey.PropertyScopeRulesKey))
                    {
                        properties.Add(GetPropertyEntry(state, errors, hiddenScopeRule.Name, hiddenScopeRule.ScopeVariableInfo.DefaultRule));
                    }
                }

                // Preserve ordering from serialized IR
                // Required for roundtrip checks
                properties        = properties.OrderBy(prop => state.Properties.Select(propState => propState.PropertyName).ToList().IndexOf(prop.Property)).ToList();
                resultControlInfo = new ControlInfoJson.Item()
                {
                    Parent            = parent,
                    Name              = controlName,
                    ControlUniqueId   = uniqueId.ToString(),
                    PublishOrderIndex = state.PublishOrderIndex,
                    VariantName       = variantName ?? string.Empty,
                    Rules             = properties.ToArray(),
                    StyleName         = state.StyleName,
                    ExtensionData     = state.ExtensionData,
                };

                if (state.IsComponentDefinition ?? false)
                {
                    templateState.ComponentDefinitionInfo = new ComponentDefinitionInfoJson(resultControlInfo, template.LastModifiedTimestamp, orderedChildren);
                    template = templateState.ToControlInfoTemplate();
                    template.IsComponentDefinition   = true;
                    template.ComponentDefinitionInfo = null;
                }
                else
                {
                    template.IsComponentDefinition = state.IsComponentDefinition;
                }
            }
            else
            {
                state                             = null;
                resultControlInfo                 = ControlInfoJson.Item.CreateDefaultControl();
                resultControlInfo.Name            = controlName;
                resultControlInfo.ControlUniqueId = uniqueId.ToString();
                resultControlInfo.Parent          = parent;
                resultControlInfo.VariantName     = variantName ?? string.Empty;
                resultControlInfo.StyleName       = $"default{templateName.FirstCharToUpper()}Style";
                var properties = new List <ControlInfoJson.RuleEntry>();
                foreach (var propIR in blockNode.Properties)
                {
                    properties.Add(CombinePropertyIRAndState(propIR, errors));
                }
                resultControlInfo.Rules = properties.ToArray();
            }
            resultControlInfo.Template = template;
            resultControlInfo.Children = orderedChildren;

            return(resultControlInfo, state?.ParentIndex ?? -1);
        }
        // Returns pair of item and index (with respect to parent order)
        private static (ControlInfoJson.Item item, int index) CombineIRAndState(BlockNode blockNode, ErrorContainer errors, string parent, bool isInResponsiveLayout, EditorStateStore stateStore, TemplateStore templateStore, UniqueIdRestorer uniqueIdRestorer, Entropy entropy)
        {
            var controlName  = blockNode.Name.Identifier;
            var templateIR   = blockNode.Name.Kind;
            var templateName = templateIR.TypeName;
            var variantName  = templateIR.OptionalVariant;

            // Bottom up, merge children first
            var children = new List <(ControlInfoJson.Item item, int index)>();

            foreach (var childBlock in blockNode.Children)
            {
                children.Add(CombineIRAndState(childBlock, errors, controlName, DynamicProperties.AddsChildDynamicProperties(templateName, variantName), stateStore, templateStore, uniqueIdRestorer, entropy));
            }

            var orderedChildren = children.OrderBy(childPair => childPair.index).Select(pair => pair.item).ToArray();

            ControlInfoJson.Template template;
            if (!templateStore.TryGetTemplate(templateName, out var templateState))
            {
                template = ControlInfoJson.Template.CreateDefaultTemplate(templateName, null);
            }
            else
            {
                template = templateState.ToControlInfoTemplate();
            }

            RecombineCustomTemplates(entropy, template, controlName);

            var uniqueId = uniqueIdRestorer.GetControlId(controlName);

            ControlInfoJson.Item resultControlInfo;
            if (stateStore.TryGetControlState(controlName, out var state))
            {
                var properties        = new List <ControlInfoJson.RuleEntry>();
                var dynamicProperties = new List <ControlInfoJson.DynamicPropertyJson>();
                foreach (var propIR in blockNode.Properties)
                {
                    // Dynamic properties could be null for the galleryTemplateTemplate
                    if (isInResponsiveLayout && state.DynamicProperties != null && DynamicProperties.IsResponsiveLayoutProperty(propIR.Identifier))
                    {
                        dynamicProperties.Add(CombineDynamicPropertyIRAndState(propIR, state));
                    }
                    else
                    {
                        properties.Add(CombinePropertyIRAndState(propIR, errors, state));
                    }
                }

                if (isInResponsiveLayout && state.DynamicProperties != null)
                {
                    // Add dummy dynamic output props in the state at the end
                    foreach (var dynPropState in state.DynamicProperties.Where(propState => propState.Property == null))
                    {
                        dynamicProperties.Add(new ControlInfoJson.DynamicPropertyJson()
                        {
                            PropertyName = dynPropState.PropertyName
                        });
                    }

                    // Reorder to preserve roundtripping
                    dynamicProperties = dynamicProperties.OrderBy(prop => state.DynamicProperties.Select(propState => propState.PropertyName).ToList().IndexOf(prop.PropertyName)).ToList();
                }

                if (blockNode.Functions.Any())
                {
                    foreach (var func in blockNode.Functions)
                    {
                        var funcName          = func.Identifier;
                        var thisPropertyBlock = func.Metadata.FirstOrDefault(metadata => metadata.Identifier == PAConstants.ThisPropertyIdentifier);
                        if (thisPropertyBlock == default)
                        {
                            errors.ParseError(func.SourceSpan.GetValueOrDefault(), "Function definition missing ThisProperty block");
                            throw new DocumentException();
                        }
                        properties.Add(GetPropertyEntry(state, errors, funcName, thisPropertyBlock.Default.Expression));

                        foreach (var arg in func.Metadata)
                        {
                            if (arg.Identifier == PAConstants.ThisPropertyIdentifier)
                            {
                                continue;
                            }

                            var propName = funcName + "_" + arg.Identifier;
                            properties.Add(GetPropertyEntry(state, errors, propName, entropy.GetInvariantScript(propName, arg.Default.Expression)));
                        }

                        RepopulateTemplateCustomProperties(func, templateState, errors, entropy);
                    }
                }
                else if (template.CustomProperties?.Any(prop => prop.IsFunctionProperty) ?? false)
                {
                    // For component uses, recreate the dummy props for function parameters
                    foreach (var hiddenScopeRule in template.CustomProperties.Where(prop => prop.IsFunctionProperty).SelectMany(prop => prop.PropertyScopeKey.PropertyScopeRulesKey))
                    {
                        if (!properties.Any(x => x.Property == hiddenScopeRule.Name))
                        {
                            var script = entropy.GetInvariantScript(hiddenScopeRule.Name, hiddenScopeRule.ScopeVariableInfo.DefaultRule);
                            properties.Add(GetPropertyEntry(state, errors, hiddenScopeRule.Name, script));
                        }
                    }
                }

                // Preserve ordering from serialized IR
                // Required for roundtrip checks
                properties        = properties.OrderBy(prop => state.Properties?.Select(propState => propState.PropertyName).ToList().IndexOf(prop.Property) ?? -1).ToList();
                resultControlInfo = new ControlInfoJson.Item()
                {
                    Parent               = parent,
                    Name                 = controlName,
                    ControlUniqueId      = uniqueId.ToString(),
                    VariantName          = variantName ?? string.Empty,
                    Rules                = properties.ToArray(),
                    DynamicProperties    = (isInResponsiveLayout && dynamicProperties.Any()) ? dynamicProperties.ToArray() : null,
                    HasDynamicProperties = state.HasDynamicProperties,
                    StyleName            = state.StyleName,
                    ExtensionData        = state.ExtensionData,
                    IsGroupControl       = state.IsGroupControl,
                    GroupedControlsKey   = state.GroupedControlsKey,
                    AllowAccessToGlobals = (state.IsComponentDefinition ?? false) ? templateState?.ComponentManifest?.AllowAccessToGlobals : state.AllowAccessToGlobals,
                };

                if (state.IsComponentDefinition ?? false)
                {
                    // Before AllowAccessToGlobals added to ComponentDefinition in msapp, it is present in component manifest as well.
                    // So when reconstructing componentdefinition, we need to identify if it was ever present on component definition or not.
                    // For this, we use state IsAllowAccessToGlobalsPresent.
                    templateState.ComponentDefinitionInfo = new ComponentDefinitionInfoJson(resultControlInfo, template.LastModifiedTimestamp, orderedChildren, entropy.IsLegacyComponentAllowGlobalScopeCase ? null : templateState.ComponentManifest.AllowAccessToGlobals);
                    template = templateState.ToControlInfoTemplate();
                    template.IsComponentDefinition = true;

                    // Set it null so that it can be ignored. We have this information at other place.
                    template.ComponentDefinitionInfo = null;
                }
                else
                {
                    template.IsComponentDefinition = state.IsComponentDefinition;
                }
            }
            else
            {
                state                             = null;
                resultControlInfo                 = ControlInfoJson.Item.CreateDefaultControl();
                resultControlInfo.Name            = controlName;
                resultControlInfo.ControlUniqueId = uniqueId.ToString();
                resultControlInfo.Parent          = parent;
                resultControlInfo.VariantName     = variantName ?? string.Empty;
                resultControlInfo.StyleName       = $"default{templateName.FirstCharToUpper()}Style";
                var properties        = new List <ControlInfoJson.RuleEntry>();
                var dynamicProperties = new List <ControlInfoJson.DynamicPropertyJson>();
                foreach (var propIR in blockNode.Properties)
                {
                    if (isInResponsiveLayout && DynamicProperties.IsResponsiveLayoutProperty(propIR.Identifier))
                    {
                        dynamicProperties.Add(CombineDynamicPropertyIRAndState(propIR));
                    }
                    else
                    {
                        properties.Add(CombinePropertyIRAndState(propIR, errors));
                    }
                }
                resultControlInfo.Rules = properties.ToArray();
                bool hasDynamicProperties = isInResponsiveLayout && dynamicProperties.Any();
                resultControlInfo.DynamicProperties    = hasDynamicProperties ? dynamicProperties.ToArray() : null;
                resultControlInfo.HasDynamicProperties = hasDynamicProperties;
                resultControlInfo.AllowAccessToGlobals = templateState?.ComponentManifest?.AllowAccessToGlobals;
            }
            resultControlInfo.Template = template;
            resultControlInfo.Children = orderedChildren;

            return(resultControlInfo, state?.ParentIndex ?? -1);
        }
        internal static SourceFile CombineIRAndState(BlockNode blockNode, ErrorContainer errors, EditorStateStore stateStore, TemplateStore templateStore, UniqueIdRestorer uniqueIdRestorer, Entropy entropy)
        {
            var topParentJson = CombineIRAndState(blockNode, errors, string.Empty, false, stateStore, templateStore, uniqueIdRestorer, entropy);

            return(SourceFile.New(new ControlInfoJson()
            {
                TopParent = topParentJson.item
            }));
        }
        private static void SplitIRAndState(ControlInfoJson.Item control, string topParentName, int index, EditorStateStore stateStore, TemplateStore templateStore, Entropy entropy, out BlockNode controlIR)
        {
            // Bottom up, recursively process children
            var children   = new List <BlockNode>();
            var childIndex = 0;

            foreach (var child in control.Children)
            {
                SplitIRAndState(child, topParentName, childIndex, stateStore, templateStore, entropy, out var childBlock);
                children.Add(childBlock);
                ++childIndex;
            }
            var isComponentDef = control.Template.IsComponentDefinition ?? false;

            var customPropsToHide = new HashSet <string>();
            var functions         = new List <FunctionNode>();

            if (control.Template.CustomProperties?.Any() ?? false)
            {
                if (!isComponentDef)
                {
                    // Skip component property params on instances
                    customPropsToHide = new HashSet <string>(control.Template.CustomProperties
                                                             .Where(customProp => customProp.IsFunctionProperty)
                                                             .SelectMany(customProp =>
                                                                         customProp.PropertyScopeKey.PropertyScopeRulesKey
                                                                         .Select(propertyScopeRule => propertyScopeRule.Name)));
                }
                else
                {
                    // Create FunctionNodes on def
                    foreach (var customProp in control.Template.CustomProperties.Where(prop => prop.IsFunctionProperty))
                    {
                        var name = customProp.Name;
                        customPropsToHide.Add(name);
                        var rule = control.Rules.FirstOrDefault(rule => rule.Property == name);
                        if (rule == null)
                        {
                            // Control does not have a rule for the custom property.
                            continue;
                        }
                        var expression     = rule.InvariantScript;
                        var expressionNode = new ExpressionNode()
                        {
                            Expression = expression
                        };

                        var resultType = new TypeNode()
                        {
                            TypeName = customProp.PropertyDataTypeKey
                        };

                        var args        = new List <TypedNameNode>();
                        var argMetadata = new List <ArgMetadataBlockNode>();
                        foreach (var arg in customProp.PropertyScopeKey.PropertyScopeRulesKey)
                        {
                            customPropsToHide.Add(arg.Name);
                            args.Add(new TypedNameNode()
                            {
                                Identifier = arg.ScopeVariableInfo.ScopeVariableName,
                                Kind       = new TypeNode()
                                {
                                    TypeName = ((PropertyDataType)arg.ScopeVariableInfo.ScopePropertyDataType).ToString()
                                }
                            });

                            var invariantScript = control.Rules.First(rule => rule.Property == arg.Name)?.InvariantScript;
                            argMetadata.Add(new ArgMetadataBlockNode()
                            {
                                Identifier = arg.ScopeVariableInfo.ScopeVariableName,
                                Default    = new ExpressionNode()
                                {
                                    Expression = invariantScript ?? arg.ScopeVariableInfo.DefaultRule
                                },
                            });

                            // Handle the case where invariantScript value of the property is not same as the default script.
                            if (invariantScript != null && invariantScript != arg.ScopeVariableInfo.DefaultRule)
                            {
                                entropy.FunctionParamsInvariantScripts.Add(arg.Name, new string[] { arg.ScopeVariableInfo.DefaultRule, invariantScript });
                            }

                            arg.ScopeVariableInfo.DefaultRule           = null;
                            arg.ScopeVariableInfo.ScopePropertyDataType = null;
                            arg.ScopeVariableInfo.ParameterIndex        = null;
                            arg.ScopeVariableInfo.ParentPropertyName    = null;
                        }

                        argMetadata.Add(new ArgMetadataBlockNode()
                        {
                            Identifier = PAConstants.ThisPropertyIdentifier,
                            Default    = new ExpressionNode()
                            {
                                Expression = expression,
                            },
                        });

                        functions.Add(new FunctionNode()
                        {
                            Args       = args,
                            Metadata   = argMetadata,
                            Identifier = name
                        });
                    }
                }
            }

            var properties    = new List <PropertyNode>();
            var propStates    = new List <PropertyState>();
            var dynPropStates = new List <DynamicPropertyState>();

            foreach (var property in control.Rules)
            {
                var(prop, state) = SplitProperty(property);
                propStates.Add(state);

                if (customPropsToHide.Contains(property.Property))
                {
                    continue;
                }

                properties.Add(prop);
            }

            foreach (var property in control.DynamicProperties ?? Enumerable.Empty <ControlInfoJson.DynamicPropertyJson>())
            {
                if (property.Rule == null)
                {
                    dynPropStates.Add(new DynamicPropertyState()
                    {
                        PropertyName = property.PropertyName
                    });
                    continue;
                }

                var(prop, state) = SplitDynamicProperty(property);
                dynPropStates.Add(state);
                properties.Add(prop);
            }

            controlIR = new BlockNode()
            {
                Name = new TypedNameNode()
                {
                    Identifier = control.Name,
                    Kind       = new TypeNode()
                    {
                        TypeName        = control.Template.TemplateDisplayName ?? control.Template.Name,
                        OptionalVariant = string.IsNullOrEmpty(control.VariantName) ? null : control.VariantName
                    }
                },
                Children   = children.ToList(),
                Properties = properties,
                Functions  = functions,
            };


            if (templateStore.TryGetTemplate(control.Template.Name, out var templateState))
            {
                if (isComponentDef)
                {
                    templateState.IsComponentTemplate = true;
                    templateState.CustomProperties    = control.Template.CustomProperties;
                }
            }
            else
            {
                templateState = new CombinedTemplateState(control.Template);
                templateState.ComponentDefinitionInfo = null;
                var templateName = templateState.TemplateDisplayName ?? templateState.Name;
                templateStore.AddTemplate(templateName, templateState);
            }

            SplitCustomTemplates(entropy, control.Template, control.Name);

            entropy.ControlUniqueIds.Add(control.Name, int.Parse(control.ControlUniqueId));
            var controlState = new ControlState()
            {
                Name                  = control.Name,
                TopParentName         = topParentName,
                Properties            = propStates,
                DynamicProperties     = dynPropStates.Any() ? dynPropStates : null,
                HasDynamicProperties  = control.HasDynamicProperties,
                StyleName             = control.StyleName,
                IsGroupControl        = control.IsGroupControl,
                GroupedControlsKey    = control.GroupedControlsKey,
                ExtensionData         = control.ExtensionData,
                ParentIndex           = index,
                AllowAccessToGlobals  = control.AllowAccessToGlobals,
                IsComponentDefinition = control.Template.IsComponentDefinition,
            };

            stateStore.TryAddControl(controlState);
        }
        internal static void SplitIRAndState(SourceFile file, EditorStateStore stateStore, TemplateStore templateStore, Entropy entropy, out BlockNode topParentIR)
        {
            var topParentJson = file.Value.TopParent;

            SplitIRAndState(topParentJson, topParentJson.Name, 0, stateStore, templateStore, entropy, out topParentIR);
        }
예제 #25
0
 internal static void Init(string templatePath, string fileMask, bool deep)
 {
     templateStore = new TemplateStore(templatePath, fileMask, deep);
 }
 internal CanvasDocument()
 {
     _editorStateStore = new EditorStateStore();
     _templateStore = new TemplateStore();
 }
        private static void SplitIRAndState(ControlInfoJson.Item control, string topParentName, int index, EditorStateStore stateStore, TemplateStore templateStore, Entropy entropy, out BlockNode controlIR)
        {
            // Bottom up, recursively process children
            var childrenWithZIndex = new List <KeyValuePair <BlockNode, double> >();
            var childIndex         = 0;

            foreach (var child in control.Children)
            {
                SplitIRAndState(child, topParentName, childIndex, stateStore, templateStore, entropy, out var childBlock);
                childrenWithZIndex.Add(new KeyValuePair <BlockNode, double>(childBlock, GetControlZIndex(child)));
                ++childIndex;
            }
            var children       = childrenWithZIndex.OrderBy(kvp => kvp.Value).Select(kvp => kvp.Key);
            var isComponentDef = control.Template.IsComponentDefinition ?? false;

            var customPropsToHide = new HashSet <string>();
            var functions         = new List <FunctionNode>();

            if (control.Template.CustomProperties?.Any() ?? false)
            {
                if (!isComponentDef)
                {
                    // Skip component property params on instances
                    customPropsToHide = new HashSet <string>(control.Template.CustomProperties
                                                             .Where(customProp => customProp.IsFunctionProperty)
                                                             .SelectMany(customProp =>
                                                                         customProp.PropertyScopeKey.PropertyScopeRulesKey
                                                                         .Select(propertyScopeRule => propertyScopeRule.Name)
                                                                         ));
                }
                else
                {
                    // Create FunctionNodes on def
                    foreach (var customProp in control.Template.CustomProperties.Where(prop => prop.IsFunctionProperty))
                    {
                        var name = customProp.Name;
                        customPropsToHide.Add(name);
                        var expression     = control.Rules.First(rule => rule.Property == name).InvariantScript;
                        var expressionNode = new ExpressionNode()
                        {
                            Expression = expression
                        };

                        var resultType = new TypeNode()
                        {
                            TypeName = customProp.PropertyDataTypeKey
                        };

                        var args        = new List <TypedNameNode>();
                        var argMetadata = new List <ArgMetadataBlockNode>();
                        foreach (var arg in customProp.PropertyScopeKey.PropertyScopeRulesKey)
                        {
                            customPropsToHide.Add(arg.Name);
                            args.Add(new TypedNameNode()
                            {
                                Identifier = arg.ScopeVariableInfo.ScopeVariableName,
                                Kind       = new TypeNode()
                                {
                                    TypeName = ((PropertyDataType)arg.ScopeVariableInfo.ScopePropertyDataType).ToString()
                                }
                            });

                            argMetadata.Add(new ArgMetadataBlockNode()
                            {
                                Identifier = arg.ScopeVariableInfo.ScopeVariableName,
                                Default    = new ExpressionNode()
                                {
                                    Expression = arg.ScopeVariableInfo.DefaultRule.Replace("\r\n", "\n").Replace("\r", "\n").TrimStart()
                                },
                            });

                            arg.ScopeVariableInfo.DefaultRule           = null;
                            arg.ScopeVariableInfo.ScopePropertyDataType = null;
                            arg.ScopeVariableInfo.ParameterIndex        = null;
                            arg.ScopeVariableInfo.ParentPropertyName    = null;
                        }

                        argMetadata.Add(new ArgMetadataBlockNode()
                        {
                            Identifier = PAConstants.ThisPropertyIdentifier,
                            Default    = new ExpressionNode()
                            {
                                Expression = expression.Replace("\r\n", "\n").Replace("\r", "\n").TrimStart(),
                            },
                        });

                        functions.Add(new FunctionNode()
                        {
                            Args       = args,
                            Metadata   = argMetadata,
                            Identifier = name
                        });
                    }
                }
            }

            var properties = new List <PropertyNode>();
            var propStates = new List <PropertyState>();

            foreach (var property in control.Rules)
            {
                var(prop, state) = SplitProperty(property);
                propStates.Add(state);

                if (customPropsToHide.Contains(property.Property))
                {
                    continue;
                }

                properties.Add(prop);
            }

            controlIR = new BlockNode()
            {
                Name = new TypedNameNode()
                {
                    Identifier = control.Name,
                    Kind       = new TypeNode()
                    {
                        TypeName        = control.Template.TemplateDisplayName ?? control.Template.Name,
                        OptionalVariant = string.IsNullOrEmpty(control.VariantName) ? null : control.VariantName
                    }
                },
                Children   = children.ToList(),
                Properties = properties,
                Functions  = functions,
            };


            if (templateStore.TryGetTemplate(control.Template.Name, out var templateState))
            {
                if (isComponentDef)
                {
                    templateState.IsComponentTemplate = true;
                    templateState.CustomProperties    = control.Template.CustomProperties;
                }
            }
            else
            {
                templateState = new CombinedTemplateState(control.Template);
                templateState.ComponentDefinitionInfo = null;
                var templateName = templateState.TemplateDisplayName ?? templateState.Name;
                templateStore.AddTemplate(templateName, templateState);
            }

            entropy.ControlUniqueIds.Add(control.Name, int.Parse(control.ControlUniqueId));
            var controlState = new ControlState()
            {
                Name = control.Name,
                PublishOrderIndex     = control.PublishOrderIndex,
                TopParentName         = topParentName,
                Properties            = propStates,
                StyleName             = control.StyleName,
                ExtensionData         = control.ExtensionData,
                ParentIndex           = index,
                IsComponentDefinition = control.Template.IsComponentDefinition,
            };

            stateStore.TryAddControl(controlState);
        }
예제 #28
0
 public ComponentDefinitionTransform(ErrorContainer errors, TemplateStore templateStore, ComponentInstanceTransform componentInstanceTransform)
 {
     _templateStore = templateStore;
     _componentInstanceTransform = componentInstanceTransform;
     _errors = errors;
 }
예제 #29
0
        public static IEnumerable <IDelta> GetControlDelta(BlockNode ours, BlockNode parent, EditorStateStore childStateStore, TemplateStore parentTemplateStore, TemplateStore childTemplateStore, bool isInComponent)
        {
            var visitor = new ControlDiffVisitor(childStateStore, parentTemplateStore, childTemplateStore);

            visitor.Visit(ours, new ControlDiffContext(new ControlPath(new List <string>()), parent, isInComponent));

            return(visitor._deltas);
        }