Пример #1
0
        public List <AqiParam> ParseParam(byte[] data)
        {
            List <AqiParam> listParam = new List <AqiParam>();

            //XNamespace b = "http://schemas.datacontract.org/2004/07/Env.Publish.Province.DAL";
            //XDocument xd = XDocument.Load(new MemoryStream(data));
            //IEnumerable<XElement> elements = xd.Descendants(XName.Get("AQICityStation", b.ToString()));

            //foreach (XElement node in elements)
            //{
            //    string name = node.Element(XName.Get("PositionName", b.ToString())).Value;
            //    string id = node.Element(XName.Get("StationID", b.ToString())).Value;
            //    string cityName = node.Element(XName.Get("CityName", b.ToString())).Value;

            //    AqiParam ap = new AqiParam(id + "_" + name);
            //    ap.Add("stationCode", id);
            //    listParam.Add(ap);
            //}
            XNamespace             b        = "http://schemas.datacontract.org/2004/07/Env.Publish.Province.DAL";
            XDocument              xd       = XDocument.Load(new MemoryStream(data));
            IEnumerable <XElement> elements = xd.Descendants(XName.Get("AQIDataPublishLive", b.ToString()));

            foreach (XElement node in elements)
            {
                string name     = node.Element(XName.Get("PositionName", b.ToString())).Value;
                string id       = node.Element(XName.Get("StationCode", b.ToString())).Value;
                string cityName = node.Element(XName.Get("Area", b.ToString())).Value;

                AqiParam ap = new AqiParam(id + "_" + name);
                ap.Add("stationCode", id);
                listParam.Add(ap);
            }
            return(listParam);
        }
Пример #2
0
        public string ToXML()
        {
            XNamespace ns_dal = string.Format("clr-namespace:{0};assembly={1}",
                                              DbSets.Any() ? DbSets.First().EntityType.Namespace : GetType().Namespace,
                                              DbSets.Any() ? DbSets.First().EntityType.Assembly.GetName().Name : GetType().Assembly.GetName().Name);

            var xElement = new XElement(NS_DATA + "Metadata",
                                        new XAttribute(XNamespace.Xmlns + "x", NS_XAML.ToString()),
                                        new XAttribute(XNamespace.Xmlns + "data", NS_DATA.ToString()),
                                        new XAttribute(XNamespace.Xmlns + "dal", ns_dal.ToString()),
                                        new XAttribute(NS_XAML + "Key", "ResourceKey"),
                                        new XElement(NS_DATA + "Metadata.DbSets",
                                                     from dbset in DbSets
                                                     select new XElement(NS_DATA + "DbSetInfo",
                                                                         new XAttribute("dbSetName", dbset.dbSetName),
                                                                         dbset.isTrackChanges
                            ? new[] { new XAttribute("isTrackChanges", dbset.isTrackChanges) }
                            : new XAttribute[0],
                                                                         new XAttribute("enablePaging", dbset.enablePaging),
                                                                         dbset.enablePaging ? new[] { new XAttribute("pageSize", dbset.pageSize) } : new XAttribute[0],
                                                                         new XAttribute("EntityType", string.Format("{{x:Type dal:{0}}}", dbset.EntityType.Name)),
                                                                         new XElement(NS_DATA + "DbSetInfo.fieldInfos", _FieldsToXElements(dbset.fieldInfos)
                                                                                      ))),
                                        new XElement(NS_DATA + "Metadata.Associations",
                                                     from assoc in Associations
                                                     select new XElement(NS_DATA + "Association",
                                                                         new XAttribute("name", assoc.name),
                                                                         string.IsNullOrWhiteSpace(assoc.parentDbSetName)
                            ? new XAttribute[0]
                            : new[] { new XAttribute("parentDbSetName", assoc.parentDbSetName) },
                                                                         string.IsNullOrWhiteSpace(assoc.childDbSetName)
                            ? new XAttribute[0]
                            : new[] { new XAttribute("childDbSetName", assoc.childDbSetName) },
                                                                         string.IsNullOrWhiteSpace(assoc.childToParentName)
                            ? new XAttribute[0]
                            : new[] { new XAttribute("childToParentName", assoc.childToParentName) },
                                                                         string.IsNullOrWhiteSpace(assoc.parentToChildrenName)
                            ? new XAttribute[0]
                            : new[] { new XAttribute("parentToChildrenName", assoc.parentToChildrenName) },
                                                                         assoc.onDeleteAction == DeleteAction.NoAction
                            ? new XAttribute[0]
                            : new[] { new XAttribute("onDeleteAction", assoc.onDeleteAction) },
                                                                         new XElement(NS_DATA + "Association.fieldRels",
                                                                                      from fldRel in assoc.fieldRels
                                                                                      select new XElement(NS_DATA + "FieldRel",
                                                                                                          new XAttribute("parentField", fldRel.parentField),
                                                                                                          new XAttribute("childField", fldRel.childField)
                                                                                                          )
                                                                                      )
                                                                         ))
                                        );

            var xml = xElement.ToString();

            return(xml);
        }
Пример #3
0
        private static Type _GetTypeFromXType(string xType, XDocument xdoc)
        {
            if (!(xType.StartsWith("{") && xType.EndsWith("}")))
            {
                throw new Exception(string.Format("Invalid EntityType attribute value: {0}", xType));
            }

            string[] typeParts = xType.TrimStart('{').TrimEnd('}').Split(' ');
            if (typeParts.Length != 2)
            {
                throw new Exception(string.Format("Invalid entity type: {0}", xType));
            }

            string[] typeParts1 = typeParts[0].Split(':').Select(s => s.Trim()).ToArray();
            string[] typeParts2 = typeParts[1].Split(':').Select(s => s.Trim()).ToArray();

            XNamespace xaml_ns = xdoc.Root.GetNamespaceOfPrefix(typeParts1[0]);

            if (xaml_ns != NS_XAML)
            {
                throw new Exception(string.Format("Can not get xaml namespace for xType: {0}", typeParts1[0]));
            }

            if (typeParts1[1] != "Type")
            {
                throw new Exception(string.Format("Invalid EntityType attribute value: {0}", xType));
            }

            XNamespace xEntity_ns = xdoc.Root.GetNamespaceOfPrefix(typeParts2[0]);

            if (xEntity_ns == null)
            {
                throw new Exception(string.Format("Can not get clr namespace for the prefix: {0}", typeParts2[0]));
            }
            if (xEntity_ns.ToString().IndexOf("clr-namespace:") < 0)
            {
                throw new Exception(string.Format("The namespace: {0} is not valid clr namespace", xEntity_ns));
            }

            string entity_ns      = RemoveWhitespace(xEntity_ns.ToString()).Replace("clr-namespace:", "");
            string entityTypeName = typeParts2[1];

            string[] nsparts = entity_ns.Split(';');

            entityTypeName = $"{nsparts[0]}.{entityTypeName}";
            if (nsparts.Length == 2 && nsparts[1].IndexOf("assembly=") >= 0)
            {
                entityTypeName = $"{entityTypeName}, {nsparts[1].Replace("assembly=", "")}";
            }
            Type entityType = Type.GetType(entityTypeName, true);

            return(entityType);
        }
Пример #4
0
        //<?xml version = "1.0" encoding="UTF-8"?>
        //<xsd:schema xmlns:SqlWs="http://hosseinnarimanirad.ir"
        //            xmlns:gml="http://www.opengis.net/gml"
        //            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        //            elementFormDefault="qualified"
        //            targetNamespace="http://hosseinnarimanirad.ir">
        //<xsd:import namespace="http://www.opengis.net/gml"
        //            schemaLocation="http://localhost:8888/geoserver/schemas/gml/3.1.1/base/gml.xsd"/>


        public static string GetWfsDescribeFeatureXsd <T>(T classValue, XNamespace theNamespace, string gmlSchemaLocation, XNamespace targetNamespace, string name, string _type)
        {
            var properties = (typeof(T)).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            XDocument doc = new XDocument();

            //XNamespace xsdNamespace = "http://www.w3.org/2001/XMLSchema";
            XNamespace xsdNamespace = System.Xml.Schema.XmlSchema.InstanceNamespace;
            XNamespace gmlNamespace = XNamespace.Get("http://www.opengis.net/gml");


            var root = new XElement(XName.Get("schema", xsdNamespace.ToString()),
                                    new XAttribute(XNamespace.Xmlns + "gml", gmlNamespace),
                                    new XAttribute(XNamespace.Xmlns + "xsd", xsdNamespace),
                                    new XAttribute("elementFormDefault", "qualified"),
                                    new XAttribute("targetNamespace", targetNamespace.ToString()),
                                    new XElement(XName.Get("import", xsdNamespace.ToString()),
                                                 new XAttribute("namespace", gmlNamespace.ToString()),
                                                 new XAttribute("schemaLocation", gmlSchemaLocation.ToString())));

            List <XElement> elements = new List <XElement>();

            foreach (var property in properties)
            {
                elements.Add(new XElement(GetXsdXName("element"),
                                          new XAttribute("maxOccurs", 1),
                                          new XAttribute("minOccurs", 0),
                                          new XAttribute("name", property.Name),
                                          new XAttribute("nillable", "true"),
                                          new XAttribute("type", clrToXsdTypeMap[property.PropertyType.Name.ToLower()])));
            }


            XElement content = new XElement(GetXsdXName("complexType"),
                                            new XAttribute("name", name + "Type"), //e.g. GIS.StructureViewType
                                            new XElement(GetXsdXName("complexContent"),
                                                         new XElement(GetXsdXName("extension"),
                                                                      new XAttribute("base", "gml:AbstractFeatureType"),
                                                                      new XElement(GetXsdXName("sequence"), elements))));

            root.Add(content);

            root.Add(new XElement(GetXsdXName("element"),
                                  new XAttribute("name", name),
                                  new XAttribute("substitutionGroup", "gml:_Feature"),
                                  new XAttribute("type", _type)));

            doc.Add(root);

            return(doc.ToString());
        }
Пример #5
0
        static void Main(string[] args)
        {
            if (!TryGetParams(args, out var param))
            {
                return;
            }
            var templatesPath = param.ContainsKey("-p") ? param["-p"] : DefaultPath;
            var findedFile    = param.ContainsKey("-g") ? string.Concat(param["-g"], ".xslt") : "*.xslt";
            var justUpdate    = param.ContainsKey("-u") && Convert.ToBoolean(param["-u"]);

            var templatesDirectory = new DirectoryInfo(templatesPath);
            var files = templatesDirectory.GetFiles(findedFile);

            NameSpaces.AddNamespace("x", X.ToString());
            NameSpaces.AddNamespace("fo", fo.ToString());
            foreach (var fileInfo in files.Where(f => f.Name.StartsWith("1")))
            {
                var fileName = fileInfo.Name.Replace(".xslt", "");
                if (fileName.Length > 6 || !Regex.IsMatch(fileName, ActiveGfvRegexDefault))
                {
                    continue;
                }
                Console.WriteLine(fileName);
                if (justUpdate)
                {
                    UpdateFiles(fileInfo);
                    continue;
                }
                AddEcpToFile(fileInfo);
                AddEcpTemplateToFile(fileInfo);
            }
        }
Пример #6
0
 //[TestInitialize]
 public void Setup()
 {
     sample = new XDocument(
         new XElement(_xdp + "xdp", new object[]
     {
         new XAttribute(XNamespace.Xmlns + "xdp", _xdp.ToString()),
         new XAttribute("timeStamp", DateTime.Now.ToString("O")),
         new XAttribute("uuid", Guid.NewGuid()),
         new XElement(_xfaTemplate + "template",
                      new XElement("subform", new object[]
         {
             new XAttribute("name", "form1"),
             new XAttribute("layout", "tb"),
             new XAttribute("locale", "en_US"),
             new XAttribute("restoreState", "auto"),
             new XElement("pageSet",
                          new XElement("pageArea", new object []
             {
                 new XAttribute("name", "page1")
             })
                          ),
         })),
         new XElement(_xci + "config"),
         new XElement(_xfaLocaleSet + "localeSet"),
         new XElement(_x + "xmpmeta", new object []
         {
             new XAttribute(XNamespace.Xmlns + "x", _x.ToString()),
             new XAttribute(_x + "xmptk", "Adobe XMP Core 4.2.1-c041 52.337767, 2008/04/13-15:41:00        ")
         }),
     })
         );
 }
Пример #7
0
        static bool IsXMLFileValid(string xmlFilePath, string xsdFilePath)
        {
            if (!File.Exists(xmlFilePath))
            {
                Console.WriteLine($"File {Path.GetFileName(xmlFilePath)} does not exists.");
                return(false);
            }

            XNamespace @namespace = "https://ww2.mini.pw.edu.pl/dla-studenta/plan/";

            var xdoc   = XDocument.Load(xmlFilePath);
            var schema = new XmlSchemaSet();

            schema.Add(@namespace.ToString(), xsdFilePath);

            Console.WriteLine($"Validating {Path.GetFileName(xmlFilePath)} file against {Path.GetFileName(xsdFilePath)} file...");
            try
            {
                xdoc.Validate(schema, null);
            }
            catch (XmlSchemaValidationException ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }

            return(true);
        }
Пример #8
0
        /// <summary>
        /// Creates an OData entry XElement representation of the package.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <returns>The OData entry XElement.</returns>
        private XElement ToODataEntryXElement(IPackage package)
        {
            string     nsAtom        = "http://www.w3.org/2005/Atom";
            XNamespace nsDataService = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            string     nsMetadata    = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
            string     downloadUrl   = string.Format(
                CultureInfo.InvariantCulture,
                "{0}package/{1}/{2}", _endPoint, package.Id, package.Version);
            string entryId = string.Format(
                CultureInfo.InvariantCulture,
                "{0}Packages(Id='{1}',Version='{2}')",
                _endPoint, package.Id, package.Version);

            var entry = new XElement(XName.Get("entry", nsAtom),
                                     new XAttribute(XNamespace.Xmlns + "d", nsDataService.ToString()),
                                     new XAttribute(XNamespace.Xmlns + "m", nsMetadata.ToString()),
                                     new XElement(XName.Get("id", nsAtom), entryId),
                                     new XElement(XName.Get("title", nsAtom), package.Id),
                                     new XElement(XName.Get("content", nsAtom),
                                                  new XAttribute("type", "application/zip"),
                                                  new XAttribute("src", downloadUrl)),
                                     new XElement(XName.Get("properties", nsMetadata),
                                                  new XElement(nsDataService + "Version", package.Version),
                                                  new XElement(nsDataService + "PackageHash", package.GetHash("SHA512")),
                                                  new XElement(nsDataService + "PackageHashAlgorithm", "SHA512"),
                                                  new XElement(nsDataService + "Description", package.Description),
                                                  new XElement(nsDataService + "Listed", package.Listed)));

            return(entry);
        }
Пример #9
0
        /// <summary>
        /// Converts an OpenXml package in OPC format to an <see cref="XDocument"/>
        /// in Flat OPC format.
        /// </summary>
        /// <param name="instruction">The processing instruction.</param>
        /// <returns>The OpenXml package in Flat OPC format.</returns>
        protected XDocument ToFlatOpcDocument(XProcessingInstruction instruction)
        {
            // Save the contents of all parts and relationships that are contained
            // in the OpenXml package to make sure we convert a consistent state.
            // This will also invoke ThrowIfObjectDisposed(), so we don't need
            // to call it here.
            Save();

            // Identify all AlternativeFormatInputParts (AltChunk parts).
            // This is necessary because AltChunk parts must be treated as binary
            // parts regardless of the actual content type, which might even be
            // XML-related such as application/xhtml+xml.
            var altChunkPartUris = new HashSet <Uri>(
                Package.GetParts()
                .Where(part => part.ContentType != RelationshipContentType)
                .SelectMany(part => part.GetRelationshipsByType(AltChunkRelationshipType))
                .Select(pr => PackUriHelper.ResolvePartUri(pr.SourceUri, pr.TargetUri)));

            // Create an XML document with a standalone declaration, processing
            // instruction (if not null), and a package root element with a
            // namespace declaration and one child element for each part.
            return(new XDocument(
                       new XDeclaration("1.0", "UTF-8", "yes"),
                       instruction,
                       new XElement(
                           Pkg + "package",
                           new XAttribute(XNamespace.Xmlns + "pkg", Pkg.ToString()),
                           Package.GetParts().Select(part => GetContentsAsXml(part, altChunkPartUris)))));
        }
Пример #10
0
        private XElement GetSchema(XsdSchema xsdSchema, string id)
        {
            var schema = new XElement(
                _xs + "schema",
                new XAttribute("id", id),
                new XAttribute("targetNamespace", xsdSchema.TargetNamespace),
                new XAttribute("elementFormDefault", "qualified"),
                new XAttribute("attributeFormDefault", "unqualified"),
                new XAttribute(XNamespace.Xmlns + "xs", _xs.ToString())
                );

            if (!string.IsNullOrEmpty(xsdSchema.XmlNamespace))
            {
                schema.SetAttributeValue("xmlns", xsdSchema.XmlNamespace);
            }
            if (!string.IsNullOrEmpty(xsdSchema.Namespace))
            {
                schema.SetAttributeValue(XNamespace.Xmlns + "ns", xsdSchema.Namespace);
            }
            if (!string.IsNullOrEmpty(xsdSchema.Common))
            {
                schema.SetAttributeValue(XNamespace.Xmlns + "common", xsdSchema.Common);
            }
            return(schema);
        }
Пример #11
0
        internal static string GenerateDefaultPage(PageInformation pageInformation)
        {
            try
            {
                using (StreamReader streamReader = new StreamReader(_baseDirectory.Value + _mainPageName))
                {
                    XmlReader xmlReader = new XmlTextReader(streamReader);
                    XDocument pageRoot  = XDocument.Load(xmlReader);

                    // Remove DOCTYPE extra []
                    pageRoot.DocumentType.InternalSubset = null;

                    XNamespace          ns = "http://www.w3.org/1999/xhtml";
                    XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlReader.NameTable);
                    xmlNamespaceManager.AddNamespace("xhtml", ns.ToString());

                    ComposePage(pageRoot, xmlNamespaceManager, pageInformation);
                    return(pageRoot.ToString());
                }
            }
            catch (Exception e)
            {
                if (e is OutOfMemoryException)
                {
                    throw;
                }

                // Not critical since the generated page only contains additional metadata used in SEO/Embedding
                return(_mainPage.Value);
            }
        }
Пример #12
0
        private XDocument DocCache(Uri uri)
        {
            EnsureCache(uri);
            // for messy html sites, adding a TidyHTML task here would make a lot of sense
            if (!documentCache.ContainsKey(uri))
            {
                HtmlWeb      web     = new HtmlWeb();
                HtmlDocument htmlDoc = web.Load(GetLocalPath(uri));
                htmlDoc.OptionOutputAsXml = true;
                using (StringWriter sw = new StringWriter())
                {
                    using (XmlTextWriter xw = new System.Xml.XmlTextWriter(sw))
                    {
                        htmlDoc.Save(xw);
                    }
                    string html = sw.ToString();
                    if (!html.Contains(xhtmlNs.ToString()))
                    {
                        html = html.Replace("<html", $"<html xmlns='{xhtmlNs}'");
                    }

                    XDocument doc = XDocument.Parse(html);
                    documentCache.Add(uri, doc);
                }
            }

            return(documentCache[uri]);
        }
Пример #13
0
        public XsdGenerator(QuantumDepth depth)
        {
            _Depth = depth;
            _Types = new MagickScriptTypes(depth);

            _Namespaces = new XmlNamespaceManager(new NameTable());
            _Namespaces.AddNamespace("xs", _Namespace.ToString());
        }
Пример #14
0
        private static string SerializeObject <T>(T obj)
        {
            // Создаём сериалайзер с пространством имён по умолчанию
            var xmlSerializer = new XmlSerializer(typeof(T), defaultNamespace.ToString());

            // Добавляем дополнительное пространство имён с префиксом
            var xmlSerializerNamespaces = new XmlSerializerNamespaces();

            xmlSerializerNamespaces.Add("i", instanceNamespace.ToString());

            // Сериализуем и печатаем
            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, obj, xmlSerializerNamespaces);
                return(stringWriter.ToString());
            }
        }
Пример #15
0
        //===========================================================================================
        private XsdGenerator(QuantumDepth depth)
        {
            _Depth             = depth;
            _GraphicsMagickNET = new GraphicsMagickNET(depth);

            _Namespaces = new XmlNamespaceManager(new NameTable());
            _Namespaces.AddNamespace("xs", _Namespace.ToString());
        }
Пример #16
0
        public override XDocument ToXml(string graphName, ref IList <IDataObject> dataObjects)
        {
            XElement rootElement = null;

            try
            {
                _graphMap    = _mapping.FindGraphMap(graphName);
                _dataObjects = dataObjects;

                if (_graphMap != null && _graphMap.classTemplateMaps.Count > 0 &&
                    _dataObjects != null && _dataObjects.Count > 0)
                {
                    if (_dataObjects.Count == 1 || FullIndex)
                    {
                        rootElement = new XElement(_appNamespace + Utility.TitleCase(graphName),
                                                   new XAttribute(XNamespace.Xmlns + "i", XSI_NS),
                                                   new XAttribute(XNamespace.Xmlns + "rdl", RDL_NS),
                                                   new XAttribute(XNamespace.Xmlns + "tpl", TPL_NS),
                                                   new XAttribute(XNamespace.Xmlns + "rdf", RDF_NS));

                        BuildXml(rootElement, String.Empty, String.Empty);
                    }
                    else
                    {
                        ClassMap classMap = _graphMap.classTemplateMaps.First().classMap;
                        rootElement = new XElement(_appNamespace + Utility.TitleCase(graphName));

                        for (int dataObjectIndex = 0; dataObjectIndex < _dataObjects.Count; dataObjectIndex++)
                        {
                            bool          hasRelatedProperty;
                            List <string> classIdentifiers = GetClassIdentifiers(classMap, dataObjectIndex, out hasRelatedProperty);

                            if (classIdentifiers.Count > 0)
                            {
                                XElement rowElement = new XElement(_appNamespace + Utility.TitleCase(classMap.name));
                                rowElement.Value = _appNamespace.ToString() + "/" + _graphMap.name + "/" + classIdentifiers.First();
                                rootElement.Add(rowElement);
                            }
                            else
                            {
                                _logger.Warn("Class identifier of [" + classMap.name + "] not found.");
                            }
                        }
                    }

                    XAttribute total = new XAttribute("total", this.Count);
                    rootElement.Add(total);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error in ToXml: " + ex);
                throw ex;
            }

            return(new XDocument(rootElement));
        }
Пример #17
0
        public static string GetNameSpace(XElement root, XNamespace ns)
        {
            var namespaceString = root.LastAttribute.ToString();
            var nsString        = namespaceString.Contains(ns.ToString())
                ? $" {namespaceString}"
                : $" {root.LastAttribute.Name}=\"{ns}\"";

            return(nsString);
        }
        public void CreateSplitXMLShouldReturnValidXml()
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.Schemas.Add(Xlmns.ToString(), @"../../../UnmarshallingSplitXml/splitXmlDefinitionTemplate.xsd");
            settings.ValidationType = ValidationType.Schema;

            XmlReader   reader   = XmlReader.Create(new MemoryStream(CreateSplitXmlBinary), settings);
            XmlDocument document = new XmlDocument();

            document.Load(reader);
            document.Validate(ValidationEventHandler);

            XDocument xdoc     = XDocument.Load(new MemoryStream(CreateSplitXmlBinary));
            var       elements = xdoc.Descendants(Xlmns + "Presentation");

            Assert.AreEqual(0, ErrorsCount);
            Assert.AreEqual(0, WarningsCount);
            Assert.IsTrue(elements.Count() > 0);
        }
Пример #19
0
    public static void AddXmlns(string csproj, XNamespace ns, bool add)
    {
        if (add)
        {
            XDocument xml = XDocument.Load(csproj);
            foreach (var element in xml.Descendants().ToList())
            {
                element.Name = ns + element.Name.LocalName;
            }
            xml.Root.SetAttributeValue("xmlns", ns.ToString());

            xml.Save(csproj);
        }
        else
        {
            var text  = TF.ReadFile(csproj);
            var xmlns = "xmlns=\"" + ns.ToString() + "\"";
            text = SH.ReplaceOnce(text, xmlns, string.Empty);
            TF.SaveFile(text, csproj);
        }
    }
Пример #20
0
        private HandlerCacheItem GetRegularSiteMap(HttpContextBase context)
        {
            bool forMobile = context.Request.Path.EndsWith("mobilesitemap.axd", StringComparison.OrdinalIgnoreCase);

            string cacheKey = forMobile ? "mobileSiteMap" : "siteMap";

            Log.Info("Generating {0}".FormatWith(cacheKey));

            HandlerCacheItem cacheItem;

            Cache.TryGet(cacheKey, out cacheItem);

            if (cacheItem == null)
            {
                XElement urlSet = new XElement(_ns + "urlset", new XAttribute("xmlns", _ns.ToString()));

                if (forMobile)
                {
                    urlSet.Add(new XAttribute(XNamespace.Xmlns + "mobile", _googleMobile.ToString()));
                }

                DateTime currentDate = SystemTime.Now();
                string   rootUrl     = Settings.RootUrl;

                AddStoriesInRegularSiteMap(context, forMobile, urlSet);
                AddPublishedPagesInRegularSiteMap(context, forMobile, urlSet, currentDate);
                AddUpcomingPagesInRegularSiteMap(context, forMobile, urlSet, currentDate);
                AddCategoryPagesInRegularSiteMap(context, forMobile, urlSet, currentDate);
                AddTagPagesInRegularSiteMap(context, forMobile, urlSet, currentDate);
                AddUserPagesInRegularSiteMap(context, forMobile, urlSet, currentDate);

                urlSet.Add(CreateEntry(context, rootUrl, "Submit", null, currentDate, SiteMapChangeFrequency.Monthly, SiteMapUpdatePriority.Low, forMobile));
                urlSet.Add(CreateEntry(context, rootUrl, "Faq", null, currentDate, SiteMapChangeFrequency.Monthly, SiteMapUpdatePriority.Low, forMobile));
                urlSet.Add(CreateEntry(context, rootUrl, "About", null, currentDate, SiteMapChangeFrequency.Monthly, SiteMapUpdatePriority.Low, forMobile));
                urlSet.Add(CreateEntry(context, rootUrl, "Contact", null, currentDate, SiteMapChangeFrequency.Monthly, SiteMapUpdatePriority.Low, forMobile));

                XDocument doc = new XDocument();
                doc.Add(urlSet);

                cacheItem = new HandlerCacheItem {
                    Content = doc.ToXml()
                };

                if ((CacheDurationInMinutes > 0) && !Cache.Contains(cacheKey))
                {
                    Cache.Set(cacheKey, cacheItem, SystemTime.Now().AddMinutes(CacheDurationInMinutes));
                }
            }

            Log.Info("{0} generated".FormatWith(cacheKey));

            return(cacheItem);
        }
Пример #21
0
            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                //
                // coreclr WCF was giving me problems interfacing with myserver due to the serialization not honoring
                // [MessageHeader].  This causes a lot of problems if your using streaming since you can only have
                // a single body member (the stream).
                //
                // I wound up just hosting an alternative interface on the server "*Text" since MTOM MessageEncoding
                // was not working at the time.
                //
                // I am leaving this in (not hooked up) as an example for reference ;) how to hijack into the XML Header
                // without manually emitting the entire XML blob with a custom binder/*
                //

                // capture the Message
                var buffer = request.CreateBufferedCopy(int.MaxValue);

                // state variable
                _data.BeforeSendRequestCalled = true;
                // setup return value (request is destroyed when we captured above)
                request       = _data.Request = buffer.CreateMessage();
                _data.Channel = channel;

                // buffer.CreateMessage(); is our Message Factory now
                var m3 = buffer.CreateMessage();

                // Use a buffered XML interface to manipulate
                XElement xe = XElement.Parse(m3.ToString());

                // WCF uses prefixed namespaces like crazy
                XNamespace tmp = "http://tempuri.org/";

                // constants/names
                var hdrns      = XName.Get("Header", "http://schemas.xmlsoap.org/soap/envelope/");
                var hdrns_user = XName.Get("username", tmp.ToString());
                var hdrns_pass = XName.Get("password");

                // extract Header attribute
                var hE = xe.Element(hdrns);

                // assign expected values
                hE.Add(new XElement(tmp + "username", new XAttribute(XNamespace.Xmlns + "h", tmp), "*****@*****.**"));
                hE.Add(new XElement(tmp + "password", new XAttribute(XNamespace.Xmlns + "h", tmp), "demo"));
                //Console.WriteLine($"xe = {xe}");

                // Dump into an outgoing message request
                request = Message.CreateMessage(xe.CreateReader(), 1024 * 1024, MessageVersion.Soap11);

                return(null);
            }
Пример #22
0
        public XDocument Get(UrlHelper urlHelper)
        {
            _url = urlHelper;
            var yaml =
                new XDocument(
                    X("rss",
                      A("version", "2.0"),
                      new XAttribute(XNamespace.Xmlns + "g", g.ToString()),
                      Goods()
                      )
                    );

            return(yaml);
        }
Пример #23
0
        private void CreateIndexXml(XElement parentElement, DataObject dataObject, int dataObjectIndex)
        {
            string uri = _objectNamespace.ToString();

            if (!uri.EndsWith("/"))
            {
                uri += "/";
            }

            int keyCounter = 0;

            foreach (KeyProperty keyProperty in dataObject.keyProperties)
            {
                DataProperty dataProperty = dataObject.dataProperties.Find(dp => dp.propertyName == keyProperty.keyPropertyName);

                var value = _dataObjects[dataObjectIndex].GetPropertyValue(dataProperty.propertyName);
                if (value != null)
                {
                    value = Utility.ConvertSpecialCharOutbound(value.ToString(), arrSpecialcharlist, arrSpecialcharValue); //Handling special Characters here.
                    XElement propertyElement = new XElement(_objectNamespace + Utility.TitleCase(dataProperty.propertyName), value);
                    parentElement.Add(propertyElement);
                    keyCounter++;

                    if (keyCounter == dataObject.keyProperties.Count)
                    {
                        uri += value;
                    }
                    else
                    {
                        uri += value + dataObject.keyDelimeter;
                    }
                }
            }

            List <DataProperty> indexProperties = dataObject.dataProperties.FindAll(dp => dp.showOnIndex == true);

            foreach (DataProperty indexProperty in indexProperties)
            {
                var value = _dataObjects[dataObjectIndex].GetPropertyValue(indexProperty.propertyName);
                if (value != null)
                {
                    XElement propertyElement = new XElement(_objectNamespace + Utility.TitleCase(indexProperty.propertyName), value);
                    parentElement.Add(propertyElement);
                }
            }

            XAttribute uriAttribute = new XAttribute("uri", uri);

            parentElement.Add(uriAttribute);
        }
    private static XDocument OpcToFlatOpc(Package package)
    {
        XNamespace pkg         = "http://schemas.microsoft.com/office/2006/xmlPackage";
        var        declaration = new XDeclaration("1.0", "UTF-8", "yes");
        var        doc         = new XDocument(
            declaration,
            new XProcessingInstruction("mso-application", "progid=\"Word.Document\""),
            new XElement(
                pkg + "package",
                new XAttribute(XNamespace.Xmlns + "pkg", pkg.ToString()),
                package.GetParts().Select(GetContentsAsXml)));

        return(doc);
    }
Пример #25
0
        private static string GenerateDefaultPage(PageInformation pageInformation)
        {
            using (StreamReader streamReader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + _mainPageName))
            {
                XmlReader xmlReader = new XmlTextReader(streamReader);
                XDocument pageRoot  = XDocument.Load(xmlReader);

                XNamespace          ns = "http://www.w3.org/1999/xhtml";
                XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlReader.NameTable);
                xmlNamespaceManager.AddNamespace("xhtml", ns.ToString());

                ComposePage(pageRoot, xmlNamespaceManager, pageInformation);
                return(pageRoot.ToString());
            }
        }
Пример #26
0
        public XMLComposer(string rootTag, Process p, Interpreter i)
        {
            process     = p;
            interpreter = i;

            maxs = $"http://www.microarea.it/Schema/2004/Smart/ERP/Items/Items/AllUsers/{process.profile}.xsd";

            data = new XElement(maxs + "Data");
            root = new XElement(maxs + rootTag,
                                new XAttribute(XNamespace.Xmlns + "maxs", maxs.ToString()),
                                new XAttribute("tbNamespace", process.document),
                                new XAttribute("xTechProfile", process.profile),
                                data
                                );
        }
Пример #27
0
        internal static XmlSchemaSet SchemaSetFromResource(string name, XNamespace ns)
        {
            var resourcename = $"MedMij.{name}";
            var resource     = typeof(XMLUtils).Assembly.GetManifestResourceStream(resourcename);

            if (resource == null)
            {
                throw new InvalidOperationException($"Resource {resourcename} not found.");
            }

            var schemareader = XmlReader.Create(resource);
            var schemas      = new XmlSchemaSet();

            schemas.Add(ns.ToString(), schemareader);
            return(schemas);
        }
Пример #28
0
        static void QueryXPathExpression()
        {
            Console.WriteLine("=== " + MethodInfo.GetCurrentMethod().Name + " ===");

            // Create XML namespace.
            XNamespace aw = "http://www.adventure-works.com";

            // Create XML document.
            var document =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XProcessingInstruction("target", "data"),
                    new XElement("Root",
                                 new XAttribute("AttName", "An Attribute"),
                                 new XAttribute(XNamespace.Xmlns + "aw", aw.ToString()),
                                 new XComment("This is a comment"),
                                 new XElement("Child",
                                              new XText("Text")),
                                 new XElement("Child",
                                              new XText("Other Text")),
                                 new XElement("ChildWithMixedContent",
                                              new XText("text"),
                                              new XElement("b", "BoldText"),
                                              new XText("otherText")),
                                 new XElement(aw + "ElementInNamespace",
                                              new XElement(aw + "ChildInNamespace"))));

            // Create LINQ query to get all descendant nodes.
            var query = document.DescendantNodes();

            // Show query results.
            Console.WriteLine("Show all descendant nodes:");
            foreach (var n in query)
            {
                Console.WriteLine(n.GetXPath());
                var el = n as XElement;
                if (el == null)
                {
                    continue;
                }

                foreach (var at in el.Attributes())
                {
                    Console.WriteLine(at.GetXPath());
                }
            }
        }
Пример #29
0
        private bool Validated(XElement root, XNamespace ns)
        {
            var schemas = new XmlSchemaSet();

            schemas.Add(ns.ToString(), XmlReader.Create(new StringReader(Resx._0336_OneNoteApplication_2013)));

            var document = new XDocument(root);

            bool valid = true;

            document.Validate(schemas, (o, e) =>
            {
                logger.WriteLine($"schema validation {e.Severity}", e.Exception);
                valid = false;
            });

            return(valid);
        }
Пример #30
0
        public XDocument ConvertToGml(IEnumerable <NatureArea> natureAreas)
        {
            var xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "no"));

            var featureCollectionElement = new XElement(
                wfsNs + "FeatureCollection",
                new XAttribute(XNamespace.Xmlns + "gml", gmlNs),
                new XAttribute(XNamespace.Xmlns + "wfs", wfsNs),
                new XAttribute(XNamespace.Xmlns + "nin", ninNs),
                new XAttribute(XNamespace.Xmlns + "xsi", xsiNs),
                new XAttribute(xsiNs + "schemaLocation", ninNs.ToString() + "/NiNCoreGmleksport.xsd"),
                AddFeatureMemberElements(natureAreas)
                );

            xDocument.Add(featureCollectionElement);

            return(xDocument);
        }