public async Task Should_make_test_with_pre_query_script() { var ctx = new Context(Mocks.ApiUser(), Mocks.App(appId)); var(provider, id) = CreateSchema( query: @" ctx.data.test = { iv: ctx.custom }; replace()", queryPre: "ctx.custom = 123;"); var content = new ContentEntity { Data = new ContentData(), SchemaId = id }; var realScriptEngine = new JintScriptEngine(new MemoryCache(Options.Create(new MemoryCacheOptions())), Options.Create(new JintScriptOptions { TimeoutScript = TimeSpan.FromSeconds(20), TimeoutExecution = TimeSpan.FromSeconds(100) })); var sut2 = new ScriptContent(realScriptEngine); await sut2.EnrichAsync(ctx, new[] { content }, provider, default); Assert.Equal(JsonValue.Create(123), content.Data["test"] !["iv"]);
private async Task SaveScriptContent(List <ScriptMap> scripts) { var scriptIds = scripts.Select(w => w.Script.Id); var existing = await _db.ScriptContents.AsQueryable().Where(w => scriptIds.Contains(w.ScriptId)).ToListAsync(); var existingDict = existing.ToDictionary(w => w.ScriptId, w => w); foreach (var map in scripts) { Console.WriteLine("Loading Script Content For: " + map.Script.Name); var content = new ScriptContent { ScriptId = map.Script.Id, Content = await GetScriptContent(map.OldScriptId) }; if (existingDict.ContainsKey(map.Script.Id)) { existingDict[map.Script.Id].Content = content.Content; _db.ScriptContents.Update(existingDict[map.Script.Id]); } else { _db.ScriptContents.Add(content); } } await _db.SaveChangesAsync(); }
///----------------------------------------------------------------- #region Rule internal protected override void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst) { variants.Clear(); var slots = new int[contentSrc.NameCount / 2]; GatherVariants(0, slots, variants, scriptContent, contentSrc, contentDst); }
///----------------------------------------------------------------- #region Rule internal protected override void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst) { keywords.Clear(); identifiers.Clear(); Glossary.Macros.GetTags(this); variants.Clear(); if (scriptContent.functionContents.Count == 0) { return; } var result = string.Empty; for (var k = 0; k < keywords.Count; k++) { result += scriptContent.functionContents[0].body; result = (Variables[0] + keywords[k]).Apply(result); } var variant = new FunctionVariant(result, 1); result = string.Empty; for (var i = 0; i < identifiers.Count; i++) { result += scriptContent.functionContents[0].body; result = (Variables[0] + identifiers[i]).Apply(result); } variant[1] = result; variants.Add(variant); }
public ScriptContentTests() { var schemaDef = new Schema(schemaId.Name); var schemaDefWithScript = new Schema(schemaWithScriptId.Name) .SetScripts(new SchemaScripts { Query = "my-query" }); schemaProvider = x => { if (x == schemaId.Id) { return(Task.FromResult(Mocks.Schema(appId, schemaId, schemaDef))); } else if (x == schemaWithScriptId.Id) { return(Task.FromResult(Mocks.Schema(appId, schemaWithScriptId, schemaDefWithScript))); } else { throw new DomainObjectNotFoundException(x.ToString(), typeof(ISchemaEntity)); } }; sut = new ScriptContent(scriptEngine); }
///----------------------------------------------------------------- #region Rule internal public override BuildResult Generate(ScriptContent scriptContent) { repeatCount = int.Parse(scriptContent.classDefaultValue); var classContent = scriptContent.classInfos[0]; var variants = new List <FunctionVariant>(); GatherVariants(variants, scriptContent, classContent, classContent); for (int r = 1; r <= repeatCount; r++) { var fileBody = scriptContent.fileBody; for (int f = 0; f < Functions.Count; f++) { if (!Functions[f].CanSwap(fileBody)) { continue; } var swap = Functions[f]; var functionContent = scriptContent.functionContents[f]; if (Names.DefaultSymbol.CanSwap(functionContent.body)) { for (int fv = 0; fv < r; fv++) { if (fv > 0) { swap += Glossary.Macros.codeDataTabsTag; } swap += variants[fv][f]; } } else { swap.Replacement = variants[r - 1][f]; } var leadingTabulations = fileBody.GetTabulation(swap.IndexOf(fileBody)); var swapTabs = (StringSwap)Glossary.Macros.codeDataTabsTag + leadingTabulations; fileBody = swap.Apply(fileBody); fileBody = swapTabs.Apply(fileBody); } if (Defaults[1].CanSwap(fileBody)) { var swap = Defaults[1] + r.ToString(); fileBody = swap.Apply(fileBody); } scriptContent.codeGenerated.Add(new ScriptContent.GeneratedCode { className = classContent.className + r.ToString(), code = fileBody }); } return(BuildResult.ValueType.Success); }
///----------------------------------------------------------------- protected void AddCodeTo(ScriptContent data, string code, StringSwap stringSwapSrc, StringSwap stringSwapDst) { code = stringSwapSrc.Apply(code); code = stringSwapDst.Apply(code); var generatedCode = data.codeGenerated.Last(); generatedCode.code += code; data.codeGenerated.Last(generatedCode); }
///----------------------------------------------------------------- #region Rule internal protected override void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst) { var slots = new int[contentDst.VarCount]; for (var s = 0; s < slots.Length; s++) { slots[s] = 0; } variants.Clear(); GatherVariantsSlots(0, slots, variants, scriptContent, contentSrc, contentDst); }
public void ScriptContent_type_is_formatted() { var script = new ScriptContent("alert('hello');"); var mimeType = Formatter.PreferredMimeTypeFor(script.GetType()); var formattedValue = new FormattedValue( mimeType, script.ToDisplayString(mimeType)); formattedValue.MimeType.Should().Be("text/html"); formattedValue.Value.Should().Be(@"<script type=""text/javascript"">alert('hello');</script>"); }
/// <summary> /// Initializes a new instance of the <see cref="BuildStyle"/> class /// with parameters copied from the specified instance of the /// <see cref="BuildStyle"/> class, a copy constructor. /// </summary> /// <param name="source"> /// An instance of the <see cref="BuildStyle"/> class from which the /// initialization parameters or values will be copied. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="source"/> is <see langword="null"/>. /// </exception> public BuildStyle(BuildStyle source) : base(source) { _styleDir = source._styleDir; _styleName = source._styleName; _stylePresentation = source._stylePresentation; _styleType = source._styleType; _scripts = source._scripts; _snippets = source._snippets; _styleSheets = source._styleSheets; _mathPackages = source._mathPackages; _mathCommands = source._mathCommands; }
public void ScriptContent_type_with_possible_html_characters_is_not_HTML_encoded() { var scriptText = "if (true && false) { alert('hello with embedded <>\" escapes'); };"; var script = new ScriptContent(scriptText); var mimeType = Formatter.GetPreferredMimeTypeFor(script.GetType()); var formattedValue = new FormattedValue( mimeType, script.ToDisplayString(mimeType)); formattedValue.MimeType.Should().Be("text/html"); formattedValue.Value.Should().Be($"<script type=\"text/javascript\">{scriptText}</script>"); }
private void BtnAccept_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtNew.Text) || string.IsNullOrEmpty(txtRepeat.Text)) { MessageBox.Show(Language.Get("msg_empty_pass"), Language.Get("error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (!txtNew.Text.Equals(txtRepeat.Text)) { MessageBox.Show(Language.Get("msg_notmatch_pass"), Language.Get("error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); txtNew.Focus(); return; } if (txtNew.Text.Length < Constant.AppConstant.MinPasswordLength) { MessageBox.Show( string.Format(Language.Get("msg_short_pass"), AppConstant.MinPasswordLength), Language.Get("error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); txtNew.Focus(); return; } if (!string.IsNullOrEmpty(ScriptGrid.Script?.Password)) { var bytes = Encoding.UTF8.GetBytes(txtOld.Text); var str = ScriptContent.ComputeSha256Hash(Convert.ToBase64String(bytes)); if (str != ScriptGrid.Script.Password) { MessageBox.Show(Language.Get("msg_wrong_pass"), Language.Get("error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); txtOld.Focus(); return; } } var newBytes = Encoding.UTF8.GetBytes(txtNew.Text); ScriptGrid.Script.Password = ScriptContent.ComputeSha256Hash(Convert.ToBase64String(newBytes)); MessageBox.Show(Language.Get("msg_success_pass"), Language.Get("info"), MessageBoxButtons.OK, MessageBoxIcon.Information); txtOld.Text = ""; txtNew.Text = ""; txtRepeat.Text = ""; this.Close(); }
public void js_wrapping_formatter_fails_if_apiUri_is_not_configured_within_the_configured_timeout() { var frontendEnvironment = new HtmlNotebookFrontedEnvironment(); CommandLineParser.SetUpFormatters(frontendEnvironment, new StartupOptions(httpPort: new HttpPort(4242)), 1.Seconds()); var script = new ScriptContent("alert('hello');"); var mimeType = Formatter.GetPreferredMimeTypeFor(script.GetType()); Action formatting = () => script.ToDisplayString(mimeType); formatting.Should() .Throw <TimeoutException>() .Which .Message .Should().Be("Timeout resolving the kernel's HTTP endpoint. Please try again."); }
public void ScriptContent_type_is_formatted() { var script = new ScriptContent("alert('hello');"); var mimeType = Formatter.PreferredMimeTypeFor(script.GetType()); var formattedValue = new FormattedValue( mimeType, script.ToDisplayString(mimeType)); formattedValue.MimeType.Should().Be("text/html"); formattedValue.Value.Should().Be($@"<script type=""text/javascript"">if (typeof window.createDotnetInteractiveClient === typeof Function) {{ createDotnetInteractiveClient('http://12.12.12.12:4242/').then(function (interactive) {{ let notebookScope = getDotnetInteractiveScope('http://12.12.12.12:4242/'); alert('hello'); }}); }}</script>"); }
protected override void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst) { variants.Clear(); for (int r = 0; r < repeatCount; r++) { var variant = new FunctionVariant(scriptContent.functionContents.Count); for (var fc = 0; fc < scriptContent.functionContents.Count; fc++) { var functionContent = scriptContent.functionContents[fc]; for (var v = 0; v < contentSrc.names.Count; v++) { var functionBody = functionContent.body; if (Defaults[0].CanSwap(functionBody)) { var swap = Defaults[0] + scriptContent.classDefaultType; functionBody = swap.Apply(functionBody); } if (Defaults[1].CanSwap(functionBody)) { var swap = Defaults[1] + (r + 1).ToString(); functionBody = swap.Apply(functionBody); } if (Names.DefaultSymbol.CanSwap(functionBody)) { var swap = Names.DefaultSymbol + contentSrc.names[v] + r.ToString(); functionBody = swap.Apply(functionBody); } if (Variables.DefaultSymbol.CanSwap(functionBody)) { var swap = Variables.DefaultSymbol + r.ToString(); functionBody = swap.Apply(functionBody); } variant[fc] = functionBody; } } variants.Add(variant); } }
public static async Task <string> DownloadScript(string scriptId) { HttpResponseMessage response = await client.GetAsync($"helper/scripts/download?version={EnvironmentVariables.CURRENT_VERSION}&license={License}&script_id={scriptId}"); if (response.IsSuccessStatusCode) { try { ScriptContent content = response.Content.ReadAsAsync <ScriptContent>().Result; return(content.script); } catch (Exception) { return(null); } } return(null); }
public void ScriptContent_type_is_wrapped_when_http_and_the_frontendEnvironment_is_JupyterFrontedEnvironment() { var frontendEnvironment = new HtmlNotebookFrontedEnvironment(new Uri("http://12.12.12.12:4242")); CommandLineParser.SetUpFormatters(frontendEnvironment, new StartupOptions(httpPort: new HttpPort(4242)), 10.Seconds()); var script = new ScriptContent("alert('hello');"); var mimeType = Formatter.GetPreferredMimeTypeFor(script.GetType()); var formattedValue = new FormattedValue( mimeType, script.ToDisplayString(mimeType)); formattedValue.MimeType.Should().Be("text/html"); formattedValue.Value.Should().Be(@"<script type=""text/javascript"">if (typeof window.createDotnetInteractiveClient === typeof Function) { createDotnetInteractiveClient('http://12.12.12.12:4242/').then(function (interactive) { let notebookScope = getDotnetInteractiveScope('http://12.12.12.12:4242/'); alert('hello'); }); }</script>"); }
public List <GalleryVideo> GetAllVideos(int companyId) { List <GalleryVideo> objListOfVideos = new List <GalleryVideo>(); List <Pitch> pitches = _context.Pitches.ToList(); foreach (var objPitch in pitches) { Delivery objDelivery = _context.Deliveries.Where(x => x.DeliveryId == objPitch.DeliveryId).SingleOrDefault(); ScriptContent objScriptContent = _context.ScriptContents.Where(x => x.ScriptId == objPitch.ScriptId).SingleOrDefault(); Script objScript = _context.Scripts.Where(x => x.ScriptId == objPitch.ScriptId).SingleOrDefault(); GalleryVideo objGalleryVideo = new GalleryVideo { ScriptContent = objScriptContent, Delivery = objDelivery, PitchId = objPitch.PitchId, Script = objScript }; objListOfVideos.Add(objGalleryVideo); } return(objListOfVideos); }
private void Validate() { var bytes = Encoding.UTF8.GetBytes(txtPassword.Text); var hash = ScriptContent.ComputeSha256Hash(Convert.ToBase64String(bytes)); if (hash.Equals(ScriptGrid.Script?.Password)) { if (chkClearPass.Checked) { hash.Equals(ScriptGrid.Script.Password = ""); } Success = true; this.Close(); } else { MessageBox.Show(Language.Get("msg_wrong_pass"), Language.Get("error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); txtPassword.Text = ""; } }
///----------------------------------------------------------------- #region Rule internal protected override void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst) { var slots = new int[contentSrc.VarCount]; for (var s = 0; s < slots.Length; s++) { slots[s] = 0; } variants.Clear(); GatherVariants(0, slots, slots.Length, variants, scriptContent, contentSrc); //Add Default vec(f) var variant = new FunctionVariant(contentSrc.names[0], 2); variant[1] = string.Format(Glossary.Code.argsN, scriptContent.classDefaultType, 0); for (var v = 0; v < contentSrc.VarCount; v++) { variant[2] = string.Format(Glossary.Code.varsN, 0); } variants.Add(variant); }
///----------------------------------------------------------------- #region Rule internal protected override void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst) { infos.Clear(); Glossary.Macros.GetTags(this); variants.Clear(); if (scriptContent.functionContents.Count == 0) { return; } var result = string.Empty; var variant = new FunctionVariant(result); for (var k = 0; k < infos.Count; k++) { result += scriptContent.functionContents[0].body; result = (Variables[0] + infos[k].name).Apply(result); } variant[0] = result; variants.Add(variant); }
/// <summary> /// Initializes a new instance of the <see cref="BuildStyle"/> class with /// the specified style type. /// </summary> /// <param name="type"> /// An enumeration of the type <see cref="BuildStyleType"/> specifying the type /// of the transformation and presentation style. /// </param> public BuildStyle(BuildStyleType type) { _styleType = type; _scripts = new ScriptContent("CommonScripts"); _styleSheets = new StyleSheetContent("CommonStyleSheets"); _snippets = new SnippetContent("CommonSnippets"); _mathPackages = new MathPackageContent(); _mathCommands = new MathCommandContent(); string sandAssistDir = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location); string codeStyleFile = Path.Combine(sandAssistDir, @"Styles\IrisModifiedVS.css"); string assistStyleFile = Path.Combine(sandAssistDir, String.Format(@"Styles\{0}\SandAssist.css", BuildStyle.StyleFolder(type))); StyleSheetItem codeStyle = new StyleSheetItem("CodeStyle", codeStyleFile); codeStyle.Condition = "CodeHighlight"; _styleSheets.Add(codeStyle); StyleSheetItem assistStyle = new StyleSheetItem("AssistStyle", assistStyleFile); _styleSheets.Add(assistStyle); string assistScriptFile = Path.Combine(sandAssistDir, String.Format(@"Scripts\{0}\SandAssist.js", BuildStyle.StyleFolder(type))); ScriptItem assistScript = new ScriptItem("AssistScripts", assistScriptFile); _scripts.Add(assistScript); }
///----------------------------------------------------------------- #region Rule internal protected override void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst) { variants.Clear(); if (scriptContent.functionContents.Count == 0) { variants.Add(new FunctionVariant()); } else { var variant = new FunctionVariant(scriptContent.functionContents.Count); for (var d = 0; d < scriptContent.functionContents.Count; d++) { var functionContent = scriptContent.functionContents[d]; for (var v = 0; v < contentSrc.variables.Count; v++) { var functionData = functionContent.body; if (Variables.DefaultSymbol.CanSwap(functionContent.body)) { var swap = Variables.DefaultSymbol + contentSrc.variables[v]; functionData = swap.Apply(functionData); } var currentVariable = Variables[v]; if (currentVariable.CanSwap(functionContent.body)) { var swap = currentVariable + contentSrc.variables[v]; functionData = swap.Apply(functionData); } variant[d] = functionData; } } variants.Add(variant); } }
///----------------------------------------------------------------- #region Utils protected void AddCodeTo(ScriptContent data, string code, StringSwap stringSwapSrc) { AddCodeTo(data, code, stringSwapSrc, new StringSwap()); }
///----------------------------------------------------------------- #region CodeRule abstract protected abstract void GatherVariants(List <FunctionVariant> variants, ScriptContent scriptContent, ClassContent contentSrc, ClassContent contentDst);
/// <summary> /// The creates the configuration information or settings required by the /// target component for the build process. /// </summary> /// <param name="group"> /// A build group, <see cref="BuildGroup"/>, representing the documentation /// target for configuration. /// </param> /// <param name="writer"> /// An <see cref="XmlWriter"/> object used to create one or more new /// child nodes at the end of the list of child nodes of the current node. /// </param> /// <returns> /// Returns <see langword="true"/> for a successful configuration; /// otherwise, it returns <see langword="false"/>. /// </returns> /// <remarks> /// The <see cref="XmlWriter"/> writer passed to this configuration object /// may be passed on to other configuration objects, so do not close or /// dispose it. /// </remarks> public override bool Configure(BuildGroup group, XmlWriter writer) { BuildExceptions.NotNull(group, "group"); BuildExceptions.NotNull(writer, "writer"); if (!this.Enabled || !this.IsInitialized) { return(false); } Debug.Assert(_settings != null, "The settings object is required."); if (_settings == null || _context == null) { return(false); } BuildGroupContext groupContext = _context.GroupContexts[group.Id]; if (groupContext == null) { throw new BuildException( "The group context is not provided, and it is required by the build system."); } //<component type="Sandcastle.Components.ReferencePostTransComponent" assembly="$(SandAssistComponent)"> // <paths outputPath=".\Output\"/> // <attributes> // <attribute name="DocSet" value="NETFramework" /> // <attribute name="DocSet" value="NETCompactFramework"/> // </attributes> // <scripts> // <IncludeItem item="assistScripts" /> // </scripts> // <styles> // <!-- Include the various styles used by the Sandcastle Assist --> // <IncludeItem item="codeStyle" /> // <IncludeItem item="assistStyle" /> // </styles> // <header> // <!-- Include the logo image support --> // <IncludeItem item="logoImage" /> // <!--<tables> // <table name="" operation="" /> // </tables>--> // </header> //</component> BuildFeedback feeback = _settings.Feedback; Debug.Assert(feeback != null, "Feedback object cannot be null (or Nothing)."); if (feeback == null) { return(false); } BuildStyle buildStyle = _settings.Style; Debug.Assert(buildStyle != null, "The style object cannot be null (or Nothing)."); if (buildStyle == null) { return(false); } writer.WriteStartElement("paths"); //start: paths writer.WriteAttributeString("outputPath", @".\Output\"); writer.WriteEndElement(); //end: paths AttributeContent attributes = _settings.Attributes; if (attributes != null && attributes.Count != 0) { writer.WriteStartElement("attributes"); //start: attributes for (int i = 0; i < attributes.Count; i++) { AttributeItem attribute = attributes[i]; if (attribute.IsEmpty) { continue; } writer.WriteStartElement("attribute"); //start: attribute writer.WriteAttributeString("name", attribute.Name); writer.WriteAttributeString("value", attribute.Value); writer.WriteEndElement(); //end: attribute } writer.WriteEndElement(); //end: attributes } writer.WriteStartElement("scripts"); //start: scripts ScriptContent scriptContent = buildStyle.Scripts; if (scriptContent != null && !scriptContent.IsEmpty) { for (int i = 0; i < scriptContent.Count; i++) { ScriptItem scriptItem = scriptContent[i]; // a. Empty item is no use. // b. Overriding scripts are added to the documentation // by the transform. if (scriptItem.IsEmpty || scriptItem.Overrides) { continue; } writer.WriteStartElement("script"); //start: script writer.WriteAttributeString("file", scriptItem.ScriptFile); writer.WriteAttributeString("condition", scriptItem.Condition); writer.WriteEndElement(); //end: script } } writer.WriteEndElement(); //end: scripts writer.WriteStartElement("styles"); //start: styles StyleSheetContent styleContent = buildStyle.StyleSheets; if (styleContent != null && !styleContent.IsEmpty) { for (int i = 0; i < styleContent.Count; i++) { StyleSheetItem styleItem = styleContent[i]; // a. Empty item is no use. // b. Overriding styles are added to the documentation // by the transform. if (styleItem.IsEmpty || styleItem.Overrides) { continue; } writer.WriteStartElement("style"); //start: style writer.WriteAttributeString("file", styleItem.StyleFile); writer.WriteAttributeString("condition", styleItem.Condition); writer.WriteEndElement(); //end: style } } writer.WriteEndElement(); //end: styles // Let the Feedback option object configure itself... feeback.Configure(group, writer); // Write roots to namespaces conversion handler... writer.WriteStartElement("rootNamespaces"); // start: rootNamespaces writer.WriteAttributeString("id", group.Id); string rootNamespacesFile = Path.Combine(_context.WorkingDirectory, groupContext["$RootNamespaces"]); if (File.Exists(rootNamespacesFile)) { writer.WriteAttributeString("source", rootNamespacesFile); } writer.WriteEndElement(); //end: rootNamespaces return(true); }
///----------------------------------------------------------------- private void GatherVariantsSlots(int s, int[] slots, List <FunctionVariant> variants, ScriptContent data, ClassContent contentSrc, ClassContent contentDst) { var varCount = contentSrc.VarCount + 1; for (var c = 0; c < varCount; c++) { slots[s] = c; if (s + 1 < slots.Length) { GatherVariantsSlots(s + 1, slots, variants, data, contentSrc, contentDst); } else { if (data.classDefaultExportOnly) { var foundValid = false; for (var exp = 0; exp < slots.Length; exp++) { if (slots[exp] >= contentSrc.VarCount) { foundValid = true; break; } } if (!foundValid) { continue; } } var sn = 0; var variant = new FunctionVariant(3); variant[1] += Glossary.Code.argsV; for (var v = 0; v < slots.Length; v++) { var sv = slots[v]; if (sv < contentSrc.VarCount) { var name = sv < contentSrc.NameCount ? contentSrc.names[sv] : contentSrc.variables[sv]; variant.Call = name; var variable = contentSrc.variables[sv]; variant[2] = string.Format(Glossary.Code.varsV, variable); } else { variant.Call = Glossary.Code.callN; variant[1] = string.Format(Glossary.Code.argsNOpt, data.classDefaultType, sn, data.classDefaultValue); variant[2] = string.Format(Glossary.Code.varsN, sn); sn++; } } if (sn != slots.Length) { variants.Add(variant); } } } }
///----------------------------------------------------------------- private void GatherVariants(int s, int[] slots, List <FunctionVariant> variants, ScriptContent data, ClassContent contentSrc, ClassContent contentDst) { if (s < slots.Length) { for (var p = 0; p < 2; p++) { slots[s] = p; GatherVariants(s + 1, slots, variants, data, contentSrc, contentDst); } } else { var variant = new FunctionVariant(2); for (var sv = 0; sv < slots.Length; sv++) { if (slots[sv] == 0) { for (var i = 0; i < data.functionContents.Count; i++) { var info = data.functionContents[i].body; info = (Names[0] + contentSrc.names[sv * 2 + 0]).Apply(info); info = (Names[1] + contentSrc.names[sv * 2 + 1]).Apply(info); variant[i] = info; } } } if (variant.Call != string.Empty) { variants.Add(variant); } } }
private void ReadXmlContents(XmlReader reader) { string startElement = reader.Name; Debug.Assert(String.Equals(startElement, "contents")); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (!reader.IsEmptyElement && String.Equals(reader.Name, "content", StringComparison.OrdinalIgnoreCase)) { switch (reader.GetAttribute("type").ToLower()) { case "scripts": if (_scripts == null) { _scripts = new ScriptContent(); } if (reader.ReadToDescendant(ScriptContent.TagName)) { _scripts.ReadXml(reader); } break; case "snippets": if (_snippets == null) { _snippets = new SnippetContent(); } if (reader.ReadToDescendant(SnippetContent.TagName)) { _snippets.ReadXml(reader); } break; case "stylesheets": if (_styleSheets == null) { _styleSheets = new StyleSheetContent(); } if (reader.ReadToDescendant(StyleSheetContent.TagName)) { _styleSheets.ReadXml(reader); } break; case "packages": if (_mathPackages == null) { _mathPackages = new MathPackageContent(); } if (reader.ReadToDescendant(MathPackageContent.TagName)) { _mathPackages.ReadXml(reader); } break; case "commands": if (_mathCommands == null) { _mathCommands = new MathCommandContent(); } if (reader.ReadToDescendant(MathCommandContent.TagName)) { _mathCommands.ReadXml(reader); } break; } } } else if (reader.NodeType == XmlNodeType.EndElement) { if (String.Equals(reader.Name, startElement, StringComparison.OrdinalIgnoreCase)) { break; } } } }
///----------------------------------------------------------------- #region CodeRule overridable public virtual BuildResult Generate(ScriptContent data) { var variants = new List <FunctionVariant>(); //If needed, Add the default value as a possible class var maxSrc = data.classInfos.Count + (GenerateDefault ? 1 : 0); //Only loop through the dst classes if required var maxDst = GenerationMode == GenerationRule.ForeachSrcCrossDest ? data.classInfos.Count : 1; var infoSrc = new ClassContent(); var infoDst = new ClassContent(); var infoDef = new ClassContent(); if (GenerateDefault) { infoDef.className = data.classDefaultType; } //Loop throught the source classes for (var iSrc = 0; iSrc < maxSrc; iSrc++) { //Add the default value as a possible class infoSrc = GenerateDefault && iSrc == 0 ? infoDef : data.classInfos[iSrc + (GenerateDefault ? -1 : 0)]; if (UseOneClassPerSource) { data.codeGenerated.Add(new ScriptContent.GeneratedCode { className = infoSrc.className, code = string.Empty }); } else if (data.codeGenerated.Count == 0) { data.codeGenerated.Add(new ScriptContent.GeneratedCode { className = string.Empty, code = string.Empty }); } //one pass or as many as the dst classes for (var iSDst = 0; iSDst < maxDst; iSDst++) { if (GenerationMode == GenerationRule.ForeachSrcCrossDest) { infoDst = data.classInfos[iSDst]; } //Gather code variants GatherVariants(variants, data, infoSrc, infoDst); var swapSrc = ClassSrc + infoSrc.className; var swapDst = ClassDst; //Add the Header from the code file if (GenerationMode == GenerationRule.ForeachSrcCrossDest) { swapDst = swapDst + infoDst.className; AddCodeTo(data, data.codeHeader, swapSrc, swapDst); } else { AddCodeTo(data, data.codeHeader, swapSrc); } //Go through all variants and apply them to the code for (var v = 0; v < variants.Count; v++) { var variant = variants[v]; var codeBody = data.codeBody; //Error out if the requested funcs result are not available if (!SwapCodeContent(ref codeBody, Functions, variant.Count, variant.Variants)) { return((BuildResult)BuildResult.ValueType.PrateekScriptInsufficientNames + GetType().Name + infoSrc.className); } //Error out if the requested Names are not available if (!SwapCodeContent(ref codeBody, Names, infoSrc.NameCount, infoSrc.names)) { return((BuildResult)BuildResult.ValueType.PrateekScriptInsufficientNames + infoSrc.className); } if (GenerationMode == GenerationRule.ForeachSrcCrossDest) { AddCodeTo(data, codeBody, swapSrc, swapDst); } else { AddCodeTo(data, codeBody, swapSrc); } } //Add the Footer from the code file if (GenerationMode == GenerationRule.ForeachSrcCrossDest) { AddCodeTo(data, data.codeFooter, swapSrc, swapDst); } else { AddCodeTo(data, data.codeFooter, swapSrc); } } } for (var c = 0; c < data.codeGenerated.Count; c++) { var codeGenerated = data.codeGenerated[c]; codeGenerated.code = codeGenerated.code.Replace(string.Empty.NewLine(), string.Empty.NewLine() + Glossary.Macros.codeDataTabsTag); data.codeGenerated[c] = codeGenerated; } return(BuildResult.ValueType.Success); }