Ejemplo n.º 1
0
        /// <summary>
        /// Serialises class into string
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">Class instance</param>
        /// <returns>Serialized string</returns>
        public static string UTF8Serialize <T>(this T value)
        {
            if (value == null)
            {
                return(null);
            }

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));

                using (StringWriter textWriter = new UTF8StringWriter())
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
                    {
                        serializer.Serialize(xmlWriter, value);
                    }
                    return(textWriter.ToString());
                }
            }
            catch (Exception exception)
            {
                throw new InvalidDataException("SerializeError".GetLocalized() + "(" + exception.Message + ")");
            }
        }
Ejemplo n.º 2
0
        public void Enviar(Entidade_NotaFiscal ObjEnt, out Entidade_NotaFiscal objDados)
        {
            docTran   = new XmlDocument();
            ns        = new XmlSerializerNamespaces();
            Settings  = new XmlWriterSettings();
            xmlStatus = new XmlSerializer(typeof(ConsReciNfe.TConsSitNFe));

            eNotaFiscal = ObjEnt;
            SitNfe      = new ConsReciNfe.TConsSitNFe(ObjEnt);

            Settings.Encoding        = UTF8Encoding.UTF8;
            Settings.NewLineHandling = NewLineHandling.None;
            Settings.Indent          = true;
            Settings.IndentChars     = "";

            ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

            Sw = new UTF8StringWriter();
            Wx = XmlWriter.Create(Sw, Settings);
            xmlStatus.Serialize(Sw, SitNfe, ns);
            string xmlGer = Sw.ToString();

            docTran.LoadXml(xmlGer);
            docTran.PreserveWhitespace = false;

            CertEmpresa = AssinaturaDigital.FindCertOnStore(ObjEnt.Loja);

            EnviarXml(docTran, CertEmpresa, ref eNotaFiscal);

            objDados = null;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates the PipData from the given object
        /// </summary>
        public static PipData CreatePipData(StringTable stringTable, ObjectLiteral obj, PipDataBuilder pipDataBuilder)
        {
            var settings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                Indent   = true,
            };

            using (var stringBuilderWrapper = Pools.StringBuilderPool.GetInstance())
            {
                var stringBuilder = stringBuilderWrapper.Instance;
                using (var writer = new UTF8StringWriter(stringBuilder))
                    using (var xmlWriter = XmlWriter.Create(writer, settings))
                    {
                        var xmlContext = new XmlWritingContext(stringTable, pipDataBuilder, stringBuilderWrapper.Instance, xmlWriter);

                        if (!WriteNode(obj, in xmlContext))
                        {
                            return(PipData.Invalid);
                        }

                        FlushXmlToPipBuilder(in xmlContext);

                        return(pipDataBuilder.ToPipData(string.Empty, PipDataFragmentEscaping.NoEscaping));
                    }
            }
        }
Ejemplo n.º 4
0
        public void Enviar(Entidade_Inutilizacao ObjEnt, out Entidade_Inutilizacao objDados)
        {
            docTran   = new XmlDocument();
            ns        = new XmlSerializerNamespaces();
            Settings  = new XmlWriterSettings();
            xmlStatus = new XmlSerializer(typeof(inutNFe.TInutNFe));

            eObjInut = ObjEnt;

            InutilNfe = new inutNFe.TInutNFe(ObjEnt);
            eObjInut.ChaveAcessoNfe = InutilNfe.infInut.Id.Replace("ID", "");
            // E DEFINIDO O TIPO DE LEITURA DO XML
            Settings.Encoding        = UTF8Encoding.UTF8;
            Settings.NewLineHandling = NewLineHandling.None;
            Settings.Indent          = true;
            Settings.IndentChars     = "";

            ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

            Sw = new UTF8StringWriter();
            Wx = XmlWriter.Create(Sw, Settings);
            xmlStatus.Serialize(Sw, InutilNfe, ns);
            string xmlGer = Sw.ToString();

            docTran.LoadXml(xmlGer);
            docTran.PreserveWhitespace = false;


            CertEmpresa = AssinaturaDigital.FindCertOnStore(ObjEnt.Loja);

            EnviarXml(AssinaturaDigital.SignXml(docTran, CertEmpresa, "infInut"), CertEmpresa, ref ObjEnt);

            objDados = ObjEnt;
        }
Ejemplo n.º 5
0
        public static string ToXML <T>(T instance)
        {
            UTF8StringWriter writer = null;
            string           str;

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                StringBuilder sb         = new StringBuilder();
                writer = new UTF8StringWriter(sb);
                serializer.Serialize((TextWriter)writer, instance);
                str = sb.ToString();
            }
            catch
            {
                str = null;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return(str);
        }
Ejemplo n.º 6
0
        private static string ApplyElementDefinitions(string path, string contents)
        {
            XDocument xDocument;

            using (StringReader stringReader = new StringReader(contents))
            {
                xDocument = XDocument.Load(stringReader);
                foreach (ElementDefinition elementDefinition in elementDefinitions)
                {
                    if (elementDefinition.SelectedEditMode == ElementDefinition.EditMode.Ignore)
                    {
                        continue;
                    }
                    xDocument.Root.SetValueRecursively(elementDefinition);
                }
            }
            using (StringWriter stringWriter = new UTF8StringWriter())
            {
                xDocument.Save(stringWriter);
                contents = stringWriter.ToString();
            }
            if (isLoggingEnabled)
            {
                Debug.LogFormat(description + " File has been updated: {0}", path);
            }
            return(contents);
        }
Ejemplo n.º 7
0
        /// <summary>
        ///     Converts to xml.
        /// </summary>
        /// <param name="withFormatting">if set to <c>true</c> [with formatting].</param>
        /// <param name="omitXmlDeclaration">if set to <c>true</c> [omit XML declaration].</param>
        /// <returns>System.String.</returns>
        public string ToXml(bool withFormatting = true, bool omitXmlDeclaration = false)
        {
            var listOfType = new List <Type>
            {
                typeof(Hangup), typeof(Answer),
                typeof(Playback), typeof(Bind), typeof(Dial), typeof(Conference),
                typeof(Echo), typeof(Intercept), typeof(Record), typeof(Ringback),
                typeof(Speak), typeof(Wait)
            };

            var settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = omitXmlDeclaration,
                Encoding           = new UTF8Encoding(true),
                ConformanceLevel   = ConformanceLevel.Document,
                CloseOutput        = false,
                Indent             = withFormatting,
                NewLineHandling    = NewLineHandling.Replace
            };

            var xns = new XmlSerializerNamespaces();

            xns.Add(string.Empty, string.Empty);
            var serializer = new XmlSerializer(typeof(ApidazeScript), listOfType.ToArray());

            using var stringWriter = new UTF8StringWriter();
            using var xmlWriter    = XmlWriter.Create(stringWriter, settings);
            serializer.Serialize(xmlWriter, this, xns);
            return(stringWriter.ToString().Replace(" />", "/>"));
        }
Ejemplo n.º 8
0
        }         //SerializeObject

        public static string SerializeObject(object o, Type t)
        {
            try
            {
                //                Dim ms As New MemoryStream
                var sw = new UTF8StringWriter();
                var xs = new XmlSerializer(t);

                var settings = new XmlWriterSettings();
                settings.NewLineHandling = NewLineHandling.Entitize;
                settings.Indent          = true;
                settings.Encoding        = new UTF8Encoding();
                settings.IndentChars     = " ";

                var writer = XmlWriter.Create(sw, settings);
                xs.Serialize(writer, o);

                return(sw.ToString());

                //ms = CType(writer.BaseStream, MemoryStream)
                //Return UTF8ByteArrayToString(ms.ToArray())
            }
            catch (Exception)
            {
                return(null);
            }
        }         //SerializeObject
Ejemplo n.º 9
0
        /// <summary>
        /// serialize an object to a file.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <returns>
        /// Null is returned if any error occurs.
        /// </returns>
        public static String ToXML <T>(T instance)
        {
            UTF8StringWriter sr = null;

            try
            {
                XmlSerializer xr = new XmlSerializer(typeof(T));
                StringBuilder sb = new StringBuilder();

                sr = new UTF8StringWriter(sb);
                xr.Serialize(sr, instance);

                return(sb.ToString());
            }
            catch (Exception ex)
            {
                LogXmlSerializeException(instance.GetType().ToString(), ex);
                return(null);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
        public ActionResult RenderSitemap()
        {
            if (_sitemapConfig.EnableSitemap == false)
            {
                return(HttpNotFound());
            }

            var startNode = UmbracoContext.PublishedRequest.PublishedContent;

            if (startNode == null)
            {
                return(HttpNotFound());
            }

            using (var writer = new UTF8StringWriter())
            {
                var doc = _sitemapBuilder.BuildSitemap(startNode);

                doc.Save(writer);

                var sitemapXml = writer.ToString();

                return(Content(sitemapXml, "text/xml", Encoding.UTF8));
            }
        }
Ejemplo n.º 11
0
        public void Enviar(Entidade_CCe ObjEnt, out Entidade_CCe objDados)
        {
            docTran    = new XmlDocument();
            docEnviNfe = new XmlDocument();
            ns         = new XmlSerializerNamespaces();
            Settings   = new XmlWriterSettings();
            xmlStatus  = new XmlSerializer(typeof(CCe.TEvento));
            EntCarta   = new Entidade_CCe();

            EntCarta = PesquisarCartaEletronica();

            docEnviNfe.PreserveWhitespace = false;
            docEnviNfe.LoadXml(CabecalhoEvento(EntCarta.Id_CCe_Lote));

            nodeListNfe = docEnviNfe.GetElementsByTagName("envEvento");

            if (EntCarta.ItemCCe != null)
            {
                foreach (var item in EntCarta.ItemCCe)
                {
                    nEventoCarta = new CCe.TEvento(item);

                    Settings.Encoding        = UTF8Encoding.UTF8;
                    Settings.NewLineHandling = NewLineHandling.None;
                    Settings.Indent          = true;
                    Settings.IndentChars     = "";

                    ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

                    Sw = new UTF8StringWriter();
                    Wx = XmlWriter.Create(Sw, Settings);
                    xmlStatus.Serialize(Sw, nEventoCarta, ns);
                    string xmlGer = Sw.ToString();

                    docTran.LoadXml(xmlGer);
                    docTran.PreserveWhitespace = false;

                    CertEmpresa = AssinaturaDigital.FindCertOnStore(item.id_loja);

                    docTran = AssinaturaDigital.SignXml(docTran, CertEmpresa, "infEvento");

                    nodeListCarregarNfe = docTran.GetElementsByTagName("evento", "http://www.portalfiscal.inf.br/nfe");
                    nodeListNfe.Item(0).AppendChild(docEnviNfe.ImportNode(nodeListCarregarNfe.Item(0), true));
                }
                try
                {
                    EnviarXml(docEnviNfe, CertEmpresa, ref EntCarta);
                    objDados = ObjEnt;
                }
                catch (Exception Ex)
                {
                    Mensagem.MensagemErro(Mensagem.TipoMensagem.CartaEletronica, "Saida", Ex.Message.ToString());
                    objDados = null;
                }
            }
            else
            {
                objDados = null;
            }
        }
Ejemplo n.º 12
0
        public void Enviar(Entidade_Status ObjEnt, out Entidade_Status objDados)
        {
            Entidade_Status eRetStatus = new Entidade_Status();

            eStatus  = new Entidade_Status();
            mLog     = new Model_LogNfe();
            NFuncoes = new NegocioFuncoesGerais();

            eStatus = ObjEnt;

            docTran   = new XmlDocument();
            ns        = new XmlSerializerNamespaces();
            Settings  = new XmlWriterSettings();
            xmlStatus = new XmlSerializer(typeof(ConsStatServ.TConsStatServ));

            try
            {
                //Passando os dados para a Class que vai ser serelizada
                cStatus = new ConsStatServ.TConsStatServ(eStatus);

                // E DEFINIDO O TIPO DE LEITURA DO XML
                Settings.Encoding        = UTF8Encoding.UTF8;
                Settings.NewLineHandling = NewLineHandling.None;
                Settings.Indent          = true;
                Settings.IndentChars     = "";

                ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

                Sw = new UTF8StringWriter();
                Wx = XmlWriter.Create(Sw, Settings);
                xmlStatus.Serialize(Sw, cStatus, ns);
                string xmlGer = Sw.ToString();

                docTran.LoadXml(xmlGer);
                docTran.PreserveWhitespace = false;

                if (nFG.ValidarEstruturaXml(docTran.OuterXml, "consStatServ_v3.10"))
                {
                    CertEmpresa = AssinaturaDigital.FindCertOnStore(eStatus.Loja);
                    EnviarXml(docTran, CertEmpresa, ref eRetStatus);
                    objDados = eRetStatus;
                }
                else
                {
                    objDados = null;
                }
            }
            catch (Exception Ex)
            {
                Mensagem.MensagemErro(Mensagem.TipoMensagem.Nfe, "Saida", Ex.Message.ToString());
                mLog.InsertErroLog(NFuncoes.TiraCampos(Ex.Message.ToString()));
                objDados = null;
            }
        }
Ejemplo n.º 13
0
        public void ReDisplayFile(XDocument xmlDocument, EDisplayedFileType displayedFileType, string fileName = null, ILog log = null, PSMSchema validationSchema = null, PSMSchema sourcePSMSchema = null, FilePresenterButtonInfo[] additionalActions = null)
        {
            StringBuilder sb = new StringBuilder();

            using (TextWriter tw = new UTF8StringWriter(sb))
            {
                xmlDocument.Save(tw);
            }

            DisplayFile(displayedFileType, sb.ToString(), fileName, log, validationSchema, sourcePSMSchema);
        }
Ejemplo n.º 14
0
        public static string Serialize <T>(T ObjectToSerialize)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "");
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

            using (StringWriter textWriter = new UTF8StringWriter())
            {
                xmlSerializer.Serialize(textWriter, ObjectToSerialize, ns);
                return(textWriter.ToString());
            }
        }
Ejemplo n.º 15
0
        public IFilePresenterTab DisplayFile(XDocument xmlDocument, EDisplayedFileType fileType, string fileName = null, ILog log = null, PSMSchema validationSchema = null, PSMSchema sourcePSMSchema = null, FilePresenterButtonInfo[] additionalActions = null, object tag = null)
        {
            StringBuilder sb = new StringBuilder();

            if (xmlDocument != null)
            {
                using (TextWriter tw = new UTF8StringWriter(sb))
                {
                    xmlDocument.Save(tw);
                }
            }
            var f = DisplayFile(sb.ToString(), fileType, fileName, log, validationSchema, sourcePSMSchema, additionalActions, tag);

            return(f);
        }
Ejemplo n.º 16
0
        private async Task UploadFileToBlob(string temporaryUploadLocationUrl, Stream file, CancellationToken cancellationToken)
        {
            const int maxBlockSize = 4 * MB;

            var blockIds = new List <string>();
            var buffer   = new byte[maxBlockSize];
            var i        = 1;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("x-ms-version", "2015-04-05");
                var baseUploadUrl = temporaryUploadLocationUrl + "&comp=block&blockid=";
                var headers       = new Dictionary <string, string>
                {
                    { "x-ms-blob-type", "BlockBlob" }
                };
                do
                {
                    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("block-" + i.ToString("000000"));
                    var blockId        = Convert.ToBase64String(plainTextBytes);
                    var bytesRead      = await file.ReadAsync(buffer, 0, maxBlockSize).ConfigureAwait(false);

                    var uploadBlockUrl = baseUploadUrl + blockId;
                    var content        = new ByteArrayContent(buffer, 0, bytesRead);
                    await SendRequest(httpClient, HttpMethod.Put, uploadBlockUrl, headers, content, HttpStatusCode.Created, cancellationToken).ConfigureAwait(false);

                    blockIds.Add(blockId);
                    i++;
                }while (file.Length - file.Position > 0);

                var blockList = new BlockList {
                    BlockIds = blockIds
                };

                var xsn = new XmlSerializerNamespaces();
                xsn.Add(string.Empty, string.Empty);

                var serializer = new XmlSerializer(typeof(BlockList));
                var myWriter   = new UTF8StringWriter();
                serializer.Serialize(myWriter, blockList, xsn);
                var requestBody = myWriter.ToString();

                headers.Clear();
                headers.Add("x-ms-blob-content-type", "application/x-zip-compressed");
                var uploadBlocListkUrl = temporaryUploadLocationUrl + "&comp=blocklist";
                await SendRequest(httpClient, HttpMethod.Put, uploadBlocListkUrl, headers, new StringContent(requestBody), HttpStatusCode.Created, cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 17
0
        public static string TransformXMLToHTML(string xsltString, string xmlData)
        {
            XslCompiledTransform transform = new XslCompiledTransform();

            using (XmlReader reader = XmlReader.Create(new StringReader(xsltString)))
            {
                transform.Load(reader);
            }
            UTF8StringWriter results = new UTF8StringWriter();

            using (XmlReader reader = XmlReader.Create(new StringReader(xmlData)))
            {
                transform.Transform(reader, null, results);
            }
            return(results.ToString());
        }
Ejemplo n.º 18
0
        public object Translate(List <Step> sequence)
        {
            lock (m_Lock) //Only one call at a time. For concurrent use, get another instance from the factory.
            {
                XDocument output = new XDocument();
                m_CaseTranslationRequired = false;

                m_Stylesheet = new XElement(xsl + "stylesheet",
                                            new XAttribute("version", "1.0"),
                                            new XAttribute(XNamespace.Xmlns + "xsl", xsl),
                                            new XAttribute(XNamespace.Xmlns + "msxsl", msxsl),
                                            new XAttribute("exclude-result-prefixes", "msxsl"));
                output.Add(m_Stylesheet);

                m_Stylesheet.Add(new XElement(xsl + "output",
                                              new XAttribute("method", "xml"),
                                              new XAttribute("indent", "yes")));

                XElement rootTemplate = new XElement(xsl + "template",
                                                     new XAttribute("name", "root"),
                                                     new XAttribute("match", "/"));
                m_Stylesheet.Add(rootTemplate);

                XElement rootElement = new XElement(DataScope.RootScopeName);
                rootTemplate.Add(rootElement);

                zTranslateRecursive(rootElement, sequence, "root", null);

                if (m_CaseTranslationRequired)
                {
                    m_Stylesheet.Add(new XElement(xsl + "variable",
                                                  new XAttribute("name", "lowerCase"),
                                                  new XAttribute("select", "'abcdefghijklmnopqrstuvwxyz'")));
                    m_Stylesheet.Add(new XElement(xsl + "variable",
                                                  new XAttribute("name", "upperCase"),
                                                  new XAttribute("select", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'")));
                }

                StringBuilder sb = new StringBuilder();
                using (TextWriter writer = new UTF8StringWriter(sb))
                {
                    output.Save(writer);
                }
                return(sb.ToString());
            }
        }
Ejemplo n.º 19
0
        public void Convert()
        {
            if (ShouldGenerateCoverPage)
            {
                if (!AcquireCoverPage())
                {
                    throw new Exception("An error occurred while aquiring the cover page!");
                }
            }

            for (int i = 0; i < Book.Chapters.Length; ++i)
            {
                using var string_writer = new UTF8StringWriter();
                using var writer        = XmlWriter.Create(string_writer, Helper.XmlWriterSettings);

                // Reset current page info
                CurrentPage = new HtmlPageInfo
                {
                    Chapter = Book.Chapters[i],
                    Html    = new HtmlGenerator(writer, Book.Chapters[i].Title),
                    InTable = false,
                    WarnedUnsupportedStyle = false
                };

                // Iterate over blocks for this chapter
                foreach (var block in CurrentPage.Chapter.Content.Blocks)
                {
                    HandleBlocks(block);
                }

                // Make sure to close the table (just in case)
                if (CurrentPage.InTable)
                {
                    CurrentPage.Html.EndTable();
                }

                // Close the stream, so we can finally obtain the XML result
                writer.Close();

                // Copy generated HTML, so we can later save it to EPUB
                Book.Chapters[i].HTML = string_writer.ToString();
            }

            Helper.Debug("Finished converting MPUB blocks to HTML");
        }
Ejemplo n.º 20
0
        public void Enviar(Entidade_ConsNFDest ObjEnt, out Entidade_ConsNFDest objDados)
        {
            Entidade_ConsNFDest ObjRetManifestacao = new Entidade_ConsNFDest();

            ObjRetManifestacao.id_loja = 1;
            NFuncoes = new NegocioFuncoesGerais();

            docTran  = new XmlDocument();
            ns       = new XmlSerializerNamespaces();
            Settings = new XmlWriterSettings();
            mLog     = new Model_LogNfe();

            xmlStatus = new XmlSerializer(typeof(TConsNFeDest));


            try
            {
                ObjConDest = new TConsNFeDest(1);

                Settings.Encoding        = UTF8Encoding.UTF8;
                Settings.NewLineHandling = NewLineHandling.None;
                Settings.Indent          = true;
                Settings.IndentChars     = "";

                ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

                Sw = new UTF8StringWriter();
                Wx = XmlWriter.Create(Sw, Settings);
                xmlStatus.Serialize(Sw, ObjConDest, ns);
                string xmlGer = Sw.ToString();

                docTran.LoadXml(xmlGer);
                docTran.PreserveWhitespace = false;

                CertEmpresa = AssinaturaDigital.FindCertOnStore(1);
                EnviarXml(docTran, CertEmpresa, ref ObjRetManifestacao);
                objDados = ObjRetManifestacao;
            }
            catch (Exception Ex)
            {
                Mensagem.MensagemErro(Mensagem.TipoMensagem.Manifestacao, "Manifestação", Ex.Message.ToString());
                mLog.InsertErroLog(NFuncoes.TiraCampos(Ex.Message.ToString()));
                objDados = null;
            }
        }
Ejemplo n.º 21
0
        public void Enviar(Entidade_DownloadNFe ObjEnt, out Entidade_DownloadNFe objDados)
        {
            Entidade_Status eRetStatus = new Entidade_Status();

            eDownloadNFe = new Entidade_DownloadNFe();
            mLog         = new Model_LogNfe();
            NFuncoes     = new NegocioFuncoesGerais();

            docTran   = new XmlDocument();
            ns        = new XmlSerializerNamespaces();
            Settings  = new XmlWriterSettings();
            xmlStatus = new XmlSerializer(typeof(TDownloadNFe));

            try
            {
                //Passando os dados para a Class que vai ser serelizada
                ObjDownloadNFeEnv = new TDownloadNFe(ObjEnt);

                // E DEFINIDO O TIPO DE LEITURA DO XML
                Settings.Encoding        = UTF8Encoding.UTF8;
                Settings.NewLineHandling = NewLineHandling.None;
                Settings.Indent          = true;
                Settings.IndentChars     = "";

                ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

                Sw = new UTF8StringWriter();
                Wx = XmlWriter.Create(Sw, Settings);
                xmlStatus.Serialize(Sw, ObjDownloadNFeEnv, ns);
                string xmlGer = Sw.ToString();

                docTran.LoadXml(xmlGer);
                docTran.PreserveWhitespace = false;

                CertEmpresa = AssinaturaDigital.FindCertOnStore(ObjEnt.id_loja);
                EnviarXml(docTran, CertEmpresa, ref ObjEnt);
                objDados = null;
            }
            catch (Exception Ex)
            {
                Mensagem.MensagemErro(Mensagem.TipoMensagem.Status, "DownloaNFe", Ex.Message.ToString());
                mLog.InsertErroLog(NFuncoes.TiraCampos(Ex.Message.ToString()));
                objDados = null;
            }
        }
Ejemplo n.º 22
0
            public RSSReader(string url)
            {
                XDocument feed = XDocument.Load(url, LoadOptions.PreserveWhitespace);

                using (StringWriter writer = new UTF8StringWriter())
                {
                    feed.Save(writer, SaveOptions.OmitDuplicateNamespaces);
                }
                this._Feeds = from item in feed.Element("rss").Element("channel").Elements("item")
                              select new RSSFeedItem
                {
                    title       = WebUtility.HtmlDecode(item.Element("title").Value),
                    link        = WebUtility.HtmlDecode(item.Element("link").Value),
                    category    = WebUtility.HtmlDecode(item.Element("category").Value),
                    description = WebUtility.HtmlDecode(item.Element("description").Value),
                    pubdate     = DateTime.Parse(item.Element("pubDate").Value)
                };
            }
Ejemplo n.º 23
0
 private static string SerializeJson(object o)
 {
     if (o == null)
     {
         return(null);
     }
     using (var sw = new UTF8StringWriter())
     {
         if (IsSimple(o.GetType()))
         {
             sw.Write(o.AsString());
         }
         else
         {
             JsonSerializer.Serialize(sw, o);
         }
         return(sw.ToString());
     }
 }
Ejemplo n.º 24
0
        //
        // The XML result structure
        // <AutoTest>
        //   <query>c =&gt; c.Window()</query>
        //   <results>
        //     <result type="Gtk.Window" fulltype="Gtk.Window" name="Main Window" visible="true" sensitive="true" allocation="1,1 1024x1024">
        //       ... contains result elements for all children widgets ...
        //     </result>
        //     ... and more result element trees for each of the AppResult in results ...
        //   </results>
        // </AutoTest>
        //
        public string ResultsAsXml(AppResult[] results)
        {
            XmlDocument document    = new XmlDocument();
            XmlElement  rootElement = document.CreateElement("AutoTest");

            document.AppendChild(rootElement);

            if (results [0].SourceQuery != null)
            {
                XmlElement queryElement = document.CreateElement("query");
                queryElement.AppendChild(document.CreateTextNode(results [0].SourceQuery));
                rootElement.AppendChild(queryElement);
            }

            XmlElement resultsElement = document.CreateElement("results");

            rootElement.AppendChild(resultsElement);

            try {
                ExecuteOnIdle(() => {
                    foreach (var result in results)
                    {
                        AddChildrenToDocument(document, resultsElement, result, false);
                    }
                });
            } catch (TimeoutException e) {
                ThrowOperationTimeoutException("ResultsAsXml", null, null, e);
            }

            string output;

            using (var sw = new UTF8StringWriter()) {
                using (var xw = XmlWriter.Create(sw, new XmlWriterSettings {
                    Indent = true
                })) {
                    document.WriteTo(xw);
                }

                output = sw.ToString();
            }

            return(output);
        }
Ejemplo n.º 25
0
        public void Enviar(Entidade_Manifestacao ObjEnt, out Entidade_Manifestacao objDados)
        {
            docTran         = new XmlDocument();
            docEnviNfe      = new XmlDocument();
            ns              = new XmlSerializerNamespaces();
            Settings        = new XmlWriterSettings();
            xmlStatus       = new XmlSerializer(typeof(TEnvEvento));
            EntManifestacao = new Entidade_Manifestacao();

            //EntManifestacao = PesquisaDados();
            envManifestacao = new TEnvEvento(ObjEnt);
            objDados        = null;

            Settings.Encoding        = UTF8Encoding.UTF8;
            Settings.NewLineHandling = NewLineHandling.None;
            Settings.Indent          = true;
            Settings.IndentChars     = "";

            ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

            try
            {
                Sw = new UTF8StringWriter();
                Wx = XmlWriter.Create(Sw, Settings);
                xmlStatus.Serialize(Sw, envManifestacao, ns);
                string xmlGer = Sw.ToString();

                docTran.LoadXml(xmlGer);
                docTran.PreserveWhitespace = false;

                CertEmpresa = AssinaturaDigital.FindCertOnStore(1);

                EnviarXml(AssinaturaDigital.SignXml(docTran, CertEmpresa, "infEvento"), CertEmpresa, ref ObjEnt);

                objDados = ObjEnt;
            }
            catch (Exception Ex)
            {
                Mensagem.MensagemErro(Mensagem.TipoMensagem.Cancelamento, "Envia Manifestação", Ex.Message.ToString());
                objDados = null;
            }
        }
        public ActionResult RenderSitemap()
        {
            var route = ((Route)RouteData.Route).Url;

            if (_sitemapCollection.TryGetValue(route, out ISitemapBuilder builder) == false)
            {
                return(HttpNotFound());
            }

            var request = UmbracoContext.PublishedRequest;

            var startNode = request?.PublishedContent;

            if (startNode == null)
            {
                return(HttpNotFound());
            }

            var culture = request?.Culture.Name;

            if (culture == null)
            {
                return(HttpNotFound());
            }

            var doc = builder.BuildSitemap(startNode, culture);

            if (doc == null)
            {
                return(HttpNotFound());
            }

            using (var writer = new UTF8StringWriter())
            {
                doc.Save(writer);

                var sitemapXml = writer.ToString();

                return(Content(sitemapXml, "text/xml", Encoding.UTF8));
            }
        }
Ejemplo n.º 27
0
        public void Enviar(Entidade_Recibo ObjEnt, out Entidade_Recibo objDados)
        {
            ReciNFe   = new TConsReciNFe();
            docTran   = new XmlDocument();
            ns        = new XmlSerializerNamespaces();
            Settings  = new XmlWriterSettings();
            xmlStatus = new XmlSerializer(typeof(TConsReciNFe));

            ReciNFe = new TConsReciNFe(ObjEnt.Recibo, ObjEnt.TpAmb);

            Settings.Encoding        = UTF8Encoding.UTF8;
            Settings.NewLineHandling = NewLineHandling.None;
            Settings.Indent          = true;
            Settings.IndentChars     = "";

            ns.Add(string.Empty, "http://www.portalfiscal.inf.br/nfe");

            Sw = new UTF8StringWriter();
            Wx = XmlWriter.Create(Sw, Settings);
            xmlStatus.Serialize(Sw, ReciNFe, ns);
            string xmlGer = Sw.ToString();

            docTran.LoadXml(xmlGer);
            docTran.PreserveWhitespace = false;

            CertEmpresa = AssinaturaDigital.FindCertOnStore(ObjEnt.Loja);
            try
            {
                EnviarXml(docTran, CertEmpresa, ref ObjEnt);

                objDados = ObjEnt;
            }
            catch (Exception Ex)
            {
                Mensagem.MensagemErro(Mensagem.TipoMensagem.RetAutoriz, "Saida", Ex.Message.ToString());
                objDados = null;
            }
        }
        private String Transform(string xsl, string xml)
        {
            string output = String.Empty;

            using (StringReader srt = new StringReader(xsl))     // xslInput is a string that contains xsl
                using (StringReader sri = new StringReader(xml)) // xmlInput is a string that contains xml
                {
                    using (XmlReader xrt = XmlReader.Create(srt))
                        using (XmlReader xri = XmlReader.Create(sri))
                        {
                            XslCompiledTransform xslt = new XslCompiledTransform();
                            xslt.Load(xrt);
                            using (UTF8StringWriter sw = new UTF8StringWriter())
                                using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
                                {
                                    xslt.Transform(xri, xwo);
                                    output = sw.ToString();
                                }
                        }
                }

            return(output);
        }
Ejemplo n.º 29
0
 public string ToXml()
 {
     using (TextWriter writer = new UTF8StringWriter())
     {
         XmlWriterSettings settings = new XmlWriterSettings()
         {
             Encoding = Encoding.UTF8,
             Indent   = true
         };
         using (XmlWriter xWriter = XmlWriter.Create(writer, settings))
         {
             xWriter.WriteStartDocument();
             xWriter.WriteStartElement(DataScope.RootScopeName);
             foreach (IStateVariable stateVariable in this.StateVariables.Values)
             {
                 zToXmlRecursive(stateVariable, xWriter, false);
             }
             xWriter.WriteEndElement();
             xWriter.WriteEndDocument();
         }
         return(writer.ToString());
     }
 }
Ejemplo n.º 30
0
        public static bool salvar(AuditFile auditFile, string pasta, string filename)
        {
            bool sucesso = true;

            try
            {
                auditFile.ToString();
                string fileName = @"\" + filename + ".xml";

                if (!Directory.Exists(pasta))
                {
                    Directory.CreateDirectory(pasta);
                }

                pasta = pasta + fileName;

                XmlSerializer xmlSer = new XmlSerializer(typeof(AuditFile));

                using (StringWriter arquivo = new UTF8StringWriter())
                {
                    xmlSer.Serialize(arquivo, auditFile);

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(arquivo.ToString());

                    xmlDoc.Save(@pasta);
                }
            }
            catch (Exception ex)
            {
                sucesso = false;
                Console.WriteLine(ex.Message);
            }

            return(sucesso);
        }
Ejemplo n.º 31
0
		//
		// The XML result structure
		// <AutoTest>
		//   <query>c =&gt; c.Window()</query>
		//   <results>
		//     <result type="Gtk.Window" fulltype="Gtk.Window" name="Main Window" visible="true" sensitive="true" allocation="1,1 1024x1024">
		//       ... contains result elements for all children widgets ...
		//     </result>
		//     ... and more result element trees for each of the AppResult in results ...
		//   </results>
		// </AutoTest>
		//
		public string ResultsAsXml (AppResult[] results)
		{
			XmlDocument document = new XmlDocument ();
			XmlElement rootElement = document.CreateElement ("AutoTest");
			document.AppendChild (rootElement);

			if (results [0].SourceQuery != null) {
				XmlElement queryElement = document.CreateElement ("query");
				queryElement.AppendChild (document.CreateTextNode (results [0].SourceQuery));
				rootElement.AppendChild (queryElement);
			}

			XmlElement resultsElement = document.CreateElement ("results");
			rootElement.AppendChild (resultsElement);

			try {
				ExecuteOnIdle (() => {
					foreach (var result in results) {
						AddChildrenToDocument (document, resultsElement, result, false);
					}
				});
			} catch (TimeoutException e) {
				ThrowOperationTimeoutException ("ResultsAsXml", null, null, e);
			}

			string output;

			using (var sw = new UTF8StringWriter ()) {
				using (var xw = XmlWriter.Create (sw, new XmlWriterSettings { Indent = true })) {
					document.WriteTo (xw);
				}

				output = sw.ToString ();
			}

			return output;
		}
            public static MvcHtmlString RenderXslt(string xslPath, string xmlString, List<KeyValuePair<string, string>> parameters = null)
            {
                string xsltResult = string.Empty;

                try
                {
                    // XML Settings
                    XmlReaderSettings xmlSettings = new XmlReaderSettings();
                    xmlSettings.XmlResolver = null;
                    xmlSettings.IgnoreComments = true;
                    xmlSettings.DtdProcessing = DtdProcessing.Ignore;
                    xmlSettings.ValidationType = ValidationType.None;

                    // Attaches an action to the valiation event handler. This will write out error messages in the Output pane.
                #if DEBUG
                    xmlSettings.ValidationEventHandler += (sender, e) =>
                    {
                        Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message));
                    };
                #endif

                    // XSLT Settings
                    XmlReaderSettings xsltSettings = new XmlReaderSettings();
                    xsltSettings.XmlResolver = null;
                    xsltSettings.DtdProcessing = DtdProcessing.Ignore;
                    xsltSettings.ValidationType = ValidationType.None;

                    // Attaches an action to the valiation event handler. This will write out error messages in the Output pane.
                #if DEBUG
                    xsltSettings.ValidationEventHandler += (sender, e) =>
                    {
                        Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message));
                    };
                #endif

                    // Init params
                    XsltArgumentList xslArgs = new XsltArgumentList();
                    if (parameters != null)
                    {
                        foreach (KeyValuePair<string, string> param in parameters)
                            xslArgs.AddParam(param.Key, string.Empty, param.Value);
                    }

                    // Load XML
                    using (XmlReader reader = XmlReader.Create(new StringReader(xmlString), xmlSettings))
                    {
                        // Load XSL
                        XsltSettings xslSettings = new XsltSettings(true, true); // Need to enable the document() fucntion

                        using (XmlReader xslSource = XmlReader.Create(xslPath, xsltSettings))
                        {
                            XslCompiledTransform xsltDoc = new XslCompiledTransform();
                            xsltDoc.Load(xslSource, xslSettings, new XmlUrlResolver());

                            // Transform
                            using (var sw = new UTF8StringWriter())
                            {
                                XmlWriterSettings settings = new XmlWriterSettings();
                                settings.Encoding = Encoding.UTF8;
                                settings.OmitXmlDeclaration = true;

                                using (var xw = XmlWriter.Create(sw, settings))
                                {
                                    xsltDoc.Transform(reader, xslArgs, sw);
                                }

                                xsltResult = sw.ToString();
                            }
                        }
                    }
                }
                catch { } // custom error handling here

                // Return result
                return MvcHtmlString.Create(xsltResult);
            }
Ejemplo n.º 33
0
        public void Execute()
        {
            //
            // LINQ to XMLにてXMLを新規作成するには
            // 以下のどちらかのインスタンスを作成する必要がある.
            //   ・XDocument
            //   ・XElement
            // 通常、よく利用されるのはXElementの方となる.
            // 保存を行うには、Saveメソッドを利用する.
            // Saveメソッドには、以下のオーバーロードが存在する. (XElement)
            //   Save(Stream)
            //   Save(String)
            //   Save(TextWriter)
            //   Save(XmlWriter)
            //   Save(Stream, SaveOptions)
            //   Save(String, SaveOptions)
            //   Save(TextWriter, SaveOptions)
            //
            var element = new XElement("RootNode",
                                       from i in Enumerable.Range(1, 10)
                                       select new XElement("Child", i)
            );

            //
            // Save(Stream)
            //
            using (var stream = new MemoryStream())
            {
                element.Save(stream);

                stream.Position = 0;
                using (var reader = new StreamReader(stream))
                {
                    Output.WriteLine(reader.ReadToEnd());
                }
            }

            Output.WriteLine("===================================");

            //
            // Save(String)
            //
            var tmpFile = Path.GetRandomFileName();
            element.Save(tmpFile);
            Output.WriteLine(File.ReadAllText(tmpFile));
            File.Delete(tmpFile);

            Output.WriteLine("===================================");

            //
            // Save(TextWriter)
            //
            using (var writer = new UTF8StringWriter())
            {
                element.Save(writer);
                Output.WriteLine(writer);
            }

            Output.WriteLine("===================================");

            //
            // Save(XmlWriter)
            //
            using (var backingStore = new UTF8StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(backingStore, new XmlWriterSettings {Indent = true}))
                {
                    element.Save(xmlWriter);
                }

                Output.WriteLine(backingStore);
            }

            Output.WriteLine("===================================");

            //
            // SaveOptions付きで書き込み.
            //   DisableFormattingを指定すると、出力されるXMLに書式が設定されなくなる.
            //
            using (var writer = new UTF8StringWriter())
            {
                element.Save(writer, SaveOptions.DisableFormatting);
                Output.WriteLine(writer);
            }
        }