Example #1
0
        /// <summary>
        /// Given a declaration return a structure which pulls it apart, including all template
        /// arguments. It deals correctly with nested templates as well.
        /// </summary>
        /// <param name="typeDef"></param>
        public static IDecl ParseForTemplates(this string typeDef)
        {
            if (typeDef == null)
                throw new ArgumentNullException("typeDef");

            ///
            /// Is the current typeDef a template?
            /// 

            var m = templateParameterFinder.Match(typeDef);
            if (!m.Success)
            {
                return new RegularDecl(typeDef);
            }

            ///
            /// Now we have to carefully split up arguments. This is painful! We split by ",", but we
            /// have to be careful of sub template definitions that might contain commas.
            /// 

            var argStrings = SplitTemplateArguments(m.Groups["types"].Value);
            var args = (from a in argStrings
                        select ParseForTemplates(a)).ToArray();

            ///
            /// Ok, now create a new template definition from that!
            /// 

            var t = new TemplateInfo(m.Groups["tclass"].Value, args);

            return t;
        }
Example #2
0
 public Task<JSchema> GetSchemaFromTemplateAsync(TemplateInfo template)
 {
     // TODO: use async
     var type = _modelTypeRepository.GetModelTypeFromTemplate(template);
     var schemaGenerator = new JSchemaGenerator();
     return Task.FromResult(schemaGenerator.Generate(type));
 }
        /// <summary>
        /// Returns a unique key that represent the template in the template cache.
        /// The template key is computed from the following parts:
        ///	 Template body hash,
        ///	 Global types hash,
        ///	 Imported templates hash,
        ///	 Referenced assemblies hash
        /// </summary>
        /// <param name="ti">Template info</param>
        /// <returns>Template key</returns>
        protected static string ComputeTemplateKey(TemplateInfo ti)
        {
            // Template body hash
            string hash = Utils.ComputeHash(ti.TemplateBody);

            // Global types hash
            hash += Utils.ComputeHash(ti.GlobalsTypes);

            // Imported templates hash
            if (ti.ImportedPrograms != null && ti.ImportedPrograms.Count > 0)
            {
                var keys = new List<string>(ti.ImportedPrograms.Keys);
                keys.Sort();
                foreach (string path in keys)
                {
                    hash += Utils.ComputeHash(ti.ImportedPrograms[path].TemplateBody);
                }
            }

            // Referenced assemblies hash
            hash += Utils.ComputeHash(ti.ReferencedAssemblies);

            // Template Key
            string templateKey = Utils.ComputeHash(hash);
            return templateKey;
        }
Example #4
0
        public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
        {
            this.templateInfo = templateInfo;

            previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
            templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
        }
Example #5
0
        public Task UpdateDefaultModelForTemplateAsync(TemplateInfo template, object content)
        {
            var filePath = GetPath(template, DefaultFilename);
            if (!_fileSystem.DirectoryExists(_fileSystem.Path.GetDirectoryName(filePath)))
                _fileSystem.CreateDirectory(_fileSystem.Path.GetDirectoryName(filePath));

            return Update(content, filePath);
        }
        public Type GetModelTypeFromTemplate(TemplateInfo template)
        {
            Type type;
            if (!_repository.TryGetValue(template.Id, out type))
                throw new KeyNotFoundException(string.Format("No type for template with id '{0}' found", template.Id));

            return type;
        }
        public Task<JSchema> GetSchemaFromTemplateAsync(TemplateInfo template)
        {
            var file = _fileSystem.Path.Combine(_viewPathInfo, SchemasPathInfo, _fileSystem.Path.ChangeExtension(PathInfo.Create(template.Id), "json"));
            if (!_fileSystem.FileExists(file))
                return null;

            return GetSchema(file);
        }
        public Task<JSchema> GetSchemaFromTemplateAsync(TemplateInfo template)
        {
            var extractor = new SchemaExtractor(new HandlebarsParser());
            var helperHandlers = _helperHandlerFactory != null ? _helperHandlerFactory.Create().ToArray() : null;

            // TODO: Use async
            var schema = extractor.Run(template.Id, new StreamReader(template.Open()), _memberLocator, helperHandlers);
            if (schema != null && string.IsNullOrEmpty(schema.Title))
                schema.Title = string.Concat(template.Id, "Model");

            return Task.FromResult(schema);
        }
		public string Generate(TemplateInfo templateInfo)
		{
			var builder = new StringBuilder();
			using (var writer = new StringWriter(builder))
			{
                writer.Write("{0}.register(\"{1}\", {{ render: function(ctx, model) {{ var w = function(v) {{ ctx.write(v); }}; var we = function(v) {{ ctx.writeEscape(v); }};", _templateRepository, templateInfo.Id);
				var clientContext = new JavascriptClientContext(templateInfo.Id, writer);
				var model = new JavascriptClientModel(null, "model");
				_templateGenerator.Generate(templateInfo, clientContext, model);

				writer.Write("}});");	
			}

			return builder.ToString();
		}
Example #10
0
        public async Task<JSchema> GetSchemaFromTemplateAsync(TemplateInfo template)
        {
            var comparer = new SchemaComparer();
            var schema1Task = _schemaProvider.GetSchemaFromTemplateAsync(template);
            var schema2Task = _schemaBaseProvider.GetSchemaFromTemplateAsync(template);

	        if (schema1Task == null)
		        return await schema2Task;

	        if (schema2Task == null)
		        return await schema1Task;

            await Task.WhenAll(schema1Task, schema2Task).ConfigureAwait(false);

            return comparer.Apply(schema1Task.Result, schema2Task.Result, new SchemaComparisionReport());
        }
Example #11
0
        public string Render(string fileName, params object[] args)
        {
            // Validate the args
            if (args.Length % 2 != 0)
                throw new ArgumentException("args must consist of key/value pairs, where the key is a string", "args");
            for (int i = 0; i < args.Length; i += 2 )
            {
                if (args[i].GetType() != typeof(string))
                    throw new ArgumentException("Args array must be string, object, string, object ...., where the strings are the argument names", "args");
            }

            TemplateInfo template = null;
            // Template exists, invoke it if have not been changed on disk.
            if (_compiledTemplates.ContainsKey(fileName))
            {
                TemplateInfo ti = _compiledTemplates[fileName];

                // Template have changed, let's reload it
                if (ti.Changed < File.GetLastWriteTime(fileName))
                {
                    object templateClass = BuildTemplate(args, fileName);
                    if (templateClass == null)
                        return null;

                    ti.compiledTemplate = templateClass;
                    ti.Changed = DateTime.Now;
                }
                template = ti;
            }
            else
            {
                object templateClass = BuildTemplate(args, fileName);
                if (templateClass == null)
                    return null;
                template = new TemplateInfo();
                template.compiledTemplate = templateClass;
                template.fileName = fileName;
                template.Changed = DateTime.Now;
                _compiledTemplates.Add(fileName, template);
            }

            object o = template.compiledTemplate;
            return (string)o.GetType().InvokeMember("RunTemplate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, o, new object[] { args });            
        }
Example #12
0
        /// <summary>
        /// Compiles a Smarty-style template file into HTML output
        /// </summary>
        /// <param name="fileName">Path to the Smarty template to compile</param>
        /// <param name="variables">Key/value collection of template variable names and values</param>
        /// <returns>A compiled HTML document</returns>
        public string Render(string fileName, IDictionary<string, object> variables)
        {
            TemplateInfo template = null;
            TemplateInfo ti;

            lock (compiledTemplates)
            {
                if (compiledTemplates.TryGetValue(fileName, out ti))
                {
                    if (ti.Changed < File.GetLastWriteTimeUtc(fileName))
                    {
                        // Template has changed, reload it
                        object templateClass = BuildTemplate(fileName, variables);
                        if (templateClass == null)
                            return null;

                        ti.CompiledTemplate = templateClass;
                        ti.Changed = DateTime.UtcNow;
                    }

                    template = ti;
                }
                else
                {
                    // Template has not been loaded yet, load it
                    object templateClass = BuildTemplate(fileName, variables);
                    if (templateClass == null)
                        return null;

                    template = new TemplateInfo();
                    template.CompiledTemplate = templateClass;
                    template.FileName = fileName;
                    template.Changed = DateTime.UtcNow;

                    compiledTemplates.Add(fileName, template);
                }
            }

            object o = template.CompiledTemplate;
            return (string)o.GetType().InvokeMember("RunTemplate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
                null, o, new object[] { variables });
        }
Example #13
0
        public async Task Should_Create_And_Delete_Template()
        {
            // Setup
            string       apiKey       = ConfigurationManager.AppSettings["APIKey"];
            string       templateName = ConfigurationManager.AppSettings["TemplateExample"] + "_temp";
            const string code         = "Foobar";

            // Exercise
            var          api    = new MandrillApi(apiKey);
            TemplateInfo result = await api.AddTemplate(new AddTemplateRequest(templateName)
            {
                FromName = "*****@*****.**",
                Code     = code,
                Text     = code,
                Publish  = true
            });

            TemplateInfo result2 = await api.DeleteTemplate(new DeleteTemplateRequest(templateName));

            // Verify
            Assert.AreEqual(code, result.Code);
            Assert.AreEqual(code, result2.Code);
        }
Example #14
0
        public PageInfo(int pageNodeId, int pageContentId, PublishmentSystemInfo publishmentSystemInfo, TemplateInfo templateInfo, UserInfo userInfo)
        {
            TemplateInfo           = templateInfo;
            PublishmentSystemId    = publishmentSystemInfo.PublishmentSystemId;
            PageNodeId             = pageNodeId;
            PageContentId          = pageContentId;
            _pageAfterBodyScripts  = new SortedDictionary <string, string>();
            _pageBeforeBodyScripts = new SortedDictionary <string, string>();
            _pageEndScripts        = new SortedDictionary <string, string>();
            _pageHeadScripts       = new SortedDictionary <string, string>();
            PublishmentSystemInfo  = publishmentSystemInfo;
            UserInfo  = userInfo;
            _uniqueId = 1;

            ChannelItems = new Stack(5);
            ContentItems = new Stack(5);
            CommentItems = new Stack(5);
            InputItems   = new Stack(5);
            SqlItems     = new Stack(5);
            SiteItems    = new Stack(5);
            PhotoItems   = new Stack(5);
            EachItems    = new Stack(5);
        }
Example #15
0
        protected virtual TemplateInfo ParseTemplate(IItemData templateItem)
        {
            if (templateItem == null)
            {
                throw new ArgumentException("Template item passed to parse was null", nameof(templateItem));
            }
            if (templateItem.TemplateId != TemplateTemplateId)
            {
                throw new ArgumentException("Template item passed to parse was not a Template item", nameof(templateItem));
            }

            var result = new TemplateInfo
            {
                Id = templateItem.Id,
                BaseTemplateIds = ParseBaseTemplatesAndRejectIgnoredBaseTemplates(GetFieldValue(templateItem, BaseTemplateFieldId, string.Empty)),
                HelpText        = GetFieldValue(templateItem, HelpTextFieldId, string.Empty),
                Name            = templateItem.Name,
                OwnFields       = ParseTemplateFields(templateItem),
                Path            = templateItem.Path
            };

            return(result);
        }
Example #16
0
        public PageInfo(int pageChannelId, int pageContentId, SiteInfo siteInfo, TemplateInfo templateInfo, Dictionary <string, object> pluginItems)
        {
            TemplateInfo  = templateInfo;
            SiteId        = siteInfo.Id;
            PageChannelId = pageChannelId;
            PageContentId = pageContentId;
            IsLocal       = false;
            HeadCodes     = new SortedDictionary <string, string>();
            BodyCodes     = new SortedDictionary <string, string>();
            FootCodes     = new SortedDictionary <string, string>();
            SiteInfo      = siteInfo;
            UserInfo      = null;
            _uniqueId     = 1;
            ApiUrl        = ApiManager.OuterApiUrl;

            ChannelItems = new Stack <ChannelItemInfo>(5);
            ContentItems = new Stack <ContentItemInfo>(5);
            SqlItems     = new Stack(5);
            SiteItems    = new Stack(5);
            EachItems    = new Stack(5);

            PluginItems = pluginItems;
        }
Example #17
0
        private void CreateScript(TemplateInfo info)
        {
            string className = Path.GetFileNameWithoutExtension(info.replacements["ClassName"]);
            string template  = info.wholeTemplate;
            string ext       = info.specialKeys["EXTENSION"];

            foreach (KeyValuePair <string, string> pairs in info.replacements)
            {
                template = template.Replace("##" + pairs.Key + "##", pairs.Value);
            }

            string finalPath = Path.Combine(_createPath, className + ext.ToLower());

            if (File.Exists(finalPath))
            {
                Debug.LogError("File already exists: " + finalPath);
            }
            else
            {
                File.WriteAllText(finalPath, template, System.Text.Encoding.UTF8);
                AssetDatabase.Refresh();
            }
        }
        public ShaderTemplateSelector(SerializedProperty prop)
        {
            this.prop = prop;

            var paths = Utils.GetShaderTemplatePathList();

            foreach (var path in paths)
            {
                if (Path.GetExtension(path) == Common.Setting.templateFileExtension)
                {
                    var index = path.IndexOf(Common.Setting.templateDirectoryPath);
                    var name  = path
                                .Substring(index + Common.Setting.templateDirectoryPath.Length + 1)
                                .Replace(Common.Setting.templateFileExtension, "");
                    var info = new TemplateInfo()
                    {
                        name = name,
                        path = path,
                    };
                    list_.Add(info);
                }
            }
        }
Example #19
0
    private static void NormalizeArgs(ProjectBuildArgs args, TemplateInfo templateInfo)
    {
        if (args.TemplateName.IsNullOrEmpty())
        {
            args.TemplateName = templateInfo.Name;
        }

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

        if (args.UiFramework == UiFramework.NotSpecified)
        {
            if (templateInfo.DefaultUiFramework != UiFramework.NotSpecified)
            {
                args.UiFramework = templateInfo.DefaultUiFramework;
            }
        }
    }
Example #20
0
        public void AddItem(UserSelection userSelection, TemplateInfo template, Func <TemplateInfo, string> getName)
        {
            if (template.MultipleInstance || !AlreadyAdded(userSelection, template))
            {
                var itemName  = getName(template);
                var usedNames = userSelection.Pages.Select(p => p.Name)
                                .Concat(userSelection.Features.Select(f => f.Name))
                                .Concat(userSelection.Services.Select(f => f.Name))
                                .Concat(userSelection.Testing.Select(f => f.Name));

                if (template.ItemNameEditable)
                {
                    var itemBameValidationService = new ItemNameService(GenContext.ToolBox.Repo.ItemNameValidationConfig, () => usedNames);
                    itemName = itemBameValidationService.Infer(itemName);
                }
                else
                {
                    itemName = template.DefaultName;
                }

                AddItem(userSelection, itemName, template);
            }
        }
        public IActionResult Update([FromBody] TemplateModel model)
        {
            TemplateInfo template = null;

            if (model.Id > 0)
            {
                template = _viewManager.GetPageTemplate(model.Id);
            }

            if (template == null)
            {
                template = new TemplateInfo();
            }

            template.Name       = model.Name;
            template.KeyName    = model.KeyName;
            template.ModelClass = model.ModelClass;
            template.ViewPath   = model.ViewPath.Replace("..", String.Empty);

            _viewManager.SavePageTemplate(template);

            return(Ok(new { template.TemplateId }));
        }
        public void AddItem(UserSelection userSelection, TemplateInfo template, Func <TemplateInfo, string> getName)
        {
            if (template.MultipleInstance || !AlreadyAdded(userSelection, template))
            {
                var itemName  = getName(template);
                var usedNames = userSelection.Pages.Select(p => p.Name)
                                .Concat(userSelection.Features.Select(f => f.Name))
                                .Concat(userSelection.Services.Select(f => f.Name))
                                .Concat(userSelection.Testing.Select(f => f.Name));
                var validators = new List <Validator>()
                {
                    new ExistingNamesValidator(usedNames),
                    new ReservedNamesValidator(),
                };
                if (template.ItemNameEditable)
                {
                    validators.Add(new DefaultNamesValidator());
                }

                itemName = Naming.Infer(itemName, validators);
                AddItem(userSelection, itemName, template);
            }
        }
Example #23
0
        public PageInfo(int pageChannelId, int pageContentId, SiteInfo siteInfo, TemplateInfo templateInfo)
        {
            TemplateInfo           = templateInfo;
            SiteId                 = siteInfo.Id;
            PageChannelId          = pageChannelId;
            PageContentId          = pageContentId;
            IsLocal                = false;
            _pageAfterBodyScripts  = new SortedDictionary <string, string>();
            _pageBeforeBodyScripts = new SortedDictionary <string, string>();
            _pageEndScripts        = new SortedDictionary <string, string>();
            _pageHeadScripts       = new SortedDictionary <string, string>();
            SiteInfo               = siteInfo;
            UserInfo               = null;
            _uniqueId              = 1;
            ApiUrl                 = PageUtility.OuterApiUrl;

            ChannelItems = new Stack <ChannelItemInfo>(5);
            ContentItems = new Stack <ContentItemInfo>(5);
            CommentItems = new Stack(5);
            SqlItems     = new Stack(5);
            SiteItems    = new Stack(5);
            EachItems    = new Stack(5);
        }
Example #24
0
        protected void btnRender_Click(object sender, EventArgs e)
        {
            try
            {
                TemplateInfo _templateInfo = new TemplateInfo();
                _templateInfo.TemplateID = new Guid(grdTemplate.SelectedRow.Cells[1].Text);

                RenderRequestInfo renderRequestInfo = new RenderRequestInfo();
                renderRequestInfo.ComputerName  = txtComputerName.Text;
                renderRequestInfo.CreatedBy     = txtCreatedBy.Text;
                renderRequestInfo.PriorityID    = PriorityId.Medium;
                renderRequestInfo.TemplateID    = new Guid(_templateInfo.TemplateID.ToString());
                renderRequestInfo.RequestTypeID = (int)(RenderMode)Enum.Parse(typeof(RenderMode), cboRenderMode.SelectedItem.Value);

                List <object> ParamValues = new List <object>()
                {
                    int.Parse(txtParam1.Text)
                };
                PackageData result = sxService.APIRenderRequest.AddToRenderRequestQ(renderRequestInfo, ParamValues);

                if (result.Status == SXStatus.Success)
                {
                    lblMessage.Text = "The output is store in reposity folder at file: " + ((string)result.Data);
                }
                else
                {
                    foreach (var code in result.ErrorCodes)
                    {
                        lblMessage.Text += " | " + code.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }
        public override void OnInitTemplateInfo(EventArgs e)
        {
            string   str      = BasePage.RequestString("updatetime");
            DateTime?nullable = null;

            if (!string.IsNullOrEmpty(str))
            {
                nullable = new DateTime?(DataConverter.CDate(str));
            }
            string dynamicConfigTemplatePath = TemplatePage.GetDynamicConfigTemplatePath(Path.GetFileNameWithoutExtension(this.Page.Request.FilePath));
            NameValueCollection values       = new NameValueCollection();

            values.Add("authorname", DataSecurity.FilterBadChar(BasePage.RequestString("authorname")));
            if (!nullable.HasValue)
            {
                values.Add("updatetime", string.Empty);
            }
            else
            {
                values.Add("updatetime", nullable.Value.ToString("yyyy-MM-dd"));
            }
            if (!string.IsNullOrEmpty(dynamicConfigTemplatePath))
            {
                TemplateInfo info = new TemplateInfo();
                info.QueryList       = values;
                info.PageName        = TemplatePage.RebuildPageName(base.Request.Url.LocalPath, base.Request.QueryString);
                info.TemplateContent = Template.GetTemplateContent(dynamicConfigTemplatePath);
                info.RootPath        = HttpContext.Current.Request.PhysicalApplicationPath;
                info.CurrentPage     = DataConverter.CLng(base.Request.QueryString["page"], 1);
                info.PageType        = 1;
                base.TemplateInfo    = info;
            }
            else
            {
                TemplatePage.WriteErrMsg("您查看的作者未设置模板!", SiteConfig.SiteInfo.VirtualPath + "Default.aspx");
            }
        }
        private void codeActivity2_ExecuteCode(object sender, EventArgs e)
        {
            AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken);

            IXmlPageTemplate newPageTemplate = this.GetBinding <IXmlPageTemplate>("NewPageTemplate");

            string newPageTemplateMarkup = null;
            Guid   copyOfId = this.GetBinding <Guid>("CopyOfId");

            if (copyOfId == Guid.Empty)
            {
                newPageTemplateMarkup = _defaultTemplateMarkup.Replace("    ", "\t");
            }
            else
            {
                XDocument copyDocument = TemplateInfo.GetTemplateDocument(copyOfId);
                newPageTemplateMarkup = copyDocument.ToString();
            }

            IPageTemplateFile pageTemplateFile = DataFacade.BuildNew <IPageTemplateFile>();

            pageTemplateFile.FolderPath = "/";
            pageTemplateFile.FileName   = string.Format("{0}.xml", PathUtil.CleanFileName(newPageTemplate.Title, true) ?? newPageTemplate.Id.ToString());
            //if (FileNameAlreadyUsed(pageTemplateFile)) pageTemplateFile.FileName = newPageTemplate.Id.ToString() + pageTemplateFile.FileName;
            pageTemplateFile.SetNewContent(newPageTemplateMarkup);

            DataFacade.AddNew <IPageTemplateFile>(pageTemplateFile, "PageTemplateFileProvider");

            newPageTemplate.PageTemplateFilePath = "/" + pageTemplateFile.FileName;
            newPageTemplate = DataFacade.AddNew <IXmlPageTemplate>(newPageTemplate);

            PageTemplateProviderRegistry.FlushTemplates();

            addNewTreeRefresher.PostRefreshMesseges(newPageTemplate.GetDataEntityToken());

            this.ExecuteAction(newPageTemplate.GetDataEntityToken(), new WorkflowActionToken(typeof(EditXmlPageTemplateWorkflow)));
        }
Example #27
0
        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)
        {
            ViewDataDictionary viewData      = html.ViewContext.ViewData;
            TemplateInfo       templateInfo  = viewData.TemplateInfo;
            ModelMetadata      modelMetadata = viewData.ModelMetadata;
            StringBuilder      builder       = new StringBuilder();

            if (templateInfo.TemplateDepth > 1)      // DDB #224751
            {
                return(modelMetadata.Model == null ? modelMetadata.NullDisplayText : modelMetadata.SimpleDisplayText);
            }

            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo)))
            {
                if (!propertyMetadata.HideSurroundingHtml)
                {
                    string label = LabelExtensions.LabelHelper(html, propertyMetadata, propertyMetadata.PropertyName).ToHtmlString();
                    if (!String.IsNullOrEmpty(label))
                    {
                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"editor-label\">{0}</div>\r\n", label);
                    }

                    builder.Append("<div class=\"editor-field\">");
                }

                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));

                if (!propertyMetadata.HideSurroundingHtml)
                {
                    builder.Append(" ");
                    builder.Append(html.ValidationMessage(propertyMetadata.PropertyName));
                    builder.Append("</div>\r\n");
                }
            }

            return(builder.ToString());
        }
        private void encryptBtn_Click(object sender, EventArgs e)
        {
            var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filepathBox.Text.Trim());

            if (checkEncryptionStatus.ToString().ToLower().Contains("encrypted"))
            {
                DialogResult isEncrypted = MessageBox.Show("Selected file is already encrypted");
                if (isEncrypted == DialogResult.OK)
                {
                    Application.Exit();
                }
            }
            else
            {
                try
                {
                    int templateNum = templateListBox.SelectedIndex;
                    //MessageBox.Show(templateNum.ToString());
                    TemplateInfo selectedTemplateInfo = templates.ElementAt(templateNum);
                    var          license           = SafeNativeMethods.IpcCreateLicenseFromTemplateId(selectedTemplateInfo.TemplateId);
                    string       encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile(filepathBox.Text.Trim(), license, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, false, true, IntPtr.Zero, null);
                    DialogResult result            = MessageBox.Show("File has been Encrypted and is at the following location: " + encryptedFilePath);
                    if (result == DialogResult.OK)
                    {
                        Application.Exit();
                    }
                }
                catch (Exception ex)
                {
                    DialogResult error = MessageBox.Show("Error: " + ex);
                    if (error == DialogResult.OK)
                    {
                        Application.Exit();
                    }
                }
            }
        }
Example #29
0
        /// <summary>
        /// 获得指定的模板信息
        /// </summary>
        /// <param name="templateid">皮肤id</param>
        /// <returns></returns>
        public static TemplateInfo GetTemplateItem(int templateid)
        {
            if (templateid <= 0)
            {
                return(null);
            }

            TemplateInfo templateinfo = null;

            DataRow[] dr = GetValidTemplateList().Select("templateid = " + templateid.ToString());

            if (dr.Length > 0)
            {
                templateinfo             = new TemplateInfo();
                templateinfo.Templateid  = Int16.Parse(dr[0]["templateid"].ToString());
                templateinfo.Name        = dr[0]["name"].ToString();
                templateinfo.Directory   = dr[0]["directory"].ToString();
                templateinfo.Copyright   = dr[0]["copyright"].ToString();
                templateinfo.Templateurl = dr[0]["templateurl"].ToString();
            }

            if (templateinfo == null)
            {
                dr = GetValidTemplateList().Select("templateid = 1");

                if (dr.Length > 0)
                {
                    templateinfo             = new TemplateInfo();
                    templateinfo.Templateid  = Int16.Parse(dr[0]["templateid"].ToString());
                    templateinfo.Name        = dr[0]["name"].ToString();
                    templateinfo.Directory   = dr[0]["directory"].ToString();
                    templateinfo.Copyright   = dr[0]["copyright"].ToString();
                    templateinfo.Templateurl = dr[0]["templateurl"].ToString();
                }
            }
            return(templateinfo);
        }
        private void cmbTemplateGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbTemplateGroup.SelectedIndex < 0)
            {
                return;
            }

            cmbTemplate.Items.Clear();

            TemplateInfo template = cmbTemplateGroup.SelectedItem as TemplateInfo;

            if (template != null)
            {
                Collection <ModuleInfo> modules = ConfigCtrl.GetModules(template.FullPath);
                foreach (ModuleInfo item in modules)
                {
                    cmbTemplate.Items.Add(item);
                }
                if (cmbTemplate.Items.Count > 0)
                {
                    cmbTemplate.SelectedIndex = 0;
                }
            }
        }
Example #31
0
        public void TestLocalizedPostActionFields(
            int postActionIndex,
            string locale,
            string expectedDescription,
            string expectedManualInstructions)
        {
            _ = LoadHostWithLocalizationTemplates(out SettingsLoader settingsLoader);

            IReadOnlyList <TemplateInfo> localizedTemplates = settingsLoader.UserTemplateCache.GetTemplatesForLocale(locale,
                                                                                                                     SettingsStore.CurrentVersion);

            Assert.True(localizedTemplates.Count != 0, "Test template couldn't be loaded.");
            TemplateInfo localizationTemplate = localizedTemplates.FirstOrDefault(t => t.Identity == "TestAssets.TemplateWithLocalization");

            Assert.NotNull(localizationTemplate);

            ITemplate template = settingsLoader.LoadTemplate(localizationTemplate, null);

            Assert.NotNull(template);
            Assert.NotNull(template.Generator);

            ICreationEffects effects = template.Generator.GetCreationEffects(
                settingsLoader.EnvironmentSettings,
                template,
                new MockParameterSet(),
                settingsLoader.Components,
                Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())
                );

            Assert.NotNull(effects);
            Assert.NotNull(effects.CreationResult);
            Assert.NotNull(effects.CreationResult.PostActions);
            Assert.True(effects.CreationResult.PostActions.Count > postActionIndex, "Template does not contain enough post actions");
            Assert.Equal(expectedDescription, effects.CreationResult.PostActions[postActionIndex].Description);
            Assert.Equal(expectedManualInstructions, effects.CreationResult.PostActions[postActionIndex].ManualInstructions);
        }
Example #32
0
        /// <summary>
        /// Occurs before any open document is saved. (Inherited from ApplicationEvents4_Event.)
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="SaveAsUI"></param>
        /// <param name="Cancel"></param>
        private void ThisDocument_DocumentBeforeSave(Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)
        {
            try
            {
                if (Doc != Application.ActiveDocument)
                {
                    return;
                }
            }
            catch { return; }

            TemplateInfo template = this.TemplateInfo;

            if (template.IsProntoDoc)
            {
                try
                {
                    ContextManager contexMgr = new ContextManager();
                    contexMgr.SaveDocument(Doc, ref SaveAsUI, ref Cancel);
                }
                catch (BaseException baseExp)
                {
                    ManagerException mgrExp = new ManagerException(ErrorCode.ipe_SaveDocumentError);
                    mgrExp.Errors.Add(baseExp);

                    throw mgrExp;
                }
                catch (Exception ex)
                {
                    ManagerException mgrExp = new ManagerException(ErrorCode.ipe_SaveDocumentError,
                                                                   MessageUtils.Expand(Properties.Resources.ipe_SaveDocumentError, ex.Message), ex.StackTrace);

                    throw mgrExp;
                }
            }
        }
Example #33
0
        /// <summary>
        /// 模板消息
        /// </summary>
        /// <param name="openid"></param>
        public void SendTemplateMessage(string openid)
        {
            TemplateInfo temp = new TemplateInfo();

            temp.template_id = "jp5-DHV2SfxMYNHpf9pRWlrKe8eHtv_j1nJOBiEKR8k";
            temp.touser      = openid;
            temp.url         = "http://ljx.pqpqpq.cn";

            temp.topcolor = "#FF0000";

            Param p = new Param();

            p.value = "黄先生";
            p.color = "#173177";

            p.value = DateTime.Now.ToString();
            p.color = "#173177";

            p.value = "0426";
            p.color = "#173177";

            p.value = "消费";
            p.color = "#173177";

            p.value = "人民币260.00元";
            p.color = "#173177";

            p.value = "06月07日19时24分";
            p.color = "#173177";

            p.value = "06月07日19时24分";
            p.color = "#173177";

            string data = JsonConvert.SerializeObject(temp);
            var    json = RequestType.HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(), data);
        }
Example #34
0
        /// <summary>Gets the template from this page's settings.  If no template is set, sets a default.</summary>
        /// <returns>The template from this page's settings, or <c>null</c> if no valid template is available</returns>
        private TemplateInfo GetTemplateSetting()
        {
            TemplateInfo template           = null;
            string       templateFolderName = ModuleSettings.TemplateFolderName.GetValueAsStringFor(this);

            if (!string.IsNullOrEmpty(templateFolderName))
            {
                template = this.GetTemplate(templateFolderName);
            }

            if (template == null)
            {
                template = this.GetDefaultTemplate();
                if (template == null)
                {
                    // if there are no templates, return null and cause the templating framework to throw an ArgumentNullException...
                    return(null);
                }

                this.SetTemplateSetting(template.FolderName);
            }

            return(template);
        }
        public async Task <ActionResult <GetResult> > Get([FromQuery] GetRequest request)
        {
            if (!await _authManager.HasAppPermissionsAsync(LoginManager.PermissionsTemplates))
            {
                return(Unauthorized());
            }

            var templateInfo = _loginManager.GetTemplateInfo(request.Name);
            var html         = _loginManager.GetTemplateHtml(templateInfo);

            var isSystem = templateInfo.Publisher == "sscms";

            if (isSystem)
            {
                templateInfo = new TemplateInfo();
            }

            return(new GetResult
            {
                TemplateInfo = templateInfo,
                TemplateHtml = html,
                IsSystem = isSystem
            });
        }
Example #36
0
        public static TemplateInfo GetDefaultTemplateInfo(int siteId, TemplateType templateType)
        {
            TemplateInfo info = null;

            var templateInfoDictionary = GetTemplateInfoDictionaryBySiteId(siteId);

            if (templateInfoDictionary != null)
            {
                foreach (var templateInfo in templateInfoDictionary.Values)
                {
                    if (templateInfo.TemplateType == templateType && templateInfo.IsDefault)
                    {
                        info = templateInfo;
                        break;
                    }
                }
            }

            return(info ?? new TemplateInfo
            {
                SiteId = siteId,
                TemplateType = templateType
            });
        }
        public static ASObject GetCodePreview(string location, string serviceName, string methodName)
        {
            ManagementService managementService = new ManagementService();
            Project           project           = managementService.GetProject();

            string templateFolder = Path.Combine("templates", location);

            templateFolder = HttpContext.Current.Server.MapPath(templateFolder);
            TemplateInfo templateInfo = new TemplateInfo(string.Empty, templateFolder);
            Hashtable    context      = new Hashtable();

            context["Project"] = project;
            context["Service"] = serviceName;
            context["Method"]  = methodName;

            string preview;

            try
            {
                // See if we're running in full trust
                new SecurityPermission(PermissionState.Unrestricted).Demand();

                WebTemplateGeneratorHost host  = new WebTemplateGeneratorHost(context);
                TemplateEngineProxy      proxy = new TemplateEngineProxy();
                preview = proxy.Preview(templateInfo, host, TemplateEngineSettings.Default);
            }
            catch (SecurityException)
            {
                preview = "Security error. Code generation is not available in Medium Trust environment.";
            }

            ASObject asoCodePreview = new ASObject();

            asoCodePreview["code"] = preview;
            return(asoCodePreview);
        }
        public void CreateNodesHtml(NodeInfo nodeInfo)
        {
            TemplateInfo        templateInfo = new TemplateInfo();
            NameValueCollection values       = new NameValueCollection();

            values.Add("id", nodeInfo.NodeId.ToString());
            values.Add("page", "1");
            templateInfo.QueryList     = values;
            templateInfo.RootPath      = this.PhysicalApplicationPath;
            templateInfo.SiteUrl       = this.SiteUrl;
            templateInfo.IsDynamicPage = false;
            templateInfo.PageType      = 1;
            this.CreateNodeDefalutPageHtml(nodeInfo, templateInfo);
            templateInfo = new TemplateInfo();
            values       = new NameValueCollection();
            values.Add("id", nodeInfo.NodeId.ToString());
            values.Add("page", "1");
            templateInfo.QueryList     = values;
            templateInfo.RootPath      = this.PhysicalApplicationPath;
            templateInfo.SiteUrl       = this.SiteUrl;
            templateInfo.IsDynamicPage = false;
            templateInfo.PageType      = 1;
            this.CreateNodeListPageHtml(nodeInfo, templateInfo);
        }
Example #39
0
        protected void BtnGoogle_Click(object sender, EventArgs e)
        {
            TemplateInfo templateInfo = new TemplateInfo();

            templateInfo.QueryList = base.Request.QueryString;
            string path = "/其他模板/Google地图模板.html";

            templateInfo.PageName        = "GoogleSiteMap_Index.xml";
            templateInfo.IsDynamicPage   = false;
            templateInfo.CurrentPage     = DataConverter.CLng(base.Request.QueryString["page"], 1);
            templateInfo.RootPath        = base.Request.PhysicalApplicationPath;
            templateInfo.SiteUrl         = SiteConfig.SiteInfo.SiteUrl;
            templateInfo.TemplateContent = Template.GetTemplateContent(path);
            TemplateTransform.GetHtml(templateInfo);
            FileSystemObject.WriteFile(VirtualPathUtility.AppendTrailingSlash(base.Request.PhysicalApplicationPath) + SiteConfig.SiteOption.CreateHtmlPath + templateInfo.PageName, TemplateTransform.GetHtml(templateInfo).TemplateContent);
            if (templateInfo.PageNum > 1)
            {
                int pageNum = templateInfo.PageNum;
                for (int i = 2; i < pageNum; i++)
                {
                    templateInfo.QueryList = base.Request.QueryString;
                    path = "/其他模板/Google地图模板.html";
                    templateInfo.PageName        = "GoogleSiteMap_Index_" + i.ToString() + ".xml";
                    templateInfo.IsDynamicPage   = false;
                    templateInfo.CurrentPage     = i;
                    templateInfo.RootPath        = base.Request.PhysicalApplicationPath;
                    templateInfo.SiteUrl         = SiteConfig.SiteInfo.SiteUrl;
                    templateInfo.TemplateContent = Template.GetTemplateContent(path);
                    TemplateTransform.GetHtml(templateInfo);
                    FileSystemObject.WriteFile(VirtualPathUtility.AppendTrailingSlash(base.Request.PhysicalApplicationPath) + SiteConfig.SiteOption.CreateHtmlPath + templateInfo.PageName, TemplateTransform.GetHtml(templateInfo).TemplateContent);
                }
            }
            this.HypGoogleMap.Visible     = true;
            this.HypGoogleMap.Text        = "生成成功,点击提交地图!";
            this.HypGoogleMap.NavigateUrl = "http://www.google.com/webmasters/sitemaps/ping?sitemap=" + templateInfo.SiteUrl + "/" + templateInfo.PageName;
        }
        public static List <TemplateInfo> GetTemplateInfoList(SiteInfo siteInfo, int specialId)
        {
            var list = new List <TemplateInfo>();

            var specialInfo = GetSpecialInfo(siteInfo.Id, specialId);

            if (specialInfo != null)
            {
                var directoryPath    = GetSpecialDirectoryPath(siteInfo, specialInfo.Url);
                var srcDirectoryPath = GetSpecialSrcDirectoryPath(directoryPath);

                var htmlFilePaths = Directory.GetFiles(srcDirectoryPath, "*.html", SearchOption.AllDirectories);
                foreach (var htmlFilePath in htmlFilePaths)
                {
                    var relatedPath = PathUtils.GetPathDifference(srcDirectoryPath, htmlFilePath);

                    var templateInfo = new TemplateInfo
                    {
                        Charset             = ECharset.utf_8,
                        Content             = GetContentByFilePath(htmlFilePath),
                        CreatedFileExtName  = ".html",
                        CreatedFileFullName = PathUtils.Combine(specialInfo.Url, relatedPath),
                        Id              = 0,
                        IsDefault       = false,
                        RelatedFileName = string.Empty,
                        SiteId          = siteInfo.Id,
                        TemplateType    = TemplateType.FileTemplate,
                        TemplateName    = relatedPath
                    };

                    list.Add(templateInfo);
                }
            }

            return(list);
        }
 private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
 {
     return
         metadata.ShowForDisplay
         && metadata.ModelType != typeof(EntityState)
         && !metadata.IsComplexType
         && !templateInfo.Visited(metadata);
 }
 private static bool ShouldShow(ModelExplorer modelExplorer, TemplateInfo templateInfo)
 {
     return
         modelExplorer.Metadata.ShowForDisplay &&
         !modelExplorer.Metadata.IsComplexType &&
         !templateInfo.Visited(modelExplorer);
 }
Example #43
0
        private void Replace(TemplateInfo template, List<StringManager> environment)
        {
            var newPrefix = new StringManager(string.Empty);

            foreach (TemplateItemInfo temp in template)
            {
                if (temp.IsBase)
                {
                    newPrefix.AppendToBack(new StringManager(new string(temp.Symbol, 1)), 0);
                    continue;
                }

                if (temp.IsProtect)
                {
                    if (temp.Reference >= environment.Count)
                        continue;

                    newPrefix.AppendToBack(Protect(temp.Level, environment[temp.Reference]), 0);
                    continue;
                }

                if (temp.IsAsNat)
                {
                    if (temp.Reference >= environment.Count)
                    {
                        newPrefix.AppendToBack(new StringManager(AsNat(0)), 0);
                        continue;
                    }

                    newPrefix.AppendToBack(new StringManager(AsNat(environment[temp.Reference].Length)), 0);
                    continue;
                }
            }

            newPrefix.AppendToBack(_runningDna, _currentIndex);
            _runningDna = newPrefix;
            _currentIndex = 0;
        }
Example #44
0
        private void MatchReplace(PatternInfo pattern, TemplateInfo template)
        {
            long index = _currentIndex;
            var environment = new List<StringManager>();
            var counters = new List<int>();

            foreach (PatternItemInfo pat in pattern)
            {
                if (pat.IsBase)
                {
                    if (index >= _runningDna.Length)
                        return;

                    if (_runningDna.HasPatternAtPosition(
                        new[]
                            {
                                new string(pat.Symbol, 1)
                            },
                        (int) index))
                        ++index;
                    else
                        return;
                    continue;
                }

                if (pat.IsSkip)
                {
                    index += pat.SkipCount;
                    if (index >= _runningDna.Length)
                        return;
                    continue;
                }

                if (pat.IsSearch)
                {
                    int patterIndex = _runningDna.IndexOf(pat.SearchPattern, (int) index);
                    if (patterIndex != -1)
                        index = patterIndex + pat.SearchPattern.Length;
                    else
                        return;

                    continue;
                }

                if (pat.IsLevelUp)
                {
                    counters.Insert(0, (int) index);
                    continue;
                }

                if (pat.IsLevelDown)
                {
                    environment.Add(_runningDna.Substring(counters[0], (int) index - counters[0]));
                    counters.RemoveAt(0);
                    continue;
                }
            }

            _currentIndex = (int) index;
            Replace(template, environment);
        }
Example #45
0
        private TemplateInfo DecodeTemplate()
        {
            var template = new TemplateInfo();

            bool flag = true;
            while (flag)
            {
                if (_currentIndex >= _runningDna.Length)
                {
                    lock (_runningMutex)
                    {
                        _state = RunningState.Stoped;
                        return null;
                    }
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "C"
                        },
                    _currentIndex))
                {
                    ++_currentIndex;
                    template.AppendBack('I');
                    continue;
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "F"
                        },
                    _currentIndex))
                {
                    ++_currentIndex;
                    template.AppendBack('C');
                    continue;
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "P"
                        },
                    _currentIndex))
                {
                    ++_currentIndex;
                    template.AppendBack('F');
                    continue;
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "IC"
                        },
                    _currentIndex))
                {
                    _currentIndex += 2;
                    template.AppendBack('P');
                    continue;
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "IF", "IP"
                        },
                    _currentIndex))
                {
                    _currentIndex += 2;
                    int level = DecodeNumber();
                    int reference = DecodeNumber();
                    template.AddReference(reference, level);
                    continue;
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "IIC", "IIF"
                        },
                    _currentIndex))
                {
                    _currentIndex += 3;
                    flag = false;
                    continue;
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "IIP"
                        },
                    _currentIndex))
                {
                    _currentIndex += 3;
                    int reference = DecodeNumber();
                    template.AddLengthOfReference(reference);
                    continue;
                }

                if (_runningDna.HasPatternAtPosition(
                    new[]
                        {
                            "III"
                        },
                    _currentIndex))
                {
                    string toRna = _runningDna.Substring(_currentIndex + 3, 7).ToString();
                    OutputToRna(toRna);
                    _currentIndex += 10;
                    continue;
                }

                // Else stop.
                lock (_runningMutex)
                {
                    _state = RunningState.Stoped;
                    return null;
                }
            }

            return template;
        }
        void CompileImportedTemplates(TemplateInfo ti, Program program)
        {
            foreach (string importCmd in program.ImportMacroCommands)
            {
                // Parse import command
                string programNamespace = importCmd.Split(new[] { ':' }, 2)[0];

                string templatePath = importCmd.Split(new[] { ':' }, 2)[1];

                Program importedProgram;
                ti.ImportedPrograms.TryGetValue(templatePath, out importedProgram);

                // Compile template program from template body
                if (importedProgram == null)
                {
                    // TODO: Implement the template loader (see TODO.txt) - load from filesystem by default
                    string templateBody = File.ReadAllText(templatePath);
                    importedProgram = GetTemplateProgram(templateBody, templatePath);
                    ti.ImportedPrograms.Add(templatePath, importedProgram);
                }

                // Compile imports of imported template
                CompileImportedTemplates(ti, importedProgram);

                // Save info about Imported program by namespace and path
                if (!ti.ImportedNamespaces.ContainsKey(programNamespace))
                    ti.ImportedNamespaces.Add(programNamespace, new HashSet<string> { templatePath });
                else if (!ti.ImportedNamespaces[programNamespace].Contains(templatePath))
                    ti.ImportedNamespaces[programNamespace].Add(templatePath);
            }
        }
Example #47
0
        private TemplateInfo Initialize(TemplateInfo info)
        {
            byte[]    barrTypeData = null;
            byte[]    barrType     = null;
            XDocument xdHeaderXml  = null;

            byte[] barrSceneDll = null;
            try
            {
                if (info.TemplateDetails != null && info.TemplateDetails.Keys.Count > 0)
                {
                    foreach (string skey in info.TemplateDetails.Keys)
                    {
                        switch (skey)
                        {
                        case CCommonConstants.FDDLL:
                            barrType = info.TemplateDetails[skey].Data;
                            break;

                        case CCommonConstants.CDLL:
                            barrTypeData = info.TemplateDetails[skey].Data;
                            break;

                        case CCommonConstants.XML:
                            byte[] barrData = info.TemplateDetails[skey].Data;
                            string sData    = WaspEncoder.GetStringfromByte(barrData);
                            xdHeaderXml = XDocument.Parse(sData);
                            break;

                        case CCommonConstants.SCENEDLL:
                            barrSceneDll = info.TemplateDetails[skey].Data;
                            break;

                        case CCommonConstants.SGXML:
                            byte[] barrSGXml = info.TemplateDetails[skey].Data;
                            string sSGXml    = WaspEncoder.GetStringfromByte(barrSGXml);
                            info.SgXml = sSGXml;
                            break;

                        case CCommonConstants.METADATAXML:
                            byte[] barrMetadataxml = info.TemplateDetails[skey].Data;
                            string sMetadataxml    = WaspEncoder.GetStringfromByte(barrMetadataxml);
                            info.MetaDataXml = sMetadataxml;
                            break;

                        default:
                            break;
                        }
                    }
                    if (xdHeaderXml != null)
                    {
                        //checks whether given template is of unified type from header xml.
                        info.IsUnifiedForm = Unified(xdHeaderXml);
                        if (barrTypeData != null)
                        {
                            info.TemplatePlayerInfo = GetTypeFromAttachment(xdHeaderXml, barrTypeData, CCommonConstants.CDLL);
                        }
                        if (barrType != null)
                        {
                            info.TemplateDataInfo = GetTypeFromAttachment(xdHeaderXml, barrType, CCommonConstants.FDDLL);
                        }
                    }
                    if (string.Compare(info.Type, "tickersg", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        info.IsTicker = true;
                    }
                    else
                    {
                        info.IsTicker = false;
                    }

                    m_objTempDtls = info;
                }
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog(ex); WriteTrace(ex.ToString());
            }

            return(m_objTempDtls);
        }
 public static TemplateInfo GetBasicSettings(string TemplateName)
 {
     TemplateInfo objTemp = new TemplateInfo();
     string filePath = Decide.IsTemplateDefault(TemplateName.Trim()) ? Utils.GetTemplateInfoFilePath_Default(TemplateName) : Utils.GetTemplateInfoFilePath(TemplateName);
     if (File.Exists(filePath))
     {
         XmlDocument doc = new XmlDocument();
         doc.Load(filePath);
         XmlNode root = doc.DocumentElement;
         objTemp.TemplateName = root.SelectSingleNode("name").ChildNodes[0].Value;
         objTemp.Author = root.SelectSingleNode("author").ChildNodes[0].Value;
         objTemp.Description = root.SelectSingleNode("description").ChildNodes[0].Value;
         objTemp.Website = root.SelectSingleNode("website").ChildNodes[0].Value;
         return objTemp;
     }
     else
     {
         return objTemp = TemplateHelper.CreateEmptyTemplateObject();
     }
 }
Example #49
0
 // Add a template to a map. If the format is 7 or earlier, which only support one template, replace templates.  Otherwise,
 // add at the end.
 void AddTemplateToMap(Map map, TemplateInfo template)
 {
     if (creationSettings.fileFormat.kind == MapFileFormatKind.OCAD && creationSettings.fileFormat.version <= 7) {
         map.Templates = new TemplateInfo[] { template };
     }
     else {
         List<TemplateInfo> templates = new List<TemplateInfo>();
         templates.AddRange(map.Templates);
         templates.Add(template);
         map.Templates = templates;
     }
 }
Example #50
0
 private PathInfo GetPath(TemplateInfo templateInfo, PathInfo id)
 {
     return _fileSystem.Path.Combine(PathInfo.Create(templateInfo.Id), FolderPath, _fileSystem.Path.ChangeExtension(id, ".json"));
 }
Example #51
0
	    public Task<object> GetModelForTemplateAsync(TemplateInfo template, string dataId)
        {
            var filePath = GetPath(template, PathInfo.Create(dataId));
            return GetModelFromPathAsync(filePath);
        }
Example #52
0
 public Task<object> GetDefaultModelForTemplateAsync(TemplateInfo template)
 {
     var filePath = GetPath(template, DefaultFilename);
     return GetModelFromPathAsync(filePath);
 }
Example #53
0
 private static LogixTag CreateStructTag(string Address, LogixProcessor Processor, ushort Elements, TemplateInfo Template)
 {
     if (Template.TemplateName == "COUNTER")
     {
         return new LogixCOUNTER(Address, Template, Processor, Elements);
     }
     else if (Template.TemplateName == "CONTROL")
     {
         return new LogixCONTROL(Address, Template, Processor, Elements);
     }
     else if (Template.TemplateName == "TIMER")
     {
         return new LogixTIMER(Address, Template, Processor, Elements);
     }
     else if (Template.TemplateName == "ASCIISTRING82")
     {
         return new LogixSTRING(Address, Template, Processor, Elements);
     }
     else
     {
         //Return as a UDT...
         return new LogixUDT(Address, Template, Processor, Elements);
     }
 }
    public List<TemplateInfo> GetTemplateList()
    {
        DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Templates"));
        List<TemplateInfo> lstTemplates = new List<TemplateInfo>();

        foreach (DirectoryInfo temp in dir.GetDirectories())
        {
            TemplateInfo tempObj = new TemplateInfo(temp.Name, temp.FullName, GetThumbPath(temp.FullName, temp.Name), false, false);
            lstTemplates.Add(tempObj);
        }
        lstTemplates.Insert(0, new TemplateInfo("Default", "/Core/Template/", GetThumbPath(HttpContext.Current.Server.MapPath("~/Core/Template/"), "Default"), true, true));
        return lstTemplates;
    }
 public static List<TemplateInfo> GetTemplateList()
 {
     string templatedir = Utils.GetAbsolutePath(TemplateConstants.TemplateDirectory);
     DirectoryInfo dir = new DirectoryInfo(templatedir);
     List<TemplateInfo> lstTemplates = new List<TemplateInfo>();
     foreach (DirectoryInfo temp in dir.GetDirectories())
     {
         TemplateInfo tempObj = new TemplateInfo(temp.Name);
         lstTemplates.Add(tempObj);
     }
     return lstTemplates;
 }
        public void GenerateTemplateProgram(ref TemplateInfo ti)
        {
            // Init per-template compiling state (including inline templates compiling)
            // Default namespaces
            SetMetaPrefix("meta");
            _metaNamespacePrefixStack = new List<string> { "meta" };
            SetTalPrefix("tal");
            _talNamespacePrefixStack = new List<string> { "tal" };
            SetMetalPrefix("metal");
            _metalNamespacePrefixStack = new List<string> { "metal" };

            ti.ImportedPrograms = new Dictionary<string, Program>();
            ti.ImportedNamespaces = new Dictionary<string, HashSet<string>>();

            // Compile main template body
            ti.MainProgram = GetTemplateProgram(ti.TemplateBody, MainTemplatePath);

            // Compile imported templates
            CompileImportedTemplates(ti, ti.MainProgram);
        }
 public static List<TemplateInfo> GetTemplateList(int PortalID)
 {
     string templates = Utils.GetAbsolutePath(TemplateConstants.TemplateDirectory);
     DirectoryInfo dir = new DirectoryInfo(templates);
     List<TemplateInfo> lstTemplates = new List<TemplateInfo>();
     string activeTemplate = TemplateController.GetActiveTemplate(PortalID).TemplateName;
     if (activeTemplate.Length < 1) { activeTemplate = "Default"; }
     foreach (DirectoryInfo temp in dir.GetDirectories())
     {
         TemplateInfo tempObj = new TemplateInfo(temp.Name, temp.FullName, GetThumbPath(temp.FullName, temp.Name, TemplateConstants.TemplateDirectory), false, false);
         if (temp.Name.ToLower().Replace(' ', '_').Equals(activeTemplate.ToLower()))
         {
             tempObj.IsActive = true;
         }
         lstTemplates.Add(tempObj);
     }
     bool IsDefaultActive = activeTemplate.ToLower().Equals("default") ? true : false;
     lstTemplates.Insert(0, new TemplateInfo("Default", "/Core/Template/", GetThumbPath(HttpContext.Current.Server.MapPath("~/Core/Template/"), "Template", "Core/"), IsDefaultActive, true));
     List<TemplateInfo> lstFinalTemplates = new List<TemplateInfo>();
     List<TemplateInfo> lstAppliedTemplates = new List<TemplateInfo>();
     try
     {
         lstAppliedTemplates = TemplateController.GetPortalTemplates();
     }
     catch (Exception)
     {
         throw;
     }
     foreach (TemplateInfo template in lstTemplates)
     {
         bool status = false;
         foreach (TemplateInfo templt in lstAppliedTemplates)
         {
             if (template.TemplateName.ToLower() == templt.TemplateName.ToLower() && templt.PortalID != PortalID)
             {
                 status = true;
                 break;
             }
         }
         if (!status)
             template.IsApplied = false;
         else
             template.IsApplied = true;
     }
     return lstTemplates;
 }
        Dictionary<string, TemplateInfo> LoadTemplatesInfo(string cacheFolder)
        {
            var templateCache = new Dictionary<string, TemplateInfo>();

            // Load assemblies containing type with full name [<TEMPLATE_NAMESPACE>.<TEMPLATE_TYPENAME>],
            // with one public method [public static string Render(Dictionary<string, object> globals)]

            var di = new DirectoryInfo(cacheFolder);
            foreach (FileInfo fi in di.GetFiles())
            {
                Match fileNameMatch = _fileNamePatternRegex.Match(fi.Name);
                if (fileNameMatch.Success)
                {
                    // Try to load file as assembly
                    try
                    {
                        AssemblyName.GetAssemblyName(fi.FullName);
                    }
                    catch (BadImageFormatException)
                    {
                        // The file is not an Assembly
                        continue;
                    }

                    // Get template hash from file name
                    string templateHash = fileNameMatch.Groups["key"].Value;

                    // Create template info
                    var ti = new TemplateInfo { TemplateKey = templateHash };

                    // Try to load the Render() method from assembly
                    Assembly assembly = Utils.ReadAssembly(fi.FullName);
                    ti.RenderMethod = GetTemplateRenderMethod(assembly, ti);

                    // Try to load the template generator version from assembly
                    ti.GeneratorVersion = GetTemplateGeneratorVersion(assembly, ti);

                    templateCache.Add(templateHash, ti);
                }
            }

            return templateCache;
        }
Example #59
0
 public static string GetDefaultName(TemplateInfo template)
 {
     return(template.DefaultName);
 }
        private TemplateInfo ComputeFieldInfo(XmlReader reader, Dictionary<string, IDictionary<long, string>> maps)
        {
            var ret = new TemplateInfo();

            ret.payloadNames = new List<string>();
            ret.payloadFetches = new List<DynamicTraceEventData.PayloadFetch>();
            ushort offset = 0;
            while (reader.Read())
            {
                if (reader.Name == "data")
                {
                    string inType = reader.GetAttribute("inType");
                    Type type = GetTypeForManifestTypeName(inType);
                    ushort size = DynamicTraceEventData.SizeOfType(type);
                    // Strings are weird in that they are encoded multiple ways.  
                    if (type == typeof(string) && inType == "win:AnsiString")
                        size = DynamicTraceEventData.NULL_TERMINATED | DynamicTraceEventData.IS_ANSI;

                    ret.payloadNames.Add(reader.GetAttribute("name"));
                    IDictionary<long, string> map = null;
                    string mapName = reader.GetAttribute("map");
                    if (mapName != null && maps != null)
                        maps.TryGetValue(mapName, out map);
                    ret.payloadFetches.Add(new DynamicTraceEventData.PayloadFetch(offset, size, type, map));
                    if (offset != ushort.MaxValue)
                    {
                        Debug.Assert(size != 0);
                        if (size < DynamicTraceEventData.SPECIAL_SIZES)
                            offset += size;
                        else
                            offset = ushort.MaxValue;
                    }
                }
            }
            return ret;
        }