Add() public méthode

public Add ( String ns, XmlReader reader ) : XmlSchema
ns String
reader System.Xml.XmlReader
Résultat XmlSchema
		public void TestAdd ()
		{
			XmlSchemaCollection col = new XmlSchemaCollection ();
			XmlSchema schema = new XmlSchema ();
			XmlSchemaElement elem = new XmlSchemaElement ();
			elem.Name = "foo";
			schema.Items.Add (elem);
			schema.TargetNamespace = "urn:foo";
			col.Add (schema);
			col.Add (schema);	// No problem !?

			XmlSchema schema2 = new XmlSchema ();
			schema2.Items.Add (elem);
			schema2.TargetNamespace = "urn:foo";
			col.Add (schema2);	// No problem !!

			schema.Compile (null);
			col.Add (schema);
			col.Add (schema);	// Still no problem !!!

			schema2.Compile (null);
			col.Add (schema2);

			schema = GetSchema ("Test/XmlFiles/xsd/3.xsd");
			schema.Compile (null);
			col.Add (schema);

			schema2 = GetSchema ("Test/XmlFiles/xsd/3.xsd");
			schema2.Compile (null);
			col.Add (schema2);
		}
Exemple #2
0
        /// <summary>
        ///     Valida se um Xml está seguindo de acordo um Schema
        /// </summary>
        /// <param name="arquivoXml">Arquivo Xml</param>
        /// <param name="arquivoSchema">Arquivo de Schema</param>
        /// <returns>True se estiver certo, Erro se estiver errado</returns>
        public void ValidaSchema(String arquivoXml, String arquivoSchema)
        {
            //Seleciona o arquivo de schema de acordo com o schema informado
            //arquivoSchema = Bll.Util.ContentFolderSchemaValidacao + "\\" + arquivoSchema;

            //Verifica se o arquivo de XML foi encontrado.
            if (!File.Exists(arquivoXml))
                throw new Exception("Arquivo de XML informado: \"" + arquivoXml + "\" não encontrado.");

            //Verifica se o arquivo de schema foi encontrado.
            if (!File.Exists(arquivoSchema))
                throw new Exception("Arquivo de schema: \"" + arquivoSchema + "\" não encontrado.");

            // Cria um novo XMLValidatingReader
            var reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(arquivoXml)));
            // Cria um schemacollection
            var schemaCollection = new XmlSchemaCollection();
            //Adiciona o XSD e o namespace
            schemaCollection.Add("http://www.portalfiscal.inf.br/nfe", arquivoSchema);
            // Adiciona o schema ao ValidatingReader
            reader.Schemas.Add(schemaCollection);
            //Evento que retorna a mensagem de validacao
            reader.ValidationEventHandler += Reader_ValidationEventHandler;
            //Percorre o XML
            while (reader.Read())
            {
            }
            reader.Close(); //Fecha o arquivo.
            //O Resultado é preenchido no reader_ValidationEventHandler

            if (validarResultado != "")
            {
                throw new Exception(validarResultado);
            }
        }
		public void TestAddDoesCompilation ()
		{
			XmlSchema schema = new XmlSchema ();
			Assert (!schema.IsCompiled);
			XmlSchemaCollection col = new XmlSchemaCollection ();
			col.Add (schema);
			Assert (schema.IsCompiled);
		}
 public clsSValidator(string sXMLFileName, string sSchemaFileName)
 {
     m_sXMLFileName = sXMLFileName;
     m_sSchemaFileName = sSchemaFileName;
     m_objXmlSchemaCollection = new XmlSchemaCollection ();
     //adding the schema file to the newly created schema collection
     m_objXmlSchemaCollection.Add (null, m_sSchemaFileName);
 }
        public NSTScorePartwise ParseString(string dataString)
        {
            //todo: parse string
            IList<NSTPart> partList = new List<NSTPart>();
            XmlTextReader textReader = new XmlTextReader(new FileStream("C:\\NM\\ScoreTranscription\\NETScoreTranscription\\NETScoreTranscriptionLibrary\\OtherDocs\\musicXML.xsd", System.IO.FileMode.Open)); //todo: pass stream in instead of absolute location for unit testing
            XmlSchemaCollection schemaCollection = new XmlSchemaCollection();
            schemaCollection.Add(null, textReader);

            NSTScorePartwise score;

            using (XmlValidatingReader reader = new XmlValidatingReader(XmlReader.Create(new StringReader(dataString), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse }))) //todo: make unobsolete
            {
                reader.Schemas.Add(schemaCollection);
                reader.ValidationType = ValidationType.Schema;
                reader.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationEventHandler);

                XmlSerializer serializer = new XmlSerializer(typeof(NSTScorePartwise), new XmlRootAttribute("score-partwise"));
                score = (NSTScorePartwise)serializer.Deserialize(reader);

                /*
                while (reader.Read())
                {
                    if (reader.IsEmptyElement)
                        throw new Exception(reader.Value); //todo: test

                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            switch (reader.Name.ToLower())
                            {
                                case "part-list":
                                    break;
                                case "score-partwise":
                                    break;
                                case "part-name":
                                    throw new Exception("pn");
                                    break;
                            }
                            break;
                        case XmlNodeType.Text:

                            break;
                        case XmlNodeType.XmlDeclaration:
                        case XmlNodeType.ProcessingInstruction:

                            break;
                        case XmlNodeType.Comment:

                            break;
                        case XmlNodeType.EndElement:

                            break;
                    }
                }*/
            }

            return score;
        }
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Invalid parameter count. Exiting...");
                return;
            }

            string xmlFile = args[0];
            string xdsFile = args[1];
            string xdsNamespace = args[2];
            string outputFile = args[3];

            try
            {
                XmlSchemaCollection cache = new XmlSchemaCollection();
                cache.Add(xdsNamespace, xdsFile);

                XmlTextReader r = new XmlTextReader(xmlFile);
                XmlValidatingReader v = new XmlValidatingReader(r);
                v.Schemas.Add(cache);

                v.ValidationType = ValidationType.Schema;

                v.ValidationEventHandler +=
                    new ValidationEventHandler(MyValidationEventHandler);

                while (v.Read()) { } // look for validation errors
                v.Close();
            }
            catch (Exception e)
            {
                encounteredFatalError = true;
                fatalError = e;
            }

            StreamWriter file = new StreamWriter(outputFile);

            if (isValid && !encounteredFatalError)
                file.WriteLine("PASSED: Document is valid");
            else
                file.WriteLine("FAILED: Document is invalid");

            // Printing
            foreach (string entry in list)
            {
                file.WriteLine(entry);
            }
            if (encounteredFatalError)
            {
                file.WriteLine("Error: a FATAL error has occured " +
                        "while reading the file.\r\n" + fatalError.ToString());
            }
            file.Close();
        }
        private void Page_Load(object sender, System.EventArgs e)
        {
            XmlValidatingReader reader = null;
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors );
            try
            {

                String xmlFrag = @"<?xml version='1.0' ?>
                                                <item>
                                                <xxx:price xmlns:xxx='xxx' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
                                                xsi:schemaLocation='test.xsd'></xxx:price>
                                                </item>";
                    /*"<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
                                            "<first-name>Herman</first-name>" +
                                            "<last-name>Melville</last-name>" +
                                            "</author>";*/
                string xsd = @"<?xml version='1.0' encoding='UTF-8'?>
            <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='xxx'>
            <xsd:element name='price' type='xsd:integer' xsd:default='12'/>
            </xsd:schema>";

                //Create the XmlParserContext.
                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
                //Implement the reader.
                reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
                //Add the schema.
                myschema.Add("xxx", new XmlTextReader(new StringReader(xsd)));

                //Set the schema type and add the schema to the reader.
                reader.ValidationType = ValidationType.Schema;
                reader.Schemas.Add(myschema);
                while (reader.Read()){Response.Write(reader.Value);}
                Response.Write("<br>Completed validating xmlfragment<br>");
            }
            catch (XmlException XmlExp)
            {
                Response.Write(XmlExp.Message + "<br>");
            }

            catch(XmlSchemaException XmlSchExp)
            {
                Response.Write(XmlSchExp.Message + "<br>");
            }
            catch(Exception GenExp)
            {
                Response.Write(GenExp.Message + "<br>");
            }
            finally
            {}
            XmlDocument doc;
        }
        //[Variation(Desc = "v2 - Contains with not added schema")]
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
#pragma warning disable 0618
            XmlSchemaCollection scl = new XmlSchemaCollection();
#pragma warning restore 0618

            XmlSchema Schema = scl.Add(null, TestData._XsdAuthor);

            Assert.Equal(sc.Contains(Schema), false);

            return;
        }
        public void Validate(string strXMLDoc)
        {
            try
            {
                // Declare local objects
                XmlTextReader tr = null;
                XmlSchemaCollection xsc = null;
                XmlValidatingReader vr = null;

                // Text reader object
                tr = new XmlTextReader(Application.StartupPath + @"\BDOCImportSchema.xsd");
                xsc = new XmlSchemaCollection();
                xsc.Add(null, tr);

                // XML validator object

                vr = new XmlValidatingReader(strXMLDoc,
                             XmlNodeType.Document, null);

                vr.Schemas.Add(xsc);

                // Add validation event handler

                vr.ValidationType = ValidationType.Schema;
                vr.ValidationEventHandler +=
                         new ValidationEventHandler(ValidationHandler);

                // Validate XML data

                while (vr.Read()) ;

                vr.Close();

                // Raise exception, if XML validation fails
                if (ErrorsCount > 0)
                {
                    throw new Exception(ErrorMessage);
                }

                // XML Validation succeeded
                Console.WriteLine("XML validation succeeded.\r\n");
            }
            catch (Exception error)
            {
                // XML Validation failed
                Console.WriteLine("XML validation failed." + "\r\n" +
                "Error Message: " + error.Message);
                throw new Exception("Error in XSD verification:\r\n" + error.Message);
            }
        }
 public static void ValidateXml(Stream xmlStream, XmlSchema xsdSchema)
 {
     XmlTextReader reader1 = null;
       try
       {
     reader1 = new XmlTextReader(xmlStream);
     XmlSchemaCollection collection1 = new XmlSchemaCollection();
     collection1.Add(xsdSchema);
     XmlValidatingReader reader2 = new XmlValidatingReader(reader1);
     reader2.ValidationType = ValidationType.Schema;
     reader2.Schemas.Add(collection1);
     ArrayList list1 = new ArrayList();
     while (reader2.ReadState != ReadState.EndOfFile)
     {
       try
       {
     reader2.Read();
     continue;
       }
       catch (XmlSchemaException exception1)
       {
     list1.Add(exception1);
     continue;
       }
     }
     if (list1.Count != 0)
     {
       throw new XmlValidationException(list1);
     }
       }
       catch (XmlValidationException exception2)
       {
     throw exception2;
       }
       catch (Exception exception3)
       {
     throw new XmlValidationException(exception3.Message, exception3);
       }
       finally
       {
     if (reader1 != null)
     {
       reader1.Close();
     }
       }
 }
Exemple #11
0
			public SchemaValidator(string xmlFile, string schemaFile)
			{
				XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection();
				XmlTextReader xmlTextReader = new XmlTextReader(schemaFile);
				try
				{
					myXmlSchemaCollection.Add(XmlSchema.Read(xmlTextReader, null));
				}
				finally
				{
					xmlTextReader.Close();
				}

				// Validate the XML file with the schema
				XmlTextReader myXmlTextReader = new XmlTextReader (xmlFile);
				myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader);
				myXmlValidatingReader.Schemas.Add(myXmlSchemaCollection);
				myXmlValidatingReader.ValidationType = ValidationType.Schema;
			}
        public PcaCompiler()
        {
            try
            {
                Assembly assembly =	Assembly.GetExecutingAssembly();

                // read	schema
                using (Stream s	= assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.pubca.xsd"))
                {
                    this.xmlSchema = XmlSchema.Read(s, null);
                }

                // read	table definitions
                using (Stream s	= assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Data.tables.xml"))
                {
                    XmlReader tableDefinitionsReader = new XmlTextReader(s);

            #if	DEBUG
                    Assembly wixAssembly = Assembly.GetAssembly(typeof(Compiler));
                    using (Stream schemaStream = wixAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.tables.xsd"))
                    {
                        XmlReader schemaReader = new XmlTextReader(schemaStream);
                        XmlSchemaCollection	schemas	= new XmlSchemaCollection();
                        schemas.Add("http://schemas.microsoft.com/wix/2003/04/tables", schemaReader);

                        XmlValidatingReader	validatingReader = new XmlValidatingReader(tableDefinitionsReader);
                        validatingReader.Schemas.Add(schemas);

                        tableDefinitionsReader = validatingReader;
                    }
            #endif

                    this.tableDefinitionCollection = TableDefinitionCollection.Load(tableDefinitionsReader);
                    tableDefinitionsReader.Close();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                System.Console.WriteLine(e.ToString());
                throw;
            }
        }
        private void NfeDadosMgs()
        {
            StreamReader ler = null; ;
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            XmlValidatingReader reader;
            string _ano = DateTime.Now.ToString("yy");
            _id = _cuf + _ano + _cnpj + _mod + _serie + _nnfini + _nnffim;         
            try
            {

                XDocument xDados = new XDocument(new XElement(pf + "inutNFe", new XAttribute("versao", _pversaoaplic),
                                                    new XElement(pf + "infInut", new XAttribute("Id", "ID" + _id),
                                                        new XElement(pf + "tpAmb", _tpamp),
                                                        new XElement(pf + "xServ", "INUTILIZAR"),
                                                        new XElement(pf + "cUF", _cuf),
                                                        new XElement(pf + "ano", DateTime.Now.ToString("yy")),
                                                        new XElement(pf + "CNPJ", _cnpj),
                                                        new XElement(pf + "mod", _mod),
                                                        new XElement(pf + "serie",  Convert.ToInt16(_serie)),
                                                        new XElement(pf + "nNFIni", Convert.ToInt32(_nnfini)),
                                                        new XElement(pf + "nNFFin", Convert.ToInt32(_nnffim)),
                                                        new XElement(pf + "xJust", _sjust))));

                xDados.Save(_spath + "\\" + _id + "_ped_inu.xml");
                 AssinaNFeInutXml assinaInuti = new AssinaNFeInutXml();
                assinaInuti.ConfigurarArquivo(_spath + "\\" + _id + "_ped_inu.xml", "infInut", cert);

                ler = File.OpenText(_spath + "\\" + _id + "_ped_inu.xml");

                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                reader = new XmlValidatingReader(ler.ReadToEnd().ToString(), XmlNodeType.Element, context);

                myschema.Add("http://www.portalfiscal.inf.br/nfe", _sschema + "\\inutNFe_v2.00.xsd");

                reader.ValidationType = ValidationType.Schema;

                reader.Schemas.Add(myschema);

                while (reader.Read())
                { }

            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
            finally
            {
                ler.Close();
            }
        }
Exemple #14
0
        /// <summary>
        /// Get the schemas required to validate a library.
        /// </summary>
        /// <returns>The schemas required to validate a library.</returns>
        internal static XmlSchemaCollection GetSchemas()
        {
            if (null == Localization.schemas)
            {
                Assembly assembly = Assembly.GetExecutingAssembly();

                using (Stream localizationSchemaStream = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.wixloc.xsd"))
                {
                    schemas = new XmlSchemaCollection();
                    XmlSchema localizationSchema = XmlSchema.Read(localizationSchemaStream, null);
                    schemas.Add(localizationSchema);
                }
            }

            return schemas;
        }
        /// <summary>
        /// Initializes the task and verifies parameters.
        /// </summary>
        /// <param name="TaskNode">Node that contains the XML fragment used to define this task instance.</param>
        protected override void InitializeTask(XmlNode TaskNode)
        {
            XmlElement taskXml = (XmlElement) TaskNode.Clone();

            // Expand all properties in the task and its child elements
            if (taskXml.ChildNodes != null) {
                ExpandPropertiesInNodes(taskXml.ChildNodes);
                if (taskXml.Attributes != null) {
                    foreach (XmlAttribute attr in taskXml.Attributes) {
                        attr.Value = Properties.ExpandProperties(attr.Value, Location);
                    }
                }
            }

            // Get the [SchemaValidator(type)] attribute
            SchemaValidatorAttribute[] taskValidators =
                (SchemaValidatorAttribute[])GetType().GetCustomAttributes(
                typeof(SchemaValidatorAttribute), true);

            if (taskValidators.Length > 0) {
                SchemaValidatorAttribute taskValidator = taskValidators[0];
                XmlSerializer taskSerializer = new XmlSerializer(taskValidator.ValidatorType);

                // get embedded schema resource stream
                Stream schemaStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    taskValidator.ValidatorType.Namespace);

                // ensure schema resource was embedded
                if (schemaStream == null) {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                        "Schema resource '{0}' could not be found.",
                        taskValidator.ValidatorType.Namespace), Location);
                }

                // load schema resource
                XmlTextReader tr = new XmlTextReader(
                    schemaStream, XmlNodeType.Element, null);

                // Add the schema to a schema collection
                XmlSchema schema = XmlSchema.Read(tr, null);
                XmlSchemaCollection schemas = new XmlSchemaCollection();
                schemas.Add(schema);

                string xmlNamespace = (taskValidator.XmlNamespace != null ? taskValidator.XmlNamespace : GetType().FullName);

                // Create a namespace manager with the schema's namespace
                NameTable nt = new NameTable();
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
                nsmgr.AddNamespace(string.Empty, xmlNamespace);

                // Create a textreader containing just the Task's Node
                XmlParserContext ctx = new XmlParserContext(
                    null, nsmgr, null, XmlSpace.None);
                taskXml.SetAttribute("xmlns", xmlNamespace);
                XmlTextReader textReader = new XmlTextReader(taskXml.OuterXml,
                    XmlNodeType.Element, ctx);

                // Copy the node from the TextReader and indent it (for error
                // reporting, since NAnt does not retain formatting during a load)
                StringWriter stringWriter = new StringWriter();
                XmlTextWriter textWriter = new XmlTextWriter(stringWriter);
                textWriter.Formatting = Formatting.Indented;

                textWriter.WriteNode(textReader, true);

                //textWriter.Close();
                XmlTextReader formattedTextReader = new XmlTextReader(
                    stringWriter.ToString(), XmlNodeType.Document, ctx);

                // Validate the Task's XML against its schema
                XmlValidatingReader validatingReader = new XmlValidatingReader(
                    formattedTextReader);
                validatingReader.ValidationType = ValidationType.Schema;
                validatingReader.Schemas.Add(schemas);
                validatingReader.ValidationEventHandler +=
                    new ValidationEventHandler(Task_OnSchemaValidate);

                while (validatingReader.Read()) {
                    // Read strictly for validation purposes
                }
                validatingReader.Close();

                if (!_validated) {
                    // Log any validation errors that have ocurred
                    for (int i = 0; i < _validationExceptions.Count; i++) {
                        BuildException ve = (BuildException) _validationExceptions[i];
                        if (i == _validationExceptions.Count - 1) {
                            // If this is the last validation error, throw it
                            throw ve;
                        }
                        Log(Level.Info, ve.Message);
                    }
                }

                NameTable taskNameTable = new NameTable();
                XmlNamespaceManager taskNSMgr = new XmlNamespaceManager(taskNameTable);
                taskNSMgr.AddNamespace(string.Empty, xmlNamespace);

                XmlParserContext context = new XmlParserContext(
                    null, taskNSMgr, null, XmlSpace.None);

                XmlTextReader taskSchemaReader = new XmlTextReader(
                    taskXml.OuterXml, XmlNodeType.Element, context);

                // Deserialize from the Task's XML to the schema wrapper object
                _schemaObject = taskSerializer.Deserialize(taskSchemaReader);
            }
        }
        private XmlNode MontaMsg()
        {
            try
            {
                XmlSchemaCollection myschema = new XmlSchemaCollection();
                XmlValidatingReader reader;
                XNamespace pf = "http://www.portalfiscal.inf.br/nfe";

                XDocument xdoc = new XDocument(new XElement(pf + "ConsCad", new XAttribute("versao", "2.00"),
                                                    new XElement(pf + "infCons",
                                                               new XElement(pf + "xServ", "CONS-CAD"),
                                                               new XElement(pf + "UF", sUF),
                                                               (sIE != "" ? new XElement(pf + "IE", (sIE != "" ? Util.TiraSimbolo(sIE, "") : "ISENTO")) : null),
                                                               ((sCNPJ != "" && sIE == "") ? new XElement(pf + "CNPJ", Util.TiraSimbolo(sCNPJ, "")) : null),
                                                               ((sCPF != "" && sIE == "" && sCNPJ == "") ? new XElement(pf + "CPF", Util.TiraSimbolo(sCPF, "")) : null))));




                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                reader = new XmlValidatingReader(xdoc.ToString(), XmlNodeType.Element, context);

                myschema.Add("http://www.portalfiscal.inf.br/nfe", Pastas.SCHEMA_NFE + "\\consCad_v2.00.xsd");

                reader.ValidationType = ValidationType.Schema;

                reader.Schemas.Add(myschema);

                while (reader.Read())
                { }
                string sDados = xdoc.ToString();
                XmlDocument Xmldoc = new XmlDocument();
                Xmldoc.LoadXml(sDados);
                XmlNode xNode = Xmldoc.DocumentElement;
                return xNode;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #17
0
        /// <summary>
        /// Main running method for the application.
        /// </summary>
        /// <param name="args">Commandline arguments to the application.</param>
        /// <returns>Returns the application error code.</returns>
        private int Run(string[] args)
        {
            try
            {
                XmlSchemaCollection objectSchema = new XmlSchemaCollection();
                FileInfo currentFile = null;

                ArrayList intermediates = new ArrayList();
                Librarian librarian = null;

                // parse the command line
                this.ParseCommandLine(args);

                // exit if there was an error parsing the command line (otherwise the logo appears after error messages)
                if (this.messageHandler.FoundError)
                {
                    return this.messageHandler.PostProcess();
                }

                if (0 == this.objectFiles.Count)
                {
                    this.showHelp = true;
                }
                else if (null == this.outputFile)
                {
                    if (1 < this.objectFiles.Count)
                    {
                        throw new ArgumentException("must specify output file when using more than one input file", "-out");
                    }

                    FileInfo fi = (FileInfo)this.objectFiles[0];
                    this.outputFile = new FileInfo(Path.ChangeExtension(fi.Name, ".wix"));   // we'll let the linker change the extension later
                }

                if (this.showLogo)
                {
                    Assembly litAssembly = Assembly.GetExecutingAssembly();

                    Console.WriteLine("Microsoft (R) Windows Installer Xml Library Tool version {0}", litAssembly.GetName().Version.ToString());
                    Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved.");
                    Console.WriteLine();
                }

                if (this.showHelp)
                {
                    Console.WriteLine(" usage:  lit.exe [-?] [-nologo] [-out outputFile] objectFile [objectFile ...]");
                    Console.WriteLine();
                    Console.WriteLine("   -nologo    skip printing lit logo information");
                    Console.WriteLine("   -out       specify output file (default: write to current directory)");
                    Console.WriteLine();
                    Console.WriteLine("   -ext       extension (class, assembly), should extend SchemaExtension or BinderExtension");
                    Console.WriteLine("   -ss        suppress schema validation of documents (performance boost)");
                    Console.WriteLine("   -sv        suppress intermediate file version mismatch checking");
                    Console.WriteLine("   -ust       use small table definitions (for backwards compatiblity)");
                    Console.WriteLine("   -wx        treat warnings as errors");
                    Console.WriteLine("   -w<N>      set the warning level (0: show all, 3: show none)");
                    Console.WriteLine("   -sw        suppress all warnings (same as -w3)");
                    Console.WriteLine("   -sw<N>     suppress warning with specific message ID");
                    Console.WriteLine("   -v         verbose output (same as -v2)");
                    Console.WriteLine("   -v<N>      sets the level of verbose output (0: most output, 3: none)");
                    Console.WriteLine("   -?         this help information");
                    Console.WriteLine();
                    Console.WriteLine("Common extensions:");
                    Console.WriteLine("   .wxs    - Windows installer Xml Source file");
                    Console.WriteLine("   .wxi    - Windows installer Xml Include file");
                    Console.WriteLine("   .wixobj - Windows installer Xml Object file (in XML format)");
                    Console.WriteLine("   .wixlib - Windows installer Xml Library file (in XML format)");
                    Console.WriteLine("   .wixout - Windows installer Xml Output file (in XML format)");
                    Console.WriteLine();
                    Console.WriteLine("   .msm - Windows installer Merge Module");
                    Console.WriteLine("   .msi - Windows installer Product Database");
                    Console.WriteLine("   .mst - Windows installer Transform");
                    Console.WriteLine("   .pcp - Windows installer Patch Creation Package");
                    Console.WriteLine();
                    Console.WriteLine("For more information see: http://wix.sourceforge.net");

                    return this.messageHandler.PostProcess();
                }

                // create the librarian
                librarian = new Librarian(this.useSmallTables);
                librarian.Message += new MessageEventHandler(this.messageHandler.Display);

                // load any extensions
                foreach (string extension in this.extensionList)
                {
                    Type extensionType = Type.GetType(extension);
                    if (null == extensionType)
                    {
                        throw new WixInvalidExtensionException(extension);
                    }

                    if (extensionType.IsSubclassOf(typeof(SchemaExtension)))
                    {
                        librarian.AddExtension((SchemaExtension)Activator.CreateInstance(extensionType));
                    }
                }

                // load the object schema
                if (!this.suppressSchema)
                {
                    Assembly wixAssembly = Assembly.Load("wix");

                    using (Stream objectsSchemaStream = wixAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.objects.xsd"))
                    {
                        XmlReader reader = new XmlTextReader(objectsSchemaStream);
                        objectSchema.Add("http://schemas.microsoft.com/wix/2003/04/objects", reader);
                    }
                }

                // add the Intermediates to the librarian
                foreach (FileInfo objectFile in this.objectFiles)
                {
                    currentFile = objectFile;

                    // load the object file into an intermediate object and add it to the list to be linked
                    using (Stream fileStream = new FileStream(currentFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        XmlReader fileReader = new XmlTextReader(fileStream);

                        try
                        {
                            XmlReader intermediateReader = fileReader;
                            if (!this.suppressSchema)
                            {
                                intermediateReader = new XmlValidatingReader(fileReader);
                                ((XmlValidatingReader)intermediateReader).Schemas.Add(objectSchema);
                            }

                            Intermediate intermediate = Intermediate.Load(intermediateReader, currentFile.FullName, librarian.TableDefinitions, this.suppressVersionCheck);
                            intermediates.Add(intermediate);
                            continue; // next file
                        }
                        catch (WixNotIntermediateException)
                        {
                            // try another format
                        }

                        Library objLibrary = Library.Load(currentFile.FullName, librarian.TableDefinitions, this.suppressVersionCheck);
                        intermediates.AddRange(objLibrary.Intermediates);
                    }

                    currentFile = null;
                }

                // and now for the fun part
                Library library = librarian.Combine((Intermediate[])intermediates.ToArray(typeof(Intermediate)));

                // save the library output if an error did not occur
                if (null != library)
                {
                    library.Save(this.outputFile.FullName);
                }
            }
            catch (WixException we)
            {
                // TODO: once all WixExceptions are converted to errors, this clause
                // should be a no-op that just catches WixFatalErrorException's
                this.messageHandler.Display("lit.exe", "LIT", we);
                return 1;
            }
            catch (Exception e)
            {
                this.OnMessage(WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace));
                if (e is NullReferenceException || e is SEHException)
                {
                    throw;
                }
            }

            return this.messageHandler.PostProcess();
        }
Exemple #18
0
        /// <summary>
        /// Main running method for the application.
        /// </summary>
        /// <param name="args">Commandline arguments to the application.</param>
        /// <returns>Returns the application error code.</returns>
        private int Run(string[] args)
        {
            int beginTickCount = Environment.TickCount;

            try
            {
                this.tempFileCollection = new TempFileCollection();

                Environment.SetEnvironmentVariable("WixUnitTempDir", this.tempFileCollection.BasePath, EnvironmentVariableTarget.Process);
                this.ParseCommandline(args);

                // get the assemblies
                Assembly wixUnitAssembly = this.GetType().Assembly;
                FileVersionInfo fv = FileVersionInfo.GetVersionInfo(wixUnitAssembly.Location);

                if (this.showHelp)
                {
                    Console.WriteLine("WixUnit version {0}", fv.FileVersion);
                    Console.WriteLine("Copyright (C) .NET Foundation and contributors. All rights reserved.");
                    Console.WriteLine();
                    Console.WriteLine(" usage: WixUnit [-?] tests.xml");
                    Console.WriteLine();
                    Console.WriteLine("   -env:<var>=<value>  Sets an environment variable to the value for the current process");
                    Console.WriteLine("   -notidy             Do not delete temporary files (for checking results)");
                    Console.WriteLine("   -rf                 Re-run the failed test from the last run");
                    Console.WriteLine("   -st                 Run the tests on a single thread");
                    Console.WriteLine("   -test:<Test_name>   Run only the specified test (may use wildcards)");
                    Console.WriteLine("   -update             Prompt user to auto-update a test if expected and actual output files do not match");
                    Console.WriteLine("   -v                  Verbose output");
                    Console.WriteLine("   -val                Run MSI validation for light unit tests");

                    return 0;
                }

                // set the environment variables for the process only
                foreach (KeyValuePair<string, string> environmentVariable in this.environmentVariables)
                {
                    Environment.SetEnvironmentVariable(environmentVariable.Key, environmentVariable.Value, EnvironmentVariableTarget.Process);
                }

                // load the schema
                XmlReader schemaReader = null;
                XmlSchemaCollection schemas = null;
                try
                {
                    schemas = new XmlSchemaCollection();

                    schemaReader = new XmlTextReader(wixUnitAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Unit.unitTests.xsd"));
                    XmlSchema schema = XmlSchema.Read(schemaReader, null);
                    schemas.Add(schema);
                }
                finally
                {
                    if (schemaReader != null)
                    {
                        schemaReader.Close();
                    }
                }

                // load the unit tests
                XmlTextReader reader = null;
                XmlDocument doc = new XmlDocument();
                try
                {
                    reader = new XmlTextReader(this.unitTestsFile);
                    XmlValidatingReader validatingReader = new XmlValidatingReader(reader);
                    validatingReader.Schemas.Add(schemas);

                    // load the xml into a DOM
                    doc.Load(validatingReader);
                }
                catch (XmlException e)
                {
                    SourceLineNumber sourceLineNumber = new SourceLineNumber(this.unitTestsFile, e.LineNumber);
                    SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber });

                    throw new WixException(WixErrors.InvalidXml(sourceLineNumbers, "unitTests", e.Message));
                }
                catch (XmlSchemaException e)
                {
                    SourceLineNumber sourceLineNumber = new SourceLineNumber(this.unitTestsFile, e.LineNumber);
                    SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber });

                    throw new WixException(WixErrors.SchemaValidationFailed(sourceLineNumbers, e.Message, e.LineNumber, e.LinePosition));
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }

                // check the document element
                if ("UnitTests" != doc.DocumentElement.LocalName || XmlNamespace != doc.DocumentElement.NamespaceURI)
                {
                    throw new InvalidOperationException("Unrecognized document element.");
                }

                // create a regular expression of the selected tests
                Regex selectedUnitTests = new Regex(String.Concat("^", String.Join("$|^", (string[])this.unitTests.ToArray(typeof(string))), "$"), RegexOptions.IgnoreCase | RegexOptions.Singleline);

                // find the unit tests
                foreach (XmlNode node in doc.DocumentElement)
                {
                    if (XmlNodeType.Element == node.NodeType)
                    {
                        switch (node.LocalName)
                        {
                            case "UnitTest":
                                XmlElement unitTestElement = (XmlElement)node;
                                string unitTestName = unitTestElement.GetAttribute("Name");

                                if (selectedUnitTests.IsMatch(unitTestName))
                                {
                                    unitTestElement.SetAttribute("TempDirectory", this.tempFileCollection.BasePath);
                                    this.unitTestElements.Enqueue(node);
                                }
                                break;
                        }
                    }
                }

                if (this.unitTests.Count > 0)
                {
                    this.totalUnitTests = this.unitTestElements.Count;
                    int numThreads;

                    if (this.updateTests || this.singleThreaded)
                    {
                        // If the tests are running with the -update switch, they must run on one thread
                        // so that all execution is paused when the user is prompted to update a test.
                        numThreads = 1;
                    }
                    else
                    {
                        // create a thread for each processor
                        numThreads = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS"), CultureInfo.InvariantCulture);
                    }

                    Thread[] threads = new Thread[numThreads];

                    for (int i = 0; i < threads.Length; i++)
                    {
                        threads[i] = new Thread(new ThreadStart(this.RunUnitTests));
                        threads[i].Start();
                    }

                    // wait for all threads to finish
                    foreach (Thread thread in threads)
                    {
                        thread.Join();
                    }

                    // report the results
                    Console.WriteLine();
                    int elapsedTime = (Environment.TickCount - beginTickCount) / 1000;
                    if (0 < this.failedUnitTests.Count)
                    {
                        Console.WriteLine("Summary of failed tests:");
                        Console.WriteLine();

                        // Put the failed tests into an ArrayList, which will get serialized
                        ArrayList serializedFailedTests = new ArrayList();
                        foreach (string failedTest in this.failedUnitTests.Keys)
                        {
                            serializedFailedTests.Add(failedTest);
                            Console.WriteLine("{0}. {1}", this.failedUnitTests[failedTest], failedTest);
                        }

                        Console.WriteLine();
                        Console.WriteLine("Re-run the failed tests with the -rf option");
                        Console.WriteLine();
                        Console.WriteLine("Failed {0} out of {1} unit test{2} ({3} seconds).", this.failedUnitTests.Count, this.totalUnitTests, (1 != this.completedUnitTests ? "s" : ""), elapsedTime);

                        using (XmlWriter writer = XmlWriter.Create(this.failedTestsFile))
                        {
                            XmlSerializer serializer = new XmlSerializer(serializedFailedTests.GetType());
                            serializer.Serialize(writer, serializedFailedTests);
                            writer.Close();
                        }
                    }
                    else
                    {
                        Console.WriteLine("Successful unit tests: {0} ({1} seconds).", this.completedUnitTests, elapsedTime);
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("No unit tests were selected.");
                }
            }
            catch (WixException we)
            {
                this.messageHandler.Display(this, we.Error);
            }
            catch (Exception e)
            {
                this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace));
                if (e is NullReferenceException)
                {
                    throw;
                }
            }
            finally
            {
                if (this.noTidy)
                {
                    Console.WriteLine();
                    Console.WriteLine("The notidy option was specified, temporary files can be found at:");
                    Console.WriteLine(this.tempFileCollection.BasePath);
                }
                else
                {
                    // try three times and give up with a warning if the temp files aren't gone by then
                    const int RetryLimit = 3;

                    for (int i = 0; i < RetryLimit; i++)
                    {
                        try
                        {
                            Directory.Delete(this.tempFileCollection.BasePath, true);   // toast the whole temp directory
                            break; // no exception means we got success the first time
                        }
                        catch (UnauthorizedAccessException)
                        {
                            if (0 == i) // should only need to unmark readonly once - there's no point in doing it again and again
                            {
                                RecursiveFileAttributes(this.tempFileCollection.BasePath, FileAttributes.ReadOnly, false); // toasting will fail if any files are read-only. Try changing them to not be.
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (DirectoryNotFoundException)
                        {
                            // if the path doesn't exist, then there is nothing for us to worry about
                            break;
                        }
                        catch (IOException) // directory in use
                        {
                            if (i == (RetryLimit - 1)) // last try failed still, give up
                            {
                                break;
                            }
                            Thread.Sleep(300);  // sleep a bit before trying again
                        }
                    }
                }
            }

            return this.failedUnitTests.Count;
        }
        /// <summary>
        /// Run the application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        /// <returns>The error code for the application.</returns>
        private int Run(string[] args)
        {
            try
            {
                this.ParseCommandline(args);

                // get the assemblies
                Assembly docCompilerAssembly = Assembly.GetExecutingAssembly();

                if (this.showHelp)
                {
                    Console.WriteLine("Microsoft (R) Documentation Compiler version {0}", docCompilerAssembly.GetName().Version.ToString());
                    Console.WriteLine("Copyright (C) Microsoft Corporation. All rights reserved.");
                    Console.WriteLine();
                    Console.WriteLine(" usage: DocCompiler [-?] [-c:hhc.exe | -w] [-v version] tableOfContents.xml output");
                    Console.WriteLine();
                    Console.WriteLine("    c - path to HTML Help Compiler to create output CHM");
                    Console.WriteLine("    w - creates Web HTML Manual to output directory");
                    Console.WriteLine("   -v       set version information for elements");

                    return 0;
                }

                // ensure the directory containing the html files exists
                Directory.CreateDirectory(Path.Combine(this.outputDir, "html"));

                // load the schema
                XmlReader schemaReader = null;
                XmlSchemaCollection schemas = null;
                try
                {
                    schemaReader = new XmlTextReader(docCompilerAssembly.GetManifestResourceStream("Microsoft.Tools.DocCompiler.Xsd.docCompiler.xsd"));
                    schemas = new XmlSchemaCollection();
                    schemas.Add(DocCompilerNamespace, schemaReader);
                }
                finally
                {
                    schemaReader.Close();
                }

                // load the table of contents
                XmlTextReader reader = null;
                try
                {
                    reader = new XmlTextReader(this.tocFile);
                    XmlValidatingReader validatingReader = new XmlValidatingReader(reader);
                    validatingReader.Schemas.Add(schemas);

                    // load the xml into a DOM
                    XmlDocument doc = new XmlDocument();
                    doc.Load(validatingReader);

                    // create a namespace manager
                    this.namespaceManager = new XmlNamespaceManager(doc.NameTable);
                    this.namespaceManager.AddNamespace("doc", DocCompilerNamespace);
                    this.namespaceManager.PushScope();

                    this.ProcessCopyFiles(doc);
                    this.ProcessTopics(doc);
                    this.ProcessSchemas(doc);
                    if (this.chm)
                    {
                        this.CompileChm(doc);
                    }
                    if (this.web)
                    {
                        this.BuildWeb(doc);
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("DocCompiler.exe : fatal error DCMP0001: {0}", e.Message);
                Console.WriteLine();
                Console.WriteLine("Stack Trace:");
                Console.WriteLine(e.StackTrace);

                if (e is NullReferenceException)
                {
                    throw;
                }

                return 1;
            }

            return 0;
        }
Exemple #20
0
        private static void Compile(XmlSchemas userSchemas) {
            XmlSchema parent = new XmlSchema();
            foreach (XmlSchema s in userSchemas) {
                if (s.TargetNamespace != null && s.TargetNamespace.Length == 0) {
                    s.TargetNamespace = null;
                }

                if (s.TargetNamespace == parent.TargetNamespace) {
                    XmlSchemaInclude include = new XmlSchemaInclude();
                    include.Schema = s;
                    parent.Includes.Add(include);
                }
                else {
                    XmlSchemaImport import = new XmlSchemaImport();
                    import.Namespace = s.TargetNamespace;
                    import.Schema = s;
                    parent.Includes.Add(import);
                }
            }
            /*  to be able to compile multiple schemas using DataSets and encoded Arrays we need three additional schemas : 
                     XmlSchema:     <xs:schema targetNamespace="http://www.w3.org/2001/XMLSchema"..
                     SoapEncoding:  <xs:schema targetNamespace="http://schemas.xmlsoap.org/soap/encoding/"..
                     Wsdl:          <xs:schema targetNamespace="http://schemas.xmlsoap.org/wsdl/"..

                we do not need them for our validation, just to fool XmlSchema.Compile, so we are going to create the bare minimum schemas
            */

            AddFakeSchemas(parent, userSchemas);

            try {
                XmlSchemaCollection xsc = new XmlSchemaCollection();
                xsc.ValidationEventHandler += new ValidationEventHandler (ValidationCallbackWithErrorCode);
                xsc.Add(parent);
                
                if (xsc.Count == 0) {
                    Console.WriteLine(Environment.NewLine + Res.GetString(Res.SchemaValidationWarning) + Environment.NewLine);
                }
            }
            catch (Exception e) {
                Console.WriteLine(Environment.NewLine + Res.GetString(Res.SchemaValidationWarning) + Environment.NewLine + e.Message + Environment.NewLine);
            }       
        }
Exemple #21
0
		/// <summary>
		/// Validates XML against a schema.
		/// </summary>
		/// <param name="xml">XML to validate.</param>
		/// <param name="shortCircuit">
		///		Defines validation behaviour should invalid XML be encountered.  Setting to a type other than None 
		///		forces the validation process to immedietely quit according to the type of problem encountered.
		///	</param>		
		/// <returns>Result as ValidatorResultType.  Extra information can be extracted from Warnings and Errors properties.</returns>		
		/// <overloaded/>
		public ValidatorResultType Validate(string xml, ValidatorShortCircuitType shortCircuit)
		{			
			// NB overloaded

			//validate arguments
			if (xml == null)
				throw new ArgumentNullException("xml");
			else if (xml.Length == 0)
				throw new ArgumentOutOfRangeException("xml");

			//initialise variables			
			m_warnings = null;
			m_errors = null;
			m_result = ValidatorResultType.Valid;

			try
			{
				//load the xml into validating reader
				XmlValidatingReader xmlValidatingReader = null;

				//configure validating reader and schema(s) according to schema type
				if (m_validationType == ValidationType.Schema)
				{				
					//if the XSD schema collection is not yet prepared, do so now
					if (!m_isSchemaCollectionPrepared)
					{
						//prepare the additional resources resolver with all of the extra XSD's
						PrepareResourceResolver();

						//load main XSD into schemas collection
						m_schemas = new XmlSchemaCollection();								
						m_schemas.Add(null, GetXmlTextReader(m_schema), m_additionalResourceResolver);
					
						//flag that we have already prepared the schemas to improve
						//performance on subsequent validation requests
						m_isSchemaCollectionPrepared = true;					
					}

					//create the validating reader and assign schemas
					xmlValidatingReader = new XmlValidatingReader(GetXmlTextReader(xml)); 								
					xmlValidatingReader.ValidationType = ValidationType.Schema;				
					xmlValidatingReader.Schemas.Add(m_schemas);
				}
				else
				{
					//set up validating reader for DTD
					XmlParserContext context = new XmlParserContext(null, null, m_dtdDocTypeName, null, null, m_schema, "", "", XmlSpace.None);					
					xmlValidatingReader = new XmlValidatingReader(xml, XmlNodeType.Element, context);
					xmlValidatingReader.ValidationType = ValidationType.DTD;         										
					xmlValidatingReader.EntityHandling = EntityHandling.ExpandCharEntities;
				}

				//assign event handler which will receive validation errors
				xmlValidatingReader.ValidationEventHandler += new ValidationEventHandler (ValidationHandler);

				//read the xml to perform validation				
				try
				{
					while (xmlValidatingReader.Read()) 
					{
						//check if we need to quit
						if (shortCircuit == ValidatorShortCircuitType.OnWarning 
							&& (m_result == ValidatorResultType.ValidWithWarnings || m_result == ValidatorResultType.InValid))
							break;
						else if (shortCircuit == ValidatorShortCircuitType.OnError && m_result == ValidatorResultType.InValid)
							break;
					}
				}
				catch (Exception exc)
				{
					//xml form error
					AddToArrayList(ref m_errors, exc.Message);
					m_result = ValidatorResultType.InValid;
				}
				
				return m_result;		
			}
			catch (Exception exc)
			{
				throw exc;
			}
		}
Exemple #22
0
        public void GerarAqruivoXml(tcLoteRps objLoteRpd)
        {
            try
            {
                List<string> ListaNfes = new List<string>();
                Globais glob = new Globais();
                XDocument xdoc = new XDocument();
                XNamespace tns = "http://www.ginfes.com.br/servico_enviar_lote_rps_envio";
                XNamespace tipos = "http://www.ginfes.com.br/tipos_v03.xsd";
                XNamespace ds = "http://www.w3.org/2000/09/xmldsig#";
                XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
                XNamespace n1 = "http://www.altova.com/samplexml/other-namespace";
                XNamespace pf = "http://www.ginfes.com.br/servico_enviar_lote_rps_envio_v03.xsd";


                XContainer conEnviarLoteRpsEnvio = (new XElement(pf + "EnviarLoteRpsEnvio", new XAttribute("xmlns", "http://www.ginfes.com.br/servico_enviar_lote_rps_envio_v03.xsd")));

                XContainer conLoteRps = (new XElement(pf + "LoteRps", new XAttribute("Id", objLoteRpd.NumeroLote),
                                                                new XAttribute(XNamespace.Xmlns + "tipos", "http://www.ginfes.com.br/tipos_v03.xsd"),
                                                                                     new XElement(tipos + "NumeroLote", objLoteRpd.NumeroLote.ToString()),
                                                                                     new XElement(tipos + "Cnpj", objLoteRpd.Cnpj.ToString()),
                                                                                     new XElement(tipos + "InscricaoMunicipal", objLoteRpd.InscricaoMunicipal.ToString()),
                                                                                     new XElement(tipos + "QuantidadeRps", objLoteRpd.QuantidadeRps.ToString())));

                XContainer conListaRps = (new XElement(tipos + "ListaRps"));
                XContainer conRps = (new XElement(tipos + "Rps"));
                XContainer conInfRps = null;
                XContainer conSubstituto = null;
                XContainer conServico = null;
                XContainer conPrestador = null;
                XContainer conTomador = null;
                XContainer conIntermediarioServico = null;
                XContainer conConstrucaoCivil = null;
                AssinaNFeXml Assinatura = new AssinaNFeXml();

                foreach (TcRps rps in objLoteRpd.Rps)
                {
                    #region IdentificacaoRps conRps
                    try
                    {
                        conInfRps = (new XElement(tipos + "InfRps", new XElement(tipos + "IdentificacaoRps",
                                                                                     new XElement(tipos + "Numero", rps.InfRps.IdentificacaoRps.Numero),
                                                                                     new XElement(tipos + "Serie", rps.InfRps.IdentificacaoRps.Serie),
                                                                                     new XElement(tipos + "Tipo", rps.InfRps.IdentificacaoRps.Tipo)),
                                                                          new XElement(tipos + "DataEmissao", HLP.Util.Util.GetDateServidor().Date.ToString("yyyy-MM-ddTHH:mm:ss")),
                                                                          new XElement(tipos + "NaturezaOperacao", rps.InfRps.NaturezaOperacao),
                                                                         ((rps.InfRps.RegimeEspecialTributacao != 0) ? new XElement(tipos + "RegimeEspecialTributacao", rps.InfRps.RegimeEspecialTributacao) : null),
                                                                          new XElement(tipos + "OptanteSimplesNacional", rps.InfRps.OptanteSimplesNacional),
                                                                          new XElement(tipos + "IncentivadorCultural", rps.InfRps.IncentivadorCultural),
                                                                          new XElement(tipos + "Status", rps.InfRps.Status)));

                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota : " + rps.InfRps.IdentificacaoRps.Numero + "Erro na geração do XML, Regiao:('IdentificacaoRps')- "
                            + Environment.NewLine + "XML_Detalhes: "
                            + Environment.NewLine + x.Message);
                    }
                    #endregion

                    #region RpsSubstituido
                    if (rps.InfRps.RpsSubstituido != null)
                    {
                        try
                        {
                            conSubstituto = (new XElement(tipos + "RpsSubstituido",
                                                         new XElement(tipos + "Numero", rps.InfRps.RpsSubstituido.Numero),
                                                         new XElement(tipos + "Serie", rps.InfRps.RpsSubstituido.Serie),
                                                         new XElement(tipos + "Tipo", rps.InfRps.RpsSubstituido.Tipo)));
                        }
                        catch (Exception x)
                        {
                            throw new Exception("Nota : " + rps.InfRps.IdentificacaoRps.Numero + "Erro na geração do XML, Regiao:('RpsSubstituido')- "
                                + Environment.NewLine + "XML_Detalhes: "
                                + Environment.NewLine + x.Message);
                        }
                    }

                    #endregion

                    #region Servico
                    try
                    {
                        conServico = (new XElement(tipos + "Servico", new XElement(tipos + "Valores",
                                                    new XElement(tipos + "ValorServicos", rps.InfRps.Servico.Valores.ValorServicos.ToString("#0.00").Replace(",", ".")),
                                                    ((rps.InfRps.Servico.Valores.ValorDeducoes > 0) ? new XElement(tipos + "ValorDeducoes", rps.InfRps.Servico.Valores.ValorDeducoes.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.ValorPis > 0) ? new XElement(tipos + "ValorPis", rps.InfRps.Servico.Valores.ValorPis.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.ValorCofins > 0) ? new XElement(tipos + "ValorCofins", rps.InfRps.Servico.Valores.ValorCofins.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.ValorInss > 0) ? new XElement(tipos + "ValorInss", rps.InfRps.Servico.Valores.ValorInss.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.ValorIr > 0) ? new XElement(tipos + "ValorIr", rps.InfRps.Servico.Valores.ValorIr.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.ValorCsll > 0) ? new XElement(tipos + "ValorCsll", rps.InfRps.Servico.Valores.ValorCsll.ToString("#0.00").Replace(",", ".")) : null),
                                                                                                      new XElement(tipos + "IssRetido", rps.InfRps.Servico.Valores.IssRetido),
                                                    ((rps.InfRps.Servico.Valores.ValorIss > 0) ? new XElement(tipos + "ValorIss", rps.InfRps.Servico.Valores.ValorIss.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.ValorIssRetido > 0) ? new XElement(tipos + "ValorIssRetido", rps.InfRps.Servico.Valores.ValorIssRetido.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.OutrasRetencoes > 0) ? new XElement(tipos + "OutrasRetencoes", rps.InfRps.Servico.Valores.OutrasRetencoes.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.BaseCalculo > 0) ? new XElement(tipos + "BaseCalculo", rps.InfRps.Servico.Valores.BaseCalculo.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.Aliquota > 0) ? new XElement(tipos + "Aliquota", (rps.InfRps.Servico.Valores.Aliquota / 100).ToString("#0.0000").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.ValorLiquidoNfse > 0) ? new XElement(tipos + "ValorLiquidoNfse", rps.InfRps.Servico.Valores.ValorLiquidoNfse.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.DescontoCondicionado > 0) ? new XElement(tipos + "DescontoCondicionado", rps.InfRps.Servico.Valores.DescontoCondicionado.ToString("#0.00").Replace(",", ".")) : null),
                                                    ((rps.InfRps.Servico.Valores.DescontoIncondicionado > 0) ? new XElement(tipos + "DescontoIncondicionado", rps.InfRps.Servico.Valores.DescontoIncondicionado.ToString("#0.00").Replace(",", ".")) : null)),
                                                                                         new XElement(tipos + "ItemListaServico", rps.InfRps.Servico.ItemListaServico),
                                       ((rps.InfRps.Servico.CodigoCnae != "") ? new XElement(tipos + "CodigoCnae", rps.InfRps.Servico.CodigoCnae) : null),
                                       (((rps.InfRps.Servico.CodigoTributacaoMunicipio != "") && (rps.InfRps.Servico.CodigoTributacaoMunicipio != "0")) ? new XElement(tipos + "CodigoTributacaoMunicipio", rps.InfRps.Servico.CodigoTributacaoMunicipio) : null),
                                                                                         new XElement(tipos + "Discriminacao", rps.InfRps.Servico.Discriminacao),
                                       new XElement(tipos + "CodigoMunicipio", rps.InfRps.Servico.CodigoMunicipio)));
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota : " + rps.InfRps.IdentificacaoRps.Numero + "Erro na geração do XML, Regiao:('Servico')- "
                            + Environment.NewLine + "XML_Detalhes: "
                            + Environment.NewLine + x.Message);
                    }
                    #endregion

                    #region Prestador
                    try
                    {
                        conPrestador = (new XElement(tipos + "Prestador", new XElement(tipos + "Cnpj", rps.InfRps.Prestador.Cnpj),
                                                                      ((rps.InfRps.Prestador.InscricaoMunicipal != "") ? new XElement(tipos + "InscricaoMunicipal", rps.InfRps.Prestador.InscricaoMunicipal) : null)));

                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota : " + rps.InfRps.IdentificacaoRps.Numero + "Erro na geração do XML, Regiao:('Prestador')- "
                            + Environment.NewLine + "XML_Detalhes: "
                            + Environment.NewLine + x.Message);
                    }
                    #endregion

                    #region Tomador
                    try
                    {
                        conTomador = (new XElement(tipos + "Tomador", ((rps.InfRps.Tomador.IdentificacaoTomador != null) ? new XElement(tipos + "IdentificacaoTomador", new XElement(tipos + "CpfCnpj",
                                                                                                               new XElement(tipos + (rps.InfRps.Tomador.IdentificacaoTomador.CpfCnpj.Cnpj != "" ? "Cnpj" : "Cpf"), (rps.InfRps.Tomador.IdentificacaoTomador.CpfCnpj.Cnpj != "" ? rps.InfRps.Tomador.IdentificacaoTomador.CpfCnpj.Cnpj : rps.InfRps.Tomador.IdentificacaoTomador.CpfCnpj.Cpf))),
                                                                    (rps.InfRps.Tomador.IdentificacaoTomador.InscricaoMunicipal != "" ? (new XElement(tipos + "InscricaoMunicipal", rps.InfRps.Tomador.IdentificacaoTomador.InscricaoMunicipal)) : null)) : null),
                                                                    new XElement(tipos + "RazaoSocial", rps.InfRps.Tomador.RazaoSocial),
                                                                    new XElement(tipos + "Endereco",
                                                                                       new XElement(tipos + "Endereco", rps.InfRps.Tomador.Endereco.Endereco),
                                                                                       new XElement(tipos + "Numero", rps.InfRps.Tomador.Endereco.Numero),
                                                                                      (rps.InfRps.Tomador.Endereco.Complemento != "" ? new XElement(tipos + "Complemento", rps.InfRps.Tomador.Endereco.Complemento) : null),
                                                                                       new XElement(tipos + "Bairro", rps.InfRps.Tomador.Endereco.Bairro),
                                                                                       new XElement(tipos + "CodigoMunicipio", rps.InfRps.Tomador.Endereco.CodigoMunicipio),
                                                                                       new XElement(tipos + "Uf", rps.InfRps.Tomador.Endereco.Uf),
                                                                                       new XElement(tipos + "Cep", rps.InfRps.Tomador.Endereco.Cep))));


                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota : " + rps.InfRps.IdentificacaoRps.Numero + "Erro na geração do XML, Regiao:('Tomador')- "
                            + Environment.NewLine + "XML_Detalhes: "
                            + Environment.NewLine + x.Message);
                    }

                    #endregion

                    #region IntermediarioServico
                    try
                    {
                        if (rps.InfRps.IntermediarioServico != null)
                        {
                            conIntermediarioServico = (new XElement(tipos + "IntermediarioServico", new XElement(tipos + "RazaoSocial", rps.InfRps.IntermediarioServico.RazaoSocial),
                                                                                               new XElement(tipos + "CpfCnpj", (new XElement(tipos + (rps.InfRps.IntermediarioServico.CpfCnpj.Cnpj != null ? "Cnpj" : "Cpf"), (rps.InfRps.IntermediarioServico.CpfCnpj.Cnpj != null ? rps.InfRps.IntermediarioServico.CpfCnpj.Cnpj : rps.InfRps.IntermediarioServico.CpfCnpj.Cpf)))),
                                                                                               new XElement(tipos + "InscricaoMunicipal", rps.InfRps.IntermediarioServico.InscricaoMunicipal)));
                        }
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota : " + rps.InfRps.IdentificacaoRps.Numero + "Erro na geração do XML, Regiao:('IntermediarioServico')- "
                            + Environment.NewLine + "XML_Detalhes: "
                            + Environment.NewLine + x.Message);
                    }
                    #endregion

                    #region ConstrucaoCivil

                    try
                    {
                        if (rps.InfRps.ConstrucaoCivil != null)
                        {
                            if ((rps.InfRps.ConstrucaoCivil.CodigoObra != "") && (rps.InfRps.ConstrucaoCivil.Art != ""))
                            {
                                conConstrucaoCivil = (new XElement(tipos + "ConstrucaoCivil", new XElement(tipos + "CodigoObra", rps.InfRps.ConstrucaoCivil.CodigoObra),
                                                                                          new XElement(tipos + "Art", rps.InfRps.ConstrucaoCivil.Art)));
                            }
                        }

                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota : " + rps.InfRps.IdentificacaoRps.Numero + "Erro na geração do XML, Regiao:('ConstrucaoCivil')- "
                            + Environment.NewLine + "XML_Detalhes: "
                            + Environment.NewLine + x.Message);
                    }
                    #endregion

                    try
                    {
                        if (conSubstituto != null)
                        {
                            conInfRps.Add(conSubstituto);
                        }
                        conInfRps.Add(conServico);
                        conInfRps.Add(conPrestador);
                        conInfRps.Add(conTomador);
                        if (conIntermediarioServico != null) { conInfRps.Add(conIntermediarioServico); }
                        if (conConstrucaoCivil != null) { conInfRps.Add(conConstrucaoCivil); }
                        conRps.Add(conInfRps);

                        // string nfe = Assinatura.ConfigurarArquivo(conRps.ToString(), "InfRps", cert);
                        // XmlDocument xml = new XmlDocument();
                        // xml.LoadXml(nfe);
                        //  conListaRps.Add(xml);
                        conListaRps.Add(conRps);


                        //Salva o Rps;
                        XDocument xdocsalvanfesemlot = new XDocument(conRps);
                        string sPasta = rps.InfRps.DataEmissao.ToString("MM/yy").Replace("/", "");
                        string sNomeArquivo = rps.InfRps.DataEmissao.ToString("MM/yy").Replace("/", "") + rps.InfRps.IdentificacaoRps.Serie + rps.InfRps.IdentificacaoRps.Numero;
                        DirectoryInfo dPastaData = new DirectoryInfo(belStaticPastas.ENVIO + "\\Servicos\\" + sPasta);
                        if (!dPastaData.Exists) { dPastaData.Create(); }
                        xdocsalvanfesemlot.Save(belStaticPastas.ENVIO + "\\Servicos\\" + sPasta + "\\" + sNomeArquivo + "-nfes.xml");

                        conRps = (new XElement(tipos + "Rps"));
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + "sNota" + "Erro ao assinar a nfe de sequencia " + "sNota" + x.Message);
                    }
                }

                conLoteRps.Add(conListaRps);
                conEnviarLoteRpsEnvio.Add(conLoteRps);
                //Assina Arquivo
                string nfes = Assinatura.ConfigurarArquivo(conEnviarLoteRpsEnvio.ToString(), "LoteRps", cert);
                sXmlLote = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + nfes;
                //Grava
                string sPathLote = belStaticPastas.ENVIO + "\\Servicos\\" + "Lote_" + objLoteRpd.NumeroLote + ".xml";
                StreamWriter sw = new StreamWriter(sPathLote);
                sw.Write(sXmlLote);
                sw.Close();

                #region Valida_Xml|

                Globais getschema = new Globais();
                XmlSchemaCollection myschema = new XmlSchemaCollection();
                XmlValidatingReader reader;
                try
                {
                    XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
                    reader = new XmlValidatingReader(sXmlLote, XmlNodeType.Element, context);
                    myschema.Add("http://www.ginfes.com.br/servico_enviar_lote_rps_envio_v03.xsd", belStaticPastas.SCHEMA_NFSE + "\\servico_enviar_lote_rps_envio_v03.xsd");
                    reader.ValidationType = ValidationType.Schema;
                    reader.Schemas.Add(myschema);
                    while (reader.Read())
                    {

                    }
                }
                catch (XmlException x)
                {
                    File.Delete(sPathLote);
                    throw new Exception(x.Message);
                }
                catch (XmlSchemaException x)
                {
                    File.Delete(sPathLote);
                    throw new Exception(x.Message);
                }
                #endregion

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private static bool ValidatePacketAgainstSchema(string xmlpacket)
        {
            XmlValidatingReader reader = null;
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            try
            {
                //Create the XmlParserContext.
                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                //Implement the reader.
                reader = new XmlValidatingReader(xmlpacket, XmlNodeType.Element, context);
                ////////Add the schema.
                //// myschema.Add(null, @"C:\inetpub\wwwroot\MsgBlasterWebServiceSetup\XmlSchema.xsd");

                myschema.Add(null, ConfigurationManager.AppSettings["SchemaFile"].ToString()); //AppDomain.CurrentDomain.BaseDirectory + "\\XmlSchema.xsd"
                //myschema.Add(null, ConfigurationManager.AppSettings["SettingFiles"] + "XmlSchema.xsd");

                //Set the schema type and add the schema to the reader.
                reader.ValidationType = ValidationType.Schema;
                reader.Schemas.Add(myschema);

                while (reader.Read())
                {
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
Exemple #24
0
            /// <summary>
            /// Main method for the MsgGen application within the MsgGenMain class.
            /// </summary>
            /// <param name="args">Commandline arguments to the application.</param>
            public MsgGenMain(string[] args)
            {
                this.showLogo = true;
                this.showHelp = false;

                this.sourceFile = null;
                this.destClassFile = null;
                this.destResourcesFile = null;

                // parse the command line
                this.ParseCommandLine(args);

                if (null == this.sourceFile || null == this.destClassFile)
                {
                    this.showHelp = true;
                }
                if (null == this.destResourcesFile)
                {
                    this.destResourcesFile = Path.ChangeExtension(this.destClassFile, ".resources");
                }

                // get the assemblies
                Assembly msgGenAssembly = Assembly.GetExecutingAssembly();

                if (this.showLogo)
                {
                    Console.WriteLine("Microsoft (R) Message Generation Tool version {0}", msgGenAssembly.GetName().Version.ToString());
                    Console.WriteLine("Copyright (C) Microsoft Corporation 2004. All rights reserved.");
                    Console.WriteLine();
                }
                if (this.showHelp)
                {
                    Console.WriteLine(" usage:  MsgGen.exe [-?] [-nologo] sourceFile destClassFile [destResourcesFile]");
                    Console.WriteLine();
                    Console.WriteLine("   -? this help information");
                    Console.WriteLine();
                    Console.WriteLine("For more information see: http://wix.sourceforge.net");
                    return;   // exit
                }

                // load the schema
                XmlReader reader = null;
                XmlSchemaCollection schemaCollection = null;
                try
                {
                    reader = new XmlTextReader(msgGenAssembly.GetManifestResourceStream("Microsoft.Tools.MsgGen.Xsd.messages.xsd"));
                    schemaCollection = new XmlSchemaCollection();
                    schemaCollection.Add("http://schemas.microsoft.com/genmsgs/2004/07/messages", reader);
                }
                finally
                {
                    reader.Close();
                }

                // load the source file and process it
                using (StreamReader sr = new StreamReader(this.sourceFile))
                {
                    XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.None);
                    XmlValidatingReader validatingReader = new XmlValidatingReader(sr.BaseStream, XmlNodeType.Document, context);
                    validatingReader.Schemas.Add(schemaCollection);

                    XmlDocument errorsDoc = new XmlDocument();
                    errorsDoc.Load(validatingReader);

                    CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

                    using (ResourceWriter resourceWriter = new ResourceWriter(this.destResourcesFile))
                    {
                        GenerateMessageFiles.Generate(errorsDoc, codeCompileUnit, resourceWriter);

                        GenerateCSharpCode(codeCompileUnit, this.destClassFile);
                    }
                }
            }
Exemple #25
0
//		private void RemoveDirectoryMatches(string rootDir, string dirPattern) 
//		{
//			foreach(string dir in Directory.GetDirectories(rootDir)) 
//			{
//				foreach(string match in Directory.GetDirectories(dir)) 
//				{//delete all child directories that match
//					Directory.Delete(Path.GetFullPath(match),true);
//				}
//				//recure through the rest checking for nested matches to delete
//				RemoveDirectoryMatches(dir,dirPattern);
//			}
//		}

		private void LoadSchema()
		{
			Assembly assembly = this.GetType().Assembly;
			Stream stream = assembly.GetManifestResourceStream("Prebuild.data." + m_Schema);
			if(stream == null) 
			{
				//try without the default namespace prepending to it in case was compiled with SharpDevelop or MonoDevelop instead of Visual Studio .NET
				stream = assembly.GetManifestResourceStream(m_Schema);
				if(stream == null)
				{
					throw new System.Reflection.TargetException(string.Format("Could not find the scheme embedded resource file '{0}'.", m_Schema));
				}
			}
			XmlReader schema = new XmlTextReader(stream);
            
			m_Schemas = new XmlSchemaCollection();
			m_Schemas.Add(m_SchemaURI, schema);
		}
Exemple #26
0
        /// <summary>
        /// Get the schemas required to validate an object.
        /// </summary>
        /// <returns>The schemas required to validate an object.</returns>
        internal static XmlSchemaCollection GetSchemas()
        {
            lock (lockObject)
            {
                if (null == schemas)
                {
                    Assembly assembly = Assembly.GetExecutingAssembly();

                    using (Stream outputSchemaStream = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.outputs.xsd"))
                    {
                        schemas = new XmlSchemaCollection();
                        schemas.Add(Intermediate.GetSchemas());
                        schemas.Add(TableDefinitionCollection.GetSchemas());
                        XmlSchema outputSchema = XmlSchema.Read(outputSchemaStream, null);
                        schemas.Add(outputSchema);
                    }
                }
            }

            return schemas;
        }
        /// <summary>
		/// IValidationStep.ExecuteValidation() implementation
		/// </summary>
		/// <param name='data'>The stream cintaining the data to be validated.</param>
		/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public void ExecuteValidation(Stream data, Context context)
        {
            var doc = new XmlDocument();
            var trData = new XmlTextReader(data);
            var vr = new XmlValidatingReader(trData);

            // If schema was specified use it to vaidate against...
            if (null != _xmlSchemaPath)
            {
                MemoryStream xsdSchema = StreamHelper.LoadFileToStream(_xmlSchemaPath);
                var trSchema = new XmlTextReader(xsdSchema);
                var xsc = new XmlSchemaCollection();

                if (null != _xmlSchemaNameSpace)
                {
                    xsc.Add(_xmlSchemaNameSpace, trSchema);
                    vr.Schemas.Add(xsc);
                }

                doc.Load(vr);
            }

            data.Seek(0, SeekOrigin.Begin);
            doc.Load(data);

            foreach (Pair validation in _xPathValidations)
            {
                var xpathExp = (string)validation.First;
                var expectedValue = (string)validation.Second;

                context.LogInfo("XmlValidationStep evaluting XPath {0} equals \"{1}\"", xpathExp, expectedValue);

                XmlNode checkNode = doc.SelectSingleNode(xpathExp);

                if (0 != expectedValue.CompareTo(checkNode.InnerText))
                {
                    throw new ApplicationException(string.Format("XmlValidationStep failed, compare {0} != {1}, xpath query used: {2}", expectedValue, checkNode.InnerText, xpathExp));
                }
            }
        }
        /// <SUMMARY>
        /// This method validates an xml string against an xml schema.
        /// </SUMMARY>
        /// <PARAM name="xml">StringReader containing xml</PARAM>
        /// <PARAM name="schemaNamespace">XML Schema Namespace</PARAM>
        /// <PARAM name="schemaUri">XML Schema Uri</PARAM>
        /// <RETURNS>bool</RETURNS>
        public bool ValidXmlDoc(StringReader xml,
                                string schemaNamespace, string schemaUri)
        {
            // Continue?
            if (xml == null || schemaNamespace == null || schemaUri == null)
            {
                return false;
            }

            isValidXml = true;
            XmlValidatingReader vr;
            XmlTextReader tr;
            var schemaCol = new XmlSchemaCollection();
            schemaCol.Add(schemaNamespace, schemaUri);

            try
            {
                // Read the xml.
                tr = new XmlTextReader(xml);
                // Create the validator.
                vr = new XmlValidatingReader(tr);
                // Set the validation tyep.
                vr.ValidationType = ValidationType.Auto;
                // Add the schema.
                if (schemaCol != null)
                {
                    vr.Schemas.Add(schemaCol);
                }
                // Set the validation event handler.
                vr.ValidationEventHandler +=
                    ValidationCallBack;
                // Read the xml schema.
                while (vr.Read())
                {
                }

                vr.Close();

                return isValidXml;
            }
            catch (Exception ex)
            {
                ValidationError = ex.Message;
                return false;
            }
            finally
            {
                // Clean up...
                vr = null;
                tr = null;
            }
        }
Exemple #29
0
        /// <summary>
        /// Gera a Estrutura do XML da NF-e
        /// </summary>
        /// <param name="sNF"></param>
        /// <param name="cert"></param>
        /// <param name="sEmp"></param>
        /// <param name="sNomeArq"></param>
        /// <param name="iStatusAtualSistema"</param>
        public void geraArquivoNFE(List<string> sNF, X509Certificate2 cert, string sEmp, string sNomeArq)
        {
            objbelGeraXml = new belGerarXML();
            Conn = objbelGeraXml.Conn;
            Conn.Open();
            try
            {
                string sPath = "";
                sPath = (sFormaEmiNFe.Equals("2") ? CarregarDadosXml("PastaContingencia").ToString() + @sNomeArq : CarregarDadosXml("PastaXmlEnvio").ToString() + @sNomeArq);
                Globais glob = new Globais();
                int iCount = 0;

                if (File.Exists(sPath))
                {
                    File.Delete(sPath);
                }


                foreach (var i in lTotNota)
                {
                    string sNota = sNF[iCount];
                    string sNFe = "NFe" + GeraChave(sEmp, sNota, Conn);
                    XDocument xdoc = new XDocument();

                    #region XML_Principal
                    XNamespace pf = "http://www.portalfiscal.inf.br/nfe";
                    XContainer conenv = new XElement(pf + "enviNFe", new XAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe"),
                                                               new XAttribute("versao", "2.00"),
                                                               new XElement(pf + "idLote", sNomeArq.Substring(7, 15)));
                    #endregion

                    #region XML_Cabeçalho


                    XContainer concabec = (new XElement(pf + "NFe", new XAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe")));
                    XContainer coninfnfe = (new XElement(pf + "infNFe", new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"), new XAttribute("Id", sNFe),
                                                                        new XAttribute("versao", "2.00")));


                    #endregion

                    #region Ide
                    XContainer conide;
                    try
                    {
                        belIde objide = i[0] as belIde;
                        #region XML_ide
                        conide = (new XElement(pf + "ide", new XElement(pf + "cUF", objide.Cuf.ToString()),
                                                                    new XElement(pf + "cNF", objide.Cnf.ToString()),
                                                                    new XElement(pf + "natOp", objide.Natop.ToString()),
                                                                    new XElement(pf + "indPag", objide.Indpag.ToString()),
                                                                    new XElement(pf + "mod", objide.Mod.ToString()),
                                                                    new XElement(pf + "serie", objide.Serie.ToString()),
                                                                    new XElement(pf + "nNF", objide.Nnf.ToString()),
                                                                    new XElement(pf + "dEmi", objide.Demi.ToString("yyyy-MM-dd")),
                                                                    new XElement(pf + "dSaiEnt", objide.Dsaient.ToString("yyyy-MM-dd")),
                                                                    new XElement(pf + "hSaiEnt", objide.HSaiEnt.ToString("HH:mm:ss")), // NFe_2.0
                                                                    new XElement(pf + "tpNF", objide.Tpnf.ToString()),
                                                                    new XElement(pf + "cMunFG", objide.Cmunfg.ToString()),
                                                                    (objide.belNFref != null ?
                                                                    (from c in objide.belNFref
                                                                     select new XElement(pf + "NFref",
                                                                                (c.RefNFe != null ? new XElement(pf + "refNFe", c.RefNFe) : null),
                                                                               (c.cUF != null ? (new XElement(pf + "refNF",
                                                                                (c.cUF != null ? new XElement(pf + "cUF", c.cUF) : null),
                                                                                 (c.AAMM != null ? new XElement(pf + "AAMM", c.AAMM) : null),
                                                                                 (c.CNPJ != null ? new XElement(pf + "CNPJ", c.CNPJ) : null),
                                                                                 (c.mod != null ? new XElement(pf + "mod", c.mod) : null),
                                                                                 (c.serie != null ? new XElement(pf + "serie", c.serie) : null),
                                                                                 (c.nNF != null ? new XElement(pf + "nNF", c.nNF) : null))) : null))) : null),//NFe_2.0_Verificar ID B14 - B20a - B20i - 
                                                                    new XElement(pf + "tpImp", objide.Tpimp.ToString()),
                                                                    new XElement(pf + "tpEmis", objide.Tpemis.ToString()),
                                                                    new XElement(pf + "cDV", objide.Cdv.ToString()),
                                                                    new XElement(pf + "tpAmb", objide.Tpamb.ToString()),
                                                                    new XElement(pf + "finNFe", objide.Finnfe.ToString()),
                                                                    new XElement(pf + "procEmi", objide.Procemi.ToString()),
                                                                    new XElement(pf + "verProc", objide.Verproc.ToString()),

                                                                    ((objide.Tpemis.Equals("2")) || (objide.Tpemis.Equals("3")) ?
                                                                                          new XElement(pf + "dhCont", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")) : null), // NFe_2.0
                                                                    ((objide.Tpemis.Equals("2")) || (objide.Tpemis.Equals("3")) ?
                                                                                          new XElement(pf + "xJust", (iStatusAtualSistema == 2 ? "FALHA DE CONEXÃO COM INTERNET" : "FALHA COM WEB SERVICE DO ESTADO")) : null)));// NFe_2.0
                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML, Regiao XML_ide - " + x.Message);
                    }
                    #endregion

                    #region Emit

                    XContainer conemit;
                    try
                    {
                        belEmit objemit = i[1] as belEmit;
                        #region XML_Emit

                        conemit = (new XElement(pf + "emit", (new XElement(pf + "CNPJ", objemit.Cnpj.ToString())),
                                                  new XElement(pf + "xNome", objemit.Xnome.ToString()),
                                                  new XElement(pf + "xFant", objemit.Xfant.ToString()),
                                                          new XElement(pf + "enderEmit",
                                                                  new XElement(pf + "xLgr", objemit.Xlgr.ToString()),
                                                                  new XElement(pf + "nro", objemit.Nro.ToString()),
                                                                  (objemit.Xcpl != null ? new XElement(pf + "xCpl", objemit.Xcpl.ToString()) : null),
                                                                  new XElement(pf + "xBairro", objemit.Xbairro.ToString()),
                                                                  new XElement(pf + "cMun", objemit.Cmun.ToString()),
                                                                  new XElement(pf + "xMun", objemit.Xmun.ToString()),
                                                                  new XElement(pf + "UF", objemit.Uf.ToString()),
                                                                  new XElement(pf + "CEP", objemit.Cep.ToString()),
                                                                  new XElement(pf + "cPais", objemit.Cpais.ToString()),
                                                                  new XElement(pf + "xPais", objemit.Xpais.ToString()),
                                                                  (objemit.Fone != null ? new XElement(pf + "fone", objemit.Fone.ToString()) : null)),
                                                  (objemit.Ie != null ? new XElement(pf + "IE", objemit.Ie.ToString()) : null),
                                                  (objemit.Iest != null ? new XElement(pf + "IEST", objemit.Iest.ToString()) : null),
                                                  (objemit.Im != null ? new XElement(pf + "IM", objemit.Im.ToString()) : null),
                                                  (objemit.Cnae != null ? new XElement(pf + "CNAE", objemit.Cnae.ToString()) : null),
                                                  new XElement(pf + "CRT", objemit.CRT.ToString()))); // NFe_2.0

                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML, Regiao XML_Emit - " + x.Message);
                    }
                    #endregion

                    #region Dest
                    XContainer condest;
                    try
                    {
                        belDest objdest = i[2] as belDest;
                        #region XML_Dest
                        objdest.Ie = (objdest.Ie == null ? "" : objdest.Ie);

                        condest = (new XElement(pf + "dest",
                                                  (objdest.Cnpj == "EXTERIOR" ? new XElement(pf + "CNPJ") :
                                                     (objdest.Cnpj != null ? new XElement(pf + "CNPJ", objdest.Cnpj) :
                                                                            new XElement(pf + "CPF", objdest.Cpf))),
                                                  new XElement(pf + "xNome", objdest.Xnome.ToString()),
                                                  new XElement(pf + "enderDest",
                                                      new XElement(pf + "xLgr", objdest.Xlgr.ToString()),
                                                      new XElement(pf + "nro", (objdest.Nro != null ? objdest.Nro.ToString() : "0")),
                                                      (objdest.Xcpl != null ? new XElement(pf + "xCpl", objdest.Xcpl.ToString()) : null),
                                                      new XElement(pf + "xBairro", objdest.Xbairro.ToString()),
                                                      new XElement(pf + "cMun", objdest.Cmun.ToString()),
                                                      new XElement(pf + "xMun", objdest.Xmun.ToString()),
                                                      new XElement(pf + "UF", objdest.Uf.ToString()),
                                                      (objdest.Cep != null ? new XElement(pf + "CEP", objdest.Cep.ToString()) : null),
                                                      new XElement(pf + "cPais", objdest.Cpais.ToString()),
                                                      (objdest.Xpais != null ? new XElement(pf + "xPais", objdest.Xpais.ToString()) : null),
                                                     (objdest.Fone != null ? new XElement(pf + "fone", objdest.Fone.ToString()) : null)),
                                                  ((objdest.Ie != null) ? (objdest.Ie != "EXTERIOR" ? new XElement(pf + "IE", objdest.Ie.ToString()) : new XElement(pf + "IE")) : null), //Claudinei - o.s. sem - 11/02/2010
                                                  (objdest.Isuf != null ? new XElement(pf + "ISUF", objdest.Isuf.ToString()) : null)));


                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML, Regiao XML_Dest - " + x.Message);
                    }

                    #endregion

                    #region Det
                    List<XElement> lcondet = new List<XElement>();
                    try
                    {
                        List<belDet> objdet = new List<belDet>();
                        objdet = i[4] as List<belDet>;
                        #region XML_Detalhes

                        foreach (var det in objdet)
                        {
                            XElement condet = (new XElement(pf + "det", new XAttribute("nItem", det.Nitem),
                                               new XElement(pf + "prod",
                                                   (det.belProd.Cprod != null ? new XElement(pf + "cProd", det.belProd.Cprod.ToString()) : null),
                                                   (det.belProd.Cean != null ? new XElement(pf + "cEAN", det.belProd.Cean.ToString()) : null),
                                                   (det.belProd.Xprod != null ? new XElement(pf + "xProd", det.belProd.Xprod.ToString()) : null),
                                                   (det.belProd.Ncm != null ? new XElement(pf + "NCM", det.belProd.Ncm.ToString()) : new XElement(pf + "NCM", det.belProd.Ncm = "00000000")), //Claudinei - o.s. 24200 - 01/03/2010
                                                   (det.belProd.Extipi != null ? new XElement(pf + "EXTIPI", det.belProd.Extipi.ToString()) : null),
                                                   (det.belProd.Genero != null ? new XElement(pf + "genero", det.belProd.Genero.ToString()) : null),
                                                   (det.belProd.Cfop != null ? new XElement(pf + "CFOP", det.belProd.Cfop.ToString()) : null),
                                                   (det.belProd.Ucom != null ? new XElement(pf + "uCom", det.belProd.Ucom.ToString()) : null),
                                                   (det.belProd.Qcom != null ? new XElement(pf + "qCom", det.belProd.Qcom.ToString("#0.0000").Replace(",", ".")) : null),
                                                   (det.belProd.Vuncom != null ? new XElement(pf + "vUnCom", det.belProd.Vuncom.ToString("#0.0000").Replace(",", ".")) : null),
                                                   (det.belProd.Vprod != null ? new XElement(pf + "vProd", det.belProd.Vprod.ToString("#0.00").Replace(",", ".")) : null),
                                                   (det.belProd.Ceantrib != null ? new XElement(pf + "cEANTrib", det.belProd.Ceantrib.ToString().PadLeft(8, '0')) : null),
                                                   (det.belProd.Utrib != null ? new XElement(pf + "uTrib", det.belProd.Utrib.ToString()) : null),
                                                   (det.belProd.Qtrib != null ? new XElement(pf + "qTrib", det.belProd.Qtrib.ToString("#0.0000").Replace(",", ".")) : null),
                                                   (det.belProd.Vuntrib != null ? new XElement(pf + "vUnTrib", det.belProd.Vuntrib.ToString("#0.0000").Replace(",", ".")) : null),
                                                   ((det.belProd.Vfrete != null) && (det.belProd.Vfrete != 0) ? new XElement(pf + "vFrete", det.belProd.Vfrete.ToString("#0.00").Replace(",", ".")) : null),
                                                   ((det.belProd.Vseg != null) && (det.belProd.Vseg != 0) ? new XElement(pf + "vSeg", det.belProd.Vseg.ToString("#0.00").Replace(",", ".")) : null),
                                                   (((det.belProd.Vdesc != null) && (det.belProd.Vdesc != 0)) ? new XElement(pf + "vDesc", det.belProd.Vdesc.ToString("#0.00").Replace(",", ".")) : null),
                                                   ((det.belProd.VOutro != null) && (det.belProd.VOutro != 0) ? new XElement(pf + "vOutro", det.belProd.VOutro.ToString("#0.00").Replace(",", ".")) : null), //NFe_2.0 
                                                   (det.belProd.IndTot != null) ? new XElement(pf + "indTot", det.belProd.IndTot.ToString()) : null), //NFe_2.0

                                               new XElement(pf + "imposto",

                                                   //---------------ICMS-----------------//

                                                   new XElement(pf + "ICMS",

                                                       //-------------ICMS00-------------//

                                                       (det.belImposto.belIcms.belIcms00 != null ?
                                                       new XElement(pf + "ICMS00",
                                                            (det.belImposto.belIcms.belIcms00.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms00.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms00.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms00.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms00.Modbc != null ? new XElement(pf + "modBC", det.belImposto.belIcms.belIcms00.Modbc.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms00.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIcms.belIcms00.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms00.Picms != null ? new XElement(pf + "pICMS", det.belImposto.belIcms.belIcms00.Picms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms00.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms00.Vicms.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                        //-------------ICMS10-------------//

                                                        (det.belImposto.belIcms.belIcms10 != null ?
                                                        new XElement(pf + "ICMS10",
                                                            (det.belImposto.belIcms.belIcms10.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms10.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms10.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms10.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms10.Modbc != null ? new XElement(pf + "modBC", det.belImposto.belIcms.belIcms10.Modbc.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms10.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIcms.belIcms10.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms10.Picms != null ? new XElement(pf + "pICMS", det.belImposto.belIcms.belIcms10.Picms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms10.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms10.Vicms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms10.Modbcst != null ? new XElement(pf + "modBCST", det.belImposto.belIcms.belIcms10.Modbcst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms10.Pmvast != 0 ? new XElement(pf + "pMVAST", det.belImposto.belIcms.belIcms10.Pmvast.ToString("#0.00").Replace(",", ".")) : null), //Claudinei - o.s. sem - 11/03/2010
                                                            (det.belImposto.belIcms.belIcms10.Predbcst.ToString() != "0" ? new XElement(pf + "pRedBCST", det.belImposto.belIcms.belIcms10.Predbcst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms10.Vbcst != null ? new XElement(pf + "vBCST", det.belImposto.belIcms.belIcms10.Vbcst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms10.Picmsst != null ? new XElement(pf + "pICMSST", det.belImposto.belIcms.belIcms10.Picmsst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms10.Vicmsst != null ? new XElement(pf + "vICMSST", det.belImposto.belIcms.belIcms10.Vicmsst.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                        //-------------ICMS20-------------//

                                                        (det.belImposto.belIcms.belIcms20 != null ?
                                                        new XElement(pf + "ICMS20",
                                                            (det.belImposto.belIcms.belIcms20.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms20.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms20.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms20.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms20.Modbc != null ? new XElement(pf + "modBC", det.belImposto.belIcms.belIcms20.Modbc.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms20.Predbc != null ? new XElement(pf + "pRedBC", det.belImposto.belIcms.belIcms20.Predbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms20.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIcms.belIcms20.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms20.Picms != null ? new XElement(pf + "pICMS", det.belImposto.belIcms.belIcms20.Picms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms20.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms20.Vicms.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                        //-------------ICMS30-------------//

                                                        (det.belImposto.belIcms.belIcms30 != null ?
                                                        new XElement(pf + "ICMS30",
                                                            (det.belImposto.belIcms.belIcms30.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms30.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms30.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms30.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms30.Modbcst != null ? new XElement(pf + "modBCST", det.belImposto.belIcms.belIcms30.Modbcst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms30.Pmvast != 0 ? new XElement(pf + "pMVAST", det.belImposto.belIcms.belIcms30.Pmvast.ToString("#0.00").Replace(",", ".")) : null), //Claudinei - o.s. sem - 12/03/2010
                                                            (det.belImposto.belIcms.belIcms30.Predbcst.ToString() != "0" ? new XElement(pf + "pRedBCST", det.belImposto.belIcms.belIcms30.Predbcst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms30.Vbcst != null ? new XElement(pf + "vBCST", det.belImposto.belIcms.belIcms30.Vbcst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms30.Picmsst != null ? new XElement(pf + "pICMSST", det.belImposto.belIcms.belIcms30.Picmsst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms30.Vicmsst != null ? new XElement(pf + "vICMSST", det.belImposto.belIcms.belIcms30.Vicmsst.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                        //-------------ICMS40-------------//

                                                        (det.belImposto.belIcms.belIcms40 != null ?
                                                        new XElement(pf + "ICMS40",
                                                            (det.belImposto.belIcms.belIcms40.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms40.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms40.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms40.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms40.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms40.Vicms.ToString()) : null), //NFe_2.0
                                                            (det.belImposto.belIcms.belIcms40.motDesICMS != null ? new XElement(pf + "motDesICMS", det.belImposto.belIcms.belIcms40.motDesICMS.ToString()) : null)) : null),//NFe_2.0

                                                        //-------------ICMS41-------------//

                                                        (det.belImposto.belIcms.belIcms41 != null ?
                                                        new XElement(pf + "ICMS41",
                                                            (det.belImposto.belIcms.belIcms41.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms41.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms41.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms41.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms41.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms41.Vicms.ToString()) : null),//NFe_2.0
                                                            (det.belImposto.belIcms.belIcms41.motDesICMS != null ? new XElement(pf + "motDesICMS", det.belImposto.belIcms.belIcms41.motDesICMS.ToString()) : null)) : null),//NFe_2.0

                                                        //-------------ICMS50-------------//

                                                        (det.belImposto.belIcms.belIcms50 != null ?
                                                        new XElement(pf + "ICMS50",
                                                            (det.belImposto.belIcms.belIcms50.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms50.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms50.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms50.Cst.ToString()) : null),
                                                                (det.belImposto.belIcms.belIcms50.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms50.Vicms.ToString()) : null),//NFe_2.0
                                                            (det.belImposto.belIcms.belIcms50.motDesICMS != null ? new XElement(pf + "motDesICMS", det.belImposto.belIcms.belIcms50.motDesICMS.ToString()) : null)) : null),//NFe_2.0

                                                        //-------------ICMS51-------------//

                                                        (det.belImposto.belIcms.belIcms51 != null ?
                                                        new XElement(pf + "ICMS51",
                                                            (det.belImposto.belIcms.belIcms51.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms51.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms51.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms51.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms51.Modbc != null ? new XElement(pf + "modBC", det.belImposto.belIcms.belIcms51.Modbc.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms51.Predbc != null ? new XElement(pf + "pRedBC", det.belImposto.belIcms.belIcms51.Predbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms51.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIcms.belIcms51.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms51.Picms != null ? new XElement(pf + "pICMS", det.belImposto.belIcms.belIcms51.Picms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms51.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms51.Vicms.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                        //-------------ICMS60-------------//

                                                        (det.belImposto.belIcms.belIcms60 != null ?
                                                        new XElement(pf + "ICMS60",//Danner - o.s. sem - 12/03/2010
                                                            (det.belImposto.belIcms.belIcms60.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms60.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms60.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms60.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms60.Vbcst != null ? new XElement(pf + "vBCSTRet", det.belImposto.belIcms.belIcms60.Vbcst.ToString("#0.00").Replace(",", ".")) : null),//NFe_2.0 - Mudança de nome de Tag
                                                            (det.belImposto.belIcms.belIcms60.Vicmsst != null ? new XElement(pf + "vICMSSTRet", det.belImposto.belIcms.belIcms60.Vicmsst.ToString("#0.00").Replace(",", ".")) : null)) : null),//NFe_2.0 Mudança de nome de Tag

                                                        //-------------ICMS70-------------//

                                                        (det.belImposto.belIcms.belIcms70 != null ?
                                                        new XElement(pf + "ICMS70",
                                                            (det.belImposto.belIcms.belIcms70.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms70.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms70.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms70.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms70.Modbc != null ? new XElement(pf + "modBC", det.belImposto.belIcms.belIcms70.Modbc.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms70.Predbc != null ? new XElement(pf + "pRedBC", det.belImposto.belIcms.belIcms70.Predbc.ToString("#0.00").Replace(',', '.')) : null), //Danner - o.s. 24091 - 06/02/2010
                                                            (det.belImposto.belIcms.belIcms70.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIcms.belIcms70.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms70.Picms != null ? new XElement(pf + "pICMS", det.belImposto.belIcms.belIcms70.Picms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms70.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms70.Vicms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms70.Modbcst != null ? new XElement(pf + "modBCST", det.belImposto.belIcms.belIcms70.Modbcst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms70.Pmvast != 0 ? new XElement(pf + "pMVAST", det.belImposto.belIcms.belIcms70.Pmvast.ToString("#0.00").Replace(",", ".")) : null), //Claudinei - o.s. sem - 12/03/2010
                                                            (det.belImposto.belIcms.belIcms70.Predbcst.ToString() != "0" ? new XElement(pf + "pRedBCST", det.belImposto.belIcms.belIcms70.Predbcst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms70.Vbcst != null ? new XElement(pf + "vBCST", det.belImposto.belIcms.belIcms70.Vbcst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms70.Picmsst != null ? new XElement(pf + "pICMSST", det.belImposto.belIcms.belIcms70.Picmsst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms70.Vicmsst != null ? new XElement(pf + "vICMSST", det.belImposto.belIcms.belIcms70.Vicmsst.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                        //-------------ICMS90-------------//

                                                        (det.belImposto.belIcms.belIcms90 != null ?
                                                        new XElement(pf + "ICMS90",
                                                            (det.belImposto.belIcms.belIcms90.Orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belIcms90.Orig.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms90.Cst != null ? new XElement(pf + "CST", det.belImposto.belIcms.belIcms90.Cst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms90.Modbc != null ? new XElement(pf + "modBC", det.belImposto.belIcms.belIcms90.Modbc.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms90.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIcms.belIcms90.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms90.Predbc != 0 ? new XElement(pf + "pRedBC", det.belImposto.belIcms.belIcms90.Predbc.ToString("#0.00").Replace(',', '.')) : null), //Danner - o.s. 24091 - 06/02/2010 //Claudinei - o.s. sem - 24/02/2010
                                                            (det.belImposto.belIcms.belIcms90.Picms != null ? new XElement(pf + "pICMS", det.belImposto.belIcms.belIcms90.Picms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms90.Vicms != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belIcms90.Vicms.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms90.Modbcst != null ? new XElement(pf + "modBCST", det.belImposto.belIcms.belIcms90.Modbcst.ToString()) : null),
                                                            (det.belImposto.belIcms.belIcms90.Pmvast != 0 ? new XElement(pf + "pMVAST", det.belImposto.belIcms.belIcms90.Pmvast.ToString("#0.00").Replace(",", ".")) : null), //Claudinei - o.s. 24076 - 01/02/2010
                                                            (det.belImposto.belIcms.belIcms90.Predbcst.ToString() != "0" ? new XElement(pf + "pRedBCST", det.belImposto.belIcms.belIcms90.Predbcst.ToString("#0.00").Replace(",", ".")) : null), //Claudinei - o.s. 24076 - 01/02/2010
                                                            (det.belImposto.belIcms.belIcms90.Vbcst != null ? new XElement(pf + "vBCST", det.belImposto.belIcms.belIcms90.Vbcst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms90.Picmsst != null ? new XElement(pf + "pICMSST", det.belImposto.belIcms.belIcms90.Picmsst.ToString("#0.00").Replace(",", ".")) : null),
                                                            (det.belImposto.belIcms.belIcms90.Vicmsst != null ? new XElement(pf + "vICMSST", det.belImposto.belIcms.belIcms90.Vicmsst.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                       //-------------ICMSSN101--------------//
                                                       (det.belImposto.belIcms.belICMSSN101 != null ?
                                                            new XElement(pf + "ICMSSN101",
                                                               (det.belImposto.belIcms.belICMSSN101.orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belICMSSN101.orig.ToString()) : null),
                                                               new XElement(pf + "CSOSN", det.belImposto.belIcms.belICMSSN101.CSOSN.ToString()),
                                                               (det.belImposto.belIcms.belICMSSN101.pCredSN != null ? new XElement(pf + "pCredSN", det.belImposto.belIcms.belICMSSN101.pCredSN.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN101.vCredICMSSN != null ? new XElement(pf + "vCredICMSSN", det.belImposto.belIcms.belICMSSN101.vCredICMSSN.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                      //-------------ICMSSN102--------------//
                                                       (det.belImposto.belIcms.belICMSSN102 != null ?
                                                            new XElement(pf + "ICMSSN102",
                                                               (det.belImposto.belIcms.belICMSSN102.orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belICMSSN102.orig.ToString()) : null),
                                                               new XElement(pf + "CSOSN", det.belImposto.belIcms.belICMSSN102.CSOSN.ToString())) : null),

                                                      //-------------ICMSSN201--------------//
                                                       (det.belImposto.belIcms.belICMSSN201 != null ?
                                                            new XElement(pf + "ICMSSN201",
                                                               (det.belImposto.belIcms.belICMSSN201.orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belICMSSN201.orig.ToString()) : null),
                                                               new XElement(pf + "CSOSN", det.belImposto.belIcms.belICMSSN201.CSOSN.ToString()),
                                                               (det.belImposto.belIcms.belICMSSN201.modBCST != null ? new XElement(pf + "modBCST", det.belImposto.belIcms.belICMSSN201.modBCST.ToString()) : null),
                                                               (det.belImposto.belIcms.belICMSSN201.pMVAST != null ? new XElement(pf + "pMVAST", det.belImposto.belIcms.belICMSSN201.pMVAST.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN201.pRedBCST != null ? new XElement(pf + "pRedBCST", det.belImposto.belIcms.belICMSSN201.pRedBCST.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN201.vBCST != null ? new XElement(pf + "vBCST", det.belImposto.belIcms.belICMSSN201.vBCST.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN201.pICMSST != null ? new XElement(pf + "pICMSST", det.belImposto.belIcms.belICMSSN201.pICMSST.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN201.vICMSST != null ? new XElement(pf + "vICMSST", det.belImposto.belIcms.belICMSSN201.vICMSST.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN201.pCredSN != null ? new XElement(pf + "pCredSN", det.belImposto.belIcms.belICMSSN201.pCredSN.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN201.vCredICMSSN != null ? new XElement(pf + "vCredICMSSN", det.belImposto.belIcms.belICMSSN201.vCredICMSSN.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                      //-------------ICMSSN500--------------//
                                                       (det.belImposto.belIcms.belICMSSN500 != null ?
                                                            new XElement(pf + "ICMSSN500",
                                                               (det.belImposto.belIcms.belICMSSN500.orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belICMSSN500.orig.ToString()) : null),
                                                               new XElement(pf + "CSOSN", det.belImposto.belIcms.belICMSSN500.CSOSN.ToString()),
                                                               (det.belImposto.belIcms.belICMSSN500.vBCSTRet != null ? new XElement(pf + "vBCSTRet", det.belImposto.belIcms.belICMSSN500.vBCSTRet.ToString("#0.00").Replace(",", ".")) : null),
                                                               (det.belImposto.belIcms.belICMSSN500.vICMSSTRet != null ? new XElement(pf + "vICMSSTRet", det.belImposto.belIcms.belICMSSN500.vICMSSTRet.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                      //-------------ICMSSN900--------------//
                                                       (det.belImposto.belIcms.belICMSSN900 != null ?
                                                            new XElement(pf + "ICMSSN900",
                                                               (det.belImposto.belIcms.belICMSSN900.orig != null ? new XElement(pf + "orig", det.belImposto.belIcms.belICMSSN900.orig.ToString()) : null),
                                                               new XElement(pf + "CSOSN", det.belImposto.belIcms.belICMSSN900.CSOSN.ToString())) : null)),
                                //(det.belImposto.belIcms.belICMSSN900.modBC != null ? new XElement(pf + "modBC", det.belImposto.belIcms.belICMSSN900.modBC.ToString()) : null),
                                //(det.belImposto.belIcms.belICMSSN900.vBC != null ? new XElement(pf + "vBC", det.belImposto.belIcms.belICMSSN900.vBC.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.pRedBC != null ? new XElement(pf + "pRedBC", det.belImposto.belIcms.belICMSSN900.pRedBC.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.pICMS != null ? new XElement(pf + "pICMS", det.belImposto.belIcms.belICMSSN900.pICMS.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.vICMS != null ? new XElement(pf + "vICMS", det.belImposto.belIcms.belICMSSN900.vICMS.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.modBCST != null ? new XElement(pf + "modBCST", det.belImposto.belIcms.belICMSSN900.modBCST.ToString()) : null),
                                //(det.belImposto.belIcms.belICMSSN900.pMVAST != null ? new XElement(pf + "pMVAST", det.belImposto.belIcms.belICMSSN900.pMVAST.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.pRedBCST != null ? new XElement(pf + "pRedBCST", det.belImposto.belIcms.belICMSSN900.pRedBCST.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.vBCST != null ? new XElement(pf + "vBCST", det.belImposto.belIcms.belICMSSN900.vBCST.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.pICMSST != null ? new XElement(pf + "pICMSST", det.belImposto.belIcms.belICMSSN900.pICMSST.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.vICMSST != null ? new XElement(pf + "vICMSST", det.belImposto.belIcms.belICMSSN900.vICMSST.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.vBCSTRet != null ? new XElement(pf + "vBCSTRet", det.belImposto.belIcms.belICMSSN900.vBCSTRet.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.vICMSSTRet != null ? new XElement(pf + "vICMSSTRet", det.belImposto.belIcms.belICMSSN900.vICMSSTRet.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.pCredSN != null ? new XElement(pf + "pCredSN", det.belImposto.belIcms.belICMSSN900.pCredSN.ToString("#0.00").Replace(",", ".")) : null),
                                //(det.belImposto.belIcms.belICMSSN900.vCredICMSSN != null ? new XElement(pf + "vCredICMSSN", det.belImposto.belIcms.belICMSSN900.vCredICMSSN.ToString("#0.00").Replace(",", ".")) : null)) : null)),

                                        //---------------IPI-------------//
                                            (det.belImposto.belIpi != null ?
                                            new XElement(pf + "IPI",
                                                (det.belImposto.belIpi.Clenq != null ?
                                                    new XElement(pf + "clEnq", det.belImposto.belIpi.Clenq.ToString()) : null),
                                                (det.belImposto.belIpi.Cnpjprod != null ?
                                                    new XElement(pf + "CNPJProd", det.belImposto.belIpi.Cnpjprod.ToString()) : null),
                                                (det.belImposto.belIpi.Cselo != null ?
                                                    new XElement(pf + "cSelo", det.belImposto.belIpi.Cselo.ToString()) : null),
                                                (det.belImposto.belIpi.Qselo != null ?
                                                    new XElement(pf + "qSelo", det.belImposto.belIpi.Qselo.ToString()) : null),
                                                (det.belImposto.belIpi.Cenq != null ?
                                                    new XElement(pf + "cEnq", det.belImposto.belIpi.Cenq.ToString()) : null),

                                                //-----------IPITrib-----------//    

                                                (det.belImposto.belIpi.belIpitrib != null ?
                                                new XElement(pf + "IPITrib",
                                                    (det.belImposto.belIpi.belIpitrib.Cst != null ? new XElement(pf + "CST", det.belImposto.belIpi.belIpitrib.Cst.ToString()) : null),
                                                    (det.belImposto.belIpi.belIpitrib.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIpi.belIpitrib.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                                    (det.belImposto.belIpi.belIpitrib.Qunid != null ? new XElement(pf + "qUnid", det.belImposto.belIpi.belIpitrib.Qunid.ToString()) : null),
                                                    (det.belImposto.belIpi.belIpitrib.Vunid != 0 ? new XElement(pf + "vUnid", det.belImposto.belIpi.belIpitrib.Vunid.ToString("#0.0000").Replace(",", ".")) : null),
                                                    (det.belImposto.belIpi.belIpitrib.Pipi != null ? new XElement(pf + "pIPI", det.belImposto.belIpi.belIpitrib.Pipi.ToString("#0.00").Replace(",", ".")) : null),
                                                    (det.belImposto.belIpi.belIpitrib.Vipi != null ? new XElement(pf + "vIPI", det.belImposto.belIpi.belIpitrib.Vipi.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                                //-----------IPINT-----------//

                                                (det.belImposto.belIpi.belIpint != null ?
                                                new XElement(pf + "IPINT",
                                                    (det.belImposto.belIpi.belIpint != null ? new XElement(pf + "CST", det.belImposto.belIpi.belIpint.Cst.ToString()) : null)) : null)) : null),




                                       //--------------II--------------//             
                                       (det.belImposto.belIi != null ?
                                       new XElement(pf + "II",
                                           (det.belImposto.belIi.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIi.Vbc.ToString("#0.00").Replace(',', '.')) : null),
                                           (det.belImposto.belIi.Vdespadu != null ? new XElement(pf + "vDespAdu", det.belImposto.belIi.Vdespadu.ToString()) : null),
                                           (det.belImposto.belIi.Vii != null ? new XElement(pf + "vII", det.belImposto.belIi.Vii.ToString("0.00").Replace(',', '.')) : null),
                                           (det.belImposto.belIi.Viof != null ? new XElement(pf + "vIOF", det.belImposto.belIi.Viof.ToString("#0.00").Replace(',', '.')) : null)) : null),



                               //----------------PIS------------//

                                 (det.belImposto.belPis != null ?
                                 new XElement(pf + "PIS",

                                     //-----------PISAliq----------//

                                     (det.belImposto.belPis.belPisaliq != null ?
                                     new XElement(pf + "PISAliq",
                                         (det.belImposto.belPis.belPisaliq.Cst != null ? new XElement(pf + "CST", det.belImposto.belPis.belPisaliq.Cst.ToString()) : null),
                                         (det.belImposto.belPis.belPisaliq.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belPis.belPisaliq.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                         (det.belImposto.belPis.belPisaliq.Ppis != null ? new XElement(pf + "pPIS", det.belImposto.belPis.belPisaliq.Ppis.ToString("#0.00").Replace(",", ".")) : null),
                                         (det.belImposto.belPis.belPisaliq.Vpis != null ? new XElement(pf + "vPIS", det.belImposto.belPis.belPisaliq.Vpis.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                    //-----------PISQtde-----------//                               
                                     (det.belImposto.belPis.belPisqtde != null ?
                                     new XElement(pf + "PISQtde",
                                         (det.belImposto.belPis.belPisqtde.Cst != null ? new XElement(pf + "CST", det.belImposto.belPis.belPisqtde.Cst.ToString()) : null),
                                         (det.belImposto.belPis.belPisqtde.Qbcprod != 0 ? new XElement(pf + "qBCProd", det.belImposto.belPis.belPisqtde.Qbcprod.ToString()) : null),
                                         (det.belImposto.belPis.belPisqtde.Valiqprod != null ? new XElement(pf + "vAliqProd", det.belImposto.belPis.belPisqtde.Valiqprod.ToString("#0.00").Replace(",", ".")) : null),
                                         (det.belImposto.belPis.belPisqtde.Vpis != null ? new XElement(pf + "vPIS", det.belImposto.belPis.belPisqtde.Vpis.ToString("#0.00").Replace(",", ".")) : null)) : null),

                                     //----------PISNT------------//

                                     (det.belImposto.belPis.belPisnt != null ?
                                     new XElement(pf + "PISNT",
                                         (det.belImposto.belPis.belPisnt.Cst != null ? new XElement(pf + "CST", det.belImposto.belPis.belPisnt.Cst.ToString()) : null)) : null),

                                     //----------PISOutr-----------//

                                     (det.belImposto.belPis.belPisoutr != null ?
                                     new XElement(pf + "PISOutr",
                                         (det.belImposto.belPis.belPisoutr.Cst != null ? new XElement(pf + "CST", det.belImposto.belPis.belPisoutr.Cst.ToString()) : null),
                                         (det.belImposto.belPis.belPisoutr.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belPis.belPisoutr.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                         (det.belImposto.belPis.belPisoutr.Ppis != null ? new XElement(pf + "pPIS", det.belImposto.belPis.belPisoutr.Ppis.ToString("#0.00").Replace(",", ".")) : null),
                                         (det.belImposto.belPis.belPisoutr.Qbcprod != 0 ? new XElement(pf + "qBCProd", det.belImposto.belPis.belPisoutr.Qbcprod.ToString()) : null),
                                         (det.belImposto.belPis.belPisoutr.Valiqprod != 0 ? new XElement(pf + "vAliqProd", det.belImposto.belPis.belPisoutr.Valiqprod.ToString("#0.0000").Replace(",", ".")) : null),
                                         (det.belImposto.belPis.belPisoutr.Vpis != null ? new XElement(pf + "vPIS", det.belImposto.belPis.belPisoutr.Vpis.ToString("#0.00").Replace(",", ".")) : null)) : null)) : null),







                                 //---------------COFINS---------------//
                                 (det.belImposto.belCofins != null ?
                                 new XElement(pf + "COFINS",

                                     //-----------COFINSAliq------------//

                                     (det.belImposto.belCofins.belCofinsaliq != null ?
                                     new XElement(pf + "COFINSAliq",
                                         new XElement(pf + "CST", det.belImposto.belCofins.belCofinsaliq.Cst.ToString()),
                                         new XElement(pf + "vBC", det.belImposto.belCofins.belCofinsaliq.Vbc.ToString("#0.00").Replace(",", ".")),
                                         new XElement(pf + "pCOFINS", det.belImposto.belCofins.belCofinsaliq.Pcofins.ToString("#0.00").Replace(",", ".")),
                                         new XElement(pf + "vCOFINS", det.belImposto.belCofins.belCofinsaliq.Vcofins.ToString("#0.00").Replace(",", "."))) : null),

                                     //------------COFINSQtde------------//

                                     (det.belImposto.belCofins.belCofinsqtde != null ?
                                     new XElement(pf + "COFINSQtde",
                                         new XElement(pf + "CST", det.belImposto.belCofins.belCofinsqtde.Cst.ToString()),
                                         new XElement(pf + "pBCProd", det.belImposto.belCofins.belCofinsqtde.Qbcprod.ToString()),
                                         new XElement(pf + "vAliqProd", det.belImposto.belCofins.belCofinsqtde.Valiqprod.ToString("#0.00").Replace(",", ".")),
                                         new XElement(pf + "vCOFINS", det.belImposto.belCofins.belCofinsqtde.Vcofins.ToString("#0.00").Replace(",", "."))) : null),

                                     //------------COFINSNT--------------//

                                     (det.belImposto.belCofins.belCofinsnt != null ?
                                     new XElement(pf + "COFINSNT",
                                         (det.belImposto.belCofins.belCofinsnt.Cst != null ? new XElement(pf + "CST", det.belImposto.belCofins.belCofinsnt.Cst.ToString()) : null)) : null),

                                     //------------COFINSOutr--------------//

                                     (det.belImposto.belCofins.belCofinsoutr != null ?
                                     new XElement(pf + "COFINSOutr",
                                         new XElement(pf + "CST", det.belImposto.belCofins.belCofinsoutr.Cst.ToString()),
                                         new XElement(pf + "vBC", det.belImposto.belCofins.belCofinsoutr.Vbc.ToString("#0.00").Replace(",", ".")),
                                         new XElement(pf + "pCOFINS", det.belImposto.belCofins.belCofinsoutr.Pcofins.ToString("#0.00").Replace(",", ".")),
                                         new XElement(pf + "vCOFINS", det.belImposto.belCofins.belCofinsoutr.Vcofins.ToString("#0.00").Replace(",", "."))) : null)) : null),


                                 //----------------ISSQN-----------------//

                                 (det.belImposto.belIss != null ?
                                 new XElement(pf + "ISSQN",
                                     (det.belImposto.belIss.Vbc != null ? new XElement(pf + "vBC", det.belImposto.belIss.Vbc.ToString("#0.00").Replace(",", ".")) : null),
                                     (det.belImposto.belIss.Valiq != null ? new XElement(pf + "vAliq", det.belImposto.belIss.Valiq.ToString("#0.00").Replace(",", ".")) : null),
                                     (det.belImposto.belIss.Vissqn != null ? new XElement(pf + "vISSQN", det.belImposto.belIss.Vissqn.ToString("#0.00").Replace(",", ".")) : null),
                                     (det.belImposto.belIss.Cmunfg != null ? new XElement(pf + "cMunFG", det.belImposto.belIss.Cmunfg.ToString()) : null),
                                     (det.belImposto.belIss.Clistserv != null ? new XElement(pf + "cListServ", det.belImposto.belIss.Clistserv.ToString()) : null),
                                     (det.belImposto.belIss.cSitTrib != null ? new XElement(pf + "cSitTrib", det.belImposto.belIss.cSitTrib.ToString()) : null)) : null)), // NFe_2.0 Tratar item


                                 //-----------INFADPROD-------------//

                                 (det.belInfadprod != null ?
                                 (det.belInfadprod.Infadprid != null ? new XElement(pf + "infAdProd", det.belInfadprod.Infadprid.ToString()) : null) : null))); //Danner - o.s. sem -21/12/2009

                            lcondet.Add(condet);
                        }
                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML, Regiao XML_Detalhes - " + x.Message);
                    }
                    #endregion

                    //Total
                    XContainer contotal;

                    try
                    {
                        belTotal objtotal = i[5] as belTotal;
                        #region XML_Total

                        contotal = (new XElement(pf + "total",
                                                (objtotal.belIcmstot != null ? new XElement(pf + "ICMSTot",
                                                      new XElement(pf + "vBC", objtotal.belIcmstot.Vbc.ToString("#0.00").Replace(",", ".")),//Danner - o.s. 24271 - 15/03/2010
                                                      new XElement(pf + "vICMS", objtotal.belIcmstot.Vicms.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vBCST", objtotal.belIcmstot.Vbcst.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vST", objtotal.belIcmstot.Vst.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vProd", objtotal.belIcmstot.Vprod.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vFrete", objtotal.belIcmstot.Vfrete.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vSeg", objtotal.belIcmstot.Vseg.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vDesc", objtotal.belIcmstot.Vdesc.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vII", objtotal.belIcmstot.Vii.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vIPI", objtotal.belIcmstot.Vipi.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vPIS", objtotal.belIcmstot.Vpis.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vCOFINS", objtotal.belIcmstot.Vcofins.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vOutro", objtotal.belIcmstot.Voutro.ToString("#0.00").Replace(",", ".")),
                                                      new XElement(pf + "vNF", objtotal.belIcmstot.Vnf.ToString("#0.00").Replace(",", "."))) : null),



                                                (objtotal.belIssqntot != null ? new XElement(pf + "ISSQNtot",
                                                    new XElement(pf + "vServ", objtotal.belIssqntot.Vserv.ToString("#0.00").Replace(",", ".")),
                                                    new XElement(pf + "vBC", objtotal.belIssqntot.Vbc.ToString("#0.00").Replace(",", ".")),
                                                    new XElement(pf + "vISS", objtotal.belIssqntot.Viss.ToString("#0.00").Replace(",", ".")),
                                                    (objtotal.belIssqntot.Vpis != 0 ? new XElement(pf + "vPIS", objtotal.belIssqntot.Vpis.ToString("#0.00").Replace(",", ".")) : null),
                                                    (objtotal.belIssqntot.Vcofins != 0 ? new XElement(pf + "vCOFINS", objtotal.belIssqntot.Vcofins.ToString("#0.00").Replace(",", ".")) : null)) : null)));
                        //(objtotal.belRetTrib != null ? new XElement(pf + "retTrib",
                        //                                   new XElement(pf + "vRetPIS", objtotal.belRetTrib.Vretpis.ToString("#0.00").Replace(",", ".")),
                        //                                   new XElement(pf + "vRetCOFINS", objtotal.belRetTrib.Vretcofins.ToString("#0.00").Replace(",", ".")),
                        //                                   new XElement(pf + "vRetCSLL", objtotal.belRetTrib.Vretcsll.ToString("#0.00").Replace(",", ".")),
                        //                                   new XElement(pf + "vBCIRRF", objtotal.belRetTrib.Vbcirrf.ToString("#0.00"),
                        //                                   new XElement(pf + "vIRRF", objtotal.belRetTrib.Virrf.ToString("#0.00").Replace(",", ".")),
                        //                                   new XElement(pf + "vBCRetPrev", objtotal.belRetTrib.Vbcretprev.ToString("#0.00").Replace(",", ".")),
                        //                                   new XElement(pf + "vRetPrev", objtotal.belRetTrib.Vretprev.ToString("#0.00").Replace(",", "."))) : null)));

                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML, Regiao XML_Total - " + x.Message);
                    }
                    //Fim - Total

                    //Frete
                    XContainer contransp;
                    belTransp objtransp;
                    try
                    {
                        objtransp = i[6] as belTransp;
                        #region XML_Transporte

                        contransp = (new XElement(pf + "transp",
                                                   new XElement(pf + "modFrete", objtransp.Modfrete.ToString()),
                                                   new XElement(pf + "transporta",
                                                       (objtransp.belTransportadora.Cnpj != null ? new XElement(pf + "CNPJ", objtransp.belTransportadora.Cnpj.ToString()) :
                                                                                                   (objtransp.belTransportadora.Cpf != null ? new XElement(pf + "CPF", objtransp.belTransportadora.Cpf.ToString()) : null)),
                                                       (objtransp.belTransportadora.Xnome != null ? new XElement(pf + "xNome", objtransp.belTransportadora.Xnome.ToString()) : null),
                                                       (objtransp.belTransportadora.Ie != null ? new XElement(pf + "IE", objtransp.belTransportadora.Ie.ToString()) : null),
                                                       (objtransp.belTransportadora.Xender != null ? new XElement(pf + "xEnder", objtransp.belTransportadora.Xender.ToString()) : null),
                                                       (objtransp.belTransportadora.Xmun != null ? new XElement(pf + "xMun", objtransp.belTransportadora.Xmun.ToString()) : null),
                                                       (objtransp.belTransportadora.Uf != null ? new XElement(pf + "UF", objtransp.belTransportadora.Uf.ToString()) : null)),
                (objtransp.belRetTransp != null ? (new XElement(pf + "retTransp",
                                                       new XElement(pf + "vServ", objtransp.belRetTransp.Vserv.ToString("#0.00").Replace(',', '.')),
                                                       new XElement(pf + "vBCRet", objtransp.belRetTransp.Vbvret.ToString("#0.00").Replace(',', '.')),
                                                       new XElement(pf + "pICMSRet", objtransp.belRetTransp.Picmsret.ToString()),
                                                       new XElement(pf + "vICMSRet", objtransp.belRetTransp.Vicmsret.ToString("#0.00").Replace(',', '.')),
                                                       new XElement(pf + "CFOP", objtransp.belRetTransp.Cfop.ToString()),
                                                       new XElement(pf + "cMunFG", objtransp.belRetTransp.Cmunfg.ToString()))) : null),
                (objtransp.belVeicTransp != null ? (new XElement(pf + "veicTransp",
                                                       (objtransp.belVeicTransp.Placa != null ? new XElement(pf + "placa", objtransp.belVeicTransp.Placa.ToString()) : null),
                                                       (objtransp.belVeicTransp.Uf != null ? new XElement(pf + "UF", objtransp.belVeicTransp.Uf.ToString()) : null),
                                                       (objtransp.belVeicTransp.Rntc != null ? new XElement(pf + "RNTC", objtransp.belVeicTransp.Rntc.ToString()) : null))) : null),
                   (objtransp.belReboque != null ? new XElement(pf + "reboque",
                                                       (objtransp.belReboque.Placa != null ? new XElement(pf + "placa", objtransp.belReboque.Placa.ToString()) : null),
                                                       (objtransp.belReboque.Uf != null ? new XElement(pf + "UF", objtransp.belReboque.Uf.ToString()) : null),
                                                       (objtransp.belReboque.Rntc != null ? new XElement(pf + "RNTC", objtransp.belReboque.Rntc.ToString()) : null)) : null),
                       (objtransp.belVol != null ? new XElement(pf + "vol",
                                                       new XElement(pf + "qVol", objtransp.belVol.Qvol.ToString("#")),
                                                       new XElement(pf + "esp", objtransp.belVol.Esp.ToString()),
                                                       new XElement(pf + "marca", objtransp.belVol.Marca.ToString()),
                                                       (objtransp.belVol.Nvol != null ? new XElement(pf + "nVol", objtransp.belVol.Nvol.ToString()) : null),//Danner - o.s. 24385 - 26/04/2010
                                                       new XElement(pf + "pesoL", objtransp.belVol.PesoL.ToString("#0.000").Replace(",", ".")),
                                                       new XElement(pf + "pesoB", objtransp.belVol.PesoB.ToString("#0.000").Replace(",", "."))) : null),
                   (objtransp.belLacres != null ? new XElement(pf + "lacres",
                                                       new XElement(pf + "nLacre", "")) : null)));



                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML, Regiao XML_Transporte - " + x.Message);
                    }
                    //Fim - Frete

                    //Duplicata
                    XContainer concobr;
                    belCobr objcob;
                    try
                    {
                        objcob = i[7] as belCobr;
                        belGerarXML BuscaConexao = new belGerarXML();
                        #region XML_Cobrança
                        concobr = (new XElement(pf + "cobr",
                                                  new XElement(pf + "fat",
                                                      new XElement(pf + "nFat", objcob.belFat.Nfat.ToString()),
                                                      (objcob.belFat.Vorig != 0 ? new XElement(pf + "vOrig", objcob.belFat.Vorig.ToString("#0.00").Replace(",", ".")) : null),
                                                      (objcob.belFat.Vdesc != null && objcob.belFat.Vdesc != 0 ? new XElement(pf + "vDesc", objcob.belFat.Vdesc.ToString("#0.00").Replace(",", ".")) : null),
                                                      (objcob.belFat.Vliq != 0 ? new XElement(pf + "vLiq", objcob.belFat.Vliq.ToString("#0.00").Replace(",", ".")) : null)),
                                                      (objcob.belFat.belDup != null ? from dup in objcob.belFat.belDup
                                                                                      select new XElement(pf + "dup", new XElement(pf + "nDup", dup.Ndup.ToString()),
                                                                                             new XElement(pf + "dVenc", dup.Dvenc.ToString("yyyy-MM-dd")),
                                                                                             (BuscaConexao.nm_Cliente != "LORENZON" ? new XElement(pf + "vDup", dup.Vdup.ToString("#0.00").Replace(",", ".")) : null)) : null)));

                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML, Region XML_Cobrança - " + x.Message);
                    }
                    //Fim - Duplicata

                    //Obs
                    XContainer conobs;
                    belInfAdic objobs;
                    try
                    {
                        objobs = i[8] as belInfAdic;
                        #region XML_Obs
                        conobs = new XElement(pf + "infAdic",
                                                    (objobs.Infcpl != null ?
                                                    new XElement(pf + "infCpl", objobs.Infcpl.ToString()) : null));
                        #endregion
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na geração do XML,Regiao XML_Obs - " + x.Message);
                    }
                    //Fim - Obs

                    //Uniao dos Containers
                    try
                    {
                        concabec.Add(coninfnfe);
                        coninfnfe.Add(conide);
                        conide.AddAfterSelf(conemit);
                        conemit.AddAfterSelf(condest);
                        condest.AddAfterSelf(contotal);
                        contotal.AddAfterSelf(contransp);

                        if (concobr != null)
                        {
                            contransp.AddAfterSelf(concobr);
                            if (objobs.Infcpl != null)
                                concobr.AddAfterSelf(conobs);
                        }
                        else
                        {
                            if (objobs.Infcpl != null)
                                contransp.AddAfterSelf(conobs);
                        }

                        foreach (XElement x in lcondet)
                        {
                            contotal.AddBeforeSelf(x);
                        }
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro na montagem do XML, União dos Containers - " + x.Message);
                    }
                    try
                    {
                        AssinaNFeXml Assinatura = new AssinaNFeXml();
                        string nfe = Assinatura.ConfigurarArquivo(concabec.ToString(), "infNFe", cert);
                        nfes.Add(nfe);
                        XElement xnfe = XElement.Parse(nfe);
                        XDocument xdocsalvanfesemlot = new XDocument(xnfe);

                        DirectoryInfo dPastaData = new DirectoryInfo(glob.LeRegConfig("PastaXmlEnvio").ToString() + "\\" + sNFe.Substring(5, 4));
                        if (!dPastaData.Exists) { dPastaData.Create(); }
                        if (sFormaEmiNFe.Equals("2"))
                        {
                            xdocsalvanfesemlot.Save(glob.LeRegConfig("PastaContingencia").ToString() + "\\" + sNFe.Replace("NFe", "") + "-nfe.xml");
                        }
                        else
                        {
                            xdocsalvanfesemlot.Save(glob.LeRegConfig("PastaXmlEnvio").ToString() + "\\" + sNFe.Substring(5, 4) + "\\" + sNFe.Replace("NFe", "") + "-nfe.xml"); // OS_25024
                        }
                        //StreamWriter swnfe = new StreamWriter(glob.LeRegWin("PastaXmlEnvio").ToString() + "\\" + sNFe.Replace("NFe", "") + "-nfe.xml");
                        //swnfe.Write(nfe);
                        //swnfe.Close();
                    }
                    catch (Exception x)
                    {
                        throw new Exception("Nota de Sequência - " + sNota + "Erro ao assinar a nfe de sequencia " + sNota + x.Message);
                    }

                    iCount++;
                }

                //Concatenando as NFes.
                string sXmlComp = "";
                //Junta todos os XML's em texto 
                foreach (var i in nfes)
                {
                    sXmlComp = sXmlComp + i;
                }
                //Estou inserindo o enviNFe pois se eu transformar o arquivo xml assinado em xml e depois em testo usando um toString,
                //a assinatura se torna invalida. Então depois de assinado do trabalho em forma de testo como xml ateh envia-lo pra fazenda.                        
                sXmlfull = "<?xml version=\"1.0\" encoding=\"utf-8\"?><enviNFe xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"2.00\"><idLote>" +
                            sNomeArq.Substring(7, 15) + "</idLote>" + sXmlComp + "</enviNFe>";

                //Grava
                StreamWriter sw = new StreamWriter(sPath);
                sw.Write(sXmlfull);
                sw.Close();

                #region Valida_Xml

                Globais getschema = new Globais();

                //string sXml = File.OpenText(sPath).ReadToEnd();

                XmlSchemaCollection myschema = new XmlSchemaCollection();

                XmlValidatingReader reader;

                //Danner - o.s. 23732 - 06/11/2009

                try
                {
                    XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                    reader = new XmlValidatingReader(sXmlfull, XmlNodeType.Element, context);

                    myschema.Add("http://www.portalfiscal.inf.br/nfe", getschema.LeRegConfig("PastaSchema") + "\\enviNFe_v2.00.xsd");

                    reader.ValidationType = ValidationType.Schema;

                    reader.Schemas.Add(myschema);

                    while (reader.Read())
                    {

                    }

                }
                catch (XmlException x)
                {
                    File.Delete(sPath);
                    throw new Exception(x.Message);
                }
                catch (XmlSchemaException x)
                {
                    File.Delete(sPath);
                    throw new Exception(x.Message);
                }

                //Fim - Danner - o.s. 23732 - 06/11/2009

                #endregion

            }
            catch (Exception ex)
            {
                Conn.Close();
                throw ex;
            }
            finally { Conn.Close(); }
        }
        private void validate()
        {
            //clear Results

            resultsBox.Clear();
            validationErrors = 0;

            //set parsing context and configure readers

            XmlParserContext context = new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None);

            //Initialize readers using the context

            xmlReader = new XmlTextReader(xmlSourceBox.Text, XmlNodeType.Element, context);
            schemaReader = new XmlTextReader(schemaSourceBox.Text, XmlNodeType.Element, context);

            XmlValidatingReader validator = new XmlValidatingReader(xmlReader);

            //set validation type to use an XSD schema
            validator.ValidationType = ValidationType.Schema;

            //load schema into xmlschemacollection using specified target namespace

            XmlSchemaCollection schemaCollection = new XmlSchemaCollection();

            try
            {
                schemaReader.Read();
                schemaCollection.Add(schemaReader.GetAttribute("targetNamespace"), schemaReader);
            }
            catch (Exception ex)
            {
                //error parsing schema, display error and quit validation

                appendResult("Read/Parser Error: " + ex.Message);
                return;

            }

            //load schema into the validator
            validator.Schemas.Add(schemaCollection);

            //configure validator event handler to handle errors
            validator.ValidationEventHandler += new ValidationEventHandler(validationError);

            try
            {
                while (validator.Read())
                {
                    // parse xml document, calling validationError as required
                }

                //display completion info

                appendResult("Validation Complete. " + validationErrors + "error(s) found.");
            }

            catch (Exception ex)
            {
                //xml document parsing error, display information

                appendResult("Read/Parse Error: " + ex.Message);
            }

            finally
            {
                //close readers
                xmlReader.Close();
                schemaReader.Close();
            }
        }