public void BaselineState_None() { string expected = @"{ ""$schema"": """ + SarifSchemaUri + @""", ""version"": """ + SarifFormatVersion + @""", ""runs"": [ { ""tool"": { ""name"": null }, ""results"": [ {} ] } ] }"; string actual = GetJson(uut => { var run = new Run(); uut.Initialize(id: null, correlationId: null); uut.WriteTool(DefaultTool); uut.WriteResults(new[] { new Result { BaselineState = BaselineState.None } }); }); Assert.AreEqual(expected, actual); var sarifLog = JsonConvert.DeserializeObject<SarifLog>(actual); Assert.AreEqual(SuppressionStates.None, sarifLog.Runs[0].Results[0].SuppressionStates); Assert.AreEqual(BaselineState.None, sarifLog.Runs[0].Results[0].BaselineState); }
private static IEnumerator _RunEvery(Run aRun, float aInitialDelay, float aSeconds, System.Action aAction) { aRun.isDone = false; if (aInitialDelay > 0f) yield return new WaitForSeconds(aInitialDelay); else { int FrameCount = Mathf.RoundToInt(-aInitialDelay); for (int i = 0; i < FrameCount; i++) yield return null; } while (true) { if (!aRun.abort && aAction != null) aAction(); else break; if (aSeconds > 0) yield return new WaitForSeconds(aSeconds); else { int FrameCount = Mathf.Max(1, Mathf.RoundToInt(-aSeconds)); for (int i = 0; i < FrameCount; i++) yield return null; } } aRun.isDone = true; }
public static Run After(float aDelay, System.Action aAction) { var tmp = new Run(); tmp.action = _RunAfter(tmp, aDelay, aAction); tmp.Start(); return tmp; }
public static Run EachFrame(System.Action aAction) { var tmp = new Run(); tmp.action = _RunEachFrame(tmp, aAction); tmp.Start(); return tmp; }
public static Run Every(float aInitialDelay, float aDelay, System.Action aAction) { var tmp = new Run(); tmp.action = _RunEvery(tmp, aInitialDelay, aDelay, aAction); tmp.Start(); return tmp; }
public IRun Create(IComparisonGeneratorsFactory factory) { var run = new Run(factory); var json = JSON.FromStream(Stream); run.GameName = json.run_name as string; run.AttemptCount = json.run_count; var timingMethod = (int)(json.timer_type) == 0 ? TimingMethod.RealTime : TimingMethod.GameTime; var segments = json.splits as IEnumerable<dynamic>; foreach (var segment in segments) { var segmentName = segment.name as string; var pbSplitTime = parseTime((int?)segment.pb_split, timingMethod); var bestSegment = parseTime((int?)segment.split_best, timingMethod); var parsedSegment = new Segment(segmentName, pbSplitTime, bestSegment); run.Add(parsedSegment); } return run; }
internal void Process(Run element, DocxNode node) { RunProperties properties = element.RunProperties; if (properties == null) { properties = new RunProperties(); } //Order of assigning styles to run property is important. The order should not change. CheckFonts(node, properties); string color = node.ExtractStyleValue(DocxColor.color); if (!string.IsNullOrEmpty(color)) { DocxColor.ApplyColor(color, properties); } CheckFontStyle(node, properties); ProcessBackGround(node, properties); ProcessVerticalAlign(node, properties); if (element.RunProperties == null && properties.HasChildren) { element.RunProperties = properties; } }
public override VisitorAction VisitRun(Run run) { // Remove the run if it is between the FieldStart and FieldSeparator of the field being converted. CheckDepthAndRemoveNode(run); return VisitorAction.Continue; }
public AveragedSpectrumExtractor(Run run, SpectrumCache spectrumCache) { this.run = run; this.spectrumCache = spectrumCache; rtToTimePointConverter = new RtToTimePointConverter(run, spectrumCache); spectrumExtractor = new SpectrumExtractor(run, spectrumCache); }
public static Run OnDelegate(SimpleEvent aDelegate, System.Action aAction) { var tmp = new Run(); tmp.action = _RunOnDelegate(tmp, aDelegate, aAction); tmp.Start(); return tmp; }
public static Run Lerp(float aDuration, System.Action<float> aAction) { var tmp = new Run(); tmp.action = _RunLerp(tmp, aDuration, aAction); tmp.Start(); return tmp; }
public static Run Coroutine(IEnumerator aCoroutine) { var tmp = new Run(); tmp.action = _Coroutine(tmp, aCoroutine); tmp.Start(); return tmp; }
/// <summary> /// Returns a OpenXMl paragraph representing formatted listItem. /// </summary> /// <param name="item">listItem object</param> /// <param name="numStyleId">style id to use</param> /// <returns></returns> private static Paragraph GetListItem(Model.ListItem item, int numStyleId) { Paragraph listItemPara = new Paragraph(); ParagraphProperties paraProps = new ParagraphProperties(); NumberingProperties numberingProps = new NumberingProperties(); NumberingLevelReference numberingLevelReference = new NumberingLevelReference() { Val = 0 }; NumberingId numberingId = new NumberingId() { Val = numStyleId }; numberingProps.Append(numberingLevelReference); numberingProps.Append(numberingId); paraProps.Append(numberingProps); Run listRun = new Run(); Text listItemText = new Text() { Text = item.Body }; listRun.Append(listItemText); listItemPara.Append(paraProps); listItemPara.Append(listRun); return listItemPara; }
static void Main(string[] args) { Console.Write("Username: "******"C:\Users\" + user + @"\Desktop\test.docx", WordprocessingDocumentType.Document); MainDocumentPart main = package.AddMainDocumentPart(); main.Document = new Document(); Document document1 = main.Document; Body body = document1.AppendChild(new Body()); document1 = package.MainDocumentPart.Document; document1.Save(); OpenXmlHelper document = new OpenXmlHelper(package, main); //You will have to have all the files below if you want to successfully test this. //Image Formats Paragraph para = new Paragraph(); Run run = new Run(); run.AppendChild(new Text("These are Image Formats")); para.AppendChild(run); document.AddParagraph(para); document.AddImage(@"C:\Users\" + user + @"\Desktop\test\test.jpg"); document.AddImage(@"C:\Users\" + user + @"\Desktop\test\test.gif"); document.AddImage(@"C:\Users\" + user + @"\Desktop\test\test.png"); document.AddImage(@"C:\Users\" + user + @"\Desktop\test\test.tif"); document.AddImage(@"C:\Users\" + user + @"\Desktop\test\test.bmp"); document.AddImage(@"C:\Users\" + user + @"\Desktop\test\test.ico"); //Office XML Formats para = new Paragraph(); run = new Run(); run.AppendChild(new Text("These are Office XML Formats")); para.AppendChild(run); document.AddParagraph(para); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.docx","test.docx"); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.xlsx", "test.xlsx"); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.pptx", "test.pptx"); //Office Basic Formats para = new Paragraph(); run = new Run(); run.AppendChild(new Text("These are Office Basic Formats")); para.AppendChild(run); document.AddParagraph(para); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.doc", "test.doc"); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.xls", "test.xls"); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.vsd", "test.vsd"); //Object Formats para = new Paragraph(); run = new Run(); run.AppendChild(new Text("These are Object Formats")); para.AppendChild(run); document.AddParagraph(para); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.xml", "test.xml"); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.txt", "test.txt"); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.pdf", "test.pdf"); document.AddObject(@"C:\Users\" + user + @"\Desktop\test\test.zip", "test.zip"); document.Close(); Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
//run execution public RunExecute(int personID, int sessionID, string type, double distance, Chronopic cp, Gtk.TextView event_execute_textview_message, Gtk.Window app, int pDN, bool metersSecondsPreferred, bool volumeOn, double progressbarLimit, ExecutingGraphData egd ) { this.personID = personID; this.sessionID = sessionID; this.type = type; this.distance = distance; this.cp = cp; this.event_execute_textview_message = event_execute_textview_message; this.app = app; this.pDN = pDN; this.metersSecondsPreferred = metersSecondsPreferred; this.volumeOn = volumeOn; this.progressbarLimit = progressbarLimit; this.egd = egd; fakeButtonUpdateGraph = new Gtk.Button(); fakeButtonEventEnded = new Gtk.Button(); fakeButtonFinished = new Gtk.Button(); simulated = false; needUpdateEventProgressBar = false; needUpdateGraph = false; //initialize eventDone as a Run eventDone = new Run(); }
/// <summary> /// Generates the paragraph. /// </summary> /// <returns> /// Returns new Paragraph with empty run /// </returns> public static Paragraph GenerateParagraph() { var paragraph = new Paragraph(); var run = new Run(); paragraph.Append(run); return paragraph; }
public override void run(){ movement = new Run(); Console.Write("The cat "); movement.move(); }
/// <summary> /// Called when a Run node is encountered in the document. /// </summary> public override VisitorAction VisitRun(Run run) { AppendText(run.Text); // Let the visitor continue visiting other nodes. return VisitorAction.Continue; }
private void ApplyFooter(FooterPart footerPart) { var footer1 = new Footer(); footer1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006"); footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office"); footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"); footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml"); footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"); footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word"); footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml"); var paragraph1 = new Paragraph { RsidParagraphAddition = "005641D2", RsidRunAdditionDefault = "005641D2" }; var paragraphProperties1 = new ParagraphProperties(); var paragraphStyleId1 = new ParagraphStyleId { Val = "Footer" }; paragraphProperties1.Append(paragraphStyleId1); var run1 = new Run(); var text1 = new Text(); text1.Text = "Generated with Pickles " + Assembly.GetExecutingAssembly().GetName().Version; run1.Append(text1); paragraph1.Append(paragraphProperties1); paragraph1.Append(run1); footer1.Append(paragraph1); footerPart.Footer = footer1; }
protected Run GenerateRun(RunProperties runProperties, string text) { SetFontRunProperties(runProperties); var run = new Run() { RunProperties = runProperties }; run.AppendChild(new Text(text)); return run; }
public void InsertField() { //ExStart //ExFor:Paragraph.InsertField //ExSummary:Shows how to insert field using several methods: "field code", "field code and field value", "field code and field value after a run of text" Aspose.Words.Document doc = new Aspose.Words.Document(); //Get the first paragraph of the document Paragraph para = doc.FirstSection.Body.FirstParagraph; //Inseting field using field code //Note: All methods support inserting field after some node. Just set "true" in the "isAfter" parameter para.InsertField(" AUTHOR ", null, false); //Using field type //Note: //1. For inserting field using field type, you can choose, update field before or after you open the document ("updateField" parameter) //2. For other methods it's works automatically para.InsertField(FieldType.FieldAuthor, false, null, true); //Using field code and field value para.InsertField(" AUTHOR ", "Test Field Value", null, false); //Add a run of text Run run = new Run(doc) { Text = " Hello World!" }; para.AppendChild(run); //Using field code and field value before a run of text //Note: For inserting field before/after a run of text you can use all methods above, just add ref on your text ("refNode" parameter) para.InsertField(" AUTHOR ", "Test Field Value", run, false); //ExEnd }
public static void GenerateParagraph(this Body body, string text, string styleId) { var paragraph = new Paragraph { RsidParagraphAddition = "00CC1B7A", RsidParagraphProperties = "0016335E", RsidRunAdditionDefault = "0016335E" }; var paragraphProperties = new ParagraphProperties(); var paragraphStyleId = new ParagraphStyleId {Val = styleId}; paragraphProperties.Append(paragraphStyleId); var run1 = new Run(); var text1 = new Text(); text1.Text = text; run1.Append(text1); paragraph.Append(paragraphProperties); paragraph.Append(run1); body.Append(paragraph); }
public static string GenerateReportBug(DBO.BugReport bugReport) { string docName = System.Web.HttpContext.Current.Server.MapPath("~/download/")+"test.docx"; using (WordprocessingDocument package = WordprocessingDocument.Create( docName, WordprocessingDocumentType.Document)) { Run run = new Run(); //besoin de le faire si c'est une creation package.AddMainDocumentPart(); foreach (string str in bugReport.Comment) { run.Append(new Text(str), new Break()); } // Création du document. package.MainDocumentPart.Document = new Document( new Body( new Paragraph( new Run( new Text("Rapport de bug"))), new Run( new Text ("Titre :" + bugReport.Title), new Break(), new Text ("Personnable responble :" + bugReport.Responsable), new Break(), new Text ("Statut :" + bugReport.Statut), new Break (), new Text ("commentaire:") ),run)); // Enregistrer le contenu dans le document package.MainDocumentPart.Document.Save(); return docName; } }
/// <summary> /// Creates a RLEBitset from a BitArray. /// </summary> /// <param name="bits">a BitArray</param> /// <returns>an RLEBitset</returns> public static IBitset CreateFrom(BitArray bits) { RLEBitset rtnVal = new RLEBitset(); rtnVal._Length = bits.Length; Run currRun = new Run(); for (int i = 0; i < bits.Count; i++) { if (bits.Get(i) == true) { currRun.StartIndex = i; currRun.EndIndex = i; for (int j = i + 1; j < bits.Count; j++) { if (bits.Get(j)) { currRun.EndIndex = j; } else { break; } } i = currRun.EndIndex; //move the counter to the end of the run we just found rtnVal._RunArray.Add(currRun); currRun = new Run(); } } return rtnVal; }
public void CloneElementCorrect() { var initial = new Run(); var cloned = initial.CloneElement(); Assert.False(ReferenceEquals(initial, cloned)); }
public IRun Create(IComparisonGeneratorsFactory factory) { var run = new Run(factory); var reader = new StreamReader(Stream); var line = reader.ReadLine(); var titleInfo = line.Split('|'); run.CategoryName = titleInfo[0].Substring(1); run.AttemptCount = int.Parse(titleInfo[1]); TimeSpan totalTime = TimeSpan.Zero; while ((line = reader.ReadLine()) != null) { if (line.Length > 0) { var majorSplitInfo = line.Split('|'); totalTime += TimeSpanParser.Parse(majorSplitInfo[1]); while (!reader.EndOfStream && reader.Read() == '*') { line = reader.ReadLine(); run.AddSegment(line); } var newTime = new Time(run.Last().PersonalBestSplitTime); newTime.GameTime = totalTime; run.Last().PersonalBestSplitTime = newTime; } else { break; } } return run; }
public TicGenerator(Run run, SpectrumCache spectrumCache) { this.run = run; this.spectrumCache = spectrumCache; spectrumExtractor = new SpectrumExtractor(run, spectrumCache); ticCache = new TicCache(); }
//Main class function, export the mutationList to DOCX file, sets file name to patient's testName. public static void saveDOC(Patient patient, List<Mutation> mutationList, bool includePersonalDetails) { WordprocessingDocument myDoc = null; string fullPath = Properties.Settings.Default.ExportSavePath + @"\" + patient.TestName; if (includePersonalDetails) fullPath += "_withDetails"; fullPath += ".docx"; try { myDoc = WordprocessingDocument.Create(fullPath, WordprocessingDocumentType.Document); } catch(IOException ) { throw ; } MainDocumentPart mainPart = myDoc.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = new Body(); Paragraph paragraph = new Paragraph(); Run run_paragraph = new Run(); paragraph.Append(run_paragraph); //add paragraph for each detail of the patient. body.Append(generateParagraph("Test Name",true)); body.Append(generateParagraph(patient.TestName,false)); //add personal details of the patien, if includePersonalDetails=true if (includePersonalDetails) { body.Append(generateParagraph("ID", true)); body.Append(generateParagraph(patient.PatientID, false)); body.Append(generateParagraph("First Name", true)); body.Append(generateParagraph(patient.FName, false)); body.Append(generateParagraph("Last Name", true)); body.Append(generateParagraph(patient.LName, false)); } body.Append(generateParagraph("Pathological Number", true)); body.Append(generateParagraph(patient.PathoNum, false)); body.Append(generateParagraph("Run Number", true)); body.Append(generateParagraph(patient.RunNum, false)); body.Append(generateParagraph("Tumour Site", true)); body.Append(generateParagraph(patient.TumourSite, false)); body.Append(generateParagraph("Disease Level", true)); body.Append(generateParagraph(patient.DiseaseLevel, false)); body.Append(generateParagraph("Backgroud", true)); body.Append(generateParagraph(patient.Background, false)); body.Append(generateParagraph("Previous Treatment", true)); body.Append(generateParagraph(patient.PrevTreatment, false)); body.Append(generateParagraph("Current Treatment", true)); body.Append(generateParagraph(patient.CurrTreatment, false)); body.Append(generateParagraph("Conclusion", true)); body.Append(generateParagraph(patient.Conclusion, false)); //Add related mutation of the patient. CreateTable(body, mutationList); mainPart.Document.Append(body); mainPart.Document.Save(); myDoc.Close(); }
public void ReplaceBookmark(WordprocessingDocument package, string bookmark, string content) { IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>(); foreach (BookmarkStart bookmarkStart in package.MainDocumentPart.RootElement.Descendants<BookmarkStart>()) { bookmarkMap[bookmarkStart.Name] = bookmarkStart; } foreach (BookmarkStart bookmarkStart in bookmarkMap.Values) { if (bookmarkStart.Name == bookmark) { Run bookmarkText = bookmarkStart.NextSibling<Run>(); if (bookmarkText != null) { bookmarkText.GetFirstChild<Text>().Text = content; } else { var textElement = new Text(content); var runElement = new Run(textElement); bookmarkStart.InsertAfterSelf(runElement); } } } }
public void CreateFormattedRun() { //ExStart //ExFor:Document.#ctor //ExFor:Font //ExFor:Font.Name //ExFor:Font.Size //ExFor:Font.HighlightColor //ExFor:Run //ExFor:Run.#ctor(DocumentBase,String) //ExFor:Story.FirstParagraph //ExSummary:Shows how to add a formatted run of text to a document using the object model. // Create an empty document. It contains one empty paragraph. Document doc = new Document(); // Create a new run of text. Run run = new Run(doc, "Hello"); // Specify character formatting for the run of text. Aspose.Words.Font f = run.Font; f.Name = "Courier New"; f.Size = 36; f.HighlightColor = Color.Yellow; // Append the run of text to the end of the first paragraph // in the body of the first section of the document. doc.FirstSection.Body.FirstParagraph.AppendChild(run); //ExEnd }
public vmCommunications() { Title.Text = "Select communication method"; Next = new Run(); }
void AddRuleWithData(WrapPanel parentStackPanel, int ruleIndex, ScrubRule scrubRule = null) { StackPanel RuleHeadersp = new StackPanel(); RuleHeadersp.Orientation = Orientation.Horizontal; TextBlock HeaderTB = new TextBlock(); HeaderTB.Text = "Rule " + (ruleIndex); Label RuleIdLabel = new Label(); RuleIdLabel.Content = ruleIndex; RuleIdLabel.Visibility = Visibility.Hidden; Button DeleteBtn = new Button(); DeleteBtn.Name = "btnDelete_" + ruleIndex; DeleteBtn.HorizontalAlignment = HorizontalAlignment.Right; //DeleteBtn.Content = "Delete"; DeleteBtn.Margin = new Thickness(265, 0, 0, 0); DeleteBtn.Click += DeleteBtn_Click; DeleteBtn.Content = new Image { Source = new BitmapImage(new Uri("/Images/closeIcon.png", UriKind.Relative)), VerticalAlignment = VerticalAlignment.Center }; RuleHeadersp.Children.Add(HeaderTB); RuleHeadersp.Children.Add(DeleteBtn); Expander exp = new Expander(); exp.Header = RuleHeadersp; exp.HorizontalAlignment = HorizontalAlignment.Left; exp.Margin = new Thickness(20, 30, 0, 0); exp.BorderThickness = new Thickness(1, 1, 1, 1); exp.Width = 350; exp.BorderBrush = Brushes.Gray; exp.Background = Brushes.White; exp.IsExpanded = true; exp.Name = "RuleExpander_" + ruleIndex; StackPanel sp = new StackPanel(); sp.Orientation = Orientation.Vertical; sp.Margin = new Thickness(20, 5, 0, 0); StackPanel filterSP = new StackPanel(); filterSP.Orientation = Orientation.Horizontal; filterSP.Margin = new Thickness(0, 5, 0, 2); StackPanel attributeSP = new StackPanel(); attributeSP.Orientation = Orientation.Horizontal; attributeSP.Margin = new Thickness(0, 5, 0, 2); StackPanel scrubTypeSP = new StackPanel(); scrubTypeSP.Orientation = Orientation.Horizontal; scrubTypeSP.Margin = new Thickness(0, 5, 0, 2); StackPanel scrubValueSP = new StackPanel(); scrubValueSP.Orientation = Orientation.Horizontal; scrubValueSP.Margin = new Thickness(0, 5, 0, 2); TextBlock FilterLabel = new TextBlock(); FilterLabel.VerticalAlignment = VerticalAlignment.Center; FilterLabel.Margin = new Thickness(10, 0, 0, 0); //FilterLabel.MaxWidth = 150; Run runFilterLabel = new Run(); runFilterLabel.Text = "Filter Query"; runFilterLabel.FontSize = 15; Run runFilterLabelHint = new Run(); runFilterLabelHint.Text = " \nEx: c.Type = \"document\""; runFilterLabelHint.FontSize = 10; FilterLabel.Inlines.Add(runFilterLabel); FilterLabel.Inlines.Add(runFilterLabelHint); TextBox FilterTB = new TextBox(); FilterTB.Name = "Filter" + ruleIndex; FilterTB.Width = 150; FilterTB.HorizontalContentAlignment = HorizontalAlignment.Left; FilterTB.VerticalAlignment = VerticalAlignment.Center; FilterTB.Margin = new Thickness(20, 0, 0, 0); TextBlock AttributeScrubLabel = new TextBlock(); AttributeScrubLabel.VerticalAlignment = VerticalAlignment.Center; AttributeScrubLabel.Margin = new Thickness(10, 0, 0, 0); //AttributeScrubLabel.Width = 120; Run runAttributeScrubLabel = new Run(); runAttributeScrubLabel.Text = "Attribute To Scrub"; runAttributeScrubLabel.FontSize = 15; Run runAttributeScrubLabelHint = new Run(); runAttributeScrubLabelHint.Text = " \nEx: c.Person.Email"; runAttributeScrubLabelHint.FontSize = 10; AttributeScrubLabel.Inlines.Add(runAttributeScrubLabel); AttributeScrubLabel.Inlines.Add(runAttributeScrubLabelHint); TextBox AttributeScrubTB = new TextBox(); AttributeScrubTB.Name = "ScrubAttribute" + ruleIndex; AttributeScrubTB.Width = 150; AttributeScrubTB.HorizontalContentAlignment = HorizontalAlignment.Left; AttributeScrubTB.VerticalAlignment = VerticalAlignment.Center; AttributeScrubTB.Margin = new Thickness(20, 0, 0, 0); TextBlock ScrubTypeLabel = new TextBlock(); ScrubTypeLabel.Text = "Scrub Type"; ScrubTypeLabel.FontSize = 15; ScrubTypeLabel.VerticalAlignment = VerticalAlignment.Center; ScrubTypeLabel.Margin = new Thickness(10, 0, 0, 0); ComboBox ScrubTypeCB = new ComboBox(); ScrubTypeCB.Name = "ScrubType" + ruleIndex; ScrubTypeCB.Width = 150; ScrubTypeCB.Margin = new Thickness(20, 0, 0, 0); foreach (RuleType val in Enum.GetValues(typeof(RuleType))) { ScrubTypeCB.Items.Add(val.ToString()); } ScrubTypeCB.SelectionChanged += new SelectionChangedEventHandler(scrubTypeComboBox_SelectedIndexChanged); TextBlock ScrubValueLabel = new TextBlock(); ScrubValueLabel.Text = "Replace with"; ScrubValueLabel.FontSize = 15; ScrubValueLabel.VerticalAlignment = VerticalAlignment.Center; ScrubValueLabel.Margin = new Thickness(10, 0, 0, 5); TextBox ScrubValueTB = new TextBox(); ScrubValueTB.Name = "ScrubValue" + ruleIndex; ScrubValueTB.Width = 150; ScrubValueTB.HorizontalContentAlignment = HorizontalAlignment.Left; ScrubValueTB.VerticalAlignment = VerticalAlignment.Center; ScrubValueTB.Margin = new Thickness(20, 0, 0, 0); FilterLabel.Width = 120; FilterTB.Width = 150; AttributeScrubLabel.Width = 120; AttributeScrubTB.Width = 150; ScrubTypeLabel.Width = 120; ScrubTypeCB.Width = 150; ScrubValueLabel.Width = 120; filterSP.Children.Add(FilterLabel); filterSP.Children.Add(FilterTB); attributeSP.Children.Add(AttributeScrubLabel); attributeSP.Children.Add(AttributeScrubTB); scrubTypeSP.Children.Add(ScrubTypeLabel); scrubTypeSP.Children.Add(ScrubTypeCB); scrubValueSP.Children.Add(ScrubValueLabel); scrubValueSP.Children.Add(ScrubValueTB); scrubValueSP.Children.Add(RuleIdLabel); scrubValueSP.Visibility = Visibility.Hidden; sp.Children.Add(attributeSP); sp.Children.Add(filterSP); sp.Children.Add(scrubTypeSP); sp.Children.Add(scrubValueSP); exp.Content = sp; if (scrubRule != null) { FilterTB.Text = scrubRule.FilterCondition; AttributeScrubTB.Text = scrubRule.PropertyName; if (scrubRule.Type != null) { ScrubTypeCB.SelectedIndex = (int)scrubRule.Type; } ScrubValueTB.Text = scrubRule.UpdateValue; } parentStackPanel.Children.Add(exp); if (!SaveRuleButton.IsEnabled) { SaveRuleButton.IsEnabled = true; } }
public override Run VisitRun(Run node) { this.artifacts = node.Artifacts; this.threadFlowLocations = node.ThreadFlowLocations; // DSP does not support submitting invocation objects. Invocations // contains potentially sensitive environment details, such as // account names embedded in paths. Invocations also store // notifications of catastrophic tool failures, however, which // means there is current no mechanism for reporting these to // DSP users in context of the security tab. node.Invocations = null; if (node.Results != null) { int errorsCount = 0; foreach (Result result in node.Results) { if (result.Level == FailureLevel.Error) { errorsCount++; } } if (errorsCount != node.Results.Count) { var errors = new List <Result>(); foreach (Result result in node.Results) { if (result.Level == FailureLevel.Error) { errors.Add(result); } if (errors.Count == s_MaxResults) { break; } } node.Results = errors; } if (node.Results.Count > s_MaxResults) { node.Results = node.Results.Take(s_MaxResults).ToList(); } } node = base.VisitRun(node); // DSP prefers a relative path local to the result. We clear // the artifacts table, as all artifact information is now // inlined with each result. node.Artifacts = null; // DSP requires threadFlowLocations to be inlined in the result, // not referenced from run.threadFlowLocations. node.ThreadFlowLocations = null; return(node); }
private void ScrambleTextFonts() { // Text to scramble string text; // Max size of text (string.length) to scramble (2000 should be just over one sheet of A4 in terms of chars) int maxStringLength = 2000; // The output text, ie the scrambled version Paragraph scrambledText = new Paragraph(); // Random number generator to select a random font var rand = new Random(); // The random font to assign to the individual character string randomFont = SelectedFonts.First(); // Get the text to be scrambled, and limit its size TextInputRichEditBox.Document.GetText(Windows.UI.Text.TextGetOptions.None, out text); if (string.IsNullOrWhiteSpace(text)) { LoadPrefabText(); TextInputRichEditBox.Document.GetText(Windows.UI.Text.TextGetOptions.None, out text); } if (text.Length > maxStringLength) { text = text.Substring(0, maxStringLength); } // Create an array of integers, to act as a weight system for the selected fonts when selecting one at random int defaultFontWeight = (int)Math.Ceiling((text.Length / SelectedFonts.Count) * 1.1); int[] fontWeights = new int[SelectedFonts.Count]; int fontWeightsTotal = defaultFontWeight * SelectedFonts.Count; for (int i = 0; i < fontWeights.Length; i++) { fontWeights[i] = defaultFontWeight; } // Pick a font at (weighted) random and assign it to the char c in a new run, and add the run to the scrambledText paragraph foreach (char c in text) { // Generate a random number based on the total weight in the weighting system, // then iterate through fontWeights, adding the value of fontWeights at i to selectingCount, until the value selectingCount exceeds that of the random number. // This means a font has been selected, with its index in SelectedFonts being i, so it's assigned to randomFont. // Finally the value in fontWeights at the current i, and fontWeightsTotal is decreased by one to make the next selection of this location relatively a little less likely int randomNumber = rand.Next(0, fontWeightsTotal); int selectingCount = 0; for (int i = 0; i < fontWeights.Length; i++) { selectingCount += fontWeights[i]; if (selectingCount >= randomNumber) { if (i > SelectedFonts.Count) { Debug.WriteLine("RansomNote: ScrambleTextFonts weighted random for-loop i-value exceeded SelectedFonts.Count."); break; } randomFont = SelectedFonts.ElementAt(i); fontWeights[i]--; fontWeightsTotal--; break; } } Run run = new Run(); run.Text = c.ToString(); run.FontFamily = new FontFamily(randomFont); scrambledText.Inlines.Add(run); } // Set the text in TextOutputRichTextBlock to the newly scrambled text TextOutputRichTextBlock.Blocks.Clear(); TextOutputRichTextBlock.Blocks.Add(scrambledText); // Write all the current fontWeights values to the debug console Debug.WriteLine(string.Format("RansomNote: Final fontWeights are;")); for (int i = 0; i < fontWeights.Length; i++) { Debug.WriteLine(string.Format("RansomNote: {0}-{1} = {2}", i.ToString(), SelectedFonts.ElementAt(i), fontWeights[i].ToString())); } }
// Token: 0x060027E1 RID: 10209 RVA: 0x000AB4D5 File Offset: 0x000A96D5 private void OnRunStart(Run run) { this.UpdateTracking(); }
/// <summary> /// Called when a Run node is encountered in the document. /// </summary> public override VisitorAction VisitRun(Run run) { IndentAndAppendLine("[Run] \"" + run.Text + "\""); return(VisitorAction.Continue); }
internal void UnsafeRemoveVisualElement(Run v) { _runs.Remove(GetLineLinkNode(v)); }
private void ProcessTd(int colIndex, DocxNode td, TableRow row, DocxTableProperties tableProperties) { TableCell cell = new TableCell(); bool hasRowSpan = false; string rowSpan = td.ExtractAttributeValue(DocxTableProperties.rowSpan); Int32 rowSpanValue; if (Int32.TryParse(rowSpan, out rowSpanValue)) { tableProperties.RowSpanInfo[colIndex] = rowSpanValue - 1; hasRowSpan = true; } DocxTableCellStyle style = new DocxTableCellStyle(); style.HasRowSpan = hasRowSpan; style.Process(cell, tableProperties, td); if (td.HasChildren) { Paragraph para = null; //If the cell is th header, apply font-weight:bold to the text if (tableProperties.IsCellHeader) { SetThStyleToRun(td); } foreach (DocxNode child in td.Children) { td.CopyExtentedStyles(child); if (child.IsText) { if (!IsEmptyText(child.InnerHtml)) { if (para == null) { para = cell.AppendChild(new Paragraph()); OnParagraphCreated(DocxTableCellStyle.GetHtmlNodeForTableCellContent(td), para); } Run run = para.AppendChild(new Run(new Text() { Text = ClearHtml(child.InnerHtml), Space = SpaceProcessingModeValues.Preserve })); RunCreated(child, run); } } else { child.ParagraphNode = DocxTableCellStyle.GetHtmlNodeForTableCellContent(td); child.Parent = cell; td.CopyExtentedStyles(child); ProcessChild(child, ref para); } } } //The last element of the table cell must be a paragraph. var lastElement = cell.Elements().LastOrDefault(); if (lastElement == null || !(lastElement is Paragraph)) { cell.AppendChild(new Paragraph()); } row.Append(cell); }
public FlowDocument Reredraw() { string[] lines = this.emu.CurrentScreenObject.Dump().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); FlowDocument flwd = new FlowDocument(); flwd.Foreground = Brushes.LimeGreen; int j = 0; for (int i = 0; i < lines.Length; i++) { List<Run> rs = new List<Run>(); rs.Add(new Run(lines[i])); if (this.emu.CurrentScreenObject.Fields != null && this.emu.CurrentScreenObject.Fields.Count > 0) { while (j < this.emu.CurrentScreenObject.Fields.Count && ((this.emu.CurrentScreenObject.Fields[j].Location.position + this.emu.CurrentScreenObject.Fields[j].Location.top) <= ((i + 1) * 80))) { if (emu.CurrentScreenObject.Fields[j].Text != null) { int index = rs[rs.Count - 1].Text.IndexOf(emu.CurrentScreenObject.Fields[j].Text); if (index >= 0) { Brush clr = Brushes.Lime; if (emu.CurrentScreenObject.Fields[j].Attributes.FieldType == "High" && emu.CurrentScreenObject.Fields[j].Attributes.Protected) clr = Brushes.White; else if (emu.CurrentScreenObject.Fields[j].Attributes.FieldType == "High") clr = Brushes.Red; else if (emu.CurrentScreenObject.Fields[j].Attributes.Protected) clr = Brushes.RoyalBlue; else if (emu.CurrentScreenObject.Fields[j].Attributes.FieldType == "Hidden") clr = Brushes.Black; string before = null; string after = null; if (index > 0) before = rs[rs.Count - 1].Text.Substring(0, index); if (index + emu.CurrentScreenObject.Fields[j].Location.length < 80) after = rs[rs.Count - 1].Text.Substring(index + this.emu.CurrentScreenObject.Fields[j].Location.length); string text = rs[rs.Count - 1].Text.Substring(index, this.emu.CurrentScreenObject.Fields[j].Location.length); if (before != null) { rs[rs.Count - 1].Text = before; Run t = new Run(text); t.Foreground = clr; rs.Add(t); } else { rs[rs.Count - 1].Text = text; rs[rs.Count - 1].Foreground = clr; } if (after != null) { rs.Add(new Run(after)); } } } j++; }; } Paragraph p = new Paragraph(); for (int k = 0; k < rs.Count; k++) { p.Inlines.Add(rs[k]); } flwd.Blocks.Add(p); } return flwd; }
public async Task <bool> IsLockedAsync(string name) { var result = await Run.WithRetriesAsync(() => _cacheClient.GetAsync <object>(name), logger : _logger).AnyContext(); return(result.HasValue); }
public virtual async Task CanHaveMultipleQueueInstances() { var queue = GetQueue(retries: 0, retryDelay: TimeSpan.Zero); if (queue == null) { return; } using (queue) { await queue.DeleteQueueAsync(); await AssertEmptyQueueAsync(queue); const int workItemCount = 50; const int workerCount = 3; var countdown = new AsyncCountdownEvent(workItemCount); var info = new WorkInfo(); var workers = new List <IQueue <SimpleWorkItem> > { queue }; try { for (int i = 0; i < workerCount; i++) { var q = GetQueue(retries: 0, retryDelay: TimeSpan.Zero); _logger.Trace("Queue Id: {0}, I: {1}", q.QueueId, i); await q.StartWorkingAsync(async w => await DoWorkAsync(w, countdown, info)); workers.Add(q); } await Run.InParallel(workItemCount, async i => { var id = await queue.EnqueueAsync(new SimpleWorkItem { Data = "Hello", Id = i }); _logger.Trace("Enqueued Index: {0} Id: {1}", i, id); }); await countdown.WaitAsync(); await SystemClock.SleepAsync(50); _logger.Trace("Completed: {0} Abandoned: {1} Error: {2}", info.CompletedCount, info.AbandonCount, info.ErrorCount); _logger.Info("Work Info Stats: Completed: {completed} Abandoned: {abandoned} Error: {errors}", info.CompletedCount, info.AbandonCount, info.ErrorCount); Assert.Equal(workItemCount, info.CompletedCount + info.AbandonCount + info.ErrorCount); // In memory queue doesn't share state. if (queue.GetType() == typeof(InMemoryQueue <SimpleWorkItem>)) { var stats = await queue.GetQueueStatsAsync(); Assert.Equal(0, stats.Working); Assert.Equal(0, stats.Timeouts); Assert.Equal(workItemCount, stats.Enqueued); Assert.Equal(workItemCount, stats.Dequeued); Assert.Equal(info.CompletedCount, stats.Completed); Assert.Equal(info.ErrorCount, stats.Errors); Assert.Equal(info.AbandonCount, stats.Abandoned - info.ErrorCount); Assert.Equal(info.AbandonCount + stats.Errors, stats.Deadletter); } else { var workerStats = new List <QueueStats>(); for (int i = 0; i < workers.Count; i++) { var stats = await workers[i].GetQueueStatsAsync(); _logger.Info("Worker#{i} Working: {working} Completed: {completed} Abandoned: {abandoned} Error: {errors} Deadletter: {deadletter}", i, stats.Working, stats.Completed, stats.Abandoned, stats.Errors, stats.Deadletter); workerStats.Add(stats); } Assert.Equal(info.CompletedCount, workerStats.Sum(s => s.Completed)); Assert.Equal(info.ErrorCount, workerStats.Sum(s => s.Errors)); Assert.Equal(info.AbandonCount, workerStats.Sum(s => s.Abandoned) - info.ErrorCount); Assert.Equal(info.AbandonCount + workerStats.Sum(s => s.Errors), (workerStats.LastOrDefault()?.Deadletter ?? 0)); } } finally { foreach (var q in workers) { await q.DeleteQueueAsync(); q.Dispose(); } } } }
public async Task Run() { IRun run = new Run(); await run.Run(); }
public static Span FormatText(this string text) { string[] lines = text.Split('\n', '\r'); Span sp = new Span { FontSize = 16, }; foreach (string line in lines) { Span span = new Span(); if (!line.IsValid()) { sp.Inlines.Add(NewLine); } else { if (!line.ContainsAnyUrl()) { Run run = new Run { Text = line + "\r", }; if (line.IsUpper()) { run.FontWeight = new FontWeight() { Weight = 700 }; } span.Inlines.Add(run); } else { string[] words = line.GetFullWords(); for (int i = 0; i < words.Length; i++) { string word = words[i]; if (word.IsValid()) { if (word.IsValidUrl()) { string url = word.SanifUrl(); url = url.StartsWith("www") ? $"http://{url}" : url; if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { try { //InlineUIContainer cont = new InlineUIContainer(); //var linkBtn = new HyperlinkButton() //{ // Tag = word.SanifUrl(), // Padding = new Thickness(0, 0, 0, -5), // VerticalAlignment = VerticalAlignment.Bottom, // VerticalContentAlignment = VerticalAlignment.Bottom, //}; var link = new Hyperlink() { AccessKey = url, TextDecorations = TextDecorations.None, NavigateUri = new Uri(url) }; link.Inlines.Add(new Run() { Text = word + " " }); //linkBtn.Content = link; //cont.Child = linkBtn; span.Inlines.Add(link); } catch (Exception) { } } else { span.Inlines.Add(new Run() { Text = word + " ", }); } } else { span.Inlines.Add(new Run() { Text = word + " ", }); } } if (i == words.Length - 1) { span.Inlines.Add(NewLine); } } } } sp.Inlines.Add(span); } return(sp); }
private void WalkDocumentTree(Action <TextElement> action, Run r) { action.Invoke(r); }
protected virtual void Analyze(Run run, string runPointer) { }
RunAsync(CancellationToken cancellationToken = default) { string snapshotName = SystemClock.UtcNow.ToString("'" + Repository + "-'yyyy-MM-dd-HH-mm"); _logger.LogInformation("Starting {Repository} snapshot {SnapshotName}...", Repository, snapshotName); await _lockProvider.TryUsingAsync("es-snapshot", async t => { var sw = Stopwatch.StartNew(); var result = await Run.WithRetriesAsync(async() => { var response = await _client.SnapshotAsync( Repository, snapshotName, d => d .Indices(IncludedIndexes.Count > 0 ? String.Join(",", IncludedIndexes) : "*") .IgnoreUnavailable() .IncludeGlobalState(false) .WaitForCompletion(false) , cancellationToken).AnyContext(); // 400 means the snapshot already exists if (!response.IsValid && response.ApiCall.HttpStatusCode != 400) { throw new ApplicationException($"Snapshot failed: {response.GetErrorMessage()}", response.OriginalException); } return(response); }, maxAttempts: 5, retryInterval: TimeSpan.FromSeconds(10), cancellationToken: cancellationToken, logger: _logger).AnyContext(); _logger.LogTrace("Started snapshot {SnapshotName} in {Repository}: httpstatus={StatusCode}", snapshotName, Repository, result.ApiCall?.HttpStatusCode); bool success = false; do { await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).AnyContext(); var status = await _client.SnapshotStatusAsync(s => s.Snapshot(snapshotName).RepositoryName(Repository), cancellationToken).AnyContext(); if (status.IsValid && status.Snapshots.Count > 0) { string state = status.Snapshots.First().State; if (state.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase)) { success = true; break; } if (state.Equals("FAILED", StringComparison.OrdinalIgnoreCase) || state.Equals("ABORTED", StringComparison.OrdinalIgnoreCase) || state.Equals("MISSING", StringComparison.OrdinalIgnoreCase)) { break; } } // max time to wait for a snapshot to complete if (sw.Elapsed > TimeSpan.FromHours(1)) { _logger.LogError("Timed out waiting for snapshot {SnapshotName} in {Repository}.", snapshotName, Repository); break; } } while (!cancellationToken.IsCancellationRequested); sw.Stop(); if (success) { await OnSuccess(snapshotName, sw.Elapsed).AnyContext(); } else { await OnFailure(snapshotName, result).AnyContext(); } }, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30)).AnyContext(); return(JobResult.Success); }
private void On_Run_OnDestroy(On.RoR2.Run.orig_OnDestroy orig, Run self) { orig(self); RespondablesMenuBindings.UpdateRespondables(); }
protected void Display(bool aFilter) { Log("Display({0})", aFilter); Log("Current Label '{0}'", mCurrentLabel); mCode.Clear(); tblkSource.Inlines.Clear(); mRunsToLines.Clear(); Log("Display - Done clearing"); if (mData.Length == 0) { return; } int nextCodeDistFromCurrent = 0; bool foundCurrentLine = false; var xFont = new FontFamily("Consolas"); //We need multiple prefix filters because method header has different prefix to IL labels. //We use: // - First "Method_" label prefix // - First label without "GUID_" or "METHOD_" on it as that will be the name of the current method List <string> xLabelPrefixes = new List <string>(); bool foundMETHOD_Prefix = false; bool foundMethodName = false; int mCurrentLineNumber = 0; Log("Display - Processing lines"); foreach (var xLine in mLines) { string xDisplayLine = xLine.ToString(); if (aFilter) { if (xLine is AsmLabel xAsmLabel) { xDisplayLine = xAsmLabel.Label + ":"; // Skip ASM labels if (xAsmLabel.Comment.ToUpper() == "ASM") { continue; } if (!foundMETHOD_Prefix && xAsmLabel.Label.StartsWith("METHOD_")) { var xLabelParts = xAsmLabel.Label.Split('.'); xLabelPrefixes.Add(xLabelParts[0] + "."); foundMETHOD_Prefix = true; } else if (!foundMethodName && !xAsmLabel.Label.StartsWith("METHOD_") && !xAsmLabel.Label.StartsWith("GUID_")) { var xLabelParts = xAsmLabel.Label.Split(':'); xLabelPrefixes.Add(xLabelParts[0] + "."); foundMethodName = true; } } else { xDisplayLine = xLine.ToString(); } // Replace all and not just labels so we get jumps, calls etc foreach (string xLabelPrefix in xLabelPrefixes) { xDisplayLine = xDisplayLine.Replace(xLabelPrefix, ""); } } if (xLine is AsmLabel) { // Insert a blank line before labels, but not if its the top line if (tblkSource.Inlines.Count > 0) { tblkSource.Inlines.Add(new LineBreak()); if (!foundCurrentLine) { mCurrentLineNumber++; } mCode.AppendLine(); } } else { xDisplayLine = "\t" + xDisplayLine; } // Even though our code is often the source of the tab, it makes // more sense to do it this was because the number of space stays // in one place and also lets us differentiate from natural spaces. xDisplayLine = xDisplayLine.Replace("\t", " "); var xRun = new Run(xDisplayLine); xRun.FontFamily = xFont; mRunsToLines.Add(xRun, xLine); var gutterRect = new Rectangle() { Width = 11, Height = 11, Fill = Brushes.WhiteSmoke }; tblkSource.Inlines.Add(gutterRect); // Set colour of line if (xLine is AsmLabel) { xRun.Foreground = Brushes.Black; } else if (xLine is AsmComment) { xRun.Foreground = Brushes.Green; } else if (xLine is AsmCode xAsmCode) { gutterRect.MouseUp += gutterRect_MouseUp; gutterRect.Fill = Brushes.LightGray; mGutterRectsToCode.Add(gutterRect, xAsmCode); mGutterRectsToRun.Add(gutterRect, xRun); Log("Current AsmCodeLabel: '{0}'", xAsmCode.AsmLabel); if (xAsmCode.LabelMatches(mCurrentLabel)) { xRun.Foreground = Brushes.WhiteSmoke; xRun.Background = Brushes.DarkRed; Package.StateStorer.CurrLineId = GetLineId(xAsmCode); Package.StoreAllStates(); foundCurrentLine = true; nextCodeDistFromCurrent = 0; } else { if (foundCurrentLine) { nextCodeDistFromCurrent++; } if (mASMBPs.Contains(GetLineId(xAsmCode))) { xRun.Background = Brushes.MediumVioletRed; } else if (Package.StateStorer.ContainsStatesForLine(GetLineId(xAsmCode))) { xRun.Background = Brushes.LightYellow; } xRun.Foreground = Brushes.Blue; } xRun.MouseUp += OnASMCodeTextMouseUp; } else { // Unknown type xRun.Foreground = Brushes.HotPink; } if (!foundCurrentLine) { mCurrentLineNumber++; } tblkSource.Inlines.Add(xRun); tblkSource.Inlines.Add(new LineBreak()); mCode.AppendLine(xDisplayLine); } Log("Display - Done processing lines"); //EdMan196: This line of code was worked out by trial and error. double offset = mCurrentLineNumber * 13.1; Log("Display - Scroll to offset"); ASMScrollViewer.ScrollToVerticalOffset(offset); }
public static void SetVisible(Run d, bool value) { d.SetValue(VisibleProperty, value); }
public void Initialize() { var spectrumpoint1A = new SpectrumPoint(2000, 550, 2.58F) { }; var spectrumpoint2A = new SpectrumPoint(3000, 551F, 3.00F) { }; List <SpectrumPoint> spectrum = new List <SpectrumPoint>() { spectrumpoint1A, spectrumpoint2A }; string tempPath = Path.GetTempPath(); Scan ms2scan1 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 550, IsolationWindowUpperOffset = 1, ScanStartTime = 0, MsLevel = 2, Density = 2, Cycle = 1, TotalIonCurrent = 1000 }; Scan ms2scan2 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 5, IsolationWindowTargetMz = 550, IsolationWindowUpperOffset = 5, ScanStartTime = 30, MsLevel = 2, Density = 4, Cycle = 2, TotalIonCurrent = 3050 }; Scan ms2scan3 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 550, IsolationWindowUpperOffset = 1, ScanStartTime = 35, MsLevel = 2, Density = 4, Cycle = 3, TotalIonCurrent = 4000 }; Scan ms2scan4 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 550, IsolationWindowUpperOffset = 1, ScanStartTime = 70, MsLevel = 2, Density = 5, Cycle = 4, TotalIonCurrent = 6000 }; Scan ms2scan5 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 550, IsolationWindowUpperOffset = 1, ScanStartTime = 70.002, MsLevel = 2, Density = 5, Cycle = 5, TotalIonCurrent = 6000 }; Scan ms2scan6 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 1050, IsolationWindowUpperOffset = 1, ScanStartTime = 0, MsLevel = 2, Density = 2, Cycle = 1, TotalIonCurrent = 1000 }; Scan ms2scan7 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 5, IsolationWindowTargetMz = 1050, IsolationWindowUpperOffset = 5, ScanStartTime = 30, MsLevel = 2, Density = 4, Cycle = 2, TotalIonCurrent = 3050 }; Scan ms2scan8 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 1050, IsolationWindowUpperOffset = 1, ScanStartTime = 35, MsLevel = 2, Density = 40, Cycle = 3, TotalIonCurrent = 4000 }; Scan ms2scan9 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 1050, IsolationWindowUpperOffset = 1, ScanStartTime = 70, MsLevel = 2, Density = 20, Cycle = 4, TotalIonCurrent = 20000 }; Scan ms2scan10 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowTargetMz = 1050, IsolationWindowUpperOffset = 1, ScanStartTime = 70.002, MsLevel = 2, Density = 18, Cycle = 5, TotalIonCurrent = 10000 }; //MS1scans Scan ms1scan1 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowUpperOffset = 1, ScanStartTime = 0, MsLevel = 1, Density = 2, Cycle = 1, TotalIonCurrent = 1000, BasePeakIntensity = 1000, BasePeakMz = 1058 }; Scan ms1scan2 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 5, IsolationWindowUpperOffset = 5, ScanStartTime = 30, MsLevel = 1, Density = 4, Cycle = 2, TotalIonCurrent = 3050, BasePeakIntensity = 1500, BasePeakMz = 459 }; Scan ms1scan3 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 5, IsolationWindowUpperOffset = 5, ScanStartTime = 70, MsLevel = 1, Density = 4, Cycle = 3, TotalIonCurrent = 3050, BasePeakIntensity = 5000, BasePeakMz = 150 }; //BasePeaks: var spectrumpoint1 = new SpectrumPoint(2000, 150, 2.58F) { }; var spectrumpoint2 = new SpectrumPoint(3000, 150.01F, 3.00F) { }; var spectrumpoint3 = new SpectrumPoint(3000, 150.01F, 60F) { }; var basePeak1 = new BasePeak(150, 2.5, 150) { BpkRTs = new List <double>() { 2.5 }, Spectrum = new List <SpectrumPoint>() { spectrumpoint1, spectrumpoint2 }, Mz = 150 }; basePeak1.FWHMs.Add(1); basePeak1.FWHMs.Add(2); basePeak1.Peaksyms.Add(1); basePeak1.Peaksyms.Add(2); basePeak1.Intensities.Add(1); basePeak1.Intensities.Add(2); basePeak1.FullWidthBaselines.Add(1); basePeak1.FullWidthBaselines.Add(2); var basePeak2 = new BasePeak(300, 60, 150) { BpkRTs = new List <double>() { 60 }, Spectrum = new List <SpectrumPoint>() { spectrumpoint3 } }; basePeak2.FWHMs.Add(2); basePeak2.Peaksyms.Add(1); basePeak2.Intensities.Add(2); basePeak2.FullWidthBaselines.Add(1); //Runs: ms2andms1Run = new Run <Scan> { AnalysisSettings = new AnalysisSettings { RtTolerance = 2.5 }, LastScanTime = 100, StartTime = 0 }; ms2andms1Run.Ms2Scans.AddRange(new Scan[] { ms2scan1, ms2scan2, ms2scan3, ms2scan4, ms2scan5, ms2scan6, ms2scan7, ms2scan8, ms2scan9, ms2scan10 }); ms2andms1Run.Ms1Scans.AddRange(new Scan[] { ms1scan1, ms1scan2, ms1scan3 }); ms2andms1Run.BasePeaks.Add(basePeak1); ms2andms1Run.BasePeaks.Add(basePeak2); ms2andms1Run.SourceFileNames.Add(" "); ms2andms1Run.SourceFileChecksums.Add(" "); /* * emptyms2scansRun = new Run * { * AnalysisSettings = new AnalysisSettings * { * RtTolerance = 2.5 * }, * Ms2Scans = new ConcurrentBag<Scan>() { ms2scan1, ms2scan2, ms2scan3, ms2scan4, ms2scan6 },//9 does not have upper and lower offsets * LastScanTime = 0, * StartTime = 1000000 * }; * * emptyms2scansRun.BasePeaks.Add(basePeak1); * emptyms2scansRun.SourceFileNames.Add(" "); * emptyms2scansRun.SourceFileChecksums.Add(" ");*/ swathGrouper = new SwathGrouper(); result = swathGrouper.GroupBySwath(ms2andms1Run); }
public static void ConvertFieldCodes(OpenXmlElement mainElement) { // search for all the Run elements Run[] runs = mainElement.Descendants <Run>().ToArray(); if (runs.Length == 0) { return; } Dictionary <Run, Run[]> newFields = new Dictionary <Run, Run[]>(); int cursor = 0; do { Run run = runs[cursor]; if (run.HasChildren && run.Descendants <FieldChar>().Any() && (run.Descendants <FieldChar>().First().FieldCharType & FieldCharValues.Begin) == FieldCharValues.Begin) { List <Run> innerRuns = new List <Run> { run }; // loop until we find the 'end' FieldChar bool found = false; string instruction = null; RunProperties runProp = null; do { cursor++; run = runs[cursor]; innerRuns.Add(run); if (run.HasChildren && run.Descendants <FieldCode>().Any()) { instruction += run.GetFirstChild <FieldCode>().Text; } if (run.HasChildren && run.Descendants <FieldChar>().Any() && (run.Descendants <FieldChar>().First().FieldCharType & FieldCharValues.End) == FieldCharValues.End) { found = true; } if (run.HasChildren && run.Descendants <RunProperties>().Any()) { runProp = run.GetFirstChild <RunProperties>(); } } while (found == false && cursor < runs.Length); // something went wrong : found Begin but no End. Throw exception if (!found) { throw new Exception("Found a Begin FieldChar but no End !"); } if (!string.IsNullOrEmpty(instruction)) { // build new Run containing a SimpleField Run newRun = new Run(); if (runProp != null) { newRun.AppendChild(runProp.CloneNode(true)); } SimpleField simpleField = new SimpleField { Instruction = instruction }; newRun.AppendChild(simpleField); newFields.Add(newRun, innerRuns.ToArray()); } } cursor++; } while (cursor < runs.Length); // replace all FieldCodes by old-style SimpleFields foreach (KeyValuePair <Run, Run[]> kvp in newFields) { kvp.Value[0].Parent.ReplaceChild(kvp.Key, kvp.Value[0]); for (int i = 1; i < kvp.Value.Length; i++) { kvp.Value[i].Remove(); } } }
public static bool GetVisible(Run d) { return((bool)d.GetValue(VisibleProperty)); }
private bool ProcessFile(string file) { ShowStatus(string.Format(loadingStatusPrompt, file)); try { if (file.EndsWith(".db", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".mmdb", StringComparison.OrdinalIgnoreCase)) { string userName = null; string password = null; string path = Path.GetFullPath(file); bool cancelled = false; dispatcher.Invoke(new Action(() => { PasswordWindow w = new PasswordWindow(); Paragraph p = (Paragraph)w.IntroMessagePrompt.Document.Blocks.FirstBlock; Run run = (Run)p.Inlines.FirstInline; run.Text = "Please enter password for the imported database"; if (w.ShowDialog() == true) { userName = w.UserName; password = w.PasswordConfirmation; path = Path.GetFullPath(file); } else { ShowStatus("Import cancelled."); cancelled = true; } })); if (!cancelled) { SqliteDatabase database = new SqliteDatabase() { DatabasePath = path, UserId = userName, Password = password }; database.Create(); // import the database, and any associated attachments or statements. MyMoney newMoney = database.Load(this); AttachmentManager importAttachments = new AttachmentManager(newMoney); importAttachments.SetupAttachmentDirectory(path); StatementManager importStatements = new StatementManager(newMoney); importStatements.SetupStatementsDirectory(path); importStatements.Load(); ImportMoneyFile(newMoney, importAttachments, importStatements); } else { return(false); } } else { ShowStatus("Import only supports sqllite money files"); return(false); } } catch (Exception ex) { ShowStatus("Error: " + ex.Message); return(false); } return(true); }
public static void MergeFieldsInElement(Dictionary <string, string> values, OpenXmlElement element) { Dictionary <SimpleField, string[]> emptyFields = new Dictionary <SimpleField, string[]>(); // first pass: fill in data but do not delete empty fields SimpleField[] list = element.Descendants <SimpleField>().ToArray(); foreach (SimpleField field in list) { string fieldName = GetFieldNameWithOptions(field, out var switches, out var options); if (!string.IsNullOrEmpty(fieldName)) { if (values.ContainsKey(fieldName) && !string.IsNullOrEmpty(values[fieldName])) { var formattedText = ApplyFormatting(options[0], values[fieldName], options[1], options[2]); // prepend any text specified to appear before the data in the MergeField if (!string.IsNullOrEmpty(options[1])) { field.Parent.InsertBeforeSelf(GetPreOrPostParagraphToInsert(formattedText[1], field)); } // append any text specified to appear after the data in the MergeField if (!string.IsNullOrEmpty(options[2])) { field.Parent.InsertAfterSelf(GetPreOrPostParagraphToInsert(formattedText[2], field)); } // replace MergeField with text Run newFieldRun = GetRunElementForText(formattedText[0], field); field.Parent.AppendChild(newFieldRun); int index = 0; foreach (OpenXmlElement item in field.Parent.ChildElements) { if (item.Equals(field)) { break; } index++; } field.Parent.ChildElements[index].Remove(); } else { // keep track of unknown or empty fields emptyFields[field] = switches; } } } // second pass : clear empty fields foreach (KeyValuePair <SimpleField, string[]> kvp in emptyFields) { // if field is unknown or empty: execute switches and remove it from document ExecuteSwitches(kvp.Key, kvp.Value); kvp.Key.Remove(); } }
//public List<string> GetDocumentTags(byte[] buffer) //{ // if (buffer == null) throw new ArgumentNullException(nameof(buffer)); // Document document; // using (var ms = new MemoryStream(buffer)) // { // document = new Document(ms); // } // return document // .GetChildNodes(NodeType.StructuredDocumentTag, true) // .ToArray() // .Select(x => ((StructuredDocumentTag)x).Title) // .ToList(); //} private void FillUserInputControl(StructuredDocumentTag std, Dictionary <string, string> userInputFieldsDictionaty, Document document, DocumentBuilder builder, string defaultValue) { //std.RemoveAllChildren(); Paragraph paragraph; var html = userInputFieldsDictionaty[std.Title.Trim()]; if (string.IsNullOrEmpty(html)) { return; } html = TrimParagraphTag(html); html = ResizeBase64Images(html); //была проблема при вставке html если тег находился в параграфе //если Content Control находится не в Body, а во вложенном теге if (std.ParentNode.NodeType != NodeType.Body) { //проверяем текущее поле на простой текст без форматирования if (std.Title.Trim().EndsWith("_UserInput")) { if (std.ParentNode.NodeType == NodeType.Paragraph) { var run = new Run(document, html); // set font Inline inlineElement = GetFirstInline(std.ChildNodes); if (inlineElement != null) { CopyFont(run.Font, inlineElement.Font); } std.RemoveAllChildren(); std.AppendChild(run); std.RemoveSelfOnly(); } else { paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std); // set font Paragraph paragraphSource = (Paragraph)std.FirstChild; Inline inlineElement = GetFirstInline(paragraphSource.ChildNodes); var run = new Run(document, html); if (inlineElement != null) { CopyFont(run.Font, inlineElement.Font); } paragraph.AppendChild(run); std.Remove(); } } //если поле со значение по умолчанию else if (std.Title.Trim().EndsWith("_UserInputDefault")) { html = html.Equals(string.Empty) ? defaultValue : html; if (std.ParentNode.NodeType == NodeType.Paragraph) { var run = new Run(document, html); // set font Inline inlineElement = GetFirstInline(std.ChildNodes); if (inlineElement != null) { CopyFont(run.Font, inlineElement.Font); } std.RemoveAllChildren(); std.AppendChild(run); std.RemoveSelfOnly(); } else { paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std); // set font Paragraph paragraphSource = (Paragraph)std.FirstChild; Inline inlineElement = GetFirstInline(paragraphSource.ChildNodes); var run = new Run(document, html); if (inlineElement != null) { CopyFont(run.Font, inlineElement.Font); } paragraph.AppendChild(run); std.Remove(); } } //если текст из wysiwyg редактора else { std.RemoveAllChildren(); if (std.ParentNode.NodeType == NodeType.Paragraph) { builder.MoveTo(std); builder.InsertHtml(html, true); std.RemoveSelfOnly(); } else { paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std); builder.MoveTo(paragraph); builder.InsertHtml(html, true); std.AppendChild(paragraph); std.RemoveSelfOnly(); } } } //если Content Control находится в корне тега Body else { if (std.Title.Trim().EndsWith("_UserInput")) { paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std); // set font Paragraph paragraphSource = (Paragraph)std.FirstChild; Inline inlineElement = GetFirstInline(paragraphSource.ChildNodes); var run = new Run(document, html); if (inlineElement != null) { CopyFont(run.Font, inlineElement.Font); } paragraph.AppendChild(run); std.Remove(); } else if (std.Title.Trim().EndsWith("_UserInputDefault")) { html = html.Equals(string.Empty) ? defaultValue : html; paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std); // set font Paragraph paragraphSource = (Paragraph)std.FirstChild; Inline inlineElement = GetFirstInline(paragraphSource.ChildNodes); var run = new Run(document, html); if (inlineElement != null) { CopyFont(run.Font, inlineElement.Font); } paragraph.AppendChild(run); std.Remove(); } //если текст из wysiwyg редактора else { paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std); builder.MoveTo(paragraph); builder.InsertHtml(html, true); std.Remove(); } } }
/// <summary> /// Renders a code element /// </summary> /// <param name="element"> The parsed inline element to render. </param> /// <param name="context"> Persistent state. </param> protected override void RenderCodeRun(CodeInline element, IRenderContext context) { var localContext = context as InlineRenderContext; if (localContext == null) { throw new RenderContextIncorrectException(); } var text = CreateTextBlock(localContext); text.Text = CollapseWhitespace(context, element.Text); text.FontFamily = InlineCodeFontFamily ?? FontFamily; text.Foreground = InlineCodeForeground ?? Foreground; if (localContext.WithinItalics) { text.FontStyle = FontStyle.Italic; } if (localContext.WithinBold) { text.FontWeight = FontWeights.Bold; } var borderthickness = InlineCodeBorderThickness; var padding = InlineCodePadding; var border = new Border { BorderThickness = borderthickness, BorderBrush = InlineCodeBorderBrush, Background = InlineCodeBackground, Child = text, Padding = padding, Margin = InlineCodeMargin }; // Aligns content in InlineUI, see https://social.msdn.microsoft.com/Forums/silverlight/en-US/48b5e91e-efc5-4768-8eaf-f897849fcf0b/richtextbox-inlineuicontainer-vertical-alignment-issue?forum=silverlightarchieve border.RenderTransform = new TranslateTransform { Y = 4 }; var inlineUIContainer = new InlineUIContainer { Child = border, }; try { // Add it to the current inline collection localContext.InlineCollection.Add(inlineUIContainer); } catch // Fallback { Run run = new Run { Text = text.Text, FontFamily = InlineCodeFontFamily ?? FontFamily, Foreground = InlineCodeForeground ?? Foreground }; // Additional formatting if (localContext.WithinItalics) { run.FontStyle = FontStyle.Italic; } if (localContext.WithinBold) { run.FontWeight = FontWeights.Bold; } // Add the fallback block localContext.InlineCollection.Add(run); } }
private void submitButton_Click(object sender, RoutedEventArgs e) { previewGrid.Visibility = System.Windows.Visibility.Hidden; resultsContainer.Visibility = Visibility.Visible; resultsTextBlock.Text = ""; submitButton.IsEnabled = false; var username = usernameInput.Text; var password = passwordInput.Password; var filePath = fileInput.Text; bool overwrite = chkOverwrite.IsChecked.Value; if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(filePath)) { MessageBox.Show("All fields must be populated."); return; } try { var backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += (s, e1) => { App.Current.Dispatcher.Invoke((Action) delegate { resultsTextBlock.Text = "Batch creating your sessions. This may take a few minutes, please be patient."; }); try { results = SetRecordingSchedules.Execute(username, password, filePath, string.Empty, overwrite); } catch (Exception ex) { log.Warn("An error occurred.", ex); MessageBox.Show("An error occurred. Details: " + ex.Message); } }; backgroundWorker.RunWorkerCompleted += (s, e2) => { App.Current.Dispatcher.Invoke((Action) delegate { resultsTextBlock.Text = string.Empty; if (results != null) { foreach (var result in results) { resultsTextBlock.Text += result.Result; resultsTextBlock.Text += "\r\n\r\n"; } resultsTextBlock.Text += string.Format("{0} out of {1} recordings were scheduled.", results.Count(r => r.Success), results.Count()); resultsTextBlock.Text += "\r\n\r\n"; var targetServername = ConfigurationManager.AppSettings["TargetServerName"]; if (targetServername != null) { Uri targetServerUri = new Uri(targetServername); Uri scheduleListUri = new Uri(targetServerUri, SCHEDULE_LIST_PATH); Run scheduleListUrl = new Run("Scheduled Recording List"); Hyperlink scheduleHyperlink = new Hyperlink(scheduleListUrl) { NavigateUri = scheduleListUri }; scheduleHyperlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(Hyperlink_RequestNavigate); resultsTextBlock.Inlines.Add(scheduleHyperlink); } } else { log.Warn("Unable to process file"); MessageBox.Show("Unable to process file"); } submitButton.IsEnabled = true; }); }; backgroundWorker.RunWorkerAsync(); } catch (Exception ex) { log.Warn(ex); MessageBox.Show(string.Format("An error has occurred. Details: {0}", ex.Message)); submitButton.IsEnabled = true; } }
public static void Main() { Run test = new Run(); test.SerializeOrder("TypeEx.xml"); }
public void Writer(Document doc) { DocumentBuilder builder = new DocumentBuilder(doc); if (AutoSummaryRecord == null) { AutoSummaryRecord = new AutoSummaryRecord(); } XmlElement summary = (AutoSummaryRecord != null && AutoSummaryRecord.MoralScore != null) ? AutoSummaryRecord.MoralScore.Summary : K12.Data.XmlHelper.LoadXml("<Summary/>"); XmlElement textScore = (AutoSummaryRecord != null && AutoSummaryRecord.MoralScore != null) ? AutoSummaryRecord.MoralScore.TextScore : K12.Data.XmlHelper.LoadXml("<TextScore/>"); double width; double miniUnitWitdh; Table table; Font font; #region 處理日常生活表現評量的名稱 /* 日常生活表現評量的名稱key: * 日常行為表現 * 其它表現 * 日常生活表現具體建議 * 團體活動表現 * 公共服務表現 * 校內外特殊表現 */ if (builder.MoveToMergeField("日常行為表現名稱")) { builder.Write(GetDLString("日常行為表現")); } if (Global.Params["Mode"] == "KaoHsiung") { #region 高雄 if (builder.MoveToMergeField("團體活動表現名稱")) { builder.Write(GetDLString("團體活動表現")); } if (builder.MoveToMergeField("公共服務表現名稱")) { builder.Write(GetDLString("公共服務表現")); } if (builder.MoveToMergeField("校內外特殊表現名稱")) { builder.Write(GetDLString("校內外特殊表現")); } if (builder.MoveToMergeField("日常生活表現具體建議名稱")) { builder.Write(GetDLString("日常生活表現具體建議")); } #endregion } else { #region 新竹 if (builder.MoveToMergeField("其他表現名稱")) { builder.Write(GetDLString("其它表現")); } if (builder.MoveToMergeField("綜合評語名稱")) { builder.Write(GetDLString("綜合評語")); } #endregion } #endregion #region 日常生活表現 // <DailyBehavior Name="日常行為表現"> // <Item Degree="大部份符合" Index="抽屜乾淨" Name="愛整潔"/> // <Item Degree="尚再努力" Index="懂得向老師,學長敬禮" Name="有禮貌"/> // <Item Degree="大部份符合" Index="自習時間能夠安靜自習" Name="守秩序"/> // <Item Degree="尚再努力" Index="打掃時間,徹底整理自己打掃範圍" Name="責任心"/> // <Item Degree="需再努力" Index="不亂丟垃圾" Name="公德心"/> // <Item Degree="大部份符合" Index="懂得關心同學朋友" Name="友愛關懷"/> // <Item Degree="大部份符合" Index="團體活動能夠遵守相關規定" Name="團隊合作"/> // </DailyBehavior> if (builder.MoveToMergeField("日常行為")) { font = builder.Font; Cell dailyBehaviorCell = builder.CurrentParagraph.ParentNode as Cell; if (Global.DLBehaviorConfigItemNameDict.ContainsKey("日常行為表現")) { foreach (string itemName in Global.DLBehaviorConfigItemNameDict["日常行為表現"]) { WordHelper.Write(dailyBehaviorCell, font, itemName); bool hasDegree = false; foreach (XmlElement item in textScore.SelectNodes("DailyBehavior/Item")) { string Name = item.GetAttribute("Name"); // 有比對到 if (itemName == Name) { WordHelper.Write(dailyBehaviorCell.NextSibling as Cell, font, item.GetAttribute("Degree")); hasDegree = true; } } if (hasDegree == false) { WordHelper.Write(dailyBehaviorCell.NextSibling as Cell, font, ""); } dailyBehaviorCell = WordHelper.GetMoveDownCell(dailyBehaviorCell, 1); } } } if (Global.Params["Mode"] == "KaoHsiung") { #region 高雄 // <GroupActivity Name="團體活動表現"> // <Item Degree="表現良好" Description="社團" Name="社團活動"/> // <Item Degree="表現優異" Description="學校" Name="學校活動"/> // <Item Degree="有待改進" Description="自治" Name="自治活動"/> // <Item Degree="需在加油" Description="班級" Name="班級活動"/> // </GroupActivity> if (builder.MoveToMergeField("團體活動")) { font = builder.Font; Cell groupActivityCell = builder.CurrentParagraph.ParentNode as Cell; groupActivityCell.Paragraphs.RemoveAt(0); if (Global.DLBehaviorConfigItemNameDict.ContainsKey("團體活動表現")) { foreach (string itemName in Global.DLBehaviorConfigItemNameDict["團體活動表現"]) { groupActivityCell.Paragraphs.Add(new Paragraph(doc)); Run run1 = new Run(doc); run1.Font.Name = font.Name; run1.Font.Size = font.Size; run1.Font.Bold = true; run1.Text = itemName + ":"; groupActivityCell.LastParagraph.Runs.Add(run1); Run run2 = new Run(doc); run2.Font.Name = font.Name; run2.Font.Size = font.Size; Run run3h = new Run(doc); Run run3 = new Run(doc); foreach (XmlElement item in textScore.SelectNodes("GroupActivity/Item")) { if (itemName == item.GetAttribute("Name")) { // 是否有文字描述 bool hasText = false; if (!string.IsNullOrEmpty(item.GetAttribute("Description"))) { hasText = true; } if (string.IsNullOrEmpty(item.GetAttribute("Degree"))) { run2.Text = item.GetAttribute("Degree"); } else { run2.Text = item.GetAttribute("Degree") + "。"; } if (hasText) { run3h.Font.Name = font.Name; run3h.Font.Size = font.Size; run3h.Font.Bold = true; run3h.Text = item.GetAttribute("Name") + ":"; run3.Font.Name = font.Name; run3.Font.Size = font.Size; run3.Text = item.GetAttribute("Description") + "。"; } else { run3h.Font.Name = font.Name; run3h.Font.Size = font.Size; run3h.Text = ""; run3.Font.Name = font.Name; run3.Font.Size = font.Size; run3.Text = ""; } } } groupActivityCell.LastParagraph.Runs.Add(run2); groupActivityCell.LastParagraph.Runs.Add(run3h); groupActivityCell.LastParagraph.Runs.Add(run3); } } } // <PublicService Name="公共服務表現"> // <Item Description="校內" Name="校內服務"/> // <Item Description="社區" Name="社區服務"/> // </PublicService> if (builder.MoveToMergeField("公共服務")) { font = builder.Font; Cell publicServiceCell = builder.CurrentParagraph.ParentNode as Cell; publicServiceCell.Paragraphs.Clear(); if (Global.DLBehaviorConfigItemNameDict.ContainsKey("公共服務表現")) { foreach (string itemName in Global.DLBehaviorConfigItemNameDict["公共服務表現"]) { publicServiceCell.Paragraphs.Add(new Paragraph(doc)); Run run1 = new Run(doc); run1.Font.Name = font.Name; run1.Font.Size = font.Size; run1.Font.Bold = true; run1.Text = itemName + ":"; bool hasDescription = false; publicServiceCell.LastParagraph.Runs.Add(run1); foreach (XmlElement item in textScore.SelectNodes("PublicService/Item")) { if (itemName == item.GetAttribute("Name")) { Run run2 = new Run(doc); run2.Font.Name = font.Name; run2.Font.Size = font.Size; run2.Text = item.GetAttribute("Description"); publicServiceCell.LastParagraph.Runs.Add(run2); hasDescription = true; } } if (hasDescription == false) { Run run2 = new Run(doc); run2.Font.Name = font.Name; run2.Font.Size = font.Size; run2.Text = ""; publicServiceCell.LastParagraph.Runs.Add(run2); } } } } // <SchoolSpecial Name="校內外特殊表現"> // <Item Description="這麼特殊" Name="校外特殊表現"/> // <Item Description="又是校內" Name="校內特殊表現"/> // </SchoolSpecial> if (builder.MoveToMergeField("校內外特殊")) { font = builder.Font; Cell schoolSpecialCell = builder.CurrentParagraph.ParentNode as Cell; schoolSpecialCell.Paragraphs.Clear(); if (Global.DLBehaviorConfigItemNameDict.ContainsKey("校內外特殊表現")) { foreach (string itemName in Global.DLBehaviorConfigItemNameDict["校內外特殊表現"]) { schoolSpecialCell.Paragraphs.Add(new Paragraph(doc)); Run run1 = new Run(doc); run1.Font.Name = font.Name; run1.Font.Size = font.Size; run1.Font.Bold = true; run1.Text = itemName + ":"; schoolSpecialCell.LastParagraph.Runs.Add(run1); bool hasDescription = false; foreach (XmlElement item in textScore.SelectNodes("SchoolSpecial/Item")) { if (itemName == item.GetAttribute("Name")) { Run run2 = new Run(doc); run2.Font.Name = font.Name; run2.Font.Size = font.Size; run2.Text = item.GetAttribute("Description"); schoolSpecialCell.LastParagraph.Runs.Add(run2); hasDescription = true; } } if (hasDescription == false) { Run run2 = new Run(doc); run2.Font.Name = font.Name; run2.Font.Size = font.Size; run2.Text = ""; schoolSpecialCell.LastParagraph.Runs.Add(run2); } } } } // <DailyLifeRecommend Description="我錯了" Name="日常生活表現具體建議"/> if (builder.MoveToMergeField("具體建議")) { font = builder.Font; Cell dailyLifeRecommendCell = builder.CurrentParagraph.ParentNode as Cell; XmlElement dailyLifeRecommend = (XmlElement)textScore.SelectSingleNode("DailyLifeRecommend"); string dailyLifeRecommendValue = string.Empty; if (dailyLifeRecommend != null) { dailyLifeRecommendValue = dailyLifeRecommend.GetAttribute("Description"); } dailyLifeRecommendCell.Paragraphs.Clear(); dailyLifeRecommendCell.Paragraphs.Add(new Paragraph(doc)); Run run = new Run(doc); run.Font.Name = font.Name; run.Font.Size = font.Size; run.Text = dailyLifeRecommendValue; dailyLifeRecommendCell.LastParagraph.Runs.Add(run); } #endregion } else { #region 新竹 if (builder.MoveToMergeField("其他表現")) { font = builder.Font; Cell otherRecommendCell = builder.CurrentParagraph.ParentNode as Cell; XmlElement otherRecommend = (XmlElement)textScore.SelectSingleNode("OtherRecommend"); string otherRecommendValue = string.Empty; if (otherRecommend != null) { otherRecommendValue = otherRecommend.GetAttribute("Description"); } otherRecommendCell.Paragraphs.Clear(); otherRecommendCell.Paragraphs.Add(new Paragraph(doc)); Run otherRecommendRun = new Run(doc); otherRecommendRun.Font.Name = font.Name; otherRecommendRun.Font.Size = font.Size; otherRecommendRun.Text = otherRecommendValue; otherRecommendCell.LastParagraph.Runs.Add(otherRecommendRun); } if (builder.MoveToMergeField("綜合評語")) { font = builder.Font; Cell dailyLifeRecommendCell = builder.CurrentParagraph.ParentNode as Cell; XmlElement dailyLifeRecommend = (XmlElement)textScore.SelectSingleNode("DailyLifeRecommend"); string dailyLifeRecommendValue = string.Empty; if (dailyLifeRecommend != null) { dailyLifeRecommendValue = dailyLifeRecommend.GetAttribute("Description"); } dailyLifeRecommendCell.Paragraphs.Clear(); dailyLifeRecommendCell.Paragraphs.Add(new Paragraph(doc)); Run dailyLifeRecommendRun = new Run(doc); dailyLifeRecommendRun.Font.Name = font.Name; dailyLifeRecommendRun.Font.Size = font.Size; dailyLifeRecommendRun.Text = dailyLifeRecommendValue; dailyLifeRecommendCell.LastParagraph.Runs.Add(dailyLifeRecommendRun); } #endregion } #endregion #region 缺曠 //<AttendanceStatistics> // <Absence Count="4" Name="公假" PeriodType="一般"/> // <Absence Count="4" Name="曠課" PeriodType="一般"/> // <Absence Count="4" Name="凹假" PeriodType="一般"/> //</AttendanceStatistics> builder.MoveToMergeField("缺曠"); if (_types.Count > 0) { Dictionary <string, string> attendance = new Dictionary <string, string>(); foreach (AbsenceCountRecord absence in AutoSummaryRecord.AbsenceCounts) { string key = GetKey(absence.PeriodType, absence.Name); if (!attendance.ContainsKey(key)) { attendance.Add(key, "" + absence.Count); } } double total = 0; foreach (List <string> list in _types.Values) { total += list.Count; } Cell attendanceCell = builder.CurrentParagraph.ParentNode as Cell; width = attendanceCell.CellFormat.Width; miniUnitWitdh = width / total; table = builder.StartTable(); builder.RowFormat.HeightRule = HeightRule.Exactly; builder.RowFormat.Height = 17.5; foreach (string type in _types.Keys) { builder.InsertCell().CellFormat.Width = miniUnitWitdh * _types[type].Count; builder.Write(type); } builder.EndRow(); foreach (string type in _types.Keys) { foreach (string item in _types[type]) { builder.InsertCell().CellFormat.Width = miniUnitWitdh; builder.Write(item); } } builder.EndRow(); foreach (string type in _types.Keys) { foreach (string item in _types[type]) { builder.InsertCell().CellFormat.Width = miniUnitWitdh; string key = GetKey(type, item); string value = attendance.ContainsKey(key) ? attendance[key] : "0"; builder.Write(value); } } builder.EndRow(); builder.EndTable(); //去除表格四邊的線 foreach (Cell c in table.FirstRow.Cells) { c.CellFormat.Borders.Top.LineStyle = LineStyle.None; } foreach (Cell c in table.LastRow.Cells) { c.CellFormat.Borders.Bottom.LineStyle = LineStyle.None; } foreach (Row r in table.Rows) { r.FirstCell.CellFormat.Borders.Left.LineStyle = LineStyle.None; r.LastCell.CellFormat.Borders.Right.LineStyle = LineStyle.None; } } #endregion #region 獎懲 //<DisciplineStatistics> // <Merit A="1" B="0" C="0"/> // <Demerit A="12" B="12" C="14"/> //</DisciplineStatistics> Dictionary <string, string> discipline = new Dictionary <string, string>(); discipline.Add("大功", "" + AutoSummaryRecord.MeritA); discipline.Add("小功", "" + AutoSummaryRecord.MeritB); discipline.Add("嘉獎", "" + AutoSummaryRecord.MeritC); discipline.Add("大過", "" + AutoSummaryRecord.DemeritA); discipline.Add("小過", "" + AutoSummaryRecord.DemeritB); discipline.Add("警告", "" + AutoSummaryRecord.DemeritC); builder.MoveToMergeField("獎懲"); Cell disciplineCell = builder.CurrentParagraph.ParentNode as Cell; width = disciplineCell.CellFormat.Width; miniUnitWitdh = width / 6f; table = builder.StartTable(); builder.RowFormat.HeightRule = HeightRule.Exactly; builder.RowFormat.Height = 17.5; foreach (string key in discipline.Keys) { builder.InsertCell().CellFormat.Width = miniUnitWitdh; builder.Write(key); } builder.EndRow(); foreach (string key in discipline.Keys) { builder.InsertCell().CellFormat.Width = miniUnitWitdh; string value = string.IsNullOrEmpty(discipline[key]) ? "0" : discipline[key]; builder.Write(value); } builder.EndRow(); builder.EndTable(); //去除表格四邊的線 foreach (Cell c in table.FirstRow.Cells) { c.CellFormat.Borders.Top.LineStyle = LineStyle.None; } foreach (Cell c in table.LastRow.Cells) { c.CellFormat.Borders.Bottom.LineStyle = LineStyle.None; } foreach (Row r in table.Rows) { r.FirstCell.CellFormat.Borders.Left.LineStyle = LineStyle.None; r.LastCell.CellFormat.Borders.Right.LineStyle = LineStyle.None; } #endregion }
internal void UnsafeAddAfter(Run after, Run run) { run.SetLinkNode(_runs.AddAfter(GetLineLinkNode(after), run), this); }