SeFaz Consulta Cadastro

06/11/2013

0

Bom dia,

Estou com um problema gigante que é o consumo do web service de Consulta de Cadastro.
Estou fazendo em C#, desenvolvendo uma DLL para consulta para poder chamar em um sistema de terceiro.

Porém estou usando SOAP 1.2 e o bidding é o customBidding.

Quando executo ocorre o seguinte problema:

System.InvalidOperationException: O nome de usuário não foi fornecido. Especifique o nome de usuário em ClientCredentials.

Alguém já passou por isso?

Josivan Laskoski

Josivan Laskoski

Responder

Post mais votado

05/01/2016

Tenho um projeto no qual estou trabalhando em casa, infelizmente não sincronizei ele ainda com o servidor, mas posso ver a noite se consigo te passar.

Já tentou algo assim?

    SEUWS.ClientCredentials.UserName.UserName = "SEU_USUARIO";
    SEUWS.ClientCredentials.UserName.Password = "SUA_SENHA";


Isso tudo antes de invocar o método que executa a chamada direta do WS?

Josivan Laskoski

Josivan Laskoski
Responder

Mais Posts

18/11/2013

Fabio Nascimento..

Você informou o certificado A1?
Há um propriedade ClientCredentials onde vc o informa.
Responder

05/01/2016

Victor Boechat

O que fez para resolver?

Estou passando o mesmo problema e não encontro solução de jeito nenhum.
Responder

05/01/2016

Josivan Laskoski

Boa tarde

Desculpe pela falta de respostas, acabei até esquecendo desse post, que ainda estava em um email antigo que não usava mais.

Basicamente fiz dessa forma que segue o codigo abaixo.

Adicionei a referencia do WS da SeFaz como uma Web References com o nome de CadConsultaWebEstados.

public class SeFazConsultaWebEstados
    {
        private CadConsultaWebEstados.CadConsultaCadastro2 cons = new CadConsultaWebEstados.CadConsultaCadastro2();
        private CadConsultaWebEstados.nfeCabecMsg cab = new CadConsultaWebEstados.nfeCabecMsg();

        [WebMethod]
        public String ConsultaCadastro(string _uf, string _versaoDados, string _ufConsulta, string _ieContribuinte, string _cnpj, string _cpf, string _caminhoCertificadoDigital, string _senhaCertificadoDigital, string _Url)
        {
            /********************* Certificado **********************************/
            X509Certificate2 certificado = new X509Certificate2(_caminhoCertificadoDigital, _senhaCertificadoDigital, X509KeyStorageFlags.PersistKeySet);
            /********************* Certificado **********************************/



            /********************* Estrutura XML Envio **********************************/
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", String.Empty));

            XmlNode nodeCab = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "ConsCad", "");

            XmlAttribute atributoVersao = xmlDoc.CreateAttribute("versao");
            atributoVersao.Value = _versaoDados;
            nodeCab.Attributes.Append(atributoVersao);



            XmlAttribute atributoxml = xmlDoc.CreateAttribute("xmlns");
            atributoxml.Value = "http://www.portalfiscal.inf.br/nfe";
            nodeCab.Attributes.Append(atributoxml);

            xmlDoc.AppendChild(nodeCab);


            XmlNode nodeInf = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "infCons", "");
            nodeCab.AppendChild(nodeInf);

            XmlNode userNode = xmlDoc.CreateElement("xServ");
            userNode.InnerText = "CONS-CAD";
            nodeInf.AppendChild(userNode);

            userNode = xmlDoc.CreateElement("UF");
            userNode.InnerText = _ufConsulta;
            nodeInf.AppendChild(userNode);


            if (!_ieContribuinte.Equals(""))
            {
                userNode = xmlDoc.CreateElement("IE");
                userNode.InnerText = _ieContribuinte;
                nodeInf.AppendChild(userNode);
            }


            if (!_cnpj.Equals(""))
            {
                userNode = xmlDoc.CreateElement("CNPJ");
                userNode.InnerText = _cnpj;
                nodeInf.AppendChild(userNode);
            }


            if (!_cpf.Equals(""))
            {
                userNode = xmlDoc.CreateElement("CPF");
                userNode.InnerText = _cpf;
                nodeInf.AppendChild(userNode);
            }
            /********************* Estrutura XML Envio **********************************/






            /********************* Configuracao **********************************/
            cons.Timeout = 70000;
            cons.nfeCabecMsgValue = cab;
            cons.nfeCabecMsgValue.cUF = _uf;
            cons.nfeCabecMsgValue.versaoDados = _versaoDados;
            cons.Url = _Url;
            cons.ClientCertificates.Add(certificado);

            /********************* Transforma XML em String **********************************/
            XmlDocument xmld = new XmlDocument();
            xmld.LoadXml(xmlDoc.InnerXml.ToString());
            /********************* Transforma XML em String **********************************/


            /********************* Envio e Retorno **********************************/
            XmlNode status = cons.consultaCadastro2(xmld);
            

            String sTexto = status.InnerXml;
            sTexto =  sTexto.Substring(52, sTexto.Length - 52);
            sTexto = "<infCons >" + sTexto;

            XmlTextReader reader = new XmlTextReader(new StringReader(sTexto));
            ArrayList elementos = new ArrayList();

            String sNome = "";

            while ((reader.Read()))
            {
                if (!reader.Name.Equals("")){
                    sNome = reader.Name;
                }
                
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        //Se existirem atributos
                        if (reader.HasAttributes)
                        {
                            while (reader.MoveToNextAttribute())
                            {
                                //Pega o valor do atributo.
                                elementos.Add(sNome + "|");
                                elementos.Add(reader.Value + "|");
                            }
                        }
                        break;
                    case XmlNodeType.Text:
                        //Incluir o texto do elemento no ArrayList
                        elementos.Add(sNome + "|");
                        elementos.Add(reader.Value + "|");
                        break;
                }
            }


            String retorno = "";

            foreach (var num in elementos)
            {
                retorno = retorno + num;
            }

            return retorno;

        }


Espero que ajude!
Responder

05/01/2016

Victor Boechat

Você tem algum exemplo passando usuário e senha ao invés de usar o certificado digital como autenticação?
Responder

05/01/2016

Josivan Laskoski

Veja se isso te ajuda

Chamada da configuração:

var configuracao = Funcao.ConfiguracaoWebConfig(
                    "link");

                var enviaClient = new SI_ProcessaConsultaNFSync_OBClient(configuracao.binding,
                    configuracao.endPoint);
                enviaClient.ClientCredentials.UserName.UserName = usuario;
                enviaClient.ClientCredentials.UserName.Password = senha;


Função da Configuração

public static ConfiguracaoWS ConfiguracaoWebConfig(string link_endPoint)
        {
            try
            {
                var endPoint = new EndpointAddress(new Uri(link_endPoint));
                var basicHttpBinding = new BasicHttpBinding
                {
                    Name = "RequestSoap",
                    Security =
                    {
                        Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                        Transport =
                        {
                            ClientCredentialType = HttpClientCredentialType.Basic,
                            ProxyCredentialType = HttpProxyCredentialType.Basic
                        },
                        Message =
                        {
                            ClientCredentialType = BasicHttpMessageCredentialType.UserName
                        }
                    },
                    ReaderQuotas =
                    {
                        MaxStringContentLength = 2147483647,
                        MaxArrayLength = 2147483647,
                        MaxBytesPerRead = 2147483647,
                        MaxDepth = 2147483647,
                        MaxNameTableCharCount = 2147483647,
                    },
                    MaxBufferPoolSize = 52428800,
                    MaxBufferSize = 65536000,
                    MaxReceivedMessageSize = 65536000
                };

                return new ConfiguracaoWS
                {
                    endPoint = endPoint,
                    binding = basicHttpBinding
                };
            }
            catch (Exception ex)
            {
                return null;
            }

        public class ConfiguracaoWS
        {
            public EndpointAddress endPoint { get; set; }
            public BasicHttpBinding binding { get; set; }
        }

Responder

06/01/2016

Victor Boechat

Obrigado Josivan, o seu primeiro exemplo por mais simples que pareça era exatamente o que eu precisava.

Consegui informar o usuário e senha do WebService, no entanto retorna o seguinte erro:

Informações adicionais: A operação unidirecional retornou uma mensagem não nula com Ação=''.

Pensei que o problema fosse que eu estivesse informando algum atributo null ou em branco no objeto que estou enviando, no entanto não é isso. Alguém tem ideia do que seja?
Responder

06/01/2016

Josivan Laskoski

Que bom que lhe ajudou!

Victor, você tem o stack trace desse erro? Já tentou usar o SoapUI para fazer testes de conexão?
Responder

06/01/2016

Victor Boechat

Utilizei o SoapUI e está tudo ok.

Segue o StackTrace:

System.ServiceModel.ProtocolException não foi manipulada
  HResult=-2146233087
  Message=A operação unidirecional retornou uma mensagem não nula com Ação=''.
  Source=mscorlib
  StackTrace:
    Server stack trace: 
       em System.ServiceModel.Dispatcher.RequestChannelBinder.ValidateNullReply(Message message)
       em System.ServiceModel.Dispatcher.RequestChannelBinder.Send(Message message, TimeSpan timeout)
       em System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       em System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       em System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]: 
       em System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       em System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       em BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_Out.OP_ReceberVendSupSet(OP_ReceberVendSupSet request)
       em BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_OutClient.BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_Out.OP_ReceberVendSupSet(OP_ReceberVendSupSet request) na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Service References\Setores_Vendedores_Supervisores\Reference.cs:linha 386
       em BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_OutClient.OP_ReceberVendSupSet(DT_SetVendSup MT_SetVendSup) na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Service References\Setores_Vendedores_Supervisores\Reference.cs:linha 392
       em BoechatSoft.Integrador.Integracao.VendSupSet() na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Integracao.cs:linha 111
       em BoechatSoft.Integrador.Integracao.Integrar() na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Integracao.cs:linha 32
       em BoechatSoft.Integrador.IntegracaoFrm.button1_Click(Object sender, EventArgs e) na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\IntegracaoFrm.cs:linha 28
       em System.Windows.Forms.Control.OnClick(EventArgs e)
       em System.Windows.Forms.Button.OnClick(EventArgs e)
       em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       em System.Windows.Forms.Control.WndProc(Message& m)
       em System.Windows.Forms.ButtonBase.WndProc(Message& m)
       em System.Windows.Forms.Button.WndProc(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.Run(Form mainForm)
       em BoechatSoft.Integrador.Program.Main() na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Program.cs:linha 19
       em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       em System.Threading.ThreadHelper.ThreadStart()
  InnerException:
Responder

06/01/2016

Josivan Laskoski

Possivelmente isso esteja acontecendo por alguma configuração de buffer ou algo assim de seu WS.

Como voce está configurando o WS?
Responder

07/01/2016

Victor Boechat

Consegui resolver o problema!

Gostaria de agradecer pela ajuda!

Para resolver basta alterar a propriedade IsOneWay para false, no meu caso, essa propriedade ficava na assinatura dos métodos da interface de mapeamento com classe do WebService.
Responder

08/01/2016

Josivan Laskoski

Legal Victor.

Se possível vote nas respostas que te ajudaram e se puder, coloque aqui a parte do fonte que você resolveu isso.

Abraços
Responder

08/01/2016

Victor Boechat

Desculpa não ter feito isso antes, sou novato em fóruns rs

Segue o código

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(Namespace="http://xxxxxxxxxxx.com.br/INTEGRA_REVENDAS/receberPDV", ConfigurationName="PDV.SI_PDV_Out")]
    public interface SI_PDV_Out {
        
        // CODEGEN: Gerando contrato de mensagem porque a operação OP_ReceberPDV não é RPC nem documento codificado.
        [System.ServiceModel.OperationContractAttribute(IsOneWay=false, Action="http://xxx.com/xi/WebService/soap1.1")]
        [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
        void OP_ReceberPDV(BoechatSoft.Integrador.PDV.OP_ReceberPDV request);
        
        [System.ServiceModel.OperationContractAttribute(IsOneWay=false, Action="http://xxx.com/xi/WebService/soap1.1")]
        System.Threading.Tasks.Task OP_ReceberPDVAsync(BoechatSoft.Integrador.PDV.OP_ReceberPDV request);
    }


Alterei o IsOneWay de true para false
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar