title: WCF - how to create programatically custom binding with binary encoding over HTTP(S)
body: <p>I'd like to convert my current HTTP/HTTPS WCF binding settings to use binary message encoding and I need to do it in code - not in XML configuration.  AFAIK it's necessary to create CustomBinding object and set proper BindingElements, but I'm not able to figure out what elements should I use in my scenario.</p>
  
  <p>Main points in my WCF configuration are:</p>
  
  <ul>
  <li>use HTTP or HTTPS transport depending on configuration (in app.config)</li>
  <li>use username message security</li>
  <li>todo: add binary encoding instead of default text</li>
  </ul>
  
  <p>My current code for setting the binding up (working, but without the binary encoding):</p>
  
  <pre><code>var isHttps = Settings.Default.wcfServiceBaseAddress.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase);
  var binding = new WSHttpBinding(isHttps ? SecurityMode.TransportWithMessageCredential : SecurityMode.Message);
  binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
  </code></pre>
  
  <p>I was trying this code, but it doesn't work - I don't know how to set message security element for username message security:</p>
  
  <pre><code>var custBinding = new CustomBinding();
  custBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
  //Transport Security (Not Required)
  if (isHttps)
  {
      custBinding.Elements.Add(SecurityBindingElement.CreateUserNameForSslBindingElement());
  }
  //Transport (Required)
  custBinding.Elements.Add(isHttps ?
      new HttpsTransportBindingElement() :
      new HttpTransportBindingElement());
  </code></pre>
  
  <p>Anybody knows how to set this up? I tried to search for similar problem/solution, but didn't succeeded...</p>