예제 #1
0
        public void Simple()
        {
            XmlDocument sdoc  = new XmlDocument();
            XmlElement  selem = sdoc.CreateElement(tagname);

            selem.InnerText = content;

            StringBuilder     syndication_string = new StringBuilder();
            XmlWriterSettings settings           = new XmlWriterSettings();
            XmlWriter         syndication        = XmlWriter.Create(syndication_string, settings);

            // Simple tests
            XmlSyndicationContent sxml = new XmlSyndicationContent(type, selem);

            Assert.AreEqual(typeof(XmlSyndicationContent), sxml.GetType(), "#S1");
            Assert.AreEqual(type, sxml.Type.ToString(), "#S2");

            // Check correct invalid argument rejection
            try
            {
                sxml.WriteTo(null, "", "");
                Assert.Fail("#S3 Expected an ArgumentNullException to be thrown.");
            }
            catch (ArgumentNullException) { }
            try
            {
                sxml.WriteTo(syndication, "", "");
                Assert.Fail("#S4 Expected an ArgumentException to be thrown.");
            }
            catch (ArgumentException) { }

            syndication.Close();
        }
예제 #2
0
		public void Type ()
		{
			XmlSyndicationContent t = new XmlSyndicationContent (null, 3, (XmlObjectSerializer) null);
			Assert.AreEqual ("text/xml", t.Type, "#1");
			t = new XmlSyndicationContent ("text/plain", 3, (XmlObjectSerializer) null);
			Assert.AreEqual ("text/plain", t.Type, "#2");
		}
예제 #3
0
        public void Clone()
        {
            XmlSyndicationContent t = new XmlSyndicationContent("text/plain", 3, (XmlObjectSerializer)null);

            t = t.Clone() as XmlSyndicationContent;
            Assert.AreEqual("text/plain", t.Type, "#1");
        }
예제 #4
0
 public object Deserialize(ControllerContext controllerContext, ModelBindingContext bindingContext, ContentType requestFormat)
 {
     if (!CanDeserialize(requestFormat))
     {
         throw new NotSupportedException();
     }
     // We assume an Atom entry is being posted - since a feed is never posted in this example.
     using (XmlReader reader = XmlReader.Create(controllerContext.HttpContext.Request.InputStream, new XmlReaderSettings()
     {
         IgnoreWhitespace = true, IgnoreComments = true
     }))
     {
         SyndicationItem       entry = SyndicationItem.Load(reader);
         XmlSyndicationContent xml   = entry.Content as XmlSyndicationContent;
         if (xml == null)
         {
             throw new InvalidOperationException("Xml content expected in Atom entry");
         }
         DataContractSerializer serializer = new DataContractSerializer(bindingContext.ModelType);
         using (XmlDictionaryReader innerReader = xml.GetReaderAtContent())
         {
             innerReader.ReadStartElement();
             return(serializer.ReadObject(innerReader, false));
         }
     }
 }
예제 #5
0
        public void Type()
        {
            XmlSyndicationContent t = new XmlSyndicationContent(null, 3, (XmlObjectSerializer)null);

            Assert.AreEqual("text/xml", t.Type, "#1");
            t = new XmlSyndicationContent("text/plain", 3, (XmlObjectSerializer)null);
            Assert.AreEqual("text/plain", t.Type, "#2");
        }
예제 #6
0
        public static List <Telemetry> GetTelemetryData(TelemetryInputs inputs)
        {
            string uri = @"https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespaceName}/NotificationHubs/{hubName}/metrics/{metricName}/rollups/{metricRollup}/Values?$filter={filterExpression}";

            uri = uri.Replace("{subscriptionId}", inputs.SubscriptionId);
            uri = uri.Replace("{namespaceName}", inputs.NamespaceName);
            uri = uri.Replace("{hubName}", inputs.NotificationHubName);
            uri = uri.Replace("{metricName}", inputs.MetricName);
            uri = uri.Replace("{metricRollup}", inputs.Rollup.ToString());

            string strFromDate = String.Format("{0:s}", inputs.FromDate);
            string strToDate   = String.Format("{0:s}", inputs.ToDate);

            // See - http://msdn.microsoft.com/library/azure/dn163590.aspx for details
            string filterExpression = String.Format
                                          ("Timestamp%20gt%20datetime'{0}Z'%20and%20Timestamp%20lt%20datetime'{1}Z'",
                                          strFromDate, strToDate);

            uri = uri.Replace("{filterExpression}", filterExpression);

            X509Certificate2 certificate = new X509Certificate2(inputs.PathToCert, inputs.CertPassword);

            HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(uri);

            sendNotificationRequest.Method      = "GET";
            sendNotificationRequest.ContentType = "application/xml";
            sendNotificationRequest.Headers.Add("x-ms-version", "2011-02-25");
            sendNotificationRequest.ClientCertificates.Add(certificate);

            List <Telemetry> data = new List <Telemetry>();

            try
            {
                HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();

                using (XmlReader reader = XmlReader.Create(response.GetResponseStream(),
                                                           new XmlReaderSettings {
                    CloseInput = true
                }))
                {
                    SyndicationFeed feed = SyndicationFeed.Load <SyndicationFeed>(reader);

                    foreach (SyndicationItem item in feed.Items)
                    {
                        XmlSyndicationContent syndicationContent = item.Content as XmlSyndicationContent;
                        MetricValue           value = syndicationContent.ReadContent <MetricValue>();
                        data.Add(new Telemetry(value.Timestamp, value.Total));
                        Console.WriteLine("Timestamp: {0} -> Total: {1}", value.Timestamp, value.Total);
                    }
                }
            }
            catch (WebException exception)
            {
                string error = new StreamReader(exception.Response.GetResponseStream()).ReadToEnd();
                Console.WriteLine(error);
            }
            return(data);
        }
예제 #7
0
        public void WriteTo()
        {
            XmlSyndicationContent t  = new XmlSyndicationContent("text/plain", 6, (XmlObjectSerializer)null);
            StringWriter          sw = new StringWriter();

            using (XmlWriter w = CreateWriter(sw))
                t.WriteTo(w, "root", String.Empty);
            Assert.AreEqual("<root type=\"text/plain\"><int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">6</int></root>", sw.ToString());
        }
        public T DeserializeResourceDescription <T>(string resourceDescription)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            Atom10ItemFormatter    formater   = new Atom10ItemFormatter();

            formater.ReadFrom(new XmlTextReader(new StringReader(resourceDescription)));
            XmlSyndicationContent content = formater.Item.Content as XmlSyndicationContent;

            return(content.ReadContent <T>(serializer));
        }
        public void WriteTo_WithEmptyReader_ReturnsExpected()
        {
            using (var stringReader = new StringReader("<ParentObject />"))
                using (var reader = XmlReader.Create(stringReader))

                {
                    var content = new XmlSyndicationContent(reader);
                    CompareHelper.AssertEqualWriteOutput(@"<OuterElementName type=""text/xml"" xmlns=""OuterElementNamespace"" />", writer => content.WriteTo(writer, "OuterElementName", "OuterElementNamespace"));
                }
        }
예제 #10
0
        public void XmlSerializerExtension()
        {
            DateTime date = new DateTime(2007, 5, 22);

            global::System.Xml.Serialization.XmlSerializer xs =
                new global::System.Xml.Serialization.XmlSerializer(typeof(Content));
            Content item        = new Content();
            string  item_object = "Content";             // tag name for serialized object

            // fill object with some data
            item.author  = author;
            item.comment = comment;
            item.date    = date;

            XmlSyndicationContent se = new XmlSyndicationContent(type, item, xs);

            Assert.AreEqual(typeof(XmlSyndicationContent), se.GetType(), "#SE1");
            Assert.AreEqual(type, se.Type.ToString(), "#SE2");
            Assert.AreSame(item, se.Extension.Object, "#SE3");
            Assert.AreEqual(SyndicationElementExtensionKind.XmlSerializer, se.Extension.ExtensionKind, "#SE4");
            Assert.AreSame(xs, se.Extension.ObjectSerializer, "#SE5");

            // Create fake IO using stringbuilders
            StringBuilder object_string      = new StringBuilder();
            StringBuilder syndication_string = new StringBuilder();

            XmlWriterSettings settings = new XmlWriterSettings();

            XmlWriter serobj      = XmlWriter.Create(object_string, settings);
            XmlWriter syndication = XmlWriter.Create(syndication_string, settings);

            xs.Serialize(serobj, item);
            se.WriteTo(syndication, documentname, "");

            serobj.Close();
            syndication.Close();

            // Pickout the 'Content' tag from original serialized object and syndicated document
            XmlDocument syndoc = new XmlDocument();
            XmlDocument serdoc = new XmlDocument();

            syndoc.LoadXml(syndication_string.ToString());
            XmlNodeList synresult = syndoc.GetElementsByTagName(item_object);
            XmlNodeList syntype   = syndoc.GetElementsByTagName(documentname);

            serdoc.LoadXml(object_string.ToString());
            XmlNodeList serresult = serdoc.GetElementsByTagName(item_object);

            // Check document type
            Assert.AreEqual(type, syntype.Item(0).Attributes.GetNamedItem("type").Value.ToString(),
                            "SE6");
            // Check content
            Assert.AreEqual(serresult.Item(0).OuterXml.ToString(), synresult.Item(0).OuterXml.ToString(),
                            "SE6");
        }
예제 #11
0
        public void GetReaderAtContent()
        {
            var x = new SyndicationElementExtension(6);

            // premise.
            Assert.AreEqual("<int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">6</int>", x.GetReader().ReadOuterXml(), "#1");

            var t = new XmlSyndicationContent("text/xml", 6, (XmlObjectSerializer)null);

            Assert.AreEqual("<content type=\"text/xml\" xmlns=\"http://www.w3.org/2005/Atom\"><int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">6</int></content>", t.GetReaderAtContent().ReadOuterXml(), "#2");
        }
        public void Clone_Empty_ReturnsExpected()
        {
            var content = new SyndicationElementExtension(new ExtensionObject {
                Value = 10
            });
            var original = new XmlSyndicationContent("type", content);
            XmlSyndicationContent clone = Assert.IsType <XmlSyndicationContent>(original.Clone());

            Assert.Empty(clone.AttributeExtensions);
            Assert.Same(original.Extension, clone.Extension);
            Assert.Equal("type", clone.Type);
        }
        public void Ctor_XmlSyndicationContent_Empty()
        {
            var content = new SyndicationElementExtension(new ExtensionObject {
                Value = 10
            });
            var original = new XmlSyndicationContent("type", content);
            var clone    = new XmlSyndicationContentSubclass(original);

            Assert.Empty(clone.AttributeExtensions);
            Assert.Same(original.Extension, clone.Extension);
            Assert.Equal("type", clone.Type);
        }
        public void GetReaderAtContent_ObjectWithXmlSerializer_ReturnsExpected()
        {
            var extensionObject = new ExtensionObject()
            {
                Value = 10
            };
            var content = new XmlSyndicationContent("type", extensionObject, new XmlSerializer(typeof(ExtensionObject)));

            using (XmlReader reader = content.GetReaderAtContent())
            {
                CompareHelper.AssertEqualLongString(@"<content type=""type"" xmlns=""http://www.w3.org/2005/Atom""><ExtensionObject xmlns="""" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><Value>10</Value></ExtensionObject></content>", reader.ReadOuterXml());
            }
        }
        public void GetReaderAtContent_ObjectWithXmlObjectSerializer_ReturnsExpected()
        {
            var extensionObject = new ExtensionObject()
            {
                Value = 10
            };
            var content = new XmlSyndicationContent("type", extensionObject, new DataContractSerializer(typeof(ExtensionObject)));

            using (XmlReader reader = content.GetReaderAtContent())
            {
                CompareHelper.AssertEqualLongString(@"<content type=""type"" xmlns=""http://www.w3.org/2005/Atom""><XmlSyndicationContentTests.ExtensionObject xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Value>10</Value></XmlSyndicationContentTests.ExtensionObject></content>", reader.ReadOuterXml());
            }
        }
        public void GetReaderAtContent_WithReader_ReturnsExpected()
        {
            var content = new XmlSyndicationContent(
                new XElement("ParentObject",
                             new XElement("ExtensionObject",
                                          new XElement("Value", 10)
                                          )
                             ).CreateReader()
                );
            XmlReader reader = content.GetReaderAtContent();

            CompareHelper.AssertEqualLongString(@"<ParentObject><ExtensionObject><Value>10</Value></ExtensionObject></ParentObject>", reader.ReadOuterXml());
        }
예제 #17
0
        public void XmlElementExtension()
        {
            XmlDocument xdoc  = new XmlDocument();
            XmlElement  xelem = xdoc.CreateElement(tagname);

            xelem.InnerText = content;

            // Same as Simple tests as setup for XmlElementExtension tests
            XmlSyndicationContent xxml = new XmlSyndicationContent(type, xelem);

            Assert.AreEqual(typeof(XmlSyndicationContent), xxml.GetType(), "#XE1");
            Assert.AreEqual(type, xxml.Type.ToString(), "#XE2");
            Assert.AreSame(xelem, xxml.Extension.Object, "#XE3");
            Assert.AreEqual(SyndicationElementExtensionKind.XmlElement, xxml.Extension.ExtensionKind, "#XE4");
            Assert.AreEqual(null, xxml.Extension.ObjectSerializer, "#XE5");

            // Create fake IO using stringbuilders
            StringBuilder element_string     = new StringBuilder();
            StringBuilder syndication_string = new StringBuilder();

            XmlWriterSettings settings = new XmlWriterSettings();

            XmlWriter element     = XmlWriter.Create(element_string, settings);
            XmlWriter syndication = XmlWriter.Create(syndication_string, settings);

            // Make sure we get the input data back out
            xelem.WriteTo(element);
            xxml.WriteTo(syndication, documentname, "");

            element.Close();
            syndication.Close();

            // Pickout the 'channel' and 'stuff' tags from original and syndicated document
            XmlDocument syndoc = new XmlDocument();
            XmlDocument eledoc = new XmlDocument();

            syndoc.LoadXml(syndication_string.ToString());
            XmlNodeList synresult = syndoc.GetElementsByTagName(tagname);
            XmlNodeList syntype   = syndoc.GetElementsByTagName(documentname);

            eledoc.LoadXml(element_string.ToString());
            XmlNodeList eleresult = eledoc.GetElementsByTagName(tagname);

            // Check document type
            Assert.AreEqual(type, syntype.Item(0).Attributes.GetNamedItem("type").Value.ToString(),
                            "XE6");
            // Check content
            Assert.AreEqual(eleresult.Item(0).OuterXml.ToString(), synresult.Item(0).OuterXml.ToString(),
                            "XE7");
        }
예제 #18
0
        static void Main(string[] args)
        {
            //Expand this region to see the code for hosting a Syndication Feed.
            #region Service

            WebServiceHost host = new WebServiceHost(typeof(ProcessService), new Uri("http://localhost:8000/diagnostics"));

            //The WebServiceHost will automatically provide a default endpoint at the base address
            //using the proper binding (the WebHttpBinding) and endpoint behavior (the WebHttpBehavior)
            host.Open();

            Console.WriteLine("Service host open");

            //The syndication feeds exposed by the service are available
            //at the following URI (for Atom use feed/?format=atom)

            // http://localhost:8000/diagnostics/feed/?format=rss

            //These feeds can be viewed directly in an RSS-aware client
            //such as IE7.
            #endregion

            //Expand this region to see the code for accessing a Syndication Feed.
            #region Client

            // Change the value of the feed query string to 'atom' to use Atom format.
            XmlReader reader = XmlReader.Create("http://localhost:8000/diagnostics/feed?format=rss",
                                                new XmlReaderSettings()
            {
                //MaxCharactersInDocument can be used to control the maximum amount of data
                //read from the reader and helps prevent OutOfMemoryException
                MaxCharactersInDocument = 1024 * 64
            });


            SyndicationFeed feed = SyndicationFeed.Load(reader);

            foreach (SyndicationItem i in feed.Items)
            {
                XmlSyndicationContent content = i.Content as XmlSyndicationContent;
                ProcessData           pd      = content.ReadContent <ProcessData>();

                Console.WriteLine(i.Title.Text);
                Console.WriteLine(pd.ToString());
            }
            #endregion

            //Press any key to end the program.
            Console.ReadLine();
        }
        public void Ctor_Type_SyndicationElementExtension_XmlObjectSerializer(string type, XmlObjectSerializer dataContractSerializer)
        {
            var content = new XmlSyndicationContent(type, new ExtensionObject {
                Value = 10
            }, dataContractSerializer);

            Assert.Empty(content.AttributeExtensions);
            Assert.Equal(string.IsNullOrEmpty(type) ? "text/xml" : type, content.Type);
            Assert.Equal(10, content.Extension.GetObject <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>().Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new DataContractSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlObjectSerializer)null).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlSerializer)null).Value);
        }
        public void WriteTo_ObjectWithXmlObjectSerializer_ReturnsExpected()
        {
            var extensionObject = new ExtensionObject()
            {
                Value = 10
            };
            var content = new XmlSyndicationContent("type", extensionObject, new DataContractSerializer(typeof(ExtensionObject)));

            CompareHelper.AssertEqualWriteOutput(
                @"<OuterElementName type=""type"" xmlns=""OuterElementNamespace"">
    <XmlSyndicationContentTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
        <Value>10</Value>
    </XmlSyndicationContentTests.ExtensionObject>
</OuterElementName>", writer => content.WriteTo(writer, "OuterElementName", "OuterElementNamespace"));
        }
        public void CreateXmlContent_XmlSerializer_ReturnsExpected(XmlSerializer serializer)
        {
            XmlSyndicationContent content = SyndicationContent.CreateXmlContent(new ExtensionObject {
                Value = 10
            }, serializer);

            Assert.Empty(content.AttributeExtensions);
            Assert.Equal("text/xml", content.Type);
            Assert.Equal(10, content.Extension.GetObject <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>().Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new DataContractSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlObjectSerializer)null).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlSerializer)null).Value);
        }
        public void WriteTo_ObjectWithXmlSerializer_ReturnsExpected()
        {
            var extensionObject = new ExtensionObject()
            {
                Value = 10
            };
            var content = new XmlSyndicationContent("type", extensionObject, new XmlSerializer(typeof(ExtensionObject)));

            CompareHelper.AssertEqualWriteOutput(
                @"<OuterElementName type=""type"" xmlns=""OuterElementNamespace"">
    <ExtensionObject xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns="""">
        <Value>10</Value>
    </ExtensionObject>
</OuterElementName>", writer => content.WriteTo(writer, "OuterElementName", "OuterElementNamespace"));
        }
예제 #23
0
        /// <summary>
        /// Gets the XmlReader for the m:properties element under the atom:content element
        /// </summary>
        /// <param name="item">item to read from</param>
        /// <returns>XmlReader for the m:properties element if found, null otherwise.</returns>
        private static XmlReader GetPropertiesReaderFromContent(SyndicationItem item)
        {
            XmlSyndicationContent itemContent = item.Content as XmlSyndicationContent;
            XmlReader             reader      = null;

            if (itemContent != null)
            {
                string contentType = itemContent.Type;
                if (!WebUtil.CompareMimeType(contentType, XmlConstants.MimeApplicationXml))
                {
                    throw DataServiceException.CreateBadRequestError(
                              Strings.Syndication_EntryContentTypeUnsupported(contentType));
                }

                bool shouldDispose = false;
                try
                {
                    reader = itemContent.GetReaderAtContent();
                    WebUtil.XmlReaderEnsureElement(reader);
                    Debug.Assert(
                        reader.NodeType == XmlNodeType.Element,
                        reader.NodeType.ToString() + " == XmlNodeType.Element -- otherwise XmlSyndicationContent didn't see a 'content' tag");

                    reader.ReadStartElement(XmlConstants.AtomContentElementName, XmlConstants.AtomNamespace);
                    if (!reader.IsStartElement(XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace))
                    {
                        shouldDispose = true;
                    }
                }
                catch
                {
                    shouldDispose = true;
                    throw;
                }
                finally
                {
                    if (shouldDispose)
                    {
                        WebUtil.Dispose(reader);
                        reader = null;
                    }
                }
            }

            return(reader);
        }
        public void WriteTo_WithReader_ReturnsExpected()
        {
            var content = new XmlSyndicationContent(
                new XElement("ParentObject",
                             new XElement("ExtensionObject",
                                          new XElement("Value", 10)
                                          )
                             ).CreateReader()
                );

            CompareHelper.AssertEqualWriteOutput(
                @"<OuterElementName type=""text/xml"" xmlns=""OuterElementNamespace"">
    <ExtensionObject xmlns="""">
        <Value>10</Value>
    </ExtensionObject>
</OuterElementName>", writer => content.WriteTo(writer, "OuterElementName", "OuterElementNamespace"));
        }
        public void Clone_Full_ReturnsExpected()
        {
            var content = new SyndicationElementExtension(new ExtensionObject {
                Value = 10
            });
            var original = new XmlSyndicationContent("type", content);

            original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value");

            XmlSyndicationContent clone = Assert.IsType <XmlSyndicationContent>(original.Clone());

            Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions);
            Assert.Equal(1, clone.AttributeExtensions.Count);
            Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]);

            Assert.Same(original.Extension, clone.Extension);
            Assert.Equal("type", clone.Type);
        }
        public void Ctor_XmlSyndicationContent_Full()
        {
            var content = new SyndicationElementExtension(new ExtensionObject {
                Value = 10
            });
            var original = new XmlSyndicationContent("type", content);

            original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value");

            var clone = new XmlSyndicationContentSubclass(original);

            Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions);
            Assert.Equal(1, clone.AttributeExtensions.Count);
            Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]);

            Assert.Same(original.Extension, clone.Extension);
            Assert.Equal("type", clone.Type);
        }
        public void Ctor_Reader_NoAttributes()
        {
            var content = new XmlSyndicationContent(
                new XElement("ParentObject",
                             new XElement("ExtensionObject",
                                          new XElement("Value", 10)
                                          )
                             ).CreateReader()
                );

            Assert.Empty(content.AttributeExtensions);
            Assert.Equal("text/xml", content.Type);
            Assert.Null(content.Extension);
            Assert.Equal(0, content.ReadContent <ExtensionObject>().Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>(new DataContractSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>((XmlObjectSerializer)null).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlSerializer)null).Value);
        }
        public void Ctor_Reader_Attributes()
        {
            var content = new XmlSyndicationContent(
                new XElement("ParentObject", new XAttribute("type", "CustomType"), new XAttribute(XNamespace.Xmlns + "name", "ignored"), new XAttribute("name1", "value1"), new XAttribute(XNamespace.Get("namespace") + "name2", "value2"),
                             new XElement("ExtensionObject", new XAttribute("ignored", "value"),
                                          new XElement("Value", 10)
                                          )
                             ).CreateReader()
                );

            Assert.Equal(2, content.AttributeExtensions.Count);
            Assert.Equal("value1", content.AttributeExtensions[new XmlQualifiedName("name1")]);
            Assert.Equal("value2", content.AttributeExtensions[new XmlQualifiedName("name2", "namespace")]);
            Assert.Equal("CustomType", content.Type);
            Assert.Null(content.Extension);
            Assert.Equal(0, content.ReadContent <ExtensionObject>().Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>(new DataContractSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>((XmlObjectSerializer)null).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlSerializer)null).Value);
        }
예제 #29
0
        /// <summary>
        /// Find the m:properties element within a feed entry
        /// </summary>
        /// <param name="item">The feed entry</param>
        /// <returns>The m:properties element</returns>
        private static XElement GetPropertiesElement(SyndicationItem item)
        {
            // Check if the m:properties element is within the content element
            XmlSyndicationContent xmlContent = item.Content as XmlSyndicationContent;

            if (xmlContent != null)
            {
                XElement contentElement = XElement.Load(xmlContent.GetReaderAtContent());
                return(contentElement.Elements().FirstOrDefault(e => e.Name == XName.Get("properties", odataMetaXmlNs)));
            }
            // If we're here, then we are dealing with a feed that has an MLE
            // i.e. the m:properties element is a peer of the content element, and shows up
            // in the elementExtensions instead
            SyndicationElementExtension propertiesElementExtension = item.ElementExtensions.FirstOrDefault(e => e.OuterName.Equals("properties"));

            if (propertiesElementExtension != null)
            {
                XNode propertiesElement = XNode.ReadFrom(propertiesElementExtension.GetReader());
                return((XElement)propertiesElement);
            }

            throw new NotSupportedException("Unsupported feed entry format");
        }
예제 #30
0
		public void XmlElementExtension ()
		{
			XmlDocument xdoc = new XmlDocument ();
			XmlElement xelem = xdoc.CreateElement (tagname);
			xelem.InnerText = content;

			// Same as Simple tests as setup for XmlElementExtension tests
			XmlSyndicationContent xxml = new XmlSyndicationContent (type, xelem);

			Assert.AreEqual (typeof (XmlSyndicationContent), xxml.GetType (), "#XE1");
			Assert.AreEqual (type, xxml.Type.ToString (), "#XE2");
			Assert.AreSame (xelem, xxml.Extension.Object, "#XE3");
			Assert.AreEqual (SyndicationElementExtensionKind.XmlElement, xxml.Extension.ExtensionKind, "#XE4");
			Assert.AreEqual (null, xxml.Extension.ObjectSerializer, "#XE5");

			// Create fake IO using stringbuilders
			StringBuilder element_string = new StringBuilder ();
			StringBuilder syndication_string = new StringBuilder ();

			XmlWriterSettings settings = new XmlWriterSettings ();

			XmlWriter element = XmlWriter.Create (element_string, settings);
			XmlWriter syndication = XmlWriter.Create (syndication_string, settings);

			// Make sure we get the input data back out
			xelem.WriteTo (element);
			xxml.WriteTo (syndication, documentname, "");

			element.Close ();
			syndication.Close ();

			// Pickout the 'channel' and 'stuff' tags from original and syndicated document
			XmlDocument syndoc = new XmlDocument();
			XmlDocument eledoc = new XmlDocument();

			syndoc.LoadXml (syndication_string.ToString ());
			XmlNodeList synresult = syndoc.GetElementsByTagName (tagname);
			XmlNodeList syntype = syndoc.GetElementsByTagName (documentname);

			eledoc.LoadXml (element_string.ToString ());
			XmlNodeList eleresult = eledoc.GetElementsByTagName (tagname);

			// Check document type
			Assert.AreEqual(type, syntype.Item (0).Attributes.GetNamedItem ("type").Value.ToString (),
					     "XE6");
			// Check content
			Assert.AreEqual (eleresult.Item (0).OuterXml.ToString (), synresult.Item (0).OuterXml.ToString (),
					      "XE7");
		}
예제 #31
0
		public void Clone ()
		{
			XmlSyndicationContent t = new XmlSyndicationContent ("text/plain", 3, (XmlObjectSerializer) null);
			t = t.Clone () as XmlSyndicationContent;
			Assert.AreEqual ("text/plain", t.Type, "#1");
		}
예제 #32
0
		public void GetReaderAtContent ()
		{
			var x = new SyndicationElementExtension (6);
			// premise.
			Assert.AreEqual ("<int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">6</int>", x.GetReader ().ReadOuterXml (), "#1");

			var t = new XmlSyndicationContent ("text/xml", 6, (XmlObjectSerializer) null);
			Assert.AreEqual ("<content type=\"text/xml\" xmlns=\"http://www.w3.org/2005/Atom\"><int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">6</int></content>", t.GetReaderAtContent ().ReadOuterXml (), "#2");
		}
예제 #33
0
		public void WriteTo ()
		{
			XmlSyndicationContent t = new XmlSyndicationContent ("text/plain", 6, (XmlObjectSerializer) null);
			StringWriter sw = new StringWriter ();
			using (XmlWriter w = CreateWriter (sw))
				t.WriteTo (w, "root", String.Empty);
			Assert.AreEqual ("<root type=\"text/plain\"><int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">6</int></root>", sw.ToString ());
		}
예제 #34
0
        /// <summary>
        /// Updates the resource property.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="atomEntry">The atom entry.</param>
        private static void UpdateResourceProperty(
            ZentityContext context,
            ScholarlyWork resource,
            AtomEntryDocument atomEntry)
        {
            resource.Title = atomEntry.Title.Text;
            SetContentType(context, resource, atomEntry.Title.Type, AtomPubConstants.TitleTypeProperty);
            resource.DateModified = DateTime.Now;
            Publication publication = resource as Publication;

            if (null != publication && atomEntry.PublishDate != DateTimeOffset.MinValue)
            {
                publication.DatePublished = atomEntry.PublishDate.DateTime;
            }

            if (null != atomEntry.Copyright)
            {
                resource.Copyright = atomEntry.Copyright.Text;
                SetContentType(context, resource, atomEntry.Copyright.Type, AtomPubConstants.CopyrightTypeProperty);
            }

            if (null != atomEntry.Summary && !string.IsNullOrEmpty(atomEntry.Summary.Text))
            {
                SetExtensionProperty(context, resource, AtomPubConstants.SummaryProperty, atomEntry.Summary.Text);
                SetContentType(context, resource, atomEntry.Summary.Type, AtomPubConstants.SummaryTypeProperty);
            }

            if (null != atomEntry.Content)
            {
                UrlSyndicationContent urlContent = atomEntry.Content as UrlSyndicationContent;

                if (null != urlContent)
                {
                    resource.Description = null;
                    SetExtensionProperty(context, resource, AtomPubConstants.ContentUrlProperty, urlContent.Url.AbsoluteUri);
                }
                else
                {
                    ResourceProperty urlContentProperty = ZentityAtomPubStoreReader.GetResourceProperty(resource, AtomPubConstants.ContentUrlProperty);

                    if (null != urlContentProperty)
                    {
                        resource.ResourceProperties.Remove(urlContentProperty);
                    }

                    TextSyndicationContent textDescription = atomEntry.Content as TextSyndicationContent;

                    if (null != textDescription)
                    {
                        resource.Description = textDescription.Text;
                    }
                    else
                    {
                        XmlSyndicationContent content = atomEntry.Content as XmlSyndicationContent;

                        if (null != content)
                        {
                            XmlDictionaryReader contentReader = content.GetReaderAtContent();
                            StringBuilder       contentValue  = new StringBuilder(151);

                            try
                            {
                                while (contentReader.Read())
                                {
                                    contentValue.Append(contentReader.Value);
                                }
                            }
                            finally
                            {
                                contentReader.Close();
                            }

                            resource.Description = contentValue.ToString();
                        }
                    }
                }

                SetContentType(context, resource, atomEntry.Content.Type, AtomPubConstants.DescriptionTypeProperty);
            }

            if (null != atomEntry.Source)
            {
                ResourceProperty source = ZentityAtomPubStoreReader.GetResourceProperty(resource, AtomPubConstants.SourceProperty);

                if (null == source)
                {
                    Property sourceProperty = GetProperty(context, AtomPubConstants.SourceProperty);
                    source = new ResourceProperty
                    {
                        Property = sourceProperty,
                        Resource = resource,
                    };
                }

                source.Value = atomEntry.Source;
            }

            #region Add Links

            List <ResourceProperty> links = ZentityAtomPubStoreReader.GetResourceProperties(resource, AtomPubConstants.LinksProperty);

            if (0 == atomEntry.XmlLinks.Count && null != links)
            {
                foreach (var item in links)
                {
                    resource.ResourceProperties.Remove(item);
                }
            }

            Property linkProperty = GetProperty(context, AtomPubConstants.LinksProperty);

            foreach (string xmlLink in atomEntry.XmlLinks)
            {
                resource.ResourceProperties.Add(new ResourceProperty
                {
                    Resource = resource,
                    Property = linkProperty,
                    Value    = xmlLink
                });
            }

            #endregion


            var authors = atomEntry.Authors.Select(author => new Person
            {
                Title = author.Name,
                Email = author.Email,
                Uri   = author.Uri
            });
            // Bug Fix : 177689 - AtomPub (M2): Author node is appending after every PUT request instead
            //                    of overwriting it.
            // Remove previous authors.
            resource.Authors.Clear();
            AddPersons(context, resource.Authors, authors);

            resource.Contributors.Clear();
            var contributors = atomEntry.Contributors.Select(author => new Person
            {
                Title = author.Name,
                Email = author.Email,
                Uri   = author.Uri
            });
            AddPersons(context, resource.Contributors, contributors);
        }
 public XmlSyndicationContentSubclass(XmlSyndicationContent source) : base(source)
 {
 }
예제 #36
0
		public void Simple ()
		{
			XmlDocument sdoc = new XmlDocument ();
			XmlElement selem = sdoc.CreateElement (tagname);
			selem.InnerText = content;

			StringBuilder syndication_string = new StringBuilder ();
			XmlWriterSettings settings = new XmlWriterSettings ();
			XmlWriter syndication = XmlWriter.Create (syndication_string, settings);

			// Simple tests
			XmlSyndicationContent sxml = new XmlSyndicationContent (type, selem);

			Assert.AreEqual (typeof (XmlSyndicationContent), sxml.GetType (), "#S1");
			Assert.AreEqual (type, sxml.Type.ToString (), "#S2");

			// Check correct invalid argument rejection
			try
			{
				sxml.WriteTo (null, "", "");
				Assert.Fail ("#S3 Expected an ArgumentNullException to be thrown.");
			}
			catch (ArgumentNullException) { }
			try
			{
				sxml.WriteTo (syndication, "", "");
				Assert.Fail ("#S4 Expected an ArgumentException to be thrown.");
			}
			catch (ArgumentException) { }

			syndication.Close ();
		}
    protected SyndicationContent GetContent(Content content)
    {
      SyndicationContent sc = null;
      if (content != null)
      {
        if (!string.IsNullOrEmpty(content.Url))
        {
          sc = new UrlSyndicationContent(
            !string.IsNullOrEmpty(content.Url) ? null : new Uri(content.Url),
            content.Type);
        }
        if (string.IsNullOrEmpty(content.Type) || content.Type == "xhtml" ||
          content.Type == "html" || content.Type == "text")
        {

          sc = new TextSyndicationContent(content.Text,
            (string.IsNullOrEmpty(content.Type) || content.Type == "text") ?
          TextSyndicationContentKind.Plaintext :
          content.Type == "xhtml" ? TextSyndicationContentKind.XHtml :
          TextSyndicationContentKind.Html);
        }
        else
        {
          sc = new XmlSyndicationContent(content.Type,
           new SyndicationElementExtension(new XmlTextReader(new StringReader(content.Text))));
        }
        LoadAttributes(sc.AttributeExtensions, content.Attributes);
      }
      return sc;
    }
예제 #38
0
		public void XmlSerializerExtension ()
		{
			DateTime date = new DateTime (2007, 5, 22);

			global::System.Xml.Serialization.XmlSerializer xs =
				new global::System.Xml.Serialization.XmlSerializer (typeof (Content));
			Content item = new Content ();
			string item_object = "Content";  // tag name for serialized object

			// fill object with some data
			item.author = author;
			item.comment = comment;
			item.date = date;

			XmlSyndicationContent se = new XmlSyndicationContent (type,item,xs);

			Assert.AreEqual (typeof (XmlSyndicationContent), se.GetType (), "#SE1");
			Assert.AreEqual (type, se.Type.ToString (), "#SE2");
			Assert.AreSame (item, se.Extension.Object, "#SE3");
			Assert.AreEqual (SyndicationElementExtensionKind.XmlSerializer, se.Extension.ExtensionKind, "#SE4");
			Assert.AreSame (xs, se.Extension.ObjectSerializer, "#SE5");

			// Create fake IO using stringbuilders
			StringBuilder object_string = new StringBuilder ();
			StringBuilder syndication_string = new StringBuilder ();

			XmlWriterSettings settings = new XmlWriterSettings ();

			XmlWriter serobj = XmlWriter.Create (object_string, settings);
			XmlWriter syndication = XmlWriter.Create (syndication_string, settings);

			xs.Serialize (serobj, item);
			se.WriteTo (syndication, documentname, "");

			serobj.Close ();
			syndication.Close ();

			// Pickout the 'Content' tag from original serialized object and syndicated document
			XmlDocument syndoc = new XmlDocument ();
			XmlDocument serdoc = new XmlDocument ();

			syndoc.LoadXml (syndication_string.ToString ());
			XmlNodeList synresult = syndoc.GetElementsByTagName (item_object);
			XmlNodeList syntype = syndoc.GetElementsByTagName (documentname);

			serdoc.LoadXml (object_string.ToString ());
			XmlNodeList serresult = serdoc.GetElementsByTagName (item_object);

			// Check document type
			Assert.AreEqual(type, syntype.Item (0).Attributes.GetNamedItem ("type").Value.ToString (),
					     "SE6");
			// Check content
			Assert.AreEqual (serresult.Item (0).OuterXml.ToString (), synresult.Item (0).OuterXml.ToString (),
					      "SE6");
		}