开发者

How to create a WCF client without settings in config file?

开发者 https://www.devze.com 2023-03-12 09:39 出处:网络
I just start work on WCF a month ago. Please forgive me if I ask something already answered. I try to search first but found nothing.

I just start work on WCF a month ago. Please forgive me if I ask something already answered. I try to search first but found nothing.

I read this article, WCF File Transfer: Streaming & Chunking Channel Hosted In IIS. It works great. Now I like to integrate client side code to be part of my application, which is a dll running inside AutoCAD. If I want to work with config file, I have to change acad.exe.config which I don't think is a good idea. So I think if it possible, I want to move all code in config file to code.

Here is config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Mtom" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
              开发者_运维问答      maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default" />
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1"
            binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IService"
            contract="MGFileServerClient.IService"
            name="BasicHttpBinding_IService" />
    </client>
</system.serviceModel>

Could you please help me to make this change?


You can do all the setting up from within code, assuming that you don't need the flexibility to change this in the future.

You can read about setting up the endpoint on MSDN. Whilst this applies to the server the configuration of the endpoint and bindingd apply to the client as well, its just that you use the classes differently.

Basically you want to do something like:

// Specify a base address for the service
EndpointAddress endpointAdress = new EndpointAddress("http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1");
// Create the binding to be used by the service - you will probably want to configure this a bit more
BasicHttpBinding binding1 = new BasicHttpBinding();
///create the client proxy using the specific endpoint and binding you have created
YourServiceClient proxy = new YourServiceClient(binding1, endpointAddress);

Obviously you'll probably want to configure the binding with security, timeouts etc the same as your config above (you can read about the BasicHttpBinding on MSDN), but this should get you going in the right direction.


This is totally code based configuration and working code. You dont need any configuration file for client. But at least you need one config file there (may be automatically generated, you dont have to think about that). All the configuration setting is done here in code.

public class ValidatorClass
{
    WSHttpBinding BindingConfig;
    EndpointIdentity DNSIdentity;
    Uri URI;
    ContractDescription ConfDescription;

    public ValidatorClass()
    {  
        // In constructor initializing configuration elements by code
        BindingConfig = ValidatorClass.ConfigBinding();
        DNSIdentity = ValidatorClass.ConfigEndPoint();
        URI = ValidatorClass.ConfigURI();
        ConfDescription = ValidatorClass.ConfigContractDescription();
    }


    public void MainOperation()
    {
        var Address = new EndpointAddress(URI, DNSIdentity);
        var Client = new EvalServiceClient(BindingConfig, Address);
        Client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
        Client.Endpoint.Contract = ConfDescription;
        Client.ClientCredentials.UserName.UserName = "companyUserName";
        Client.ClientCredentials.UserName.Password = "companyPassword";
        Client.Open();

        string CatchData = Client.CallServiceMethod();

        Client.Close();
    }



    public static WSHttpBinding ConfigBinding()
    {
        // ----- Programmatic definition of the SomeService Binding -----
        var wsHttpBinding = new WSHttpBinding();

        wsHttpBinding.Name = "BindingName";
        wsHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
        wsHttpBinding.SendTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.BypassProxyOnLocal = false;
        wsHttpBinding.TransactionFlow = false;
        wsHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
        wsHttpBinding.MaxBufferPoolSize = 524288;
        wsHttpBinding.MaxReceivedMessageSize = 65536;
        wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;
        wsHttpBinding.TextEncoding = Encoding.UTF8;
        wsHttpBinding.UseDefaultWebProxy = true;
        wsHttpBinding.AllowCookies = false;

        wsHttpBinding.ReaderQuotas.MaxDepth = 32;
        wsHttpBinding.ReaderQuotas.MaxArrayLength = 16384;
        wsHttpBinding.ReaderQuotas.MaxStringContentLength = 8192;
        wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 4096;
        wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;

        wsHttpBinding.ReliableSession.Ordered = true;
        wsHttpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
        wsHttpBinding.ReliableSession.Enabled = false;

        wsHttpBinding.Security.Mode = SecurityMode.Message;
        wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
        wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
        wsHttpBinding.Security.Transport.Realm = "";

        wsHttpBinding.Security.Message.NegotiateServiceCredential = true;
        wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
        wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
       // ----------- End Programmatic definition of the SomeServiceServiceBinding --------------

       return wsHttpBinding;

   }

   public static Uri ConfigURI()
   {
       // ----- Programmatic definition of the Service URI configuration -----
       Uri URI = new Uri("http://localhost:8732/Design_Time_Addresses/TestWcfServiceLibrary/EvalService/");

       return URI;
   }

   public static EndpointIdentity ConfigEndPoint()
   {
       // ----- Programmatic definition of the Service EndPointIdentitiy configuration -----
       EndpointIdentity DNSIdentity = EndpointIdentity.CreateDnsIdentity("tempCert");

       return DNSIdentity;
   }


   public static ContractDescription ConfigContractDescription()
   {
        // ----- Programmatic definition of the Service ContractDescription Binding -----
        ContractDescription Contract = ContractDescription.GetContract(typeof(IEvalService), typeof(EvalServiceClient));

        return Contract;
   }
}


Are you looking to retain your custom config and reference it within your application? You may try this article: Reading WCF Configuration from a Custom Location (In regards to WCF)

Otherwise, you can use ConfigurationManager.OpenExeConfiguration.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号