protected override async Task <string> CreateStructureAsync(IEnumerable <Sentence> sentences)
        {
            var header = new XDeclaration(version: "1.0", encoding: "utf-8", standalone: "yes");
            var doc    = new XDocument( // xml -> xsd, xmlsoap -> wsdl, xslt (transformata)
                new XElement("text",
                             from sentence in sentences
                             select new XElement("sentence",
                                                 from word in sentence.Words
                                                 select new XElement("word", word)//SecurityElement.Escape(word).Replace("\'", "&apos;"))
                                                 )));

            var text = doc.ToString()
                       .Replace("&amp;", "&amp;amp;")
                       .Replace("&lt;", "&amp;lt;")
                       .Replace("&gt;", "&amp;gt;")
                       .Replace("\'", "&amp;apos;")
                       .Replace("\"", "&amp;quot;");

            var xml = new StringWriterUtf8();
            await xml.WriteAsync(header.ToString() + "\r\n" + text);

            var ooo = xml.ToString();

            return(await Task.FromResult(ooo));
        }
Ejemplo n.º 2
0
        public void Add(Member item)
        {
            //Tranforma un objeto a formato XML
            XmlSerializer serializer   = new XmlSerializer(item.GetType());
            var           memoryStream = new MemoryStream();
            var           strWriter    = new StringWriterUtf8();

            serializer.Serialize(strWriter, item);
            var strXML = strWriter.ToString();

            strWriter.Close();
            try
            {
                MemoryStream ms = new MemoryStream(
                    System.Text.Encoding.UTF8.GetBytes(strXML));
                //conexión a la base de datos
                Session session = new Session("localhost", 1984, "admin", "admin");
                //abre base de datos
                session.Execute("check biblioteca");
                //Agrega un miembro a la biblioteca
                session.Add("members", ms);
                session.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Convertir Modelo Comprobante a string XML
        /// </summary>
        /// <param name="comprobante">Modelo Comprobante</param>
        /// <returns>Cadena XML</returns>
        private string ConvertirComprobanteString(Comprobante comprobante)
        {
            try
            {
                var xmlNameSpace = new XmlSerializerNamespaces();
                xmlNameSpace.Add("cfdi", "http://www.sat.gob.mx/cfd/3");
                xmlNameSpace.Add("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital");
                xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                if (comprobante.TipoDeComprobante == "P")
                {
                    xmlNameSpace.Add("pago10", "http://www.sat.gob.mx/Pagos");
                }

                XmlSerializer oXmlSerializar = new XmlSerializer(typeof(Comprobante));

                string sXml = string.Empty;

                using (var sww = new StringWriterUtf8())
                {
                    using (XmlWriter writter = XmlWriter.Create(sww))
                    {
                        oXmlSerializar.Serialize(writter, comprobante, xmlNameSpace);
                        sXml = sww.ToString();
                    }
                }

                return(!string.IsNullOrWhiteSpace(sXml) ? sXml : string.Empty);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 4
0
        internal XmlDocument ToXmlDocument(object invoice)
        {
            Assembly        assembly  = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi       = FileVersionInfo.GetVersionInfo(assembly.Location);
            string          fversion  = fvi.FileVersion;
            IInvoiceBase    invBase   = (IInvoiceBase)invoice;
            string          genSystem = invBase.InvoiceSubtype.DocTypeNew + GetTfsString();// String.Format("DotNetApi für ebInterface V{0}", fversion);

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            // ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            foreach (var ebISchema in invBase.CurrentSchemas)
            {
                ns.Add(ebISchema.Prefix, ebISchema.Url);
            }
            XmlDocument xDoc = new XmlDocument();
            // XmlSerializer serializer = new XmlSerializer(this.GetType(), null, Type.EmptyTypes, new XmlRootAttribute("InvoiceType"), "http://schemas.microsoft.com/2003/10/serialization/");
            XmlSerializer serializer = new XmlSerializer(invoice.GetType());

            using (StringWriterUtf8 stringWriter = new StringWriterUtf8())
            {
                XmlWriterSettings settings = new XmlWriterSettings
                {
                    Encoding     = Encoding.UTF8,
                    Indent       = true,
                    IndentChars  = "\t",
                    NewLineChars = Environment.NewLine,
                    //ConformanceLevel = ConformanceLevel.Document
                };

                using (XmlWriter writer = XmlWriter.Create(stringWriter, settings))
                {
                    serializer.Serialize(writer, invoice, ns);
                    string xmlString = stringWriter.ToString();
                    xDoc.LoadXml(xmlString);
                }
            }


            var    nspUriSel = from si in invBase.CurrentSchemas where si.CacheName.EndsWith("Invoice.xsd") select si;
            string NspUri    = nspUriSel.FirstOrDefault().Url;
            string prefix    = nspUriSel.FirstOrDefault().Prefix;
            XmlAttributeCollection attrColl = xDoc.DocumentElement.Attributes;
            string genSysTag = (string.IsNullOrEmpty(prefix) ? "" : $"{prefix}:") + "GeneratingSystem";

            if (attrColl.GetNamedItem("GeneratingSystem") != null)
            {
                attrColl.Remove(attrColl[genSysTag]);
            }

            XmlAttribute genSys = xDoc.CreateAttribute(prefix, "GeneratingSystem", NspUri);

            genSys.Value = genSystem;
            xDoc.DocumentElement.Attributes.Append(genSys);

            return(RemoveEmptyNodes(xDoc));
        }
Ejemplo n.º 5
0
        public static string SerializeObject <T>(this T toSerialize)
        {
            var xmlSerializer = new XmlSerializer(toSerialize.GetType());

            using (var textWriter = new StringWriterUtf8())
            {
                xmlSerializer.Serialize(textWriter, toSerialize);
                return(textWriter.ToString());
            }
        }
Ejemplo n.º 6
0
        public string Serialize <T>(T ObjectToSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

            using (StringWriterUtf8 stringWriter = new StringWriterUtf8())
            {
                xmlSerializer.Serialize(stringWriter, ObjectToSerialize);
                return(stringWriter.ToString());
            }
        }
Ejemplo n.º 7
0
        public string GetXmlSitemap()
        {
            var activeLanguages = _languageRepository.GetActiveLanguages();

            _isMultilingual   = activeLanguages != null && activeLanguages.Count > 0;
            _enabledLanguages = _isMultilingual ? activeLanguages.Select(al => al.CultureCode).ToList() : null;
            var isSecureConnection = _httpContextAccessor.HttpContext.Request.IsHttps;

            _requestHost = _httpContextAccessor.HttpContext.Request.Host.Host;
            var scheme = isSecureConnection ? "https://" : "http://";

            _protocolHost = scheme + _requestHost;


            var publicPages = _navigation.GetPublicPages();
            List <SitemapUrl> sitemapUrls = new List <SitemapUrl>();

            if (publicPages != null && publicPages.Count > 0)
            {
                foreach (var page in publicPages)
                {
                    sitemapUrls.Add(GetSitemapUrl(page));
                }
            }


            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent   = true;
            settings.Encoding = Encoding.UTF8;

            using (var stringWriter = new StringWriterUtf8())
            {
                using (var writer = XmlWriter.Create(stringWriter, settings))
                {
                    // build header
                    writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/" + SITEMAP_VERSION);
                    writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                    writer.WriteAttributeString("xmlns", "xhtml", null, "http://www.w3.org/1999/xhtml");
                    var schemaLocation = "http://www.sitemaps.org/schemas/sitemap/" + SITEMAP_VERSION;
                    writer.WriteAttributeString("xsi", "schemaLocation", null, string.Format("{0} {0}/sitemap.xsd", schemaLocation));

                    // write urls to output
                    foreach (SitemapUrl url in sitemapUrls)
                    {
                        AddURL(url, writer);
                    }

                    writer.WriteEndElement();
                    writer.Close();
                }
                return(stringWriter.ToString());
            }
        }
Ejemplo n.º 8
0
        /// <inheritdoc />
        public BaseMessage Serialize(T message)
        {
            var result = new TextMessage();
            var writer = new StringWriterUtf8();

            new XmlSerializer(typeof(T)).Serialize(writer, message);
            var xml = writer.ToString();

            ValidateXml(xml);
            result.Body = xml;
            return(result);
        }
Ejemplo n.º 9
0
        private string SerializeToString(ParamsList list, bool includeReferenceNumber)
        {
            using (TextWriter writer = new StringWriterUtf8())
                using (XmlWriter xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings {
                    Indent = true, Encoding = Encoding.UTF8
                }))
                {
                    (includeReferenceNumber ? _serializerWithReferenceNumber : _serializer).Serialize(xmlWriter, list);
                    string xml = writer.ToString();

                    return(xml);
                }
        }
Ejemplo n.º 10
0
        public static string Serialize <T>(T value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using var stringWriter = new StringWriterUtf8();
            serializer.Serialize(stringWriter, value, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
            return(stringWriter.ToString());
        }
        private static string GetSerializedAssembly(SerializableAssembly assembly)
        {
            var serializer = new XmlSerializer(typeof(SerializableAssembly));
            var xmlns      = new XmlSerializerNamespaces();

            xmlns.Add("gml", "http://www.opengis.net/gml/3.2");
            xmlns.Add("asm", "http://localhost/standaarden/assemblage");

            var writer = new StringWriterUtf8();

            serializer.Serialize(writer, assembly, xmlns);
            return(writer.ToString());
        }
    protected void SaveLevelButton_Click(object sender, EventArgs e)
    {
        int ySize = Convert.ToInt32(LevelYSizeTextBox.Text);

        XMLToCSharp.Level level = new XMLToCSharp.Level();
        level.Name = LevelNameTextBox.Text;
        level.Blocks = new List<XMLToCSharp.Block>();

        string[] lines = LevelDataTextBox.Text.Split(',');
        for (int row = 0; row < lines.Length; row++)
        {
            for (var col = 0; col < lines[row].Length; col++)
            {
                int realY = ySize - row - 1;
                switch (lines[row][col])
                {
                    case '8':
                        level.Exit = new XMLToCSharp.Exit() { X = col, Y = realY };
                        break;
                    case '4':
                        level.Player = new XMLToCSharp.Player() { X = col, Y = realY };
                        break;
                    case '2':
                        level.Blocks.Add(new XMLToCSharp.Block() { Type = "Gem", X = col, Y = realY });
                        break;
                    case '1':
                        level.Blocks.Add(new XMLToCSharp.Block() { Type = "Ground", X = col, Y = realY });
                        break;
                }
            }
        }

        string resultingFile;
        XmlSerializer serializer = new XmlSerializer(typeof(XMLToCSharp.Level));
        using (StringWriterUtf8 textWriter = new StringWriterUtf8())
        {
            serializer.Serialize(textWriter, level);
            resultingFile = textWriter.ToString();
        }

        SimplePlatformerEntities ents = new SimplePlatformerEntities();
        ents.levels.Add(new levels() { name = level.Name, level = resultingFile });
        ents.SaveChanges();

        Response.Redirect("~/Default.aspx");
    }
Ejemplo n.º 13
0
        /// <summary>
        /// Settings to XML.
        /// </summary>
        ///
        /// <returns>
        /// A String.
        /// </returns>
        public String SettingsToXml()
        {
            XmlSerializer ser = new XmlSerializer(Settings.GetType());

            using (StringWriterUtf8 textWriter = new StringWriterUtf8())
            {
                //! Use DataContractSerializer or DataContractJsonSerializer?
                // See https://msdn.microsoft.com/en-us/library/bb412170(v=vs.100).aspx
                // See https://msdn.microsoft.com/en-us/library/bb924435(v=vs.110).aspx
                // See https://msdn.microsoft.com/en-us/library/aa347875(v=vs.110).aspx
                //
                ser.Serialize(textWriter, Settings);

                textWriter.Flush();

                return(textWriter.ToString());
            }
        }
Ejemplo n.º 14
0
        private string WriteXML(XmlDocument xdoc)
        {
            var xwsetting = new XmlWriterSettings
            {
                Indent       = true,
                NewLineChars = Environment.NewLine,
                Encoding     = Encoding.UTF8
            };
            StringWriterUtf8 sWrt        = new StringWriterUtf8();
            XmlWriter        myXMLWriter = XmlWriter.Create(sWrt, xwsetting);

            xdoc.Save(myXMLWriter);
            myXMLWriter.Close();
            // myXMLWriter.Flush();
            string xmlStr = sWrt.ToString();

            return(xmlStr);
        }
Ejemplo n.º 15
0
        public static string GetAuthenticationCookie(string IdProviderUrl, string RP_Uri, string RP_Realm, string UserName, string Password, string Domain)
        {
            //-----------------------------------------------------------------------------
            // Pass the Windows auth credential to the endpoint of the Identity Provider (ADFS)
            //-----------------------------------------------------------------------------
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.EstablishSecurityContext = false;
            var endpoint = new EndpointAddress(IdProviderUrl + "/adfs/services/trust/13/windowsmixed");
            RequestSecurityTokenResponse rstr;

            using (var factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(binding, endpoint))
            {
                factory.Credentials.Windows.ClientCredential =
                    new NetworkCredential(UserName, Password, Domain);
                factory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13;

                var rst = new RequestSecurityToken();

                rst.AppliesTo   = new EndpointAddress(RP_Realm);
                rst.KeyType     = WSTrust13Constants.KeyTypes.Bearer;
                rst.RequestType = WSTrust13Constants.RequestTypes.Issue;

                var channel = (Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel)factory.CreateChannel();
                channel.Issue(rst, out rstr);
            }

            //-----------------------------------------------------------------------------
            // Send the security token acquired from the Identity Provider (ADFS)
            //  to Replying Party (SharePoint)
            // And acquire authorization cookie from SharePoint Server.
            //-----------------------------------------------------------------------------
            using (var output = new StringWriterUtf8(new StringBuilder()))
            {
                using (var xmlwr = XmlWriter.Create(output))
                {
                    WSTrust13ResponseSerializer rs = new WSTrust13ResponseSerializer();
                    rs.WriteXml(rstr, xmlwr, new WSTrustSerializationContext());
                }
                var str = string.Format("wa=wsignin1.0&wctx={0}&wresult={1}",
                                        HttpUtility.UrlEncode(RP_Uri + "/_layouts/15/Authenticate.aspx?Source=%2F"),
                                        HttpUtility.UrlEncode(output.ToString()));

                var req = (HttpWebRequest)HttpWebRequest.Create(RP_Uri + "/_trust/");

                req.Method            = "POST";
                req.ContentType       = "application/x-www-form-urlencoded";
                req.CookieContainer   = new CookieContainer();
                req.AllowAutoRedirect = false;

                using (var res = req.GetRequestStream())
                {
                    byte[] postData = Encoding.UTF8.GetBytes(str);
                    res.Write(postData, 0, postData.Length);
                }

                using (var res = (HttpWebResponse)req.GetResponse())
                {
                    return(res.Cookies["FedAuth"].Value);
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Convertir Modelo Comprobante a XML Reader
        /// </summary>
        /// <param name="comprobante">Modelo Comprobante</param>
        /// <returns>Objeto XmlReader</returns>
        private async Task <string> GenerarComprobanteXmlTemp(Comprobante comprobante)
        {
            string sXml;
            string rutaXmlTemp;

            try
            {
                var xmlNameSpace = new XmlSerializerNamespaces();
                xmlNameSpace.Add("cfdi", "http://www.sat.gob.mx/cfd/3");
                xmlNameSpace.Add("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital");
                xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                if (comprobante.TipoDeComprobante == "P")
                {
                    xmlNameSpace.Add("pago10", "http://www.sat.gob.mx/Pagos");
                }

                var oXmlSerializar = new XmlSerializer(typeof(Comprobante));

                using (var sww = new StringWriterUtf8())
                {
                    using (XmlWriter writter = XmlWriter.Create(sww))
                    {
                        oXmlSerializar.Serialize(writter, comprobante, xmlNameSpace);
                        sXml = sww.ToString();
                    }
                }

                var carpeta    = $@"Temp\";
                var directorio = $@"{_facturaRutaTimbrado}\{carpeta}";
                var archivo    = $@"{_facturaRutaTimbrado}\{carpeta}{comprobante.Emisor.Rfc}_{comprobante.TipoDeComprobante}_{comprobante.Serie}_{comprobante.Folio}.xml";

                if (!string.IsNullOrEmpty(sXml))
                {
                    rutaXmlTemp = archivo;
                }
                else
                {
                    return(string.Empty);
                }

                if (!Directory.Exists(directorio))
                {
                    DirectoryInfo di = Directory.CreateDirectory(directorio);
                }

                using (StreamWriter outputFile = new StreamWriter(archivo, false, Encoding.UTF8))
                {
                    await outputFile.WriteAsync(sXml);
                }

                if (File.Exists(archivo))
                {
                    return(archivo);
                }
                else
                {
                    return(string.Empty);
                }
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }