Inheritance: IXmlElement, IXmlNode, IXmlNodeSelector, IXmlNodeSerializer
Example #1
0
        public static void AddChildWithInnerText(this Windows.Data.Xml.Dom.XmlElement rootNode, string name, string innerText)
        {
            var node = rootNode.OwnerDocument.CreateElement(name);

            node.InnerText = innerText;
            rootNode.AppendChild(node);
        }
Example #2
0
        public async Task <BlogPost> GetPost(string blogId, string postId)
        {
            Login();

            FixupBlogId(ref blogId);

            XmlRestRequestHelper.XmlRequestResult result = new XmlRestRequestHelper.XmlRequestResult();

            result.uri             = PostIdToPostUri(postId);
            result.responseHeaders = new HttpResponseMessage().Headers;
            var doc = await xmlRestRequestHelper.Get(RequestFilter, result);

            XmlDocument remotePost = (XmlDocument)doc.CloneNode(true);
            XmlElement  entryNode  = doc.SelectSingleNodeNS("/atom:entry", _nsMgr.ToNSMethodFormat()) as XmlElement;

            if (entryNode == null)
            {
                throw new BlogClientInvalidServerResponseException("GetPost", "No post entry returned from server", doc.GetXml());
            }

            BlogPost post = Parse(entryNode, true, result.uri);

            post.Id             = postId;
            post.ETag           = FilterWeakEtag(result.responseHeaders["ETag"]);
            post.AtomRemotePost = remotePost;
            return(post);
        }
            public override XmlElement CreateCategoryElement(XmlDocument ownerDoc, string category, string categoryScheme, string categoryLabel)
            {
                XmlElement element = ownerDoc.CreateElementNS(DC_URI, "dc:subject");

                element.InnerText = category;
                return(element);
            }
Example #4
0
 // Constructor
 public CssStylesheet(XmlElement htmlElement)
 {
     if (htmlElement != null)
     {
         this.DiscoverStyleDefinitions(htmlElement);
     }
 }
Example #5
0
        private async Task AddCategoriesXml(XmlElement categoriesNode, XmlElement containerNode, XmlRestRequestHelper.XmlRequestResult result)
        {
            if (categoriesNode.Attributes.Any(a => a.NodeName == "href"))
            {
                string href = XmlHelper.GetUrl(categoriesNode, "@href", result.uri);
                if (href != null && href.Length > 0)
                {
                    Uri uri = new Uri(href);
                    if (result.uri == null || !uri.Equals(result.uri)) // detect simple cycles
                    {
                        XmlDocument doc = await xmlRestRequestHelper.Get(RequestFilter, result);

                        XmlElement categories = (XmlElement)doc.SelectSingleNodeNS(@"app:categories", _nsMgr.ToNSMethodFormat());
                        if (categories != null)
                        {
                            await AddCategoriesXml(categories, containerNode, result);
                        }
                    }
                }
            }
            else
            {
                containerNode.AppendChild(containerNode.OwnerDocument.ImportNode(categoriesNode, true));
            }
        }
Example #6
0
        private void ParseMPDElement()
        {
            Windows.Data.Xml.Dom.XmlElement root = document.DocumentElement;
            if (root.GetAttribute("type").ToLower().Equals("dynamic"))
            {
                manifest.IsLive = true;
            }
            if (root.GetAttribute("profiles").ToLower().Contains(LiveProfile))
            {
                manifest.IsSupportedProfile = true;
            }
            if (!root.GetAttribute("availabilityStartTime").Equals(""))
            {
                string availabilityStartTime = root.GetAttribute("availabilityStartTime");
                manifest.AvailibilityStartTime = XmlConvert.ToDateTimeOffset(availabilityStartTime);
            }
            if (!root.GetAttribute("minBufferTime").Equals(""))
            {
                string minBufferTime = root.GetAttribute("minBufferTime");
                manifest.MinBufferTime = XmlConvert.ToTimeSpan(minBufferTime);
            }
            if (!root.GetAttribute("minimumUpdatePeriod").Equals(""))
            {
                manifest.HasMinimumUpdatePeriod = true;
                string minUpdatePeriod = root.GetAttribute("minimumUpdatePeriod");
                manifest.MinimumUpdatePeriod = XmlConvert.ToTimeSpan(minUpdatePeriod);
            }
            if (!root.GetAttribute("mediaPresentationDuration").Equals(""))
            {
                manifest.HasPresentationDuration = true;
                string mediaPresentationDuration = root.GetAttribute("mediaPresentationDuration");
                manifest.MediaPresentationDuration = XmlConvert.ToTimeSpan(mediaPresentationDuration);
            }
            if (!root.GetAttribute("timeShiftBufferDepth").Equals(""))
            {
                string timeShiftBufferDepth = root.GetAttribute("timeShiftBufferDepth");
                manifest.TimeShiftBufferDepth = XmlConvert.ToTimeSpan(timeShiftBufferDepth);
            }
            if (!root.GetAttribute("publishTime").Equals(""))
            {
                string publishTime = root.GetAttribute("publishTime");
                manifest.PublishTime = XmlConvert.ToDateTimeOffset(publishTime);
            }
            else
            {
                manifest.PublishTime = DateTimeOffset.MinValue;
            }
            Windows.Data.Xml.Dom.XmlNodeList periods = root.GetElementsByTagName("Period");
            if (periods.Count() > 1)
            {
                manifest.HasMultiplePeriods = true;
            }

            IXmlNode lastPeriod = periods.Last <IXmlNode>();

            if (lastPeriod.Attributes.GetNamedItem("duration") != null)
            {
                manifest.LastPeriodDuration = XmlConvert.ToTimeSpan(lastPeriod.Attributes.GetNamedItem("duration").InnerText);
            }
        }
Example #7
0
        protected virtual async Task <XmlDocument> GetCategoryXml(string blogId)
        {
            // Get the service document
            Login();

            FixupBlogId(ref blogId);

            XmlRestRequestHelper.XmlRequestResult result = new XmlRestRequestHelper.XmlRequestResult();
            result.uri = FeedServiceUrl;
            var xmlDoc = await xmlRestRequestHelper.Get(RequestFilter, result);

            foreach (XmlElement entryEl in xmlDoc.SelectNodesNS("app:service/app:workspace/app:collection", _nsMgr.ToNSMethodFormat()))
            {
                string href = XmlHelper.GetUrl(entryEl, "@href", result.uri);
                if (blogId == href)
                {
                    XmlDocument results     = new XmlDocument();
                    XmlElement  rootElement = results.CreateElement("categoryInfo");
                    results.AppendChild(rootElement);
                    foreach (XmlElement categoriesNode in entryEl.SelectNodesNS("app:categories", _nsMgr.ToNSMethodFormat()))
                    {
                        await AddCategoriesXml(categoriesNode, rootElement, result);
                    }
                    return(results);
                }
            }
            //Debug.Fail("Couldn't find collection in service document:\r\n" + xmlDoc.OuterXml);
            return(new XmlDocument());
        }
Example #8
0
		internal SvgSvgElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);

			this.ViewPort = SvgRect.Parse(element.GetAttribute("viewBox"));
		}
Example #9
0
		internal SvgUseElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			var nan = new SvgLength(SvgLength.SvgLengthType.Unknown, float.NaN);
			this.X = element.ParseCoordinate("x", nan);
			this.Y = element.ParseCoordinate("y", nan);
			this.Width = element.ParseLength("width", nan);
			this.Height = element.ParseLength("height", nan);
			this.Href = element.GetAttribute("xlink:href").Substring(1);
			
			var child = (SvgElement)this.OwnerDocument.GetElementById(this.Href).CloneNode(true);
			if (child.GetType() == typeof(SvgSymbolElement))
			{
				throw new NotImplementedException();
			}
			else if (child.GetType() == typeof(SvgRectElement))
			{
				var casted = (SvgRectElement)child;
				if (this.Width.UnitType != SvgLength.SvgLengthType.Unknown) casted.Width = this.Width;
				if (this.Height.UnitType != SvgLength.SvgLengthType.Unknown) casted.Height = this.Height;
			}
			this.InstanceRoot = child;

			if (this.X.UnitType != SvgLength.SvgLengthType.Unknown && this.Y.UnitType != SvgLength.SvgLengthType.Unknown)
			{
				this.Transform.Add(SvgTransform.CreateTranslate(
					this.X.UnitType != SvgLength.SvgLengthType.Unknown ? this.X.ValueAsPixel : 0.0F,
					this.Y.UnitType != SvgLength.SvgLengthType.Unknown ? this.Y.ValueAsPixel : 0.0F));
			}
		}
Example #10
0
		internal SvgStopElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);

			this.Offset = element.ParseNumberOrPercentage("offset");
		}
Example #11
0
        public static void Toast(string msg)
        {
            //1. create element
            ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText01;
            XmlDocument       toastXml      = ToastNotificationManager.GetTemplateContent(toastTemplate);
            //2.设置消息文本
            XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");

            toastTextElements[0].AppendChild(toastXml.CreateTextNode(msg));
            //3. 图标
            Windows.Data.Xml.Dom.XmlNodeList toastImageAttributes = toastXml.GetElementsByTagName("image");
            ((XmlElement)toastImageAttributes[0]).SetAttribute("src", $"ms-appx:///Assets/StoreLogo.png");
            ((XmlElement)toastImageAttributes[0]).SetAttribute("alt", "logo");
            // 4. duration
            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");

            ((XmlElement)toastNode).SetAttribute("duration", "short");

            // 5. audio
            XmlElement audio = toastXml.CreateElement("audio");

            audio.SetAttribute("src", $"ms-winsoundevent:Notification.SMS");
            toastNode.AppendChild(audio);

            ToastNotification toast = new ToastNotification(toastXml);

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        private static void ParseElement(XmlElement element, ITextContainer parent)
        {
            foreach (var child in element.ChildNodes)
            {
                if (child is Windows.Data.Xml.Dom.XmlText)
                {
                    if (string.IsNullOrEmpty(child.InnerText) ||
                        child.InnerText == "\n")
                    {
                        continue;
                    }

                    parent.Add(new Run { Text = child.InnerText.Trim(new char[] {'\n'}) });
                }
                else if (child is XmlElement)
                {
                    XmlElement e = (XmlElement)child;
                    switch (e.TagName.ToUpper())
                    {
                        case "P":
                            var paragraph = new Paragraph();
                            parent.Add(paragraph);
                            ParseElement(e, new ParagraphTextContainer(paragraph));
                            break;
                        case "STRONG":
                            var bold = new Bold();
                            parent.Add(bold);
                            ParseElement(e, new SpanTextContainer(bold));
                            break;
                        case "U":
                            var underline = new Underline();
                            parent.Add(underline);
                            ParseElement(e, new SpanTextContainer(underline));
                            break;
                        case "A":
                            var inlineElt = new InlineUIContainer();
                            var hyperlink = new HyperlinkButton();
                            inlineElt.Child = hyperlink;
                            hyperlink.Style = (Style)App.Current.Resources["HyperlinkButtonStyle"];
                            hyperlink.Content = e.InnerText;
                            hyperlink.Click += delegate(object sender, RoutedEventArgs eventArgs)
                            {
                                string uriString = e.GetAttribute("href");
                                Messenger.Default.Send<LinkClickedMessage>(new LinkClickedMessage()
                                {
                                    UriToNavigate = uriString
                                });
                            };
                            parent.Add(inlineElt);
                            //ParseElement(e, parent);
                            break;
                        case "BR":
                                parent.Add(new LineBreak());
                            break;
                    }
                }

            }
        }
            public override XmlElement PlaintextToTextNode(XmlDocument ownerDoc, string text)
            {
                XmlElement el = ownerDoc.CreateElementNS(NamespaceUri, "atom:content");

                el.SetAttribute("type", "text");
                el.InnerText = text;
                return(el);
            }
            public override XmlElement HtmlToTextNode(XmlDocument ownerDoc, string html)
            {
                XmlElement el = ownerDoc.CreateElementNS(NamespaceUri, "atom:content");

                el.SetAttribute("type", "html");
                el.InnerText = html;
                return(el);
            }
            public override XmlElement CreateCategoryElement(XmlDocument ownerDoc, string category, string categoryScheme, string categoryLabel)
            {
                // Blogger doesn't support category labels and will error out if you pass them
                XmlElement el = base.CreateCategoryElement(ownerDoc, category, categoryScheme, categoryLabel);

                el.RemoveAttribute("label");
                return(el);
            }
Example #16
0
		internal SvgPolygonElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			this.Points = new SvgPointCollection(element.GetAttribute("points"));
		}
		internal SvgLinearGradientElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this.X1 = element.ParseCoordinate("x1", 0.0F);
			this.Y1 = element.ParseCoordinate("y1", 0.0F);
			this.X2 = element.ParseCoordinate("x2", 100.0F);
			this.Y2 = element.ParseCoordinate("y2", 0.0F);
		}
        public NotificationsImpl()
        {
            this.badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
            this.toastNotifier = ToastNotificationManager.CreateToastNotifier();

            this.badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
            this.badgeEl = (XmlElement)this.badgeXml.SelectSingleNode("/badge");
        }
		internal SvgRadialGradientElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this.CenterX = element.ParseCoordinate("cx", 0.5F);
			this.CenterY = element.ParseCoordinate("cy", 0.5F);
			this.Radius = element.ParseLength("r", 0.5F);
			this.FocusX = element.ParseCoordinate("fx", this.CenterX);
			this.FocusY = element.ParseCoordinate("fy", this.CenterY);
		}
Example #20
0
		internal SvgPathElement(INode parent, XmlElement element)
			: base(parent, element.GetAttribute("id"))
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			this.Data = element.GetAttribute("d");
			this.Segments = SvgPathSegmentParser.Parse(this.Data);
		}
Example #21
0
 public AtomEntry(AtomProtocolVersion atomVer, Namespace atomNS, string categoryScheme, XmlNamespaceManager nsMgr, Uri documentUri, XmlElement entryNode)
 {
     _atomVer        = atomVer;
     _categoryScheme = categoryScheme;
     _nsMgr          = nsMgr;
     _documentUri    = documentUri;
     _entryNode      = entryNode;
     _atomNS         = atomNS;
 }
Example #22
0
        public void SetImageAttribute(XmlElement imageElement)
        {
            if (imageElement == null) return;

            imageElement.SetAttribute("src", GetImageSource());
            if (!string.IsNullOrWhiteSpace(Alt))
            {
                imageElement.SetAttribute("alt", Alt);
            }
        }
Example #23
0
		internal SvgClipPathElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			var clipPathUnits = SvgUnitTypeHelper.Parse(element.GetAttribute("clipPathUnits"));
			if (clipPathUnits == SvgUnitType.Unknown) clipPathUnits = SvgUnitType.UserSpaceOnUse;
			this.ClipPathUnits = clipPathUnits;
		}
Example #24
0
		internal SvgCircleElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			this.CenterX = element.ParseCoordinate("cx", 0.0F);
			this.CenterY = element.ParseCoordinate("cy", 0.0F);
			this.Radius = element.ParseLength("r", 0.0F);
		}
Example #25
0
		protected internal SvgElement(INode parent, XmlElement element)
		{
			this.ParentNode = parent;
			this.Id = element.GetAttribute("id");
			this.ChildNodes = ParseChildren(this, element.ChildNodes);

			if (!string.IsNullOrEmpty(this.Id))
			{
				this.OwnerDocument.AddIdCache(this.Id, this);
			}
		}
Example #26
0
		internal SvgLineElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			this.X1 = element.ParseCoordinate("x1", 0.0F);
			this.Y1 = element.ParseCoordinate("y1", 0.0F);
			this.X2 = element.ParseCoordinate("x2", 0.0F);
			this.Y2 = element.ParseCoordinate("y2", 0.0F);
		}
Example #27
0
		public SvgStylableHelper(ISvgStylable parent, XmlElement element)
		{
			this.ClassName = element.GetAttribute("class");
			this.Style = new CssStyleDeclaration(parent, element.GetAttribute("style"));

			foreach (var pn in PRESENTATION_ATTRIBUTE_NAMES)
			{
				var value = element.GetAttribute(pn);
				if (!string.IsNullOrWhiteSpace(value)) this.Style.SetProperty(pn, value, string.Empty, true);
			}
		}
Example #28
0
        public static string GetChildNodeTextValue(this Windows.Data.Xml.Dom.XmlElement node, string childName, string defaultValue)
        {
            var child = node.ChildNodes.FirstOrDefault(n => n.NodeName == childName);

            if (child == null)
            {
                return(defaultValue);
            }

            return(child.InnerText);
        }
        private static XmlNodeList GetNodes(XmlElement xml, string xpath)
        {
            var ns = new PropertySet {
                {"root", "http://www.w3.org/2005/Atom"},
                {"media", "http://search.yahoo.com/mrss/"},
                {"openSearch", "http://a9.com/-/spec/opensearchrss/1.0/"}, //"http://a9.com/-/spec/opensearch/1.1/"}, //http://a9.com/-/spec/opensearchrss/1.0/
                {"gd", "http://schemas.google.com/g/2005"},
                {"yt", "http://gdata.youtube.com/schemas/2007"}
            };

            return xml.SelectNodesNS(xpath, ns);
        }
Example #30
0
        private string GetTextNodePlaintext(string xpath, string defaultValue)
        {
            XmlElement el = GetElement(xpath);

            if (el != null)
            {
                return(_atomVer.TextNodeToPlaintext(el));
            }
            else
            {
                return(defaultValue);
            }
        }
        private static string GetNodeValue(XmlElement xml, string xpath)
        {
            var ns = new PropertySet {
                {"root", "http://www.w3.org/2005/Atom"},
                {"media", "http://search.yahoo.com/mrss/"},
                {"openSearch", "http://a9.com/-/spec/opensearchrss/1.0/"}, //"http://a9.com/-/spec/opensearch/1.1/"}, //http://a9.com/-/spec/opensearchrss/1.0/
                {"gd", "http://schemas.google.com/g/2005"},
                {"yt", "http://gdata.youtube.com/schemas/2007"}
            };

            var node = xml.SelectSingleNodeNS(xpath, ns);
            return node == null ? "" : node.InnerText;
        }
Example #32
0
        public static string GetChildNodeAttribute(this Windows.Data.Xml.Dom.XmlElement node, string childName, string attributeName, string defaultValue)
        {
            var child = node.ChildNodes.FirstOrDefault(n => n.NodeName == childName);

            if (child == null)
            {
                return(defaultValue);
            }

            var xmlElement = child as Windows.Data.Xml.Dom.XmlElement;

            return(xmlElement?.GetAttribute(attributeName));
        }
Example #33
0
        public static Windows.Data.Xml.Dom.XmlElement GetChildByName(this Windows.Data.Xml.Dom.XmlElement node, string childName)
        {
            return((Windows.Data.Xml.Dom.XmlElement)node.ChildNodes.FirstOrDefault(n =>
            {
                var element = n as Windows.Data.Xml.Dom.XmlElement;

                if (element == null)
                {
                    return false;
                }

                return n.NodeName == childName;
            }));
        }
Example #34
0
		protected internal SvgGradientElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			var gradientUnits = SvgUnitTypeHelper.Parse(element.GetAttribute("gradientUnits"));
			if (gradientUnits == SvgUnitType.Unknown) gradientUnits = SvgUnitType.ObjectBoundingBox;
			this.GradientUnits = gradientUnits;

			this.GradientTransform = SvgTransformParser.Parse(element.GetAttribute("gradientTransform"));

			var spreadMethod = SvgSpreadMethodTypeHelper.Parse(element.GetAttribute("spreadMethod"));
			if (spreadMethod == SvgSpreadMethodType.Unknown) spreadMethod = SvgSpreadMethodType.Pad;
			this.SpreadMethod = spreadMethod;
		}
Example #35
0
 string getNodeValue(XmlElement element, string name)
 {
     try
     {
         if (element.GetElementsByTagName(name).Count > 0)
         {
             return element.GetElementsByTagName(name)[0].InnerText;
         }
         return "";
     }
     catch (Exception e)
     {
         Debug.WriteLine("Problem geting value " + name + "element null" + (element == null) + " =" + (element.GetElementsByTagName(name) == null));
         Debug.WriteLine("element " + element.GetXml());
         return e.Message;
     }
 }
            public override XmlElement CreateCategoryElement(XmlDocument ownerDoc, string category, string categoryScheme, string categoryLabel)
            {
                if (categoryScheme == null)
                {
                    throw new ArgumentException("Null category scheme not supported");
                }

                XmlElement element = ownerDoc.CreateElementNS(NamespaceUri, "atom:category");

                element.SetAttribute("term", category);
                if (categoryScheme.Length > 0)
                {
                    element.SetAttribute("scheme", categoryScheme);
                }
                element.SetAttribute("label", categoryLabel);
                return(element);
            }
        private static void ParseElement(XmlElement element, ITextContainer parent)
        {
            foreach (var child in element.ChildNodes)
            {
                if (child is Windows.Data.Xml.Dom.XmlText)
                {
                    if (string.IsNullOrEmpty(child.InnerText) ||
                        child.InnerText == "\n")
                    {
                        continue;
                    }

                    parent.Add(new Run { Text = child.InnerText });
                }
                else if (child is XmlElement)
                {
                    XmlElement e = (XmlElement)child;
                    switch (e.TagName.ToUpper())
                    {
                        case "P":
                            var paragraph = new Paragraph();
                            parent.Add(paragraph);
                            ParseElement(e, new ParagraphTextContainer(paragraph));
                            break;
                        case "STRONG":
                            var bold = new Bold();
                            parent.Add(bold);
                            ParseElement(e, new SpanTextContainer(bold));
                            break;
                        case "U":
                            var underline = new Underline();
                            parent.Add(underline);
                            ParseElement(e, new SpanTextContainer(underline));
                            break;
                        case "A":
                            ParseElement(e, parent);
                            break;
                        case "BR":
                            parent.Add(new LineBreak());
                            break;
                    }
                }

            }
        }
Example #38
0
        public virtual BlogPost Parse(XmlElement entryNode, bool includeCategories, Uri documentUri)
        {
            BlogPost  post      = new BlogPost();
            AtomEntry atomEntry = new AtomEntry(_atomVer, _atomNS, CategoryScheme, _nsMgr, documentUri, entryNode);

            post.Title         = atomEntry.Title;
            post.Excerpt       = atomEntry.Excerpt;
            post.Id            = PostUriToPostId(atomEntry.EditUri);
            post.Permalink     = atomEntry.Permalink;
            post.Contents      = atomEntry.ContentHtml;
            post.DatePublished = atomEntry.PublishDate;
            if (Options.SupportsCategories && includeCategories)
            {
                post.Categories = atomEntry.Categories;
            }

            return(post);
        }
Example #39
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background task starting");

            tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text04);

            tileText = tileXml.GetElementsByTagName("text")[0] as XmlElement;

            buses = new Bus[]
            {
                new Bus("99", 3),
                new Bus("88", 7),
                new Bus("6", 16),
                new Bus("47", 21),
            };

            new Timer(onTimer, new object(), 0, 1000);
        }
            public override BlogPostCategory[] ExtractCategories(XmlElement entry, string categoryScheme, Uri documentUri)
            {
                XmlNamespaceManager nsMgr = new XmlNamespaceManager(new NameTable());

                nsMgr.AddNamespace("dc", DC_URI);

                ArrayList results = new ArrayList();

                foreach (XmlElement el in entry.SelectNodesNS("dc:subject", nsMgr.ToNSMethodFormat()))
                {
                    string subject = el.InnerText;
                    if (subject != string.Empty)
                    {
                        results.Add(new BlogPostCategory(subject, subject));
                    }
                }

                return((BlogPostCategory[])results.ToArray(typeof(BlogPostCategory)));
            }
            public override BlogPostCategory[] ExtractCategories(XmlElement entry, string categoryScheme, Uri documentUri)
            {
                if (categoryScheme == null)
                {
                    return(new BlogPostCategory[0]);
                }

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(new NameTable());

                nsMgr.AddNamespace("atom", NamespaceUri);

                ArrayList results = new ArrayList();

                foreach (XmlElement el in entry.SelectNodesNS("atom:category", nsMgr.ToNSMethodFormat()))
                {
                    if (!SchemesEqual(el.GetAttribute("scheme"), categoryScheme))
                    {
                        continue;
                    }

                    string term  = el.GetAttribute("term");
                    string label = el.GetAttribute("label");

                    bool noTerm  = term == null || term == string.Empty;
                    bool noLabel = label == null || label == string.Empty;

                    if (noTerm && noLabel)
                    {
                        continue;
                    }
                    if (noTerm)
                    {
                        term = label;
                    }
                    if (noLabel)
                    {
                        label = term;
                    }
                    results.Add(new BlogPostCategory(term, label));
                }
                return((BlogPostCategory[])results.ToArray(typeof(BlogPostCategory)));
            }
Example #42
0
 string getNodeAttribute(XmlElement element, string node, string attribute)
 {
     try
     {
         if (element.GetElementsByTagName(node).Count > 0)
         {
             if (element.GetElementsByTagName(node)[0].Attributes.GetNamedItem(attribute) != null)
             {
                 return element.GetElementsByTagName(node)[0].Attributes.GetNamedItem(attribute).NodeValue.ToString();
             }
         }
         return "";
     }
     catch (Exception e)
     {
         Debug.WriteLine("Problem geting value " + attribute);
         Debug.WriteLine("element " + element.GetXml());
         return e.Message;
     }
 }
Example #43
0
		internal SvgRectElement(INode parent, XmlElement element)
			: base(parent, element)
		{
			this._stylableHelper = new SvgStylableHelper(this, element);
			this._transformableHelper = new SvgTransformableHelper(element);

			this.X = element.ParseCoordinate("x", 0.0F);
			this.Y = element.ParseCoordinate("y", 0.0F);
			this.Width = element.ParseLength("width", 0.0F);
			this.Height = element.ParseLength("height", 0.0F);

			SvgLength rx, ry;
			var fx = element.TryParseLength("rx", out rx);
			if (fx && rx < 0.0F) fx = false;

			var fy = element.TryParseLength("ry", out ry);
			if (fy && ry < 0.0F) fy = false;

			if (!fx && !fy)
			{
				rx = 0.0F;
				ry = 0.0F;
			}
			else if (fx && !fy)
			{
				ry = rx;
			}
			else if (!fx && fy)
			{
				rx = ry;
			}

			var hw = this.Width / 2.0F;
			if (rx > hw) rx = hw;

			var hh = this.Height / 2.0F;
			if (ry > hh) ry = hh;

			this.RoundedX = rx;
			this.RoundedY = ry;
		}
Example #44
0
 private void ShowToastNotification()
 {
     for (int i = 0; i < ViewModel.AllItems.Count; i++)
     {
         if (ViewModel.AllItems[i].date.Day == DateTime.Now.Day)
         {
             ToastTemplateType toastTemplate                    = ToastTemplateType.ToastImageAndText01;
             Windows.Data.Xml.Dom.XmlDocument toastXml          = ToastNotificationManager.GetTemplateContent(toastTemplate);
             Windows.Data.Xml.Dom.XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
             toastTextElements[0].AppendChild(toastXml.CreateTextNode(ViewModel.AllItems[i].title + "\n" + ViewModel.AllItems[i].description));
             Windows.Data.Xml.Dom.XmlNodeList toastImageAttributes = toastXml.GetElementsByTagName("image");
             IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
             ((Windows.Data.Xml.Dom.XmlElement)toastImageAttributes[0]).SetAttribute("src", "Assets//2015071504.jpg");
             Windows.Data.Xml.Dom.XmlElement audio = toastXml.CreateElement("audio");
             ((Windows.Data.Xml.Dom.XmlElement)toastNode).SetAttribute("duration", "long");
             audio.SetAttribute("silent", "true");
             ToastNotification toast = new ToastNotification(toastXml);
             ToastNotificationManager.CreateToastNotifier().Show(toast);
         }
     }
 }
Example #45
0
        private void ParseFeedDoc(XmlDocument xmlDoc, Uri baseUri, bool includeTitle, ref string homepageUrl, ref string title)
        {
            if (includeTitle)
            {
                XmlElement titleEl = xmlDoc.SelectSingleNodeNS(@"atom:feed/atom:title", _nsMgr.ToNSMethodFormat()) as XmlElement;
                if (titleEl != null)
                {
                    title = _atomVer.TextNodeToPlaintext(titleEl);
                }
            }

            foreach (XmlElement linkEl in xmlDoc.SelectNodesNS(@"atom:feed/atom:link[@rel='alternate']", _nsMgr.ToNSMethodFormat()))
            {
                IDictionary contentTypeInfo = MimeHelper.ParseContentType(linkEl.GetAttribute("type"), true);
                switch (contentTypeInfo[""] as string)
                {
                case "text/html":
                case "application/xhtml+xml":
                    homepageUrl = XmlHelper.GetUrl(linkEl, "@href", baseUri);
                    return;
                }
            }
        }
Example #46
0
        private XmlElement CreateElementCopy(XmlElement htmlElement)
        {
            XmlElement htmlElementCopy = _document.CreateElementNS(XhtmlNamespace, (string)htmlElement.LocalName);

            for (int i = 0; i < htmlElement.Attributes.Count; i++)
            {
                var attribute = htmlElement.Attributes[i];

                htmlElementCopy.SetAttribute(attribute.NodeName, (string)attribute.NodeValue);
            }

            return htmlElementCopy;
        }
Example #47
0
        private void AddEmptyElement(XmlElement htmlEmptyElement)
        {
            InvariantAssert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");

            XmlElement htmlParent = _openedElements.Peek();

            htmlParent.AppendChild(htmlEmptyElement);
        }
        // .............................................................
        //
        // Tables
        //
        // .............................................................
        /// <summary>
        /// Converts htmlTableElement to a Xaml Table element. Adds tbody elements if they are missing so
        /// that a resulting Xaml Table element is properly formed.
        /// </summary>
        /// <param name="xamlParentElement">
        /// Parent xaml element to which a converted table must be added.
        /// </param>
        /// <param name="htmlTableElement">
        /// XmlElement reprsenting the Html table element to be converted
        /// </param>
        /// <param name="inheritedProperties">
        /// Hashtable representing properties inherited from parent context. 
        /// </param>
        private static void AddTable(XmlElement xamlParentElement, XmlElement htmlTableElement, IDictionary inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext)
        {
            // Parameter validation
            Debug.Assert(htmlTableElement.LocalName.ToLower() == "table");
            Debug.Assert(xamlParentElement != null);
            Debug.Assert(inheritedProperties != null);

            // Create current properties to be used by children as inherited properties, set local properties
            IDictionary localProperties;
            IDictionary currentProperties = GetElementProperties(htmlTableElement, inheritedProperties, out localProperties, stylesheet, sourceContext);

            // TODO: process localProperties for tables to override defaults, decide cell spacing defaults

            // Check if the table contains only one cell - we want to take only its content
            XmlElement singleCell = GetCellFromSingleCellTable(htmlTableElement);

            if (singleCell != null)
            {
                //  Need to push skipped table elements onto sourceContext
                sourceContext.Add(singleCell);

                // Add the cell's content directly to parent
                for (IXmlNode htmlChildNode = singleCell.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null)
                {
                    htmlChildNode = AddBlock(xamlParentElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
                }

                Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == singleCell);
                sourceContext.RemoveAt(sourceContext.Count - 1);
            }
            else
            {
                // Create xamlTableElement
                XmlElement xamlTableElement = xamlParentElement.OwnerDocument.CreateElementNS(_xamlNamespace,Xaml_Table);

                // Analyze table structure for column widths and rowspan attributes
                IList columnStarts = AnalyzeTableStructure(htmlTableElement, stylesheet);

                // Process COLGROUP & COL elements
                AddColumnInformation(htmlTableElement, xamlTableElement, columnStarts, currentProperties, stylesheet, sourceContext);

                // Process table body - TBODY and TR elements
                IXmlNode htmlChildNode = htmlTableElement.FirstChild;

                while (htmlChildNode != null)
                {
                    string htmlChildName = htmlChildNode.LocalName.ToLower();

                    // Process the element
                    if (htmlChildName == "tbody" || htmlChildName == "thead" || htmlChildName == "tfoot")
                    {
                        //  Add more special processing for TableHeader and TableFooter
                        XmlElement xamlTableBodyElement = xamlTableElement.OwnerDocument.CreateElementNS(_xamlNamespace,Xaml_TableRowGroup);
                        xamlTableElement.AppendChild(xamlTableBodyElement);

                        sourceContext.Add((XmlElement)htmlChildNode);

                        // Get properties of Html tbody element
                        IDictionary tbodyElementLocalProperties;
                        IDictionary tbodyElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out tbodyElementLocalProperties, stylesheet, sourceContext);
                        // TODO: apply local properties for tbody

                        // Process children of htmlChildNode, which is tbody, for tr elements
                        AddTableRowsToTableBody(xamlTableBodyElement, htmlChildNode.FirstChild, tbodyElementCurrentProperties, columnStarts, stylesheet, sourceContext);
                        if (xamlTableBodyElement.HasChildNodes())
                        {
                            xamlTableElement.AppendChild(xamlTableBodyElement);
                            // else: if there is no TRs in this TBody, we simply ignore it
                        }

                        Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode);
                        sourceContext.RemoveAt(sourceContext.Count - 1);

                        htmlChildNode = htmlChildNode.NextSibling;
                    }
                    else if (htmlChildName == "tr")
                    {
                        // Tbody is not present, but tr element is present. Tr is wrapped in tbody
                        XmlElement xamlTableBodyElement = xamlTableElement.OwnerDocument.CreateElementNS(_xamlNamespace,Xaml_TableRowGroup);

                        // We use currentProperties of xamlTableElement when adding rows since the tbody element is artificially created and has
                        // no properties of its own

                        htmlChildNode = AddTableRowsToTableBody(xamlTableBodyElement, htmlChildNode, currentProperties, columnStarts, stylesheet, sourceContext);
                        if (xamlTableBodyElement.HasChildNodes())
                        {
                            xamlTableElement.AppendChild(xamlTableBodyElement);
                        }
                    }
                    else
                    {
                        // Element is not tbody or tr. Ignore it.
                        // TODO: add processing for thead, tfoot elements and recovery for td elements
                        htmlChildNode = htmlChildNode.NextSibling;
                    }
                }

                if (xamlTableElement.HasChildNodes())
                {
                    xamlParentElement.AppendChild(xamlTableElement);
                }
            }
        }
Example #49
0
 public static string GetAttributeValue(this Windows.Data.Xml.Dom.XmlElement node, string attributeName)
 {
     return(node.GetAttribute(attributeName));
 }
Example #50
0
        private void ParseAttributes(XmlElement xmlElement)
        {
            while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF && //
                _htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && //
                _htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd)
            {
                // read next attribute (name=value)
                if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
                {
                    string attributeName = _htmlLexicalAnalyzer.NextToken;
                    _htmlLexicalAnalyzer.GetNextEqualSignToken();

                    _htmlLexicalAnalyzer.GetNextAtomToken();

                    string attributeValue = _htmlLexicalAnalyzer.NextToken;
                    xmlElement.SetAttribute(attributeName, attributeValue);
                }
                _htmlLexicalAnalyzer.GetNextTagToken();
            }
        }
Example #51
0
        public static string GetUrl(IXmlNode el, string xpath, XmlNamespaceManager nsMgr, Uri documentUri)
        {
            if (el == null)
            {
                return(null);
            }
            var node = nsMgr == null
                ? el.SelectSingleNode(xpath)
                : el.SelectSingleNodeNS(xpath, nsMgr.DefaultNamespace);

            if (node == null)
            {
                return(null);
            }
            string rawUrl = node.NodeValue.ToString();

            if (rawUrl == null || rawUrl.Length == 0)
            {
                return(null);
            }

            // optimize for common case of absolute path
            if (rawUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    return(UrlHelper.SafeToAbsoluteUri(new Uri(rawUrl)));
                }
                catch { }
            }

            ArrayList ancestors = new ArrayList();

            var parent = node.ParentNode;

            while (parent != null)
            {
                ancestors.Add(parent);
                parent = parent.ParentNode;
            }

            ancestors.Reverse();

            Uri uri = documentUri;

            foreach (var anc in ancestors)
            {
                if (anc is XmlElement)
                {
                    XmlElement baseEl = (XmlElement)anc;
                    if (baseEl.Attributes.Any(a => a.LocalName == "xml:base"))
                    {
                        string thisUri = baseEl.GetAttribute("xml:base");
                        if (uri == null)
                        {
                            uri = new Uri(thisUri);
                        }
                        else
                        {
                            uri = new Uri(uri, thisUri);
                        }
                    }
                }
            }

            if (uri == null)
            {
                return(UrlHelper.SafeToAbsoluteUri(new Uri(rawUrl)));
            }
            else
            {
                return(UrlHelper.SafeToAbsoluteUri(new Uri(uri, rawUrl)));
            }
        }
Example #52
0
 protected virtual bool ShouldPromote(XmlElement collection)
 {
     return(false);
 }
Example #53
0
        public async Task <string> NewPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, PostResult postResult)
        {
            if (!publish && !Options.SupportsPostAsDraft)
            {
                //Debug.Fail("Post to draft not supported on this provider");
                throw new BlogClientPostAsDraftUnsupportedException();
            }

            Login();

            FixupBlogId(ref blogId);

            XmlDocument doc       = new XmlDocument();
            XmlElement  entryNode = doc.CreateElementNS(_atomNS.Uri, _atomNS.Prefix + ":entry");

            doc.AppendChild(entryNode);
            Populate(post, null, entryNode, publish);

            string slug = null;

            if (Options.SupportsSlug)
            {
                slug = post.Slug;
            }

            XmlRestRequestHelper.XmlRequestResult xmlResult2 = new XmlRestRequestHelper.XmlRequestResult();
            xmlResult2.uri = new Uri(blogId);
            XmlDocument result = await xmlRestRequestHelper.Post(
                new HttpAsyncRequestFilter(new NewPostRequest(this, slug).RequestFilter),
                ENTRY_CONTENT_TYPE,
                doc,
                _clientOptions.CharacterSet,
                xmlResult2);

            postResult.ETag = FilterWeakEtag(xmlResult2.responseHeaders["ETag"]);
            string location = xmlResult2.responseHeaders["Location"];

            if (string.IsNullOrEmpty(location))
            {
                throw new BlogClientInvalidServerResponseException("POST", "The HTTP response was missing the required Location header.", "");
            }
            if (location != xmlResult2.responseHeaders["Content-Location"] || result == null)
            {
                XmlRestRequestHelper.XmlRequestResult xmlResult = new XmlRestRequestHelper.XmlRequestResult();
                xmlResult.uri = new Uri(location);
                result        = await xmlRestRequestHelper.Get(RequestFilter, xmlResult);

                postResult.ETag = FilterWeakEtag(xmlResult.responseHeaders["ETag"]);
            }

            postResult.AtomRemotePost = (XmlDocument)result.CloneNode(true);
            Parse(result.DocumentElement, true, xmlResult2.uri);

            if (Options.SupportsNewCategories)
            {
                foreach (BlogPostCategory category in post.NewCategories)
                {
                    newCategoryContext.NewCategoryAdded(category);
                }
            }

            return(PostUriToPostId(location));
        }
Example #54
0
        public void AddCategory(BlogPostCategory category)
        {
            XmlElement catEl = _atomVer.CreateCategoryElement(_entryNode.OwnerDocument, category.Id, _categoryScheme, category.Name);

            _entryNode.AppendChild(catEl);
        }
Example #55
0
 private void OpenInlineElement(XmlElement htmlInlineElement)
 {
     _pendingInlineElements.Push(htmlInlineElement);
 }
Example #56
0
        protected async Task <BlogInfo[]> GetUsersBlogsInternal()
        {
            XmlRestRequestHelper.XmlRequestResult xmlResult = new XmlRestRequestHelper.XmlRequestResult();
            xmlResult.uri = FeedServiceUrl;
            XmlDocument xmlDoc = await xmlRestRequestHelper.Get(RequestFilter, xmlResult);

            // Either the FeedServiceUrl points to a service document OR a feed.

            if (xmlDoc.SelectSingleNodeNS("/app:service", _nsMgr.ToNSMethodFormat()) != null)
            {
                ArrayList blogInfos = new ArrayList();
                foreach (XmlElement coll in xmlDoc.SelectNodesNS("/app:service/app:workspace/app:collection", _nsMgr.ToNSMethodFormat()))
                {
                    bool promote = ShouldPromote(coll);

                    // does this collection accept entries?
                    XmlNodeList acceptNodes    = coll.SelectNodesNS("app:accept", _nsMgr.ToNSMethodFormat());
                    bool        acceptsEntries = false;
                    if (acceptNodes.Count == 0)
                    {
                        acceptsEntries = true;
                    }
                    else
                    {
                        foreach (XmlElement acceptNode in acceptNodes)
                        {
                            if (AcceptsEntry(acceptNode.InnerText))
                            {
                                acceptsEntries = true;
                                break;
                            }
                        }
                    }

                    if (acceptsEntries)
                    {
                        string feedUrl = XmlHelper.GetUrl(coll, "@href", xmlResult.uri);
                        if (feedUrl == null || feedUrl.Length == 0)
                        {
                            continue;
                        }

                        // form title
                        StringBuilder titleBuilder = new StringBuilder();
                        foreach (XmlElement titleContainerNode in new XmlElement[] { coll.ParentNode as XmlElement, coll })
                        {
                            Debug.Assert(titleContainerNode != null);
                            if (titleContainerNode != null)
                            {
                                XmlElement titleNode = titleContainerNode.SelectSingleNodeNS("atom:title", _nsMgr.ToNSMethodFormat()) as XmlElement;
                                if (titleNode != null)
                                {
                                    string titlePart = _atomVer.TextNodeToPlaintext(titleNode);
                                    if (titlePart.Length != 0)
                                    {
                                        //Res.LOCME("loc the separator between parts of the blog name");
                                        if (titleBuilder.Length != 0)
                                        {
                                            titleBuilder.Append(" - ");
                                        }
                                        titleBuilder.Append(titlePart);
                                    }
                                }
                            }
                        }

                        // get homepage URL
                        string homepageUrl = "";
                        string dummy       = "";


                        XmlRestRequestHelper.XmlRequestResult xmlResult2 = new XmlRestRequestHelper.XmlRequestResult();
                        xmlResult2.uri = new Uri(feedUrl);
                        XmlDocument feedDoc = await xmlRestRequestHelper.Get(RequestFilter, xmlResult2);

                        ParseFeedDoc(feedDoc, xmlResult2.uri, false, ref homepageUrl, ref dummy);

                        // TODO: Sniff out the homepage URL
                        BlogInfo blogInfo = new BlogInfo(feedUrl, titleBuilder.ToString().Trim(), homepageUrl);
                        if (promote)
                        {
                            blogInfos.Insert(0, blogInfo);
                        }
                        else
                        {
                            blogInfos.Add(blogInfo);
                        }
                    }
                }

                return((BlogInfo[])blogInfos.ToArray(typeof(BlogInfo)));
            }
            else
            {
                string title       = string.Empty;
                string homepageUrl = string.Empty;

                ParseFeedDoc(xmlDoc, xmlResult.uri, true, ref homepageUrl, ref title);

                return(new BlogInfo[] { new BlogInfo(UrlHelper.SafeToAbsoluteUri(FeedServiceUrl), title, homepageUrl) });
            }
        }
Example #57
0
        // Opens structurig element such as Div or Table etc.
        private void OpenStructuringElement(XmlElement htmlElement)
        {
            // Close all pending inline elements
            // All block elements are considered as delimiters for inline elements
            // which forces all inline elements to be closed and re-opened in the following
            // structural element (if any).
            // By doing that we guarantee that all inline elements appear only within most nested blocks
            if (HtmlSchema.IsBlockElement((string)htmlElement.LocalName))
            {
                while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement((string)_openedElements.Peek().LocalName))
                {
                    XmlElement htmlInlineElement = _openedElements.Pop();

                    InvariantAssert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here");

                    _pendingInlineElements.Push(CreateElementCopy(htmlInlineElement));
                }
            }

            // Add this block element to its parent
            if (_openedElements.Count > 0)
            {
                XmlElement htmlParent = _openedElements.Peek();

                // Check some known block elements for auto-closing (LI and P)
                if (HtmlSchema.ClosesOnNextElementStart((string)htmlParent.LocalName, (string)htmlElement.LocalName))
                {
                    _openedElements.Pop();
                    htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null;
                }

                if (htmlParent != null)
                {
                    // NOTE:
                    // Actually we never expect null - it would mean two top-level P or LI (without a parent).
                    // In such weird case we will loose all paragraphs except the first one...
                    htmlParent.AppendChild(htmlElement);
                }
            }

            // Push it onto a stack
            _openedElements.Push(htmlElement);
        }
Example #58
0
        public virtual async Task <bool> EditPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, EditPostResult result)
        {
            if (!publish && !Options.SupportsPostAsDraft)
            {
                //Debug.Fail("Post to draft not supported on this provider");
                throw new BlogClientPostAsDraftUnsupportedException();
            }

            Login();

            FixupBlogId(ref blogId);

            XmlDocument doc       = post.AtomRemotePost;
            XmlElement  entryNode = doc.SelectSingleNodeNS("/atom:entry", _nsMgr.ToNSMethodFormat()) as XmlElement;

            // No documentUri is needed because we ensure xml:base is set on the root
            // when we retrieve from XmlRestRequestHelper
            Populate(post, null, entryNode, publish);
            string etagToMatch = FilterWeakEtag(post.ETag);

            try
            {
retry:
                try
                {
                    XmlRestRequestHelper.XmlRequestResult xmlResult2 = new XmlRestRequestHelper.XmlRequestResult();
                    xmlResult2.uri = PostIdToPostUri(post.Id);
                    await xmlRestRequestHelper.Put(etagToMatch, RequestFilter, ENTRY_CONTENT_TYPE, doc, _clientOptions.CharacterSet, true, xmlResult2);
                }
                catch (WebException we)
                {
                    if (we.Status == WebExceptionStatus.ProtocolError)
                    {
                        if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.PreconditionFailed)
                        {
                            if (etagToMatch != null && etagToMatch.Length > 0)
                            {
                                HttpRequestHelper.LogException(we);

                                string currentEtag = await GetEtag(UrlHelper.SafeToAbsoluteUri(PostIdToPostUri(post.Id)));

                                if (currentEtag != null && currentEtag.Length > 0 &&
                                    currentEtag != etagToMatch)
                                {
                                    if (ConfirmOverwrite())
                                    {
                                        etagToMatch = currentEtag;
                                        goto retry;
                                    }
                                    else
                                    {
                                        throw new BlogClientOperationCancelledException();
                                    }
                                }
                            }
                        }
                    }
                    throw;
                }
            }
            catch (Exception e)
            {
                if (!AttemptEditPostRecover(e, blogId, post, newCategoryContext, publish, result))
                {
                    // convert to a provider exception if this is a 404 (allow us to
                    // catch this case explicitly and attempt a new post to recover)
                    if (e is WebException)
                    {
                        WebException    webEx    = e as WebException;
                        HttpWebResponse response = webEx.Response as HttpWebResponse;
                        if (response != null && response.StatusCode == HttpStatusCode.NotFound)
                        {
                            throw new BlogClientProviderException("404", e.Message);
                        }
                    }

                    // no special handling, just re-throw
                    throw;
                }
            }

            XmlRestRequestHelper.XmlRequestResult xmlResult = new XmlRestRequestHelper.XmlRequestResult();
            xmlResult.uri             = PostIdToPostUri(post.Id);
            xmlResult.responseHeaders = new HttpResponseMessage().Headers;
            result.remotePost         = await xmlRestRequestHelper.Get(RequestFilter, xmlResult);

            result.etag = FilterWeakEtag(xmlResult.responseHeaders["ETag"]);
            //Debug.Assert(remotePost != null, "After successful PUT, remote post could not be retrieved");

            if (Options.SupportsNewCategories)
            {
                foreach (BlogPostCategory category in post.NewCategories)
                {
                    newCategoryContext.NewCategoryAdded(category);
                }
            }

            return(true);
        }
Example #59
0
        protected async Task <BlogPost[]> GetRecentPostsInternal(string blogId, int maxPosts, bool includeCategories, DateTime?now)
        {
            Login();

            FixupBlogId(ref blogId);

            HashSet <string> seenIds = new HashSet <string>();

            ArrayList blogPosts = new ArrayList();

            try
            {
                while (true)
                {
                    XmlDocument doc;
                    XmlRestRequestHelper.XmlRequestResult result = new XmlRestRequestHelper.XmlRequestResult();
                    result.uri = new Uri(blogId);

                    // This while-loop nonsense is necessary because New Blogger has a bug
                    // where the official URL for getting recent posts doesn't work when
                    // the orderby=published flag is set, but there's an un-official URL
                    // that will work correctly. Therefore, subclasses need the ability
                    // to inspect exceptions that occur, along with the URI that was used
                    // to make the request, and determine whether an alternate URI should
                    // be used.
                    while (true)
                    {
                        try
                        {
                            doc = await xmlRestRequestHelper.Get(RequestFilter, result);

                            break;
                        }
                        catch (Exception e)
                        {
                            //Debug.WriteLine(e.ToString());
                            if (AttemptAlternateGetRecentPostUrl(e, ref blogId))
                            {
                                continue;
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }

                    XmlNodeList nodeList = doc.SelectNodesNS("/atom:feed/atom:entry", _nsMgr.ToNSMethodFormat());
                    if (nodeList.Count == 0)
                    {
                        break;
                    }
                    foreach (XmlElement node in nodeList)
                    {
                        BlogPost blogPost = this.Parse(node, includeCategories, result.uri);
                        if (blogPost != null)
                        {
                            if (seenIds.Contains(blogPost.Id))
                            {
                                throw new DuplicateEntryIdException();
                            }
                            seenIds.Add(blogPost.Id);

                            if (!now.HasValue || blogPost.DatePublished.CompareTo(now.Value) < 0)
                            {
                                blogPosts.Add(blogPost);
                            }
                        }
                        if (blogPosts.Count >= maxPosts)
                        {
                            break;
                        }
                    }
                    if (blogPosts.Count >= maxPosts)
                    {
                        break;
                    }

                    XmlElement nextNode = doc.SelectSingleNodeNS("/atom:feed/atom:link[@rel='next']", _nsMgr.ToNSMethodFormat()) as XmlElement;
                    if (nextNode == null)
                    {
                        break;
                    }
                    blogId = XmlHelper.GetUrl(nextNode, "@href", result.uri);
                    if (blogId.Length == 0)
                    {
                        break;
                    }
                }
            }
            catch (DuplicateEntryIdException)
            {
                //if (ApplicationDiagnostics.AutomationMode)
                //    Debug.WriteLine("Duplicate IDs detected in feed");
                //else
                //    Debug.Fail("Duplicate IDs detected in feed");
            }
            return((BlogPost[])blogPosts.ToArray(typeof(BlogPost)));
        }
Example #60
0
        /// <summary>
        /// Take the blog post data and put it into the XML node.
        /// </summary>
        protected virtual void Populate(BlogPost post, Uri documentUri, XmlElement node, bool publish)
        {
            AtomEntry atomEntry = new AtomEntry(_atomVer, _atomNS, CategoryScheme, _nsMgr, documentUri, node);

            if (post.IsNew)
            {
                atomEntry.GenerateId();
            }
            atomEntry.Title = post.Title;
            if (Options.SupportsExcerpt && post.Excerpt != null && post.Excerpt.Length > 0)
            {
                atomEntry.Excerpt = post.Excerpt;
            }
            // extra space is to work around AOL Journals XML parsing bug
            atomEntry.ContentHtml = post.Contents + " ";
            if (Options.SupportsCustomDate && post.HasDatePublishedOverride)
            {
                atomEntry.PublishDate = post.DatePublishedOverride;
            }

            if (Options.SupportsCategories)
            {
                atomEntry.ClearCategories();

                foreach (BlogPostCategory cat in post.Categories)
                {
                    if (!BlogPostCategoryNone.IsCategoryNone(cat))
                    {
                        atomEntry.AddCategory(cat);
                    }
                }

                if (Options.SupportsNewCategories)
                {
                    foreach (BlogPostCategory cat in post.NewCategories)
                    {
                        if (!BlogPostCategoryNone.IsCategoryNone(cat))
                        {
                            atomEntry.AddCategory(cat);
                        }
                    }
                }
            }

            if (Options.SupportsPostAsDraft)
            {
                // remove existing draft nodes
                while (true)
                {
                    var draftNode = node.SelectSingleNodeNS(@"app:control/app:draft", _nsMgr.ToNSMethodFormat());
                    if (draftNode == null)
                    {
                        break;
                    }
                    draftNode.ParentNode.RemoveChild(draftNode);
                }

                if (!publish)
                {
                    // ensure control node exists
                    var controlNode = node.SelectSingleNodeNS(@"app:control", _nsMgr.ToNSMethodFormat());
                    if (controlNode == null)
                    {
                        controlNode = node.OwnerDocument.CreateElementNS(_pubNS.Uri, _pubNS.Prefix + ":control");
                        node.AppendChild(controlNode);
                    }
                    // create new draft node
                    XmlElement newDraftNode = node.OwnerDocument.CreateElementNS(_pubNS.Uri, _pubNS.Prefix + ":draft");
                    newDraftNode.InnerText = "yes";
                    controlNode.AppendChild(newDraftNode);
                }
            }

            //post.Categories;
            //post.CommentPolicy;
            //post.CopyFrom;
            //post.Excerpt;
            //post.HasDatePublishedOverride;
            //post.Id;
            //post.IsNew;
            //post.IsTemporary;
            //post.Keywords;
            //post.Link;
            //post.Permalink;
            //post.PingUrls;
            //post.ResetToNewPost;
            //post.TrackbackPolicy;
        }