Inquiridor
Validação de arquivo XML do NFServico eletronica da PBH

Pergunta
-
Pessoal bom dia.
Estou desenvolvedo uma aplicacao c# para envio de NFServico eletronica, e estou encontrando erro na hora de validar o arquivo xml.
Inclusive, estou validando um arquivo xml passado pela prefeitura como exemplo.
O que ocorre, é que eles criaram um xsd servico_gerar_nfse_envio.xsd e neste arquivo, eles apontam
outros xsd´s. Um deles é este "tipos_complexos.xsd" que é apontado no erro.
veja em "http://bhisshomologa.pbh.gov.br/bhiss-ws/schemas/servico_gerar_nfse_envio.xsd"
O erro que ocorre no event handler é
O exemplo de validação que utilizo está em http://support.microsoft.com/kb/307379/pt-br.
Validdation event
Could not find schema information for the elemente http://bhissdigital.pbh.gov.br/bhiss-ws/schemas/tipos_complexos.xsd:compNfse;
OBS: Tentei utilizar a validação por cache, onde adicionei os dois xsd e tambem ocorreu o mesmo erro.
Alguem poderia ajudar?
obrigado.
bom trabalho a todos.
Todas as Respostas
-
-
Oi Ari.
Sim, está no endereço abaixo, em "Notas fiscais" que está no centro da tela (abaixo de Exemplos de arquivos XML).
http://www.pbh.gov.br/bhissdigital/portal/index.php?content=nfse/documentacao.php
É um arquivo zip, o arquivo interno "nfse_200900000000017_normal.xml"
Desde já obrigado. -
-
-
Existe um sistema para controle completo de NFS-e, é o CW NFS-e da Conceito W. Atende Belo Horizonte.
Este software importa dados de outros sistemas, faz todo controle de geração de lotes e RPS (em cidades que tem RPS), envia para o portal e armazena o retorno. O software está homologado para várias prefeituras do Brasil, e também para BH, onde já tem clientes utilizando.
A solução é simples para utilizar, implantar e tem baixo custo, vale pesquisar antes de desenvolver.
É uma ótima opção também para empresas de TI, que podem gerar um layout e importar no CW NFS-e, que se necessário, também tem um software complementar para agendar a integração, mas na maioria dos casos é viável o usuário importar o arquivo manualmente.
-
Tenho más notícias para tiO pessoal da prefeitura não sabe o que fez, eles compraram uma dll fechada (caixa preta) de assinatura, e não podem repassar, não sabem como funciona, e eles não possuem exemplos de código de assinatura, uma ingerência total, de qualquer forma, parece que há programas pagos que funcionam (imagino que são os mesmos que venderam para prefeitura) e também algum exemplo em java que funciona, por isso, depois de alguns dias tentando fazer funcionar em C#, estamos mudando para java.
Mas se tiver sucesso, por favor, poste aqui !!
Abraços -
Olá eu já estou conseguindo enviar as minhas "rps" normalmente.
Vou colocar o codigo que eu fiz em C# para pegar os dados do certificado, assinar e validar a assinatura.
Depois é preciso adicionar o XML assinado em um lote e assinar o lote tbém. Mas aí é outra história.....
Function: X509Certificate2Collection
String _xnome: contém o nome do certificado. Com este parametro a janela para selecionar os cerificados existentes na máquina não será aberta.
Returns: Class X509Certificate2Collectionpublic static X509Certificate2Collection CheckCertificate(string _xnome)
{
X509Certificate2 _X509Cert = new X509Certificate2();
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, _xnome, false);
return collection1;
}
------------
Function: SignXmlFileParametros (4)
string FileName: Documento XML a ser assinado
string SignedFileName: Documento XML assinado
string URI: Elemento XML a ser assinado
Class X509Certificate2 X509Cert: Classe contendo os atributos do certificado digital obtido na rotina anteriorpublic static void SignXmlFile(string FileName, string SignedFileName, string URI, X509Certificate2 X509Cert)
{
// Create a new XML document for loading the XML to be signed
XmlDocument doc = new XmlDocument();
// Format the document to ignore white spaces.
doc.PreserveWhitespace = false;
// Load the passed XML file using it's name.
doc.Load(new XmlTextReader(FileName));
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
// Add the key of the certificate to the SignedXml document
signedXml.SigningKey = X509Cert.PrivateKey; // CHAVE PRIVADA DO CERTIFICADO DIGITAL
// Load the certificate into a KeyInfoX509Data object and add it to the KeyInfo object.
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(X509Cert));
// Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyInfo;
// Create a reference to be signed.
Reference reference = new Reference();
// Search for the URI to be signed. (it must find only one)
XmlAttributeCollection _Uri = doc.GetElementsByTagName(URI).Item(0).Attributes;
foreach (XmlAttribute _atributo in _Uri)
{
if (_atributo.Name == "Id")
{
reference.Uri = "#" + _atributo.InnerText;
URI = "Ass_" + _atributo.InnerText;
}
}
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Specify a canonicalization method BEFORE singing
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigC14NWithCommentsTransformUrl;
// Add the signature to the SignedXml object.
signedXml.AddReference(reference);
// add an ID in the signature tag
signedXml.Signature.Id = signedXml.Signature.Id + URI;
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the signature element to the XML document.
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
// Remove the xml declaration if the new outputted xml contains the standard
// xml format declaration <?xml version=’1.0…>:
if (doc.FirstChild is XmlDeclaration)
{
doc.RemoveChild(doc.FirstChild);
}
// Write out the final signed XML file //
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.PreserveWhitespace = false;
XMLDoc = doc;
// Save the signed XML document to a file specified using the passed string.
XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
doc.WriteTo(xmltw);
xmltw.Close();
}
---------
Function name: VerifyXmlFile
Description: This function validates an XML document signed with an enveloped XML Signature generated using X509 certificates.Parameters (3)
string Name: XML document signed
Class X509Certificate2 X509Cert: Class containing the certificate attributes
Int _num: index of the signature nodelist to be validated.
public static Boolean VerifyXmlFile(String Name, X509Certificate2 X509Cert, int _num)
{
// Create a new XML document.
XmlDocument xmlDocument = new XmlDocument();
// Format using white spaces.
xmlDocument.PreserveWhitespace = true;
// Load the passed XML file into the document.
xmlDocument.Load(Name);
// Create a new SignedXml object and pass it the XML document class.
SignedXml signedXml = new SignedXml(xmlDocument);
// Find the "Signature" node and create a new XmlNodeList object.
XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");
// Load the signature node.
signedXml.LoadXml((XmlElement)nodeList[_num]);
// Check the signature and return the result.
return signedXml.CheckSignature(X509Cert, false);
}
-
Conheço também uma empresa em Belo Horizonte que especializou na integração com a prefeitura de Belo Horizonte. A integração é feita com arquivos XML, TXT ou no banco de dados e muito fácil a utilização.
Especialmente para empresas que tenham desenvolvimento próprio e que queiram manter seu foco nos negócios da empresa, utilizar o software deles pode agilizar bastante o tempo de resultado.
www.sobdemanda.net -
-
Olá, Branca_mm.
Estou desenvolvendo um aplicativo em C# para trabalhar com nota fiscal eletrônica de serviço da PBH e P.Contagem-MG. Estou precisando de repassar alguns serviços. A forma de contratação é negociável (contrato temporário / freelancer ou outra de seu interesse).
Se for do seu interesse, favor me contactar pelo e-mail: elias.cena@infocena.com.br
Obrigado.