예제 #1
0
 public static Section AddPageBreak(this FlowDocument flowDoc)
 {
     Section section = new Section();
     section.BreakPageBefore = true;
     flowDoc.Blocks.Add(section);
     return section;
 }
        /// <summary>
        /// Creates the specified exception to convert.
        /// </summary>
        /// <param name="exceptionToConvert">The exception to convert.</param>
        /// <returns><see cref="FlowDocument"/> that describe the exception</returns>
        internal static FlowDocument Create(Exception exceptionToConvert)
        {
            Paragraph paraTitle = new Paragraph(new Bold(new Run("Error occurred")));
            paraTitle.FontSize = 16;
            paraTitle.Foreground = System.Windows.SystemColors.HighlightBrush;

            Paragraph paraLineBreak = new Paragraph(new LineBreak());

            Section errorInfoSection = new Section();

            Paragraph paraErrorInfo = new Paragraph(new Run(exceptionToConvert.ToString()));
            paraErrorInfo.TextIndent = 20;

            errorInfoSection.Blocks.Add(paraErrorInfo);

            if (exceptionToConvert.InnerException != null)
            {
                Paragraph paraInnerException = new Paragraph(new Run(exceptionToConvert.InnerException.ToString()));
                paraInnerException.TextIndent = 40;
                errorInfoSection.Blocks.Add(paraInnerException);
            }

            FlowDocument mainDocument = new FlowDocument();
            mainDocument.Blocks.Add(paraTitle);
            mainDocument.Blocks.Add(paraLineBreak);
            mainDocument.Blocks.Add(errorInfoSection);

            return mainDocument;
        }
예제 #3
0
        public static FileTransferControl AddNewFileTransfer(this FlowDocument doc, Tox tox, FileTransfer transfer)
        {
            var fileTableCell = new TableCell();
            var fileTransferControl = new FileTransferControl(transfer, fileTableCell);

            var usernameParagraph = new Section();
            var newTableRow = new TableRow();
            newTableRow.Tag = transfer;

            var fileTransferContainer = new BlockUIContainer();
            fileTransferControl.HorizontalAlignment = HorizontalAlignment.Stretch;
            fileTransferControl.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            fileTransferContainer.Child = fileTransferControl;

            usernameParagraph.Blocks.Add(fileTransferContainer);
            usernameParagraph.Padding = new Thickness(0);

            fileTableCell.ColumnSpan = 3;
            fileTableCell.Blocks.Add(usernameParagraph);
            newTableRow.Cells.Add(fileTableCell);
            fileTableCell.Padding = new Thickness(0, 10, 0, 10);

            var MessageRows = (TableRowGroup)doc.FindName("MessageRows");
            MessageRows.Rows.Add(newTableRow);

            return fileTransferControl;
        }
예제 #4
0
        public static FileTransfer AddNewFileTransfer(this FlowDocument doc, Tox tox, int friendnumber, int filenumber, string filename, ulong filesize, bool is_sender)
        {
            FileTransferControl fileTransferControl = new FileTransferControl(tox.GetName(friendnumber), friendnumber, filenumber, filename, filesize);
            FileTransfer transfer = new FileTransfer() { FriendNumber = friendnumber, FileNumber = filenumber, FileName = filename, FileSize = filesize, IsSender = is_sender, Control = fileTransferControl };

            Section usernameParagraph = new Section();
            TableRow newTableRow = new TableRow();

            BlockUIContainer fileTransferContainer = new BlockUIContainer();
            fileTransferControl.HorizontalAlignment = HorizontalAlignment.Stretch;
            fileTransferControl.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            fileTransferContainer.Child = fileTransferControl;

            usernameParagraph.Blocks.Add(fileTransferContainer);
            usernameParagraph.Padding = new Thickness(0);

            TableCell fileTableCell = new TableCell();
            fileTableCell.ColumnSpan = 2;
            fileTableCell.Blocks.Add(usernameParagraph);
            newTableRow.Cells.Add(fileTableCell);
            fileTableCell.Padding = new Thickness(0, 10, 0, 10);

            TableRowGroup MessageRows = (TableRowGroup)doc.FindName("MessageRows");
            MessageRows.Rows.Add(newTableRow);

            return transfer;
        }
예제 #5
0
 public FlowDocumentBasis (String HeadLineParameter, Section ElementSectionParameter)
     {
     ElementSection = ElementSectionParameter;
     HeadLine = HeadLineParameter;
     LogicalElementType = DocumentPrintOut.ElementType.ContentLevel1;
     ElementParagraph = new Paragraph(new Run(HeadLine ));
     }
        //
        // A good overview over the various classes for the
        // WPF flowdocument can be found here:
        //
        // http://msdn.microsoft.com/en-us/library/aa970909.aspx
        //

        Section RenderBox(Element element)
        {
            var box = new Section();
            Render(element, box);
            FlushBuffer(box.Blocks);
            return box;
        }
        protected override TextElement CreateChildElement()
        {
            var section = new Section(new Paragraph(new Run(string.Empty)));

            Volume.Blocks.Add(section);

            return section;
        }
 private static void SetHyperlinksHandler(Section doc)
 {
     foreach (Paragraph p in doc.Blocks.OfType<Paragraph>())
     {
         foreach (Inline inline in p.Inlines)
             LookupHyperlinks(inline);
     }
 }
예제 #9
0
		private void AddSection(Section section)
		{
			var splitTableSection = (SplitTable)_splitTable;
			section.FontSize = splitTableSection.FontSize;
			section.FontWeight = splitTableSection.FontWeight;
			section.TextAlignment = splitTableSection.TextAlignment;
			_flowDocument.Blocks.InsertAfter(_lastSection, section);
			_lastSection = section;
		}
        public Block BuildDocument(int indentation)
        {
            Section s = new Section();
            s.Blocks.Add(new Paragraph(new Run("{")));
            s.Blocks.Add(Body.BuildDocument(indentation));
            s.Blocks.Add(new Paragraph(new Run("}")));

            return s;
        }
예제 #11
0
 protected override Block BuildDocumentInternal()
 {
     var section = new Section();
     foreach (var element in children)
     {
         var inline = element as XInline;
         section.Blocks.Add(inline != null
             ? new Paragraph(inline.BuildElement())
             : ((XBlock) element).BuildDocument());
     }
     return section;
 }
        public Block BuildDocument(int indentation)
        {
            Paragraph p = new Paragraph();
            p.Inlines.Add(new Run("repeat") { Foreground = StyleSettings.KeyWordColor });
            p.Inlines.Add(" (");
            p.Inlines.AddRange(Expression.BuildDocument());
            p.Inlines.Add(")");

            Section s = new Section() { Margin = new Thickness(indentation, 0, 0, 0) };
            s.Blocks.Add(p);
            s.Blocks.Add(Body.BuildDocument(indentation));

            return s;
        }
예제 #13
0
파일: BLRecipes.cs 프로젝트: msilo/IIO11300
    public static FlowDocument PrintRecipe(Recipe r)
    {
      // Before printing check that all fields are valid
      if (r.Name == String.Empty || r.Time == String.Empty || r.Instructions == String.Empty || r.Writer == String.Empty)
      {
        throw new Exception("Reseptissä ei voi olla tyhjiä kenttiä!");
      }
      // If all fields are valid print the recipe
      else
      {
        // Create a FlowDocument
        FlowDocument doc = new FlowDocument();

        // Create a Section
        Section sec = new Section();
        Section sec2 = new Section();

        // Create first Paragraph
        Paragraph p1 = new Paragraph();
        Paragraph p2 = new Paragraph();

        // Create and add a new Bold, Italic and Underline
        Bold bld = new Bold();
        bld.Inlines.Add(new Run(r.Name));
        Italic italicBld = new Italic();
        italicBld.Inlines.Add(bld);
        Underline underlineItalicBld = new Underline();
        underlineItalicBld.Inlines.Add(italicBld);

        // Add Bold, Italic, Underline to Paragraph
        p1.Inlines.Add(underlineItalicBld);
        p1.Inlines.Add(new Run("\n" + r.Time));
        p1.Inlines.Add(new Run("\n" + r.Writer));

        p2.Inlines.Add(new Run(r.Instructions));

        // Add Paragraph to Section
        sec.Blocks.Add(p1);
        sec2.Blocks.Add(p2);

        // Add Section to FlowDocument
        doc.Blocks.Add(sec);
        doc.Blocks.Add(sec2);

        return doc;
      }
    }
예제 #14
0
        private static void WriteEnumerable(BlockCollection blocks, HashSet<object> objects, IEnumerable enumerable)
        {
            //var list = new List();
            //foreach (var item in enumerable)
            //{
            //    var listItem = new ListItem();
            //    WriteProperties(listItem.Blocks, objects, item);
            //    list.ListItems.Add(listItem);
            //}
            //blocks.Add(list);

            foreach (var e in enumerable)
            {
                var section = new Section { TextAlignment = TextAlignment.Left };
                WriteProperties(section.Blocks, objects, e);
                blocks.Add(section);
            }
        }
        public IBlockFormatter Text(string text)
        {
            string[] lines = text.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

            var section = new Section();

            foreach (var line in lines)
            {
                var paragraph = new Paragraph(new Run(line));
                paragraph.TextAlignment = TextAlignment.Justify;
                paragraph.FontSize = 14;
                paragraph.LineHeight = 20;
                paragraph.TextIndent = 10;
                section.Blocks.Add(paragraph);
            }

            return new RelayBlockFormatter(_ => section);
        }
예제 #16
0
        public void ConvertHTML(string htmlString)
        {
          //  string NEW_LINE = Environment.NewLine;

            //htmlString.Replace()
            htmlMain = HtmlParser.ParseHtml(htmlString);
            CssStylesheet stylesheet = new CssStylesheet(htmlMain);
            // Source context is a stack of all elements - ancestors of a parentElement
            List<XmlElement> sourceContext = new List<XmlElement>(10);


            Block b =  AddBlock(htmlMain, new Hashtable(), stylesheet);

            if(b is Section)
            {
                master = (Section)b;
            }
            master = new Section();
            master.Blocks.Add(b);
        }
예제 #17
0
        internal static Section GetParagraphWithFigures(Paragraph figure1, Section figure2)
        {
            MemoryStream ms = new MemoryStream();
            StreamWriter writer = new StreamWriter(ms);
            writer.Write("<Section xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">");
            writer.Write("<Paragraph><Figure VerticalAnchor=\"PageTop\" HorizontalAnchor=\"PageLeft\" Margin=\"0,0,0,0\" Padding=\"0,0,0,0\">");
            writer.Write("<Paragraph Margin=\"0,0,0,0\">ПИЗДЕЦ</Paragraph>");
            writer.Write("</Figure><Figure VerticalAnchor=\"PageTop\" HorizontalAnchor=\"PageLeft\" Margin=\"0,0,0,0\" Padding=\"0,0,0,0\">");
            writer.Write("<Paragraph Margin=\"0,0,0,0\">ПИЗДЕЦ 2</Paragraph>");
            writer.Write("</Figure></Paragraph></Section>");
            writer.Flush();
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            settings.CheckCharacters = false;

            XmlReader reader = XmlReader.Create(ms, settings);
            return XamlReader.Load(reader) as Section;
        }
        public static Section Convert(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                Section section = null;
                try
                {
                    string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(BbCodesToHtmlConverter.BbCodesToHtml(value),
                                                                        false);
                    section = XamlReader.Parse(xaml) as Section;
                    CommonHelper.Try(() => SetHyperlinksHandler(section));
                }
                catch
                {
                    section = new Section(new Paragraph(new Run(value)));
                }

                return section;
            }
            return new Section(new Paragraph(new Run(value)));
        }
예제 #19
0
        public void AddAmendmentLine1(string textValue)
        {
            Paragraph paragraph = new Paragraph(new Run(textValue));
            paragraph.Margin = new Thickness(10, 0, 0, 0);
            paragraph.FontSize = (double)m_FontSizeConverter.ConvertFromString("8pt");
            paragraph.FontFamily = new FontFamily("Verdana");
            paragraph.TextAlignment = TextAlignment.Left;

            Section section = new Section(paragraph);
            section.Margin = new Thickness(0, 1, 0, 0);
            section.BorderBrush = Brushes.Black;
            section.BorderThickness = new Thickness(0, 1, 0, 0);

            TableCell cell = new TableCell(section);
            cell.ColumnSpan = 3;
            cell.BorderBrush = Brushes.Black;
            cell.BorderThickness = new Thickness(0, 2, 0, 0);

            TableRow row = new TableRow();
            row.Cells.Add(cell);

            this.m_MoneyBoxTable.RowGroups[0].Rows.Add(row);
        }
예제 #20
0
		public void FillTable()
		{
			var splitTableSection = _splitTable as SplitTable;
			if (splitTableSection == null)
				return;
			_flowDocument = splitTableSection.Parent as FlowDocument;
			if (_flowDocument == null)
				throw new InvalidDataException("SplitTable must have FlowDocument as parent");
			_lastSection = splitTableSection;
			if (_splitTable.PageBreakBefore)
				AddSection(new Section() { BreakPageBefore = true });
			if (_splitTable.Header != null)
				AddSection(_splitTable.Header);

			FillTableInternal();

			if (_splitTable.Footer != null)
				AddSection(_splitTable.Footer);
			if (_splitTable.PageBreakAfter)
				AddSection(new Section() { BreakPageBefore = true });
			_flowDocument.Blocks.Remove(splitTableSection);
			_lastSection = null;
			_flowDocument = null;
		}
예제 #21
0
        public void AddMsgToOutputBox(IMMessage imMessage, string senderName, AddMsgToOutputBoxCallBackHandler callBack)
        {
            this.CheckMsgPiece();
            InputBox box = this;
            MessagePack messagePack = imMessage.MessagePack;
            if (messagePack != null)
            {
                if (messagePack.NeedShowHeader && (imMessage.Sender == null))
                {
                    messagePack.NeedShowHeader = false;
                }
                if (messagePack.NeedShowHeader && string.IsNullOrEmpty(senderName))
                {
                    senderName = imMessage.SenderName;
                    if (string.IsNullOrEmpty(senderName))
                    {
                        senderName = imMessage.Sender.NickName;
                    }
                }
                uint elemCount = messagePack.GetElemCount();
                Section newItem = new Section();
                Block lastBlock = box.Document.Blocks.LastBlock;
                if ((lastBlock != null) && (string.Compare(lastBlock.Tag as string, "LastTag") != 0))
                {
                    lastBlock = null;
                }
                if (lastBlock == null)
                {
                    Paragraph paragraph = new Paragraph
                    {
                        Tag = "LastTag",
                        Margin = new Thickness(0.0)
                    };
                    lastBlock = paragraph;
                    box.Document.Blocks.Add(lastBlock);
                }
                if (messagePack.NeedShowHeader)
                {
                    if ((imMessage.Sender != null) && (imMessage.Sender.Uin == Util_Buddy.GetCurrentBuddy().Uin))
                    {
                        newItem.Tag = "me";
                    }
                    else
                    {
                        newItem.Tag = "other";
                    }
                }
                else
                {
                    newItem.Tag = "info";
                }
                box.Document.Blocks.InsertBefore(lastBlock, newItem);
                Paragraph item = new Paragraph();
                if (messagePack.NeedShowHeader)
                {
                    string str;
                    Paragraph paragraph3 = new Paragraph
                    {
                        Foreground = new SolidColorBrush((imMessage.Sender.Uin == Util_Buddy.GetCurrentBuddy().Uin) ? this._selfColor : this._oppColor)
                    };
                    if (this.IsMsgRecord)
                    {
                        str = senderName + "  " + imMessage.DateTime.ToLocalTime().ToString();
                    }
                    else
                    {
                        str = senderName + "  " + imMessage.DateTime.ToLocalTime().ToLongTimeString();
                        item.Margin = new Thickness(13.0, 0.0, 0.0, 0.0);
                    }
                    paragraph3.Inlines.Add(str);
                    newItem.Blocks.Add(paragraph3);
                }
                SetDateTime(newItem, imMessage.DateTime);
                Paragraph paragraph4 = new Paragraph
                {
                    Margin = new Thickness(13.0, 0.0, 0.0, 0.0)
                };
                string fontName = messagePack.Header.FontName;
                if ((string.IsNullOrEmpty(fontName) || (fontName == "宋体")) || (((fontName == "新宋体") || (fontName == "仿宋")) || (fontName == "黑体")))
                {
                    fontName = "Microsoft YaHei";
                }
                if (messagePack.Header.FontSize == 0)
                {
                    messagePack.Header.FontSize = 9;
                }
                item.FontFamily = new FontFamily(fontName);
                item.FontSize = messagePack.Header.FontSize + 3;
                item.Foreground = new SolidColorBrush(messagePack.Header.FontColor);
                paragraph4.FontFamily = new FontFamily(messagePack.Header.FontName);
                paragraph4.FontSize = messagePack.Header.FontSize + 3;
                paragraph4.Foreground = new SolidColorBrush(messagePack.Header.FontColor);
                Dictionary<string, bool> imagelist = new Dictionary<string, bool>();
                Paragraph paragraph5 = item;
                bool flag = false;
                for (uint i = 0; i < elemCount; i++)
                {
                    ImageElement element4;
                    string path;
                    ImageEx ex2;
                    MessageElement elem = messagePack.GetElem(i);
                    switch (elem.Category)
                    {
                        case MsgPackCat.ELEMTYPE_TEXT:
                            {
                                Guid guid;
                                Guid guid2;
                                TextElement element2 = (TextElement)elem;
                                string text = element2.GetText();
                                if (!flag && element2.NeedIndent)
                                {
                                    Span lastInline = item.Inlines.LastInline as Span;
                                    if (lastInline != null)
                                    {
                                        Run run = lastInline.Inlines.LastInline as Run;
                                        if (run != null)
                                        {
                                            run.Text = run.Text.Replace("\r", "").Replace("\n", "");
                                        }
                                    }
                                    paragraph5 = paragraph4;
                                }
                                string url = element2.GetUrl(out guid, out guid2);
                                Span span2 = new Span();
                                Span span3 = span2;
                                paragraph5.Inlines.Add(span3);
                                if ((messagePack.Header.FontEffect & 2) != 0)
                                {
                                    span2.FontStyle = FontStyles.Italic;
                                }
                                if ((messagePack.Header.FontEffect & 1) != 0)
                                {
                                    span2.FontWeight = FontWeights.Bold;
                                }
                                if (string.IsNullOrEmpty(url))
                                {
                                    if ((messagePack.Header.FontEffect & 4) != 0)
                                    {
                                        Underline underline = new Underline();
                                        span2.Inlines.Add(underline);
                                        span2 = underline;
                                    }
                                    span2.Inlines.Add(text);
                                }
                                else
                                {
                                    ImageHyperlink hyperlink = new ImageHyperlink
                                    {
                                        Guid = guid,
                                        SoureUrl = url
                                    };
                                    span2.Inlines.Add(hyperlink);
                                    span2 = hyperlink;
                                    hyperlink.AddText(text);
                                    this.OnImageHyperLinkAdd(imMessage, hyperlink);
                                }
                                continue;
                            }
                        case MsgPackCat.ELEMTYPE_SYSFACE:
                            {
                                SysFaceElement element = (SysFaceElement)elem;
                                ImageEx uiElement = ReplaceControls.CreateImageExWithId(element.FileName, element.Index.ToString());
                                uiElement.Width = element.FaceWidth;
                                uiElement.Height = element.FaceHeight;
                                paragraph5.Inlines.Add(uiElement);
                                if (callBack != null)
                                {
                                    callBack(imMessage, element);
                                }
                                continue;
                            }
                        case MsgPackCat.ELEMTYPE_IMAGE:
                        case MsgPackCat.ELEMTYPE_OFFLINEPIC:
                            element4 = (ImageElement)elem;
                            path = element4.Path;
                            if (string.IsNullOrEmpty(path))
                            {
                                continue;
                            }
                            ex2 = new ImageEx
                            {
                                HorizontalAlignment = HorizontalAlignment.Left,
                                VerticalAlignment = VerticalAlignment.Top,
                                Stretch = Stretch.None,
                                SnapsToDevicePixels = true,
                                Tag = element4
                            };
                            path = path.ToLower();
                            if (!CheckFileExists(imagelist, path))
                            {
                                break;
                            }
                            ex2.Source = path;
                            goto Label_0710;

                        case MsgPackCat.ELEMTYPE_FILE:
                            {
                                FileElement element5 = (FileElement)elem;
                                string str7 = Helper_Icon.MakeSysIconFileByFileName(element5.Path);
                                string fileSize = element5.GetFileSize();
                                string fileName = element5.GetFileName();
                                if (!string.IsNullOrEmpty(str7))
                                {
                                    ImageEx ex3 = new ImageEx
                                    {
                                        HorizontalAlignment = HorizontalAlignment.Left,
                                        VerticalAlignment = VerticalAlignment.Top,
                                        Stretch = Stretch.Uniform,
                                        SnapsToDevicePixels = true,
                                        Width = 32.0,
                                        Height = 32.0
                                    };
                                    if (!string.IsNullOrEmpty(element5.Tip))
                                    {
                                        ex3.ToolTip = element5.Tip;
                                    }
                                    ex3.Source = str7;
                                    StackPanel panel = new StackPanel
                                    {
                                        Margin = new Thickness(0.0, 2.0, 0.0, 2.0),
                                        Orientation = Orientation.Horizontal
                                    };
                                    panel.Children.Add(ex3);
                                    TextBlock block2 = new TextBlock(new Run(fileName + "\n" + fileSize))
                                    {
                                        Margin = new Thickness(0.0, 4.0, 0.0, 0.0)
                                    };
                                    panel.Children.Add(block2);
                                    paragraph5.Inlines.Add(panel);
                                }
                                continue;
                            }
                        default:
                            goto Label_087B;
                    }
                    if (this.IsMsgRecord)
                    {
                        ex2.Source = CoreMessenger.Instance.GetAppPath(KernelWrapper.APP_PATH_TYPE.APP_PATH_DATA) + "errorBmp.gif";
                    }
                    else if (MsgPackCat.ELEMTYPE_IMAGE == elem.Category)
                    {
                        TXLog.TXLogImage(string.Concat(new object[] { "收到图片文件需要下载:", element4.Id, "  ", path }));
                        ex2.Source = CoreMessenger.Instance.GetAppPath(KernelWrapper.APP_PATH_TYPE.APP_PATH_DATA) + "sendingBmp.gif";
                        this.AddToImagesDownloadingList(element4.Id, ex2);
                    }
                    else if (MsgPackCat.ELEMTYPE_OFFLINEPIC == elem.Category)
                    {
                        TXLog.TXLogImage(string.Concat(new object[] { "收到离线图片文件需要下载:", element4.Id, "  ", path }));
                        ex2.IsEnabledClick = true;
                        ex2.Source = CoreMessenger.Instance.GetAppPath(KernelWrapper.APP_PATH_TYPE.APP_PATH_DATA) + "OfflinepicManualGet.png";
                        ex2.ToolTip = "点击获取图片";
                        ex2.Cursor = Cursors.Hand;
                    }
                Label_0710:
                    paragraph5.Inlines.Add(ex2);
                    continue;
                Label_087B:
                    TXLog.TXLog3("Msg", "AIO 未处理的消息类型, ");
                }
                if (item.Inlines.Count > 0)
                {
                    newItem.Blocks.Add(item);
                }
                if (paragraph4.Inlines.Count > 0)
                {
                    newItem.Blocks.Add(paragraph4);
                }
                box.ScrollToEnd();
            }
        }
 public void InsertSections(BlockCollection blocks, int hdDepth)
 {
     var cur = blocks.FirstBlock;
     while (cur != null)
     {
         if (GetHeadingDepth(cur) >= hdDepth)
         {
             var sec = new Section();
             sec.BorderThickness = new Thickness(2);
             sec.BorderBrush = new SolidColorBrush(Colors.Gray);
             sec.Margin = new Thickness(5);
             blocks.InsertBefore(cur, sec);
             blocks.Remove(cur);
             sec.Blocks.Add(cur);
             cur = sec.NextBlock;
             while (cur != null)
             {
                 int depth = GetHeadingDepth(cur);
                 if (0<depth && depth <= hdDepth) break;
                 var next = cur.NextBlock;
                 blocks.Remove(cur);
                 sec.Blocks.Add(cur);
                 cur = next;
             }
             InsertSections(sec.Blocks, hdDepth + 1);
         }
         else
         {
             cur = cur.NextBlock;
         }
     }
 }
        /// <summary>
        /// Handle related topics elements
        /// </summary>
        /// <param name="props">The element properties</param>
        /// <remarks>If empty, the related topics section is omitted</remarks>
        private static void RelatedTopicsElement(ElementProperties props)
        {
            List<XElement> tasks = new List<XElement>(), reference = new List<XElement>(),
                concepts = new List<XElement>(), otherResources = new List<XElement>(),
                tokenContent = new List<XElement>();
            XElement token;
            XAttribute attribute;
            Guid topicId, href;
            string linkType;

            if(!props.ParseChildren || !props.Element.HasElements)
            {
                props.ParseChildren = props.ReturnToParent = false;
                return;
            }

            // All links are handled here
            props.ParseChildren = false;

            // A name is added here for use by autoOutline elements
            Section s = new Section { Name = ToElementName("seeAlsoSection") };
            props.Converter.AddToBlockContainer(s);

            // Add the section title
            Paragraph p = new Paragraph(new Run(NamedSectionTitles[props.Element.Name.LocalName]));
            s.Blocks.Add(p);
            p.SetResourceReference(Paragraph.StyleProperty, NamedStyle.Title);

            // Expand tokens first
            foreach(var link in props.Element.Nodes().OfType<XElement>().Where(n => n.Name.LocalName == "token"))
                if(props.Converter.Tokens.TryGetValue(link.Value.Trim(), out token))
                    tokenContent.AddRange(token.Nodes().OfType<XElement>());

            // Group the elements by type or topic ID
            foreach(var link in props.Element.Nodes().OfType<XElement>().Concat(tokenContent))
            {
                linkType = link.Name.LocalName;
                attribute = link.Attribute("topicType_id");

                if(attribute == null || !Guid.TryParse(attribute.Value, out topicId))
                    topicId = Guid.Empty;

                attribute = link.Attribute(xlink + "href");

                if(attribute == null || !Guid.TryParse(attribute.Value, out href))
                    href = Guid.Empty;

                if(href != Guid.Empty && (linkType == "link" || linkType == "legacyLink") && (
                  topicId == HowToId || topicId == WalkthroughId || topicId == SampleId ||
                  topicId == TroubleshootingId))
                {
                    tasks.Add(link);
                }
                else
                    if(linkType == "codeEntityReference" || ((linkType == "link" || linkType == "legacyLink") && (
                      href == Guid.Empty || topicId == ReferenceWithoutSyntaxId ||
                      topicId == ReferenceWithSyntaxId || topicId == XmlReferenceId ||
                      topicId == ErrorMessageId || topicId == UIReferenceId)))
                    {
                        reference.Add(link);
                    }
                    else
                        if(href != Guid.Empty && (linkType == "link" || linkType == "legacyLink") && (
                          topicId == ConceptualId || topicId == SdkTechnologyOverviewArchitectureId ||
                          topicId == SdkTechnologyOverviewCodeDirectoryId ||
                          topicId == SdkTechnologyOverviewScenariosId ||
                          topicId == SdkTechnologyOverviewTechnologySummaryId))
                            concepts.Add(link);
                        else
                            if(linkType == "externalLink" || ((linkType == "link" || linkType == "legacyLink") &&
                              href != Guid.Empty && (topicId == Guid.Empty || topicId == OrientationId ||
                              topicId == WhitePaperId || topicId == CodeEntityId || topicId == GlossaryId ||
                              topicId == SDKTechnologyOverviewOrientationId)))
                                otherResources.Add(link);
            }

            // Add each set
            AddRelatedTopicLinks(props.Converter, s, tasks, "Tasks");
            AddRelatedTopicLinks(props.Converter, s, reference, "Reference");
            AddRelatedTopicLinks(props.Converter, s, concepts, "Concepts");
            AddRelatedTopicLinks(props.Converter, s, otherResources, "Other Resources");
        }
        /// <summary>
        /// This is used to add the related topic links
        /// </summary>
        /// <param name="converter">The converter used to add the elements</param>
        /// <param name="s">The section used to contain the links</param>
        /// <param name="links">The list of links to add</param>
        /// <param name="sectionTitle">The section title</param>
        private static void AddRelatedTopicLinks(MamlToFlowDocumentConverter converter, Section s,
          List<XElement> links, string sectionTitle)
        {
            Paragraph p;
            bool isFirst = true;

            if(links.Count != 0)
            {
                p = new Paragraph(new Run(sectionTitle));
                s.Blocks.Add(p);
                p.SetResourceReference(Paragraph.StyleProperty, NamedStyle.RelatedTopicTitle);

                p = new Paragraph();
                s.Blocks.Add(p);
                p.SetResourceReference(Paragraph.StyleProperty, NamedStyle.NoTopMargin);

                foreach(var link in links)
                {
                    if(isFirst)
                        isFirst = false;
                    else
                        p.Inlines.Add(new LineBreak());

                    converter.ParseChildren(p, new[] { link });
                }
            }
        }
예제 #25
0
 public static Doc.Paragraph AddParagraph(this Doc.Section doc)
 {
     Doc.Paragraph paragraph = CreateParagraph();
     doc.Blocks.Add(paragraph);
     return(paragraph);
 }
예제 #26
0
        public Intro()
        {
            InitializeComponent();

            AdControl hypeMachineAd = new AdControl() { ApplicationId = "4d3667ee-44c1-494c-929d-5e661b011918", AdUnitId = "10019312" };
            LayoutRoot.Children.Add(hypeMachineAd);
            Grid.SetRow(hypeMachineAd, 1);

            Assets.Instance.Create("IntroBackground", new BitmapImage(new Uri("backgrounds/IntroBackground.png", UriKind.Relative)));
            Assets.Instance.Create("IntroBackgroundDark", new BitmapImage(new Uri("backgrounds/IntroBackgroundDark.png", UriKind.Relative)));

            if (((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible))
            {
                mainView.Background = new ImageBrush() { ImageSource = Assets.Instance.ReadBitmapImage("IntroBackgroundDark"), Stretch = Stretch.None };
                mainView.Foreground = new SolidColorBrush(Colors.White);
            }
            else
            {
                mainView.Background = new ImageBrush() { ImageSource = Assets.Instance.ReadBitmapImage("IntroBackground"), Stretch = Stretch.None };
                mainView.Foreground = new SolidColorBrush(Colors.Black);
            }

            Assets.Instance.Create("robot", new BitmapImage(new Uri("intro/robot.png", UriKind.Relative)));

            List<Entry> firstPageEntries = new List<Entry>()
            {
                new Entry("WHAT?", "hype machine is a simple app that lets you see which upcoming video games people are most excited about.", "robot"),
                new Entry("WHY?", "with new titles coming out all the time, it's important that we gamers work together to seperate the great from the 'OH GOD NO!'.", "robot"),
                new Entry("WHO?", "you! well, not only you, infact there are many other users for you to interact with... but you're our favorite!.", "robot")
            };
            Section firstPage = new Section("SUP NOOB!", "thanks for downloading.", firstPageEntries, (Color)Resources["PhoneForegroundColor"], (Color)Resources["PhoneBackgroundColor"], true);

            List<Entry> secondPageEntries = new List<Entry>()
            {
                new Entry("WHAT?", "hype machine is a simple app that lets you see which upcoming video games people are most excited about.", "robot"),
                new Entry("WHY?", "with new titles coming out all the time, it's important that we gamers work together to seperate the great from the 'OH GOD NO!'.", "robot"),
                new Entry("WHO?", "you! well, not only you, infact there are many other users for you to interact with... but you're our favorite!.", "robot")
            };
            Section secondPage = new Section("HYPE", "equivalent to 4 redbulls.", secondPageEntries, (Color)Resources["PhoneBackgroundColor"], (Color)Resources["PhoneForegroundColor"], false);

            List<Entry> thirdPageEntries = new List<Entry>()
            {
                new Entry("WHAT?", "hype machine is a simple app that lets you see which upcoming video games people are most excited about.", "robot"),
                new Entry("WHY?", "with new titles coming out all the time, it's important that we gamers work together to seperate the great from the 'OH GOD NO!'.", "robot"),
                new Entry("WHO?", "you! well, not only you, infact there are many other users for you to interact with... but you're our favorite!.", "robot")
            };
            Section thirdPage = new Section("AFTERMATH", "equivalent to 4 redbulls.", thirdPageEntries, (Color)Resources["PhoneForegroundColor"], (Color)Resources["PhoneBackgroundColor"], true);

            List<Entry> fourthPageEntries = new List<Entry>()
            {
                new Entry("WHAT?", "hype machine is a simple app that lets you see which upcoming video games people are most excited about.", "robot"),
                new Entry("WHY?", "with new titles coming out all the time, it's important that we gamers work together to seperate the great from the 'OH GOD NO!'.", "robot"),
                new Entry("WHO?", "you! well, not only you, infact there are many other users for you to interact with... but you're our favorite!.", "robot")
            };
            Section fourthPage = new Section("COMMENTS", "equivalent to 4 redbulls.", fourthPageEntries, (Color)Resources["PhoneBackgroundColor"], (Color)Resources["PhoneForegroundColor"], false);

            mainView.Items.Add(panoramaItemFromSection(firstPage));
            mainView.Items.Add(panoramaItemFromSection(secondPage));
            mainView.Items.Add(panoramaItemFromSection(thirdPage));
            mainView.Items.Add(panoramaItemFromSection(fourthPage));

            this.Loaded += new RoutedEventHandler(Intro_Loaded) ;
        }
예제 #27
0
		void AddSection(Inline title, Action addChildren)
		{
			var section = new Section();
			AddBlock(section);
			var oldBlockCollection = blockCollection;
			try {
				blockCollection = section.Blocks;
				inlineCollection = null;
				
				if (title != null)
					AddInline(new Bold(title));
				
				addChildren();
				FlushAddedText(false);
			} finally {
				blockCollection = oldBlockCollection;
				inlineCollection = null;
			}
		}
        internal static System.Windows.Documents.Section CreateContentControl(QuestionContent content, string prefix, System.Windows.Documents.Section paragraph, Response response)
        {
            System.Windows.Documents.Section rootSection = paragraph;
            if (rootSection == null)
            {
                rootSection = new System.Windows.Documents.Section();
            }

            if (content.ContentType == ContentType.Html ||
                content.ContentType == ContentType.FlowDocument)
            {
                string doc = string.Empty;
                if (content.ContentType == ContentType.Html)
                {
                    doc = HtmlToXamlConverter.ConvertHtmlToXaml(content.Content, true);
                }
                else
                {
                    doc = content.Content;
                }

                System.Windows.Documents.FlowDocument flowDocument = HtmlToXamlConverter.DeserializeFlowDocument(doc);

                replaceTextBoxWithText(flowDocument, content, null);

                List <Block> tempList = new List <Block>();
                tempList.AddRange(flowDocument.Blocks);
                flowDocument.Blocks.Clear();
                rootSection.Blocks.AddRange(tempList);

                Paragraph firstPara = null;
                if (rootSection.Blocks.FirstBlock is Paragraph)
                {
                    firstPara = rootSection.Blocks.FirstBlock as Paragraph;
                }
                else
                {
                    firstPara = new Paragraph();
                    rootSection.Blocks.InsertBefore(rootSection.Blocks.FirstBlock, firstPara);
                }

                if (firstPara.Inlines.Count > 0)
                {
                    firstPara.Inlines.InsertBefore(firstPara.Inlines.FirstInline, new Run(prefix));
                }
                else
                {
                    firstPara.Inlines.Add(prefix);
                }
            }
            else
            {
                Paragraph para = null;
                if (rootSection.Blocks.LastBlock is Paragraph)
                {
                    para = rootSection.Blocks.LastBlock as Paragraph;
                }
                else
                {
                    para = new Paragraph();
                    rootSection.Blocks.Add(para);
                }

                string questionContent = content.Content;
                int    startIndex      = 0;

                para.Inlines.Add(prefix);

                while (true)
                {
                    startIndex = questionContent.IndexOf("_$", 0);
                    if (startIndex >= 0)
                    {
                        int    endIndex    = questionContent.IndexOf("$_", startIndex);
                        string placeHolder = questionContent.Substring(startIndex, endIndex - startIndex + 2);

                        string text = questionContent.Substring(0, startIndex);

                        if (!string.IsNullOrEmpty(text) &&
                            text[text.Length - 1] == '\n')
                        {
                            para.Inlines.Add(CreateText(text.Remove(text.Length - 1)));
                        }
                        else
                        {
                            para.Inlines.Add(CreateText(text));
                        }

                        QuestionContentPart part = content.GetContentPart(placeHolder);
                        if (response is FIBQuestionResponse)
                        {
                            FIBQuestionResponse fibResponse = response as FIBQuestionResponse;
                            para.Inlines.Add(CreateUIPart(part, fibResponse.GetBlankResponse(part.Id, false)));
                        }
                        else
                        {
                            para.Inlines.Add(CreateUIPart(part, null));
                        }

                        questionContent = questionContent.Remove(0, endIndex + 2);
                        if (string.IsNullOrEmpty(questionContent))
                        {
                            break;
                        }
                    }
                    else
                    {
                        para.Inlines.Add(CreateText(questionContent));
                        break;
                    }
                }
            }

            return(rootSection);
        }
        private static Paragraph CreateTableQuestion(TableQuestion question,
                                                     int index,
                                                     FlowDocument flowDocument,
                                                     bool showAnswer,
                                                     bool showResponse,
                                                     SelectableQuestionResponse response)
        {
            Paragraph questionPara = new Paragraph();

            flowDocument.Blocks.Add(questionPara);

            Run questionBodyRun = new Run((index + 1).ToString() + ". " + question.Content.Content + "\n");

            questionPara.Inlines.Add(questionBodyRun);

            Table         optionTable   = new Table();
            TableRowGroup tableRowGroup = new TableRowGroup();

            optionTable.RowGroups.Add(tableRowGroup);
            flowDocument.Blocks.Add(optionTable);

            int i        = 0;
            int rowCount = (int)System.Math.Sqrt(question.QuestionOptionCollection.Count);

            for (int row = 0; row < rowCount; row++)
            {
                tableRowGroup.Rows.Add(new TableRow());
                TableRow tableRow = tableRowGroup.Rows[row];
                for (int col = 0; col < rowCount; col++)
                {
                    QuestionOption option = question.QuestionOptionCollection[i++];

                    System.Windows.Documents.Section optionPara = CreateContentControl(option.OptionContent, string.Empty, null, response);
                    if (showResponse)
                    {
                        if (Enumerable.Count <string>(Enumerable.Where <string>(response.OptionIdList, (c => (c == option.Id)))) > 0)
                        {
                            optionPara.FontWeight = FontWeights.Bold;
                            optionPara.FontSize   = 16f;
                            optionPara.FontStyle  = FontStyles.Italic;
                        }
                    }
                    TableCell cell = new TableCell(optionPara);
                    cell.BorderThickness = new Thickness(1);
                    cell.BorderBrush     = new SolidColorBrush(Colors.Black);
                    cell.TextAlignment   = TextAlignment.Center;
                    cell.LineHeight      = 30f;
                    tableRow.Cells.Add(cell);
                }
            }

            if (showAnswer)
            {
                System.Windows.Documents.Section answerSection = new System.Windows.Documents.Section();

                Paragraph answerPara = new Paragraph();

                answerSection.Blocks.Add(answerPara);

                flowDocument.Blocks.Add(answerSection);

                answerPara.Inlines.Add("答案:");
                foreach (QuestionOption option in question.QuestionOptionCollection)
                {
                    if (option.IsCorrect)
                    {
                        CreateContentControl(option.OptionContent, " ", answerSection, response);
                        answerPara.Inlines.Add(", ");
                    }
                }
            }

            return(questionPara);
        }
        // Removes nested ListItems in the beginning of a fragment
        // to avoid multiple bulleting.
        // 
        private static void CorrectLeadingNestedLists(Section fragment)
        {
            List list = fragment.Blocks.FirstBlock as List;
            while (list != null)
            {
                ListItem listItem = list.ListItems.FirstListItem;
                if (listItem == null)
                {
                    return;
                }

                if (listItem.NextListItem != null)
                {
                    return;
                }

                List nestedList = listItem.Blocks.FirstBlock as List;
                if (nestedList == null)
                {
                    return;
                }

                // So we have nested list in the very beginning of the outer single-item list:
                // remove that outer list
                listItem.Reposition(null, null);
                list.Reposition(null, null);

                list = nestedList;
            }
        }
        /// <summary>
        /// Handle general and named section elements
        /// </summary>
        /// <param name="props">The element properties</param>
        /// <remarks>If the section is empty, it will be omitted</remarks>
        private static void SectionElement(ElementProperties props)
        {
            if(props.ParseChildren && props.Element.HasElements)
            {
                Section s = new Section();
                string title;

                // If this is a named section, add the standard title
                if(NamedSectionTitles.TryGetValue(props.Element.Name.LocalName, out title))
                {
                    Paragraph p = new Paragraph(new Run(title));
                    s.Blocks.Add(p);
                    p.SetResourceReference(Paragraph.StyleProperty, NamedStyle.Title);
                }

                props.Converter.AddToBlockContainer(s);
            }
            else
                props.ParseChildren = props.ReturnToParent = false;
        }
예제 #32
0
        private PanoramaItem panoramaItemFromSection(Section section)
        {
            PanoramaItem panoramaItem = new PanoramaItem();
            ScrollViewer scrollViewer = new ScrollViewer();
            panoramaItem.Content = scrollViewer;
            Grid grid = new Grid() { Margin = new Thickness(0, 10, 0, 0) };

            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            TextBlock headerText = new TextBlock() { Text = section.Header, FontFamily = new FontFamily("Segoe WP Black"), FontSize = 65, Foreground = new SolidColorBrush((Color)Resources["PhoneForegroundColor"]), HorizontalAlignment = System.Windows.HorizontalAlignment.Left };
            Grid.SetRow(headerText, 0);
            grid.Children.Add(headerText);

            TextBlock captionText = new TextBlock() { Text = section.Caption, FontFamily = new FontFamily("Segoe WP Black"), FontSize = 20, Foreground = new SolidColorBrush((Color)Resources["PhoneForegroundColor"]), HorizontalAlignment = System.Windows.HorizontalAlignment.Right};
            Grid.SetRow(captionText, 1);
            grid.Children.Add(captionText);

            Boolean alternate = section.AlternateSeed;

            for (int i = 0; i < section.Entries.Count; i++)
            {
                grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                grid.Children.Add(rowFromEntry(section.Entries[i], 2+i, alternate, section.DefaultColor, section.AlternateColor));
                alternate = !alternate;
            }

            scrollViewer.Content = grid;

            return panoramaItem;
        }
 /// <summary>
 /// Handle definition elements
 /// </summary>
 /// <param name="props">The element properties</param>
 private static void DefinitionElement(ElementProperties props)
 {
     Section s = new Section();
     props.Converter.AddToBlockContainer(s);
     s.SetResourceReference(Section.StyleProperty, NamedStyle.Definition);
 }
        private static void CreateMCQuestion(SelectableQuestion question,
                                             int index,
                                             FlowDocument flowDocument,
                                             bool showAnswer,
                                             bool showResponse,
                                             SelectableQuestionResponse response)
        {
            System.Windows.Documents.Section questionSection = new System.Windows.Documents.Section();
            flowDocument.Blocks.Add(questionSection);

            // Shuffle options
            List <int> optionIndexList = new List <int>();

            if (question.RandomOption)
            {
                Random rand = new Random((int)DateTime.Now.Ticks);
                while (true)
                {
                    int  i     = rand.Next(question.QuestionOptionCollection.Count * 10) % question.QuestionOptionCollection.Count;
                    bool found = false;
                    foreach (int temp in optionIndexList)
                    {
                        if (temp == i)
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        optionIndexList.Add(i);
                    }

                    if (optionIndexList.Count == question.QuestionOptionCollection.Count)
                    {
                        break;
                    }

                    Thread.Sleep(10);
                }
            }
            else
            {
                for (int i = 0; i < question.QuestionOptionCollection.Count; i++)
                {
                    optionIndexList.Add(i);
                }
            }

            System.Windows.Documents.Section questionContentBlock = CreateContentControl(question.Content, (index + 1).ToString() + ". ", null, response);
            Paragraph lastParagraph = null;

            if (questionContentBlock.Blocks.LastBlock is Paragraph)
            {
                lastParagraph = questionContentBlock.Blocks.LastBlock as Paragraph;
            }
            if (lastParagraph == null)
            {
                lastParagraph = new Paragraph();
                questionContentBlock.Blocks.Add(lastParagraph);
            }
            if (showResponse)
            {
                if (Enumerable.Count <string>(response.OptionIdList) > 0)
                {
                    for (int i = 0; i < question.QuestionOptionCollection.Count; i++)
                    {
                        QuestionOption option = question.QuestionOptionCollection[optionIndexList[i]];
                        if (option.Id == response.OptionIdList[0])
                        {
                            lastParagraph.Inlines.Add(CreateText(" ( " + (char)('A' + i) + " )"));
                            break;
                        }
                    }
                }
                else
                {
                    lastParagraph.Inlines.Add(CreateText("(    )"));
                }
            }
            else
            {
                lastParagraph.Inlines.Add(CreateText("(    )"));
            }

            if (showAnswer)
            {
                for (int i = 0; i < question.QuestionOptionCollection.Count; i++)
                {
                    QuestionOption option = question.QuestionOptionCollection[optionIndexList[i]];
                    if (option.IsCorrect)
                    {
                        lastParagraph.Inlines.Add(CreateText("    正确答案:" + (char)('A' + i)));
                        break;
                    }
                }
            }

            questionSection.Blocks.Add(questionContentBlock);

            for (int i = 0; i < question.QuestionOptionCollection.Count; i++)
            {
                QuestionOption option = question.QuestionOptionCollection[optionIndexList[i]];
                System.Windows.Documents.Section optionSec = CreateContentControl(option.OptionContent, string.Format("\t{0}. ", (char)('A' + i)), null, response);
                List <Block> tempList = new List <Block>();
                tempList.AddRange(optionSec.Blocks);
                optionSec.Blocks.Clear();

                questionSection.Blocks.AddRange(tempList);
            }
        }
예제 #35
0
        CreateDocument(IRecipe recipe, ICommand linkToRecipeCommand)
        {
            Doc.FlowDocument doc = new Doc.FlowDocument();
            doc.PagePadding         = new System.Windows.Thickness(40);
            doc.ColumnWidth         = 640;
            doc.Typography.Fraction = System.Windows.FontFraction.Slashed;
            doc.FontFamily          = new System.Windows.Media.FontFamily("Palatino Linotype");

            var cookTimeConverter = new Converters.CookTimespanConverter();

            {
                Doc.Section recipeHeader = new Doc.Section();
                doc.Blocks.Add(recipeHeader);

                Doc.Paragraph p;
                // Recipe Name
                p = recipeHeader.AddParagraph();
                p.Inlines.Add(new Doc.Underline(new Doc.Run(recipe.Name)));


                if (recipe.Ratings != null && recipe.Ratings.Count > 0)
                {
                    int rating =
                        (recipe.Ratings == null || recipe.Ratings.Count == 0)
                  ? 0
                  : (int)(recipe.Ratings.Aggregate(0.0, (sum, r) => sum + r.Value) / recipe.Ratings.Count);

                    string ratedString    = new string('«', rating);
                    string notRatedString = new string('«', m_ratingDescriptions.Length - rating);
                    p = recipeHeader.AddParagraph();
                    if (!string.IsNullOrEmpty(ratedString))
                    {
                        p.Inlines.Add(new Doc.Run(ratedString)
                        {
                            FontFamily = new System.Windows.Media.FontFamily("Wingdings"), Foreground = System.Windows.Media.Brushes.Red
                        });
                    }
                    if (!string.IsNullOrEmpty(notRatedString))
                    {
                        p.Inlines.Add(new Doc.Run(notRatedString)
                        {
                            FontFamily = new System.Windows.Media.FontFamily("Wingdings"), Foreground = System.Windows.Media.Brushes.Silver
                        });
                    }
                }

                if (recipe.Source != null)
                {
                    p = recipeHeader.AddParagraph();
                    p.Inlines.Add(new Doc.Italic(new Doc.Run("From ")));
                    p.Inlines.Add(new Doc.Run(recipe.Source.Name));
                }

                if (recipe.Servings.ToDouble() > 0 || recipe.Yield.ToDouble() > 0)
                {
                    string yieldAndOrServings = null;
                    if (recipe.Servings.ToDouble() > 0)
                    {
                        yieldAndOrServings = "Serves " + recipe.Servings;
                    }
                    if (recipe.Yield.ToDouble() > 0)
                    {
                        string yieldUnit = recipe.YieldUnit == null ? null : recipe.YieldUnit.Name;
                        string makes     = "Makes " + recipe.Yield + " " + yieldUnit;
                        if (yieldAndOrServings != null)
                        {
                            yieldAndOrServings = yieldAndOrServings + " \u2022 " + makes;
                        }
                        else
                        {
                            yieldAndOrServings = makes;
                        }
                    }
                    recipeHeader.AddParagraph().Inlines.Add(new Doc.Run(yieldAndOrServings));
                }

                //string tags =
                //   recipe.Tags
                //   .Aggregate(
                //      new StringBuilder ("Tags: "),
                //      (sb, t) =>
                //      {
                //         sb.Append (t.Name);
                //         sb.Append (", ");
                //         return sb;
                //      },
                //      sb => sb[sb.Length - 2] == ',' ? sb.ToString (0, sb.Length - 2) : sb.ToString ());
                //recipeHeader.AddParagraph ().Inlines.Add (new Doc.Run(tags)));
            }

            foreach (IRecipePart part in recipe.Parts)
            {
                Doc.Section partHeader = new Doc.Section();
                doc.Blocks.Add(partHeader);

                //
                // Part Name
                //
                if (!string.IsNullOrWhiteSpace(part.Name) && part.Name != recipe.Name)
                {
                    var pName = partHeader.AddParagraph();
                    pName.Margin = new Thickness(0);
                    pName.Inlines.Add(new Doc.Underline(new Doc.Run(part.Name)));
                }

                //
                // Times/prep method
                //
                string             prepMethod = part.PreparationMethod != null ? part.PreparationMethod.Name : null;
                SmartListFormatter times      = new SmartListFormatter(" \u2022 ", ": ");
                if (part.PreparationTime != TimeSpan.Zero)
                {
                    times.Append("Prep Time", cookTimeConverter.Convert(part.PreparationTime, typeof(string), null, null) as string);
                }
                if (prepMethod != null)
                {
                    times.Append(prepMethod);
                }
                if (part.CookTime != TimeSpan.Zero)
                {
                    times.Append("Cook", cookTimeConverter.Convert(part.CookTime, typeof(string), null, null) as string);
                }
                if (part.Temperature != 0)
                {
                    times.Append(part.Temperature + " \u00BA F");
                }
                if (part.ChillTime != TimeSpan.Zero)
                {
                    times.Append("Chill", cookTimeConverter.Convert(part.ChillTime, typeof(string), null, null) as string);
                }

                if (times.GetStringBuilder().Length > 0)
                {
                    Doc.Paragraph stats = partHeader.AddParagraph();
                    stats.Margin = new Thickness(0);
                    stats.Inlines.Add(new Doc.Run(times.ToString()));
                }

                //
                // Ingredients
                //
                if (part.Ingredients != null)
                {
                    Doc.Paragraph partIngredients = partHeader.AddParagraph();
                    partIngredients.TextAlignment = TextAlignment.Left;
                    partIngredients.Margin        = new Thickness(0);
                    partIngredients.Inlines.Add(new Doc.LineBreak());
                    partIngredients.Inlines.Add(new Doc.Run("Ingredients:"));
                    foreach (var ingredient in part.Ingredients)
                    {
                        partIngredients.Inlines.Add(new Doc.LineBreak());
                        Sellars.Data.Model.ModelId <IRecipe> recipeId;
                        if (ingredient.Ingredient == null)
                        {
                            recipeId = null;
                        }
                        else
                        {
                            recipeId = ingredient.Ingredient.Id;
                        }

                        string text           = IngredientToString(ingredient);
                        string ingredientName = ingredient.Ingredient.Name;
                        if (recipeId != null && recipeId.Id != Guid.Empty && linkToRecipeCommand != null && !string.IsNullOrEmpty(ingredientName))
                        {
                            int iName = text.IndexOf(ingredientName);
                            if (iName > 0)
                            {
                                partIngredients.Inlines.Add(new Doc.Run(text.Substring(0, iName)));
                            }
                            partIngredients.Inlines.Add(new Doc.Hyperlink(new Doc.Run(ingredientName))
                            {
                                Command = linkToRecipeCommand, CommandParameter = recipeId
                            });
                            if (text.Length - iName - ingredientName.Length > 0)
                            {
                                partIngredients.Inlines.Add(new Doc.Run(text.Substring(iName + ingredientName.Length)));
                            }
                        }
                        else
                        {
                            partIngredients.Inlines.Add(new Doc.Run(text));
                        }
                    }
                    ;
                }

                if (!string.IsNullOrWhiteSpace(part.Instructions))
                {
                    var p = partHeader.AddParagraph();
                    p.Inlines.Add(new Doc.LineBreak());
                    p.Inlines.Add(new Doc.Run("Instructions:"));

                    foreach (string paragraph in part.Instructions.Split(new [] { Environment.NewLine }, StringSplitOptions.None))
                    {
                        p.Inlines.Add(new Doc.LineBreak());
                        p.Inlines.Add(new Doc.Run(paragraph));
                    }
                }
                string comments = (part.Comments == null || part.Comments.Count == 0) ? "" :
                                  part.Comments
                                  .Aggregate(
                    new StringBuilder(),
                    (sb, t) =>
                {
                    sb.Append("On " + t.CreatedOn + ", " + t.UserName + " commented: " + t.Text + Environment.NewLine);
                    return(sb);
                },
                    sb => sb.ToString(0, sb.Length - Environment.NewLine.Length));
                if (!string.IsNullOrWhiteSpace(comments))
                {
                    partHeader.AddParagraph().Inlines.Add(new Doc.Run(comments));
                }
            }

            return(doc);
        }