Esempio n. 1
0
        public static string ToFrontMatter(this RulePage rulePage)
        {
            return($@"---
{MdWriter.YamlSerializer.Serialize(new RuleMdModel(rulePage))}
---
");
        }
Esempio n. 2
0
        public static string ToMarkdown(this ContentVersion contentVersion, RulePage rulePage)
        {
            var result = $@"{rulePage.ToFrontMatter()}
{ToMarkdownBody(contentVersion.IntroText, contentVersion.Content, true)}
";

            return(result);
        }
Esempio n. 3
0
        public static string ToMarkdown(this RulePage rulePage, bool skipHtmlMarkdownConversion)
        {
            var result = $@"{rulePage.ToFrontMatter()}
{ToMarkdownBody(rulePage.IntroText, rulePage.Content, skipHtmlMarkdownConversion)}
";

            return(result);
        }
Esempio n. 4
0
 public RuleMdModel(RulePage rule)
 {
     Title          = rule.Title;
     Created        = rule.CreatedUtc;
     Guid           = rule.Guid;
     Uri            = rule.Name.CreateUriAndRedirect(rule);
     Authors        = rule.Employees.Select(e => new AuthorMdModel(e)).ToList();
     ArchivedReason = rule.ArchivedReason;
     Related        = rule.Related.ToList();
     Redirects      = rule.Redirects.Distinct().Where(r => !r.ToLower().Equals(Uri)).ToList();
 }
Esempio n. 5
0
 public static string GetRuleUri(this RulePage rule)
 {
     //Check for any friendly urls
     if (rule.Redirects.Count > 0)
     {
         return(rule.Redirects[0].ToFileName());
     }
     else
     {
         return(rule.Name.ToFileName());
     }
 }
Esempio n. 6
0
 private void UpdateImageUrlsInRule(RulePage rule)
 {
     if (!rule.ImageUrls.Any())
     {
         return;
     }
     foreach (var url in rule.ImageUrls)
     {
         var filename = GetImageFilename(url);
         rule.IntroText = WebUtility.HtmlDecode(rule.IntroText)?.Replace(url, filename);
         rule.Content   = WebUtility.HtmlDecode(rule.Content)?.Replace(url, filename);
     }
 }
Esempio n. 7
0
        private void WriteRule(RulePage rule)
        {
            var tempRule = rule.ToFrontMatter(); //Hack to make sure the redirect Urls are populated

            var rulePaths = new RulePaths(_config, rule);

            if (!Directory.Exists(rulePaths.RuleFolderFull))
            {
                Directory.CreateDirectory(rulePaths.RuleFolderFull);
            }

            _log.LogInformation("writing file {Path}", rulePaths.RuleFileFull);

            if (_config.ProcessHistory)
            {
                ProcessRuleHistory(rule);
            }

            // Write final HTML Version
            using (var writer = new StreamWriter(rulePaths.RuleFileFull, false))
            {
                writer.Write(rule.ToMarkdown(true));
                writer.Flush();
            }
            if (_config.ProcessHistory)
            {
                GitCommit(
                    _config.TargetRepository,
                    $"Extracted from Sharepoint to Git",
                    new LibGit2Sharp.Signature("SSW.Rules.SharePointExtractor", "*****@*****.**", DateTime.UtcNow),
                    new LibGit2Sharp.Signature("SSW.Rules.SharePointExtractor", "*****@*****.**", DateTime.UtcNow),
                    rulePaths.RuleFileRelative);
            }

            // Write final Markdown version
            using (var writer = new StreamWriter(rulePaths.RuleFileFull, false))
            {
                writer.Write(rule.ToMarkdown(false));
                writer.Flush();
            }
            if (_config.ProcessHistory)
            {
                GitCommit(
                    _config.TargetRepository,
                    $"Converted to Markdown",
                    new LibGit2Sharp.Signature("SSW.Rules.SharePointExtractor", "*****@*****.**", DateTime.UtcNow),
                    new LibGit2Sharp.Signature("SSW.Rules.SharePointExtractor", "*****@*****.**", DateTime.UtcNow),
                    rulePaths.RuleFileRelative);
            }
        }
        /// <summary>
        /// process related rules for a rule page
        /// </summary>
        /// <param name="item"></param>
        /// <param name="dataSet"></param>
        /// <param name="rulePage"></param>
        private void RulePageRelated(ListItem item, SpRulesDataSet dataSet, RulePage rulePage)
        {
            //Check if the rule has any keywords for related rules
            if (string.IsNullOrEmpty(item["RulesKeyWords"]?.ToString()))
            {
                return;
            }

            string url = rulePage.Name;
            var    web = new HtmlWeb();

            WebClient webClient = new WebClient();

            var        ruleKeyWords = item["RulesKeyWords"]?.ToString().Split(';');
            XNamespace xmlns        = "http://schemas.microsoft.com/ado/2007/08/dataservices";

            foreach (var keyWord in ruleKeyWords)
            {
                try
                {
                    var relatedUri           = _appSettings.SharePointUrl + "/_api/web/lists/getByTitle('Pages')/Items?$filter=GUID ne '" + rulePage.Guid + "' and substringof('" + keyWord + "',RulesKeyWords)&$select=GUID,Title,RulesKeyWords,FileRef";
                    var relatedXmlPageString = webClient.DownloadString(relatedUri);

                    var xmlDoc            = XDocument.Parse(relatedXmlPageString);
                    var relatedRulesNodes = xmlDoc.Descendants(xmlns + "RulesKeyWords");

                    foreach (var node in relatedRulesNodes)
                    {
                        var keywordsArray = node.Value.Trim().Split(';');
                        if (keywordsArray.Contains(keyWord))
                        {
                            var relatedRuleTitle = node.Parent.Descendants(xmlns + "Title").FirstOrDefault();
                            var relatedRuleUri   = relatedRuleTitle.Value.ToFileName();
                            rulePage.Related.Add(relatedRuleUri);
                        }
                    }
                }
                catch (WebException ex)
                {
                    _log.LogWarning("ignored http error when fetching related rules: ", ex);
                }
            }
            rulePage.Related = rulePage.Related.Distinct().ToList();
        }
Esempio n. 9
0
        //This is for preserving the SharePoint Beta Link Redirects
        public static string CreateUriAndRedirect(this string name, RulePage rule)
        {
            var gatsbyUri = rule.GetRuleUri();

            //Add SharePoint Beta-Link redirect
            var spBetaLink = rule.Name.ToFileName();

            if (spBetaLink != gatsbyUri)
            {
                rule.Redirects.Add(spBetaLink);
            }

            //Add SharePoint Link Redirect
            var spNewName = name.ToSharePointUri();

            if (spNewName != gatsbyUri)
            {
                rule.Redirects.Add(spNewName);
            }

            return(gatsbyUri);
        }
Esempio n. 10
0
        private void ProcessRuleHistory(RulePage rule)
        {
            var rulePaths = new RulePaths(_config, rule);

            bool isFirst = true;

            foreach (var version in rule.Versions
                     .Where(v => !string.IsNullOrWhiteSpace(v.IntroText) || !string.IsNullOrWhiteSpace(v.Content)) // filter out where we have no content
                     .OrderBy(v => v.ModifiedUtc))
            {
                using (var writer = new StreamWriter(rulePaths.RuleFileFull, false))
                {
                    writer.Write(version.ToMarkdown(rule));
                    writer.Flush();
                }

                var gitComment = $"{version.VersionLabel} - {version.Comment}";
                // if the first version label isn't 1.0, the history was truncated by SharePoint. add comment.
                if (isFirst && !version.VersionLabel.StartsWith("1.0"))
                {
                    gitComment = gitComment +
                                 " Note: previous versions of this content may have been deleted by SharePoint.";
                }

                var sw = new Stopwatch();
                sw.Start();
                GitCommit(
                    _config.TargetRepository,
                    gitComment,
                    new LibGit2Sharp.Signature(version.ModifiedByName, version.ModifiedByEmail, version.ModifiedUtc),
                    new LibGit2Sharp.Signature(version.ModifiedByName, version.ModifiedByEmail, version.ModifiedUtc),
                    rulePaths.RuleFileRelative);
                sw.Stop();
                _log.LogInformation($"{version.VersionLabel} committed in {sw.Elapsed.TotalMilliseconds}ms");

                isFirst = false;
            }
        }
        /// <summary>
        /// process authors for a rule page
        /// </summary>
        /// <param name="item"></param>
        /// <param name="dataSet"></param>
        /// <param name="rulePage"></param>
        private void RulePageAuthors(ListItem item, SpRulesDataSet dataSet, RulePage rulePage)
        {
            var employeeRefs = item["EmployeeLookup"] as FieldLookupValue[];

            if (employeeRefs == null || employeeRefs.Length < 1)
            {
                return;
            }
            foreach (var employeeRef in employeeRefs)
            {
                var employee = dataSet.Employees.FirstOrDefault(e => e.Id == employeeRef.LookupId);
                if (employee == null)
                {
                    employee = new Employee()
                    {
                        Id    = employeeRef.LookupId,
                        Title = employeeRef.LookupValue
                    };
                    dataSet.Employees.Add(employee);
                }
                rulePage.Employees.Add(employee);
            }
        }
Esempio n. 12
0
        private void LoadRulePage(SpRulesDataSet dataSet, JToken page)
        {
            if (page["Title"].IsNull())
            {
                return;
            }
            var ruleData = new RulePage()
            {
                Title       = page["Title"].Value <string>().Trim(),
                Id          = page["Id"].Value <int>(),
                Content     = page["PublishingPageContent"].NpValue <string>(),
                IntroText   = page["RuleContentTop"].NpValue <string>(),
                CreatedUtc  = page["Created"].Value <DateTime>(),
                ModifiedUtc = page["Modified"].Value <DateTime>(),
                Guid        = page["GUID"].Value <string>()
            };

            // follow metadata -> term store reference to set rule->category relationship
            // we will use this relationship with screen scraping later to set ordered category->rules list
            foreach (var catRef in page["RuleCategoriesMetadata"].Children())
            {
                var termStoreRef = catRef["TermGuid"].NpValue <string>();
                var catData      = dataSet.Categories.FirstOrDefault(c =>
                                                                     c.TermStoreGuid.Equals(termStoreRef, StringComparison.InvariantCultureIgnoreCase));
                if (catData == null)
                {
                    _log.LogWarning("Failed to resolve category term store giud {TermStoreRef} for rule {RuleTitle}",
                                    termStoreRef, ruleData.Title);
                }
                else
                {
                    ruleData.Categories.Add(catData);
                }
            } // end foreach category reference
            dataSet.Rules.Add(ruleData);
        }
Esempio n. 13
0
        public async Task TestAddAndUpdatePages()
        {
            var pages = Controller.GetPages().ToList();

            var page = new RulePage
            {
                ObjId             = Guid.NewGuid(),
                Name              = "NewPage1",
                Description       = "NewPage1Description",
                This2RulePageType = 1
            };

            pages.Add(page);

            var savedPages = (await Controller.Save(pages)).ToList();

            Assert.Equal(page.Name, savedPages.First(a => a.ObjId == page.ObjId).Name);

            page.Name        = "UpdatePage1";
            page.Description = null;
            var savedPages2 = (await Controller.Save(pages)).ToList();

            Assert.Equal(page.Name, savedPages2.First(a => a.ObjId == page.ObjId).Name);
        }
Esempio n. 14
0
        public static void EnsureDatabaseCreated(IServiceProvider services)
        {
            var context         = services.GetRequiredService <AutomaticaContext>();
            var visuInitFactory = services.GetRequiredService <IVisualisationFactory>();
            var config          = services.GetRequiredService <IConfiguration>();

            context.Database.Migrate();

            bool dbCreated = !context.BoardTypes.Any();

            if (dbCreated)
            {
                context.RuleInterfaceDirections.Add(new EF.Models.RuleInterfaceDirection()
                {
                    ObjId       = 1,
                    Name        = "Input",
                    Description = "Input",
                    Key         = "I"
                });
                context.RuleInterfaceDirections.Add(new EF.Models.RuleInterfaceDirection()
                {
                    ObjId       = 2,
                    Name        = "Output",
                    Description = "Output",
                    Key         = "O"
                });
                context.RuleInterfaceDirections.Add(new EF.Models.RuleInterfaceDirection()
                {
                    ObjId       = 3,
                    Name        = "Parameter",
                    Description = "Parameter",
                    Key         = "P"
                });

                context.RulePageTypes.Add(new RulePageType()
                {
                    ObjId       = 1,
                    Name        = "Rules",
                    Description = "Rules",
                    Key         = "rules"
                });
                context.VisuPageTypes.Add(new VisuPageType()
                {
                    ObjId       = 1,
                    Name        = "PC",
                    Description = "PC",
                    Key         = "pc"
                });
                context.VisuPageTypes.Add(new VisuPageType()
                {
                    ObjId       = 2,
                    Name        = "Mobile",
                    Description = "Mobile",
                    Key         = "mobile"
                });
                context.SaveChanges();

                context.Slaves.Add(new Slave()
                {
                    ObjId       = new Guid(ServerInfo.SelfSlaveId),
                    Name        = "local",
                    Description = "this is me",
                    ClientId    = "",
                    ClientKey   = ""
                });


                context.Settings.Add(new Setting
                {
                    ObjId     = 1,
                    ValueKey  = "ConfigVersion",
                    Type      = (long)PropertyTemplateType.Numeric,
                    Value     = 0,
                    Group     = "ConfigVersion",
                    IsVisible = false,
                    Order     = 10
                });
                context.SaveChanges();
            }

            var lat = context.Settings.SingleOrDefault(a => a.ValueKey == "Latitude");

            if (lat == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "Latitude",
                    Type      = (long)PropertyTemplateType.Numeric,
                    Value     = 0,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 10
                });

                context.Settings.Add(new Setting
                {
                    ValueKey  = "Longitude",
                    Type      = (long)PropertyTemplateType.Numeric,
                    Value     = 0,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 11
                });
            }
            else
            {
                var longi = context.Settings.SingleOrDefault(a => a.ValueKey == "Longitude");

                if (lat.ValueDouble == null)
                {
                    lat.ValueDouble = 0;
                }

                if (longi.ValueDouble == null)
                {
                    longi.ValueDouble = 0;
                }

                context.Settings.Update(longi);
                context.Settings.Update(lat);
            }

            var apiKey = context.Settings.SingleOrDefault(a => a.ValueKey == "apiKey");

            if (apiKey == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "apiKey",
                    Type      = (long)PropertyTemplateType.Text,
                    Value     = "",
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 0
                });
            }

            var autoUpdate      = context.Settings.SingleOrDefault(a => a.ValueKey == "autoUpdate");
            var autoUpdateTime  = context.Settings.SingleOrDefault(a => a.ValueKey == "autoUpdateTime");
            var reportCrashLogs = context.Settings.SingleOrDefault(a => a.ValueKey == "reportCrashLogs");

            if (autoUpdate == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "autoUpdate",
                    Type      = (long)PropertyTemplateType.Bool,
                    Value     = false,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 20
                });
            }
            else
            {
                autoUpdate.Order = 20;
                context.Update(autoUpdate);
            }

            if (autoUpdateTime == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "autoUpdateTime",
                    Type      = (long)PropertyTemplateType.Time,
                    Value     = new DateTime(2000, 12, 31, 2, 0, 0),
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 21
                });
            }
            else
            {
                autoUpdateTime.Order = 21;
                autoUpdateTime.Type  = (long)PropertyTemplateType.Time;
                context.Update(autoUpdateTime);
            }

            if (reportCrashLogs == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "reportCrashLogs",
                    Type      = (long)PropertyTemplateType.Bool,
                    Value     = false,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 22
                });
            }
            else
            {
                reportCrashLogs.Order = 22;
                context.Update(reportCrashLogs);
            }

            var cloudUrl = context.Settings.SingleOrDefault(a => a.ValueKey == "cloudUrl");

            if (cloudUrl == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "cloudUrl",
                    Type      = (long)PropertyTemplateType.Text,
                    Value     = "https://automatica-core-cloud.azurewebsites.net",
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 1
                });
            }

            var cloudEnvironment = context.Settings.SingleOrDefault(a => a.ValueKey == "cloudEnvironment");

            if (cloudEnvironment == null)
            {
                var cloudEnvironmentType = "master";
#if DEBUG
                cloudEnvironmentType = "develop";
#else
                cloudEnvironmentType = "master";
#endif

                context.Settings.Add(new Setting
                {
                    ValueKey  = "cloudEnvironment",
                    Type      = (long)PropertyTemplateType.Text,
                    Value     = cloudEnvironmentType,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 2
                });
            }

            var projectName = context.Settings.SingleOrDefault(a => a.ValueKey == "projectName");

            if (projectName == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "projectName",
                    Type      = (long)PropertyTemplateType.Text,
                    Value     = "Automatica.Core",
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 3
                });
            }

            var propertyTypes = Enum.GetValues(typeof(PropertyTemplateType));

            foreach (var propertyType in propertyTypes)
            {
                var propertyTypeDb = context.PropertyTypes.SingleOrDefault(a => a.Type == Convert.ToInt64(propertyType));
                var isNewObject    = false;
                if (propertyTypeDb == null)
                {
                    propertyTypeDb = new PropertyType {
                        Type = (int)propertyType
                    };
                    isNewObject = true;
                }

                var type       = propertyType.GetType();
                var memInfo    = type.GetMember(propertyType.ToString());
                var attributes = memInfo[0].GetCustomAttributes(typeof(PropertyTemplateTypeAttribute), false);

                if (attributes.Length > 0 && attributes[0] is PropertyTemplateTypeAttribute attribute)
                {
                    propertyTypeDb.Name        = attribute.Name;
                    propertyTypeDb.Description = attribute.Description;
                    propertyTypeDb.Meta        = attribute.Meta;
                }
                else
                {
                    propertyTypeDb.Name        = propertyType.GetType().Name;
                    propertyTypeDb.Description = propertyType.GetType().Name;
                    propertyTypeDb.Meta        = null;
                }

                if (isNewObject)
                {
                    context.PropertyTypes.Add(propertyTypeDb);
                }
                else
                {
                    context.PropertyTypes.Update(propertyTypeDb);
                }
            }

            var nodeDataTypes = Enum.GetValues(typeof(NodeDataType));

            foreach (var nodeDataType in nodeDataTypes)
            {
                var nodeDataTypeDb = context.NodeDataTypes.SingleOrDefault(a => a.Type == Convert.ToInt64(nodeDataType));
                var isNewObject    = false;
                if (nodeDataTypeDb == null)
                {
                    nodeDataTypeDb      = new EF.Models.NodeDataType();
                    nodeDataTypeDb.Type = (int)nodeDataType;
                    isNewObject         = true;
                }

                var type       = nodeDataType.GetType();
                var memInfo    = type.GetMember(nodeDataType.ToString());
                var attributes = memInfo[0].GetCustomAttributes(typeof(NodeDataTypeEnumAttribute), false);

                if (attributes.Length > 0 && attributes[0] is NodeDataTypeEnumAttribute attribute)
                {
                    nodeDataTypeDb.Name        = attribute.Name;
                    nodeDataTypeDb.Description = attribute.Description;
                }
                else
                {
                    nodeDataTypeDb.Name        = nodeDataType.GetType().Name;
                    nodeDataTypeDb.Description = nodeDataType.GetType().Name;
                }

                if (isNewObject)
                {
                    context.NodeDataTypes.Add(nodeDataTypeDb);
                }
                else
                {
                    context.NodeDataTypes.Update(nodeDataTypeDb);
                }
            }


            context.SaveChanges();
            visuInitFactory.Initialize(context, config);
            context.SaveChanges();

            CreateInterfaceTypes(context);
            context.SaveChanges();

            AddSystemTemplates(context);

            IDatabaseBoardType boardType = null;

            if (BoardTypes.Docker.Docker.InDocker)
            {
                boardType = new BoardTypes.Docker.Docker();
            }
            else
            {
                boardType = new RaspberryPi();
            }

            ServerInfo.BoardType = boardType;

            AddBoard(context, boardType);

            AddAreaData(context);
            CategoryGroup.GenerateDefault(context);
            context.SaveChanges();
            CategoryInstance.GenerateDefault(context);

            context.SaveChanges();


            if (!context.AreaInstances.Any())
            {
                var projectInstance = new AreaInstance
                {
                    ObjId             = Guid.NewGuid(),
                    Name              = "Project",
                    Description       = "",
                    Icon              = "home",
                    This2AreaTemplate = AreaTemplateAttribute.GetFromEnum(AreaTemplates.Project),
                    This2Parent       = null
                };
                context.AreaInstances.Add(projectInstance);
            }

            if (dbCreated)
            {
                var rootNodeTemplate = context.NodeTemplates.SingleOrDefault(a => a.ObjId == GuidTemplateTypeAttribute.GetFromEnum(boardType.BoardType));
                var rootNode         = NodeInstanceFactory.CreateNodeInstanceFromTemplate(rootNodeTemplate);

                rootNode.Name        = boardType.Name;
                rootNode.Description = "";

                context.NodeInstances.Add(rootNode);

                var childs = context.NodeTemplates.Where(a => a.NeedsInterface2InterfacesType == rootNodeTemplate.ObjId);

                foreach (var child in childs)
                {
                    if (child.NeedsInterface2InterfacesType == child.ProvidesInterface2InterfaceType)
                    {
                        continue;
                    }
                    var node = NodeInstanceFactory.CreateNodeInstanceFromTemplate(child);
                    node.This2ParentNodeInstance = rootNode.ObjId;
                    context.NodeInstances.Add(node);
                }


                var rulePage = new RulePage
                {
                    ObjId             = Guid.NewGuid(),
                    Name              = "Page1",
                    Description       = "",
                    This2RulePageType = 1
                };

                context.RulePages.Add(rulePage);


                var visuPage = new VisuPage
                {
                    ObjId             = Guid.NewGuid(),
                    Name              = "Page1",
                    Description       = "",
                    This2VisuPageType = 2,
                    DefaultPage       = true
                };

                context.VisuPages.Add(visuPage);

                AddInitUserManagementData(context);

                context.SaveChanges();
            }


            context.SaveChanges();
        }
        private RulePage LoadRulePage(SpRulesDataSet dataSet, ClientContext ctx, ListItem item)
        {
            if (string.IsNullOrEmpty(item["Title"]?.ToString()))
            {
                return(null);
            }


            var rulePage = new RulePage()
            {
                ArchivedReason = item["ObsoleteReason"]?.ToString(),
                Title          = item["Title"].ToString().Trim(),
                Id             = Convert.ToInt32(item["ID"]),
                Content        = item["PublishingPageContent"]?.ToString(),
                IntroText      = item["RuleContentTop"]?.ToString(),
                RulesKeyWords  = item["RulesKeyWords"]?.ToString(),
                CreatedUtc     = (DateTime)item["Created"],
                ModifiedUtc    = (DateTime)item["Modified"],
                Guid           = item["GUID"].ToString(),
                FileName       = item["FileLeafRef"].ToString()
            };

            RulePageAuthors(item, dataSet, rulePage);
            RulePageRelated(item, dataSet, rulePage);

            rulePage.ImageUrls.UnionWith(GetImageUrls(rulePage.IntroText));
            rulePage.ImageUrls.UnionWith(GetImageUrls(rulePage.Content));

            // I could not work out how to drill into the RuleCategoriesMetaData object other than serializing to json and parsing via JObject
            var metadataJason = JsonConvert.SerializeObject(item["RuleCategoriesMetadata"]);
            // follow metadata -> term store reference to set rule->category relationship

            var jArray = JArray.Parse(metadataJason);

            foreach (var elt in jArray)
            {
                var termGuid = elt["TermGuid"].NpValue <string>();
                var catData  = dataSet.Categories.FirstOrDefault(c =>
                                                                 c.TermStoreGuid.Equals(termGuid, StringComparison.InvariantCultureIgnoreCase));
                if (catData != null)
                {
                    rulePage.Categories.Add(catData);
                }
            }

            /* var jObject = JObject.Parse(metadataJason);
             *
             * foreach (var reference in jObject["_Child_Items_"].Children())
             * {
             *  //_log.LogInformation("link to {REF}", reference);
             *
             *  var termGuid = reference["TermGuid"].NpValue<string>();
             *  var catData = dataSet.Categories.FirstOrDefault(c =>
             *      c.TermStoreGuid.Equals(termGuid, StringComparison.InvariantCultureIgnoreCase));
             *  if (catData != null)
             *  {
             *      rulePage.Categories.Add(catData);
             *  }
             * }*/

            if (rulePage.Content != null)
            {
                MatchEvaluator matchEval = new MatchEvaluator(ReplaceRelativeURl);
                rulePage.Content = Regex.Replace(rulePage.Content, @"(""(\/_layouts\/15\/FIXUPREDIRECT.ASPX)[^""]*"")", matchEval);
            }

            dataSet.Rules.Add(rulePage);
            return(rulePage);
        }
Esempio n. 16
0
        public static void EnusreDatabaseCreated(IServiceProvider services)
        {
            var context         = services.GetRequiredService <AutomaticaContext>();
            var visuInitFactory = services.GetRequiredService <IVisualisationFactory>();
            var config          = services.GetRequiredService <IConfiguration>();

            context.Database.Migrate();

            bool dbCreated = !context.BoardTypes.Any();



            if (dbCreated)
            {
                context.Database.ExecuteSqlCommand($@"	       

		            INSERT INTO RuleInterfaceDirections (ObjId, Name, Description, Key) VALUES 
		                (1, 'Input', 'Input', 'I'),
		                (2, 'Output', 'Output', 'O'),
		                (3, 'Parameter', 'Parameter', 'P');

	                INSERT INTO Settings (ObjId, ValueKey, ValueInt, Type) VALUES (1, 'ConfigVersion', 0, 0);

		        
		        INSERT INTO RulePageTypes (ObjId, Name, Description, Key) VALUES 
		        (1, 'Rules', 'Rules', 'rules');


		        INSERT INTO VisuPageTypes (ObjId, Name, Description, Key) VALUES 
		        (1, 'PC', 'PC', 'pc');


		        INSERT INTO VisuPageTypes (ObjId, Name, Description, Key) VALUES 
		        (2, 'Mobile', 'Mobile', 'mobile')"        );
                context.SaveChanges();
            }

            var lat = context.Settings.SingleOrDefault(a => a.ValueKey == "Latitude");

            if (lat == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "Latitude",
                    Type      = (long)PropertyTemplateType.Numeric,
                    Value     = 0,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 10
                });

                context.Settings.Add(new Setting
                {
                    ValueKey  = "Longitude",
                    Type      = (long)PropertyTemplateType.Numeric,
                    Value     = 0,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 11
                });
            }
            else
            {
                var longi = context.Settings.SingleOrDefault(a => a.ValueKey == "Longitude");

                if (lat.ValueDouble == null)
                {
                    lat.ValueDouble = 0;
                }

                if (longi.ValueDouble == null)
                {
                    longi.ValueDouble = 0;
                }

                context.Settings.Update(longi);
                context.Settings.Update(lat);
            }

            var apiKey = context.Settings.SingleOrDefault(a => a.ValueKey == "apiKey");

            if (apiKey == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "apiKey",
                    Type      = (long)PropertyTemplateType.Text,
                    Value     = "",
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 0
                });
            }

            var autoUpdate      = context.Settings.SingleOrDefault(a => a.ValueKey == "autoUpdate");
            var autoUpdateTime  = context.Settings.SingleOrDefault(a => a.ValueKey == "autoUpdateTime");
            var reportCrashLogs = context.Settings.SingleOrDefault(a => a.ValueKey == "reportCrashLogs");

            if (autoUpdate == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "autoUpdate",
                    Type      = (long)PropertyTemplateType.Bool,
                    Value     = false,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 20
                });
            }
            else
            {
                autoUpdate.Order = 20;
                context.Update(autoUpdate);
            }

            if (autoUpdateTime == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "autoUpdateTime",
                    Type      = (long)PropertyTemplateType.Time,
                    Value     = new DateTime(2000, 12, 31, 2, 0, 0),
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 21
                });
            }
            else
            {
                autoUpdateTime.Order = 21;
                autoUpdateTime.Type  = (long)PropertyTemplateType.Time;
                context.Update(autoUpdateTime);
            }

            if (reportCrashLogs == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "reportCrashLogs",
                    Type      = (long)PropertyTemplateType.Bool,
                    Value     = false,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 22
                });
            }
            else
            {
                reportCrashLogs.Order = 22;
                context.Update(reportCrashLogs);
            }

            var cloudUrl = context.Settings.SingleOrDefault(a => a.ValueKey == "cloudUrl");

            if (cloudUrl == null)
            {
                context.Settings.Add(new Setting
                {
                    ValueKey  = "cloudUrl",
                    Type      = (long)PropertyTemplateType.Text,
                    Value     = "https://automatica-core-cloud.azurewebsites.net",
                    Group     = "SERVER.SETTINGS",
                    IsVisible = true,
                    Order     = 1
                });
            }

            var propertyTypes = Enum.GetValues(typeof(PropertyTemplateType));

            foreach (var propertyType in propertyTypes)
            {
                var propertyTypeDb = context.PropertyTypes.SingleOrDefault(a => a.Type == (int)propertyType);
                var isNewObject    = false;
                if (propertyTypeDb == null)
                {
                    propertyTypeDb = new PropertyType {
                        Type = (int)propertyType
                    };
                    isNewObject = true;
                }

                var type       = propertyType.GetType();
                var memInfo    = type.GetMember(propertyType.ToString());
                var attributes = memInfo[0].GetCustomAttributes(typeof(PropertyTemplateTypeAttribute), false);

                if (attributes.Length > 0 && attributes[0] is PropertyTemplateTypeAttribute attribute)
                {
                    propertyTypeDb.Name        = attribute.Name;
                    propertyTypeDb.Description = attribute.Description;
                    propertyTypeDb.Meta        = attribute.Meta;
                }
                else
                {
                    propertyTypeDb.Name        = propertyType.GetType().Name;
                    propertyTypeDb.Description = propertyType.GetType().Name;
                    propertyTypeDb.Meta        = null;
                }

                if (isNewObject)
                {
                    context.PropertyTypes.Add(propertyTypeDb);
                }
                else
                {
                    context.PropertyTypes.Update(propertyTypeDb);
                }
            }

            var nodeDataTypes = Enum.GetValues(typeof(NodeDataType));

            foreach (var nodeDataType in nodeDataTypes)
            {
                var nodeDataTypeDb = context.NodeDataTypes.SingleOrDefault(a => a.Type == (int)nodeDataType);
                var isNewObject    = false;
                if (nodeDataTypeDb == null)
                {
                    nodeDataTypeDb      = new EF.Models.NodeDataType();
                    nodeDataTypeDb.Type = (int)nodeDataType;
                    isNewObject         = true;
                }

                var type       = nodeDataType.GetType();
                var memInfo    = type.GetMember(nodeDataType.ToString());
                var attributes = memInfo[0].GetCustomAttributes(typeof(NodeDataTypeEnumAttribute), false);

                if (attributes.Length > 0 && attributes[0] is NodeDataTypeEnumAttribute attribute)
                {
                    nodeDataTypeDb.Name        = attribute.Name;
                    nodeDataTypeDb.Description = attribute.Description;
                }
                else
                {
                    nodeDataTypeDb.Name        = nodeDataType.GetType().Name;
                    nodeDataTypeDb.Description = nodeDataType.GetType().Name;
                }

                if (isNewObject)
                {
                    context.NodeDataTypes.Add(nodeDataTypeDb);
                }
                else
                {
                    context.NodeDataTypes.Update(nodeDataTypeDb);
                }
            }


            context.SaveChanges();
            visuInitFactory.Initialize(context, config);
            context.SaveChanges();

            CreateInterfaceTypes(context);
            AddSystemTemplates(context);
            AddRaspberryPi3Board(context);
            AddAreaData(context);
            CategoryGroup.GenerateDefault(context);
            context.SaveChanges();
            CategoryInstance.GenerateDefault(context);

            context.SaveChanges();


            if (!context.AreaInstances.Any())
            {
                var projectInstance = new AreaInstance
                {
                    ObjId             = Guid.NewGuid(),
                    Name              = "Project",
                    Description       = "",
                    Icon              = "home",
                    This2AreaTemplate = AreaTemplateAttribute.GetFromEnum(AreaTemplates.Project),
                    This2Parent       = null
                };
                context.AreaInstances.Add(projectInstance);
            }

            if (dbCreated)
            {
                var rootNodeTemplate = context.NodeTemplates.SingleOrDefault(a => a.ObjId == GuidTemplateTypeAttribute.GetFromEnum(BoardTypeEnum.RaspberryPi3));
                var rootNode         = NodeInstanceFactory.CreateNodeInstanceFromTemplate(rootNodeTemplate);

                rootNode.Name        = "Raspberry PI 3";
                rootNode.Description = "";

                context.NodeInstances.Add(rootNode);

                var childs = context.NodeTemplates.Where(a => a.NeedsInterface2InterfacesType == rootNodeTemplate.ObjId);

                foreach (var child in childs)
                {
                    if (child.NeedsInterface2InterfacesType == child.ProvidesInterface2InterfaceType)
                    {
                        continue;
                    }
                    var node = NodeInstanceFactory.CreateNodeInstanceFromTemplate(child);
                    node.This2ParentNodeInstance = rootNode.ObjId;
                    context.NodeInstances.Add(node);
                }


                var rulePage = new RulePage
                {
                    ObjId             = Guid.NewGuid(),
                    Name              = "Page1",
                    Description       = "",
                    This2RulePageType = 1
                };

                context.RulePages.Add(rulePage);


                var visuPage = new VisuPage
                {
                    ObjId             = Guid.NewGuid(),
                    Name              = "Page1",
                    Description       = "",
                    This2VisuPageType = 2,
                    DefaultPage       = true
                };

                context.VisuPages.Add(visuPage);

                AddInitUserManagementData(context);

                context.SaveChanges();
            }


            context.SaveChanges();
        }
Esempio n. 17
0
 public RulePaths(MdWriterConfig config, RulePage rule)
 {
     _config = config;
     _rule   = rule;
 }