Criar DLL C# para ser utilizada no Delphi 7

Pessoal,

Preciso chamar um serviço da Sefaz em nosso ERP, usamos Delphi 7.
Bom com as pesquisas no Google descobrimos que o Delphi 7 para usar HTTPS é um parto e que não compensa investir tempo nisso.

Logo pensamos em criar uma DLL em C#. Seguimos alguns tutoriais e chegamos a chamar a nossa DLL no Delphi, como na Informática nada funciona de primeira, tivemos os seguintes problemas:

Primeiro: Quando gera a DLL no Visual Studio o arquivo app.config não vai junto com a DLL, com isso quando é chamado o endpoint, um erro é lançado, não sabemos como resolver.

Segundo: Quando mandamos registrar a DLL no Windows esta gerando a seguinte mensagem:

Aviso: O exportador da biblioteca de tipos encontrou uma instância de tipo genérico em uma assinatura. Não é possível exportar o código genérico para COM.

Esse erro é da classe que o Wizard do Visual Studio gera no WSDL da Sefaz, colocamos as anotações sugeridas e mesmo assim não tivemos sucesso.

Bom, como não avançamos nesses 2 problemas, então não sei se vamos encontrar mais algum!

Queria a ajuda de vocês, em como solucionar esses problemas ou apresentando alguma outra solução viável.

Apresentamos a biblioteca ACBr para o gestor do projeto, fomos barrado com o um “fatality master”.

Att

Vinicius Castro

Sem o código fonte fica mais difícil pra alguém ajudar aqui. Caso esteja no desespero, uma alternativa feia, porém com menos obstáculos, seria criar uma aplicação console em C# fazendo tudo que tem quer feito e seu programa em Delphi chama esse executável feito em C# via shellexecute.

Pensamos nisso. Isso seria o ultimo caso mesmo. Vou postar os fontes.

Segue os fontes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace DFeUtil
{
    [InterfaceType(ComInterfaceType.InterfaceIsDual),
    Guid("87877628-A903-4A53-B2ED-3EB62DA2669F"),
    ComVisible(true)]
    public interface IDFeUtil
    {
        string NFeDistribuicaoDFe(string xml_string);
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Xml.Linq;
using System.Runtime.InteropServices;

namespace DFeUtil
{
    [ClassInterface(ClassInterfaceType.None),
    Guid("D90EB076-AC36-4C4C-AB6E-00EF53916EF2"),
    ComVisible(true),
    ProgId("DFeUtilCOM")]
    public class DFeUtilClass : IDFeUtil
    {   
        private string GetSerialCertificado()
        {
            string ns = string.Empty;
            X509Store store = new X509Store("My");
            store.Open(OpenFlags.ReadOnly);
            foreach (var certificado in store.Certificates)
            {
                if (certificado.SubjectName.Name.Contains("02603104683"))
                {
                    ns = certificado.SerialNumber;
                }
            }
            store.Close();
            return ns;
        }

        public string NFeDistribuicaoDFe(string xml_string)
        {
            string retorno = string.Empty;
            try
            {
                string ns = GetSerialCertificado();
                XElement xml = XElement.Parse(xml_string.ToString());
                var NFe_Sc = new NFeDistribuicaoDFe.NFeDistribuicaoDFeSoapClient();
                NFe_Sc.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySerialNumber, ns);
                retorno = NFe_Sc.nfeDistDFeInteresse(xml).ToString();
            }
            catch (Exception ex)
            {
                retorno = ex.Message;
            }
            return retorno;
        }
    }
}


using System.Runtime.InteropServices;
namespace DFeUtil.NFeDistribuicaoDFe {


[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("07ED96BC-A53A-453B-AC46-6430C462A922"),
ComVisible(true)]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe", ConfigurationName="NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap")]
public interface NFeDistribuicaoDFeSoap {
    
    // CODEGEN: Generating message contract since element name nfeDadosMsg from namespace http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe is not marked nillable
    [System.ServiceModel.OperationContractAttribute(Action="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe/nfeDistDFeInteresse", ReplyAction="*")]
    DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponse nfeDistDFeInteresse(DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest request);
    
    [System.ServiceModel.OperationContractAttribute(Action="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe/nfeDistDFeInteresse", ReplyAction="*")]
    System.Threading.Tasks.Task<DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponse> nfeDistDFeInteresseAsync(DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest request);
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class nfeDistDFeInteresseRequest {
    
    [System.ServiceModel.MessageBodyMemberAttribute(Name="nfeDistDFeInteresse", Namespace="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe", Order=0)]
    public DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequestBody Body;
    
    public nfeDistDFeInteresseRequest() {
    }
    
    public nfeDistDFeInteresseRequest(DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequestBody Body) {
        this.Body = Body;
    }
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe")]
public partial class nfeDistDFeInteresseRequestBody {
    
    [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
    public System.Xml.Linq.XElement nfeDadosMsg;
    
    public nfeDistDFeInteresseRequestBody() {
    }
    
    public nfeDistDFeInteresseRequestBody(System.Xml.Linq.XElement nfeDadosMsg) {
        this.nfeDadosMsg = nfeDadosMsg;
    }
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class nfeDistDFeInteresseResponse {
    
    [System.ServiceModel.MessageBodyMemberAttribute(Name="nfeDistDFeInteresseResponse", Namespace="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe", Order=0)]
    public DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponseBody Body;
    
    public nfeDistDFeInteresseResponse() {
    }
    
    public nfeDistDFeInteresseResponse(DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponseBody Body) {
        this.Body = Body;
    }
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.Runtime.Serialization.DataContractAttribute(Namespace="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe")]
public partial class nfeDistDFeInteresseResponseBody {
    
    [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
    public System.Xml.Linq.XElement nfeDistDFeInteresseResult;
    
    public nfeDistDFeInteresseResponseBody() {
    }
    
    public nfeDistDFeInteresseResponseBody(System.Xml.Linq.XElement nfeDistDFeInteresseResult) {
        this.nfeDistDFeInteresseResult = nfeDistDFeInteresseResult;
    }
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface NFeDistribuicaoDFeSoapChannel : DFeUtil.NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap, System.ServiceModel.IClientChannel {
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[ClassInterface(ClassInterfaceType.None),
Guid("872F6FCA-F012-4366-AB36-A2C126B5B7D0"),
ComVisible(true),
ProgId("DFeUtilCOM")]
public partial class NFeDistribuicaoDFeSoapClient : System.ServiceModel.ClientBase<DFeUtil.NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap>, DFeUtil.NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap {
    
    public NFeDistribuicaoDFeSoapClient() {
    }
    
    public NFeDistribuicaoDFeSoapClient(string endpointConfigurationName) : 
            base(endpointConfigurationName) {
    }
    
    public NFeDistribuicaoDFeSoapClient(string endpointConfigurationName, string remoteAddress) : 
            base(endpointConfigurationName, remoteAddress) {
    }
    
    public NFeDistribuicaoDFeSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(endpointConfigurationName, remoteAddress) {
    }
    
    public NFeDistribuicaoDFeSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress) {
    }
    
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponse DFeUtil.NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap.nfeDistDFeInteresse(DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest request) {
        return base.Channel.nfeDistDFeInteresse(request);
    }
    
    public System.Xml.Linq.XElement nfeDistDFeInteresse(System.Xml.Linq.XElement nfeDadosMsg) {
        DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest inValue = new DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest();
        inValue.Body = new DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequestBody();
        inValue.Body.nfeDadosMsg = nfeDadosMsg;
        DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponse retVal = ((DFeUtil.NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap)(this)).nfeDistDFeInteresse(inValue);
        return retVal.Body.nfeDistDFeInteresseResult;
    }
    
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    System.Threading.Tasks.Task<DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponse> DFeUtil.NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap.nfeDistDFeInteresseAsync(DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest request) {
        return base.Channel.nfeDistDFeInteresseAsync(request);
    }
    
    public System.Threading.Tasks.Task<DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseResponse> nfeDistDFeInteresseAsync(System.Xml.Linq.XElement nfeDadosMsg) {
        DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest inValue = new DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequest();
        inValue.Body = new DFeUtil.NFeDistribuicaoDFe.nfeDistDFeInteresseRequestBody();
        inValue.Body.nfeDadosMsg = nfeDadosMsg;
        return ((DFeUtil.NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap)(this)).nfeDistDFeInteresseAsync(inValue);
    }
}

}

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
              <binding name="NFeDistribuicaoDFeSoap">
                <security mode="Transport">
                  <transport clientCredentialType="Certificate" proxyCredentialType="None" realm="" />
                </security>
              </binding>
                <binding name="NFeDistribuicaoDFeSoap1" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://hom.nfe.fazenda.gov.br/NFeDistribuicaoDFe/NFeDistribuicaoDFe.asmx"
                binding="basicHttpBinding" bindingConfiguration="NFeDistribuicaoDFeSoap"
                contract="NFeDistribuicaoDFe.NFeDistribuicaoDFeSoap" name="NFeDistribuicaoDFeSoap" />
        </client>
    </system.serviceModel>
</configuration>

No aguardo de ideias!

Vi um pessoal usando HttpListener no C#, Alguém tem algum exemplo de como utilizar?