.Net | Sitecore

– Abhishek D V


Leave a comment

Sitecore – SOLR Installation

Use below powershell script to install SOLR automatically without any hassle.

Thanks to whoever created it!

Parameters to be changed:

  1. $solrVersion ( version you want to install )
  2. $installFolder
  3. $solrPort ( Any unused port )
  4. $nssmVersion
  5. $JREVersion

// Scripts Starts

Param(
$solrVersion = “6.6.2”,
$installFolder = “c:\Solr662”,
$solrPort = “8982”,
$solrHost = “solr662”,
$solrSSL = $true,
$nssmVersion = “2.24”,
$JREVersion = “1.8.0_77”
)

$JREPath = “C:\Program Files\Java\jre$JREVersion” ## Note that if you’re running 32bit java, you will need to change this path
$solrName = “solr-$solrVersion”
$solrRoot = “$installFolder\$solrName”
$nssmRoot = “$installFolder\nssm-$nssmVersion”
$solrPackage = “https://archive.apache.org/dist/lucene/solr/$solrVersion/$solrName.zip”
$nssmPackage = “https://nssm.cc/release/nssm-$nssmVersion.zip”
$downloadFolder = “~\Downloads”

## Verify elevated
## https://superuser.com/questions/749243/detect-if-powershell-is-running-as-administrator
$elevated = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match “S-1-5-32-544”)
if($elevated -eq $false)
{
throw “In order to install services, please run this script elevated.”
}

function downloadAndUnzipIfRequired
{
Param(
[string]$toolName,
[string]$toolFolder,
[string]$toolZip,
[string]$toolSourceFile,
[string]$installRoot
)

if(!(Test-Path -Path $toolFolder))
{
if(!(Test-Path -Path $toolZip))
{
Write-Host “Downloading $toolName…”
Start-BitsTransfer -Source $toolSourceFile -Destination $toolZip
}

Write-Host “Extracting $toolName to $toolFolder…”
Expand-Archive $toolZip -DestinationPath $installRoot
}
}
# download & extract the solr archive to the right folder
$solrZip = “$downloadFolder\$solrName.zip”
downloadAndUnzipIfRequired “Solr” $solrRoot $solrZip $solrPackage $installFolder

# download & extract the nssm archive to the right folder
$nssmZip = “$downloadFolder\nssm-$nssmVersion.zip”
downloadAndUnzipIfRequired “NSSM” $nssmRoot $nssmZip $nssmPackage $installFolder

# Ensure Java environment variable
$jreVal = [Environment]::GetEnvironmentVariable(“JAVA_HOME”, [EnvironmentVariableTarget]::Machine)
if($jreVal -ne $JREPath)
{
Write-Host “Setting JAVA_HOME environment variable”
[Environment]::SetEnvironmentVariable(“JAVA_HOME”, $JREPath, [EnvironmentVariableTarget]::Machine)
}

# if we’re using HTTP
if($solrSSL -eq $false)
{
# Update solr cfg to use right host name
if(!(Test-Path -Path “$solrRoot\bin\solr.in.cmd.old”))
{
Write-Host “Rewriting solr config”

$cfg = Get-Content “$solrRoot\bin\solr.in.cmd”
Rename-Item “$solrRoot\bin\solr.in.cmd” “$solrRoot\bin\solr.in.cmd.old”
$newCfg = $newCfg | % { $_ -replace “REM set SOLR_HOST=192.168.1.1”, “set SOLR_HOST=$solrHost” }
$newCfg | Set-Content “$solrRoot\bin\solr.in.cmd”
}
}

# Ensure the solr host name is in your hosts file
if($solrHost -ne “localhost”)
{
$hostFileName = “c:\\windows\system32\drivers\etc\hosts”
$hostFile = [System.Io.File]::ReadAllText($hostFileName)
if(!($hostFile -like “*$solrHost*”))
{
Write-Host “Updating host file”
“`r`n127.0.0.1`t$solrHost” | Add-Content $hostFileName
}
}

# if we’re using HTTPS
if($solrSSL -eq $true)
{
# Generate SSL cert
$existingCert = Get-ChildItem Cert:\LocalMachine\Root | where FriendlyName -eq “$solrName”
if(!($existingCert))
{
Write-Host “Creating & trusting an new SSL Cert for $solrHost”

# Generate a cert
# https://docs.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps
$cert = New-SelfSignedCertificate -FriendlyName “$solrName” -DnsName “$solrHost” -CertStoreLocation “cert:\LocalMachine” -NotAfter (Get-Date).AddYears(10)

# Trust the cert
# https://stackoverflow.com/questions/8815145/how-to-trust-a-certificate-in-windows-powershell
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store “Root”,”LocalMachine”
$store.Open(“ReadWrite”)
$store.Add($cert)
$store.Close()

# remove the untrusted copy of the cert
$cert | Remove-Item
}

# export the cert to pfx using solr’s default password
if(!(Test-Path -Path “$solrRoot\server\etc\solr-ssl.keystore.pfx”))
{
Write-Host “Exporting cert for Solr to use”

$cert = Get-ChildItem Cert:\LocalMachine\Root | where FriendlyName -eq “$solrName”

$certStore = “$solrRoot\server\etc\solr-ssl.keystore.pfx”
$certPwd = ConvertTo-SecureString -String “secret” -Force -AsPlainText
$cert | Export-PfxCertificate -FilePath $certStore -Password $certpwd | Out-Null
}

# Update solr cfg to use keystore & right host name
if(!(Test-Path -Path “$solrRoot\bin\solr.in.cmd.old”))
{
Write-Host “Rewriting solr config”

$cfg = Get-Content “$solrRoot\bin\solr.in.cmd”
Rename-Item “$solrRoot\bin\solr.in.cmd” “$solrRoot\bin\solr.in.cmd.old”
$newCfg = $cfg | % { $_ -replace “REM set SOLR_SSL_KEY_STORE=etc/solr-ssl.keystore.jks”, “set SOLR_SSL_KEY_STORE=$certStore” }
$newCfg = $newCfg | % { $_ -replace “REM set SOLR_SSL_KEY_STORE_PASSWORD=secret”, “set SOLR_SSL_KEY_STORE_PASSWORD=secret” }
$newCfg = $newCfg | % { $_ -replace “REM set SOLR_SSL_TRUST_STORE=etc/solr-ssl.keystore.jks”, “set SOLR_SSL_TRUST_STORE=$certStore” }
$newCfg = $newCfg | % { $_ -replace “REM set SOLR_SSL_TRUST_STORE_PASSWORD=secret”, “set SOLR_SSL_TRUST_STORE_PASSWORD=secret” }
$newCfg = $newCfg | % { $_ -replace “REM set SOLR_HOST=192.168.1.1”, “set SOLR_HOST=$solrHost” }
$newCfg | Set-Content “$solrRoot\bin\solr.in.cmd”
}
}

# install the service & runs
$svc = Get-Service “$solrName” -ErrorAction SilentlyContinue
if(!($svc))
{
Write-Host “Installing Solr service”
&”$installFolder\nssm-$nssmVersion\win64\nssm.exe” install “$solrName” “$solrRoot\bin\solr.cmd” “-f” “-p $solrPort”
$svc = Get-Service “$solrName” -ErrorAction SilentlyContinue
}
if($svc.Status -ne “Running”)
{
Write-Host “Starting Solr service”
Start-Service “$solrName”
}

# finally prove it’s all working
$protocol = “http”
if($solrSSL -eq $true)
{
$protocol = “https”
}
Invoke-Expression “start $($protocol)://$($solrHost):$solrPort/solr/#/”

// Script Ends


Leave a comment

SignalR – simple chat application

Steps to follow to set up signalR

Step 1: Install SignalR components

Install signalR from Nuget as shown below

 image

After installing you can see all scripts related to signalR and assemblies added to the project.

Step 2: Sample UI

  1. <head runat="server">
  2.     <title></title>
  3.     <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
  4.     <script src="Scripts/jquery.signalR-1.1.2.min.js" type="text/javascript"></script>
  5.     <script src="../signalr/hubs" type="text/javascript"></script>
  6. </head>
  7. <body>
  8.     <form id="form1" runat="server">
  9.     <div>
  10.         <asp:TextBox ID="txtMsg" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox>
  11.         <br />
  12.         <input type="button" id="btnSend" value="Send" />
  13.         <br />
  14.         <ul id="lstMsgs"></ul>
  15.     </div>
  16.     </form>
  17. </body>

The UI contains a textbox where we can type message to send and also all necessary signalR scripts added.

 

Step3: Create Hub

 

  1. using Microsoft.AspNet.SignalR;
  2. using Microsoft.AspNet.SignalR.Hubs;
  3.  
  4. namespace SignalRExp
  5. {
  6.     [HubName("chathub")]
  7.     public class ChatHub : Hub
  8.     {
  9.         public void sendMessage(string msg)
  10.         {
  11.             Clients.All.addMessage(msg);
  12.         }
  13.     }
  14. }

 

Step 4: Client script

In the client script we will create connection to hub and onclick of send button we will have the message send to server and server sends the message to all connected clients.

  1. <script type="text/javascript">
  2.  
  3.     var $j = jQuery.noConflict();
  4.  
  5.     $j(function () {
  6.         var chatConn = $j.connection.chathub;
  7.  
  8.         chatConn.client.addMessage = function (msg) {
  9.             $j('#lstMsgs').append('<li>' + msg + '</li>');
  10.         };
  11.               
  12.         $j.connection.hub.start().done(function () {
  13.             $j('#btnSend').click(function () {
  14.                 chatConn.server.sendMessage($j('#txtMsg').val());
  15.                 $j('#txtMsg').val('');
  16.             });
  17.         });;
  18.     });
  19. </script>

 

Note:

Make sure the server and client methods are camel case as signalR converts method names to camel case.

Demo:

In the below demo we can see we have 3 clients and messages passed to all clients from one another.

image


Leave a comment

WCF Transactions

Steps to follow to setup transactions working in WCF.

Step 1:

Declare the contract with TransactionFlow attribute with Mandatory option which means this method needs to be called within transaction scope at client-side.

  1. [ServiceContract]
  2.     public interface IService
  3.     {
  4.         [OperationContract, TransactionFlow(TransactionFlowOption.Mandatory)]
  5.         void DebitAccount(int accountId,int amount);
  6.     }

Step 2:

Implement the contract method by decorating the method with TransactionScope parameter as shown below:

  1. [OperationBehavior(TransactionScopeRequired = true)]
  2.         public void DebitAccount(int accountId, int amount)
  3.         {
  4.  
  5.             using (DataDataContext ctx = new DataDataContext())
  6.             {
  7.                 ctx.DebitOperation(accountId, amount);
  8.             }
  9.         }

 

Step 3:

In the config file of service set the transactionFlow to true for wsHttpBinding

  1. <wsHttpBinding>
  2.         <binding name="MyServiceBinding" transactionFlow="true">

Add this to endpoint

  1. <endpoint address="" binding="wsHttpBinding" contract="WcfTransactionService.IService"
  2.                   bindingConfiguration="MyServiceBinding">
  3.           <identity>
  4.             <dns value="localhost"/>
  5.           </identity>
  6.         </endpoint>

Step 4:

At client side call the method within TransactionScope

  1. TransService.ServiceClient ts = new TransService.ServiceClient();
  2.  
  3.                 using (TransactionScope tss = new TransactionScope())
  4.                 {
  5.                     ts.DebitAccount(1, 10);
  6.                     tss.Complete();
  7.                 }

Remember to call Complete() method otherwise changes in DB will be reverted.

The above sample is a simple example showing configuration for transactions to work.


Leave a comment

WCF REST with Fiddler

In this article we will discuss about setting up WCF REST and self-hosting it and testing it with the brilliant tool Fiddler.

Code Sample:

  1. [DataContract(Namespace="")]
  2.     public class Vehicle
  3.     {
  4.         [DataMember]
  5.         public int Id { get; set; }
  6.         [DataMember]
  7.         public string Model { get; set; }
  8.     }

 

  1.  
  2.     [ServiceContract]
  3.     public interface IVehicle
  4.     {
  5.         [WebInvoke(Method="POST", UriTemplate="vehicles", RequestFormat=WebMessageFormat.Xml)]
  6.         [OperationContract]
  7.         void AddVehicle( Vehicle v);
  8.  
  9.         [WebGet(UriTemplate="vehicles")]
  10.         [OperationContract]
  11.         List<Vehicle> GetVehicle();
  12.     }

 

In the above code we have ServiceContract which lists all vehicles when we do Http Get request and adds vehicle when we do a Http POST request.

Service Implementation:

  1. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
  2. public class LibraryService : IVehicle
  3. {
  4.     List<Vehicle> veh = new List<Vehicle>();
  5.  
  6.     void IVehicle.AddVehicle(Vehicle v)
  7.     {
  8.         veh.Add(v);
  9.     }
  10.  
  11.     List<Vehicle> IVehicle.GetVehicle()
  12.     {
  13.         return veh;
  14.     }
  15. }

In the above code  We have implemented the interface and class is marked as Singleton( service behavior attribute ) just to check the added vehicles when we test it through fiddler.

Hosting the service:

We will have our REST service working by doing self-hosting as shown below:

  1. string httpUrl = "http://localhost:8732/SeviceLibraryService&quot;;
  2.  
  3.             WebServiceHost host = new WebServiceHost( typeof( LibraryService ), new Uri( httpUrl ) );
  4.  
  5.             try
  6.             {
  7.                 host.Open();
  8.                 Console.WriteLine( "Service is ready at: " + httpUrl );
  9.                 Console.Read();
  10.             }
  11.             catch( Exception ex )
  12.             {
  13.                 Console.WriteLine( ex.Message );
  14.             }

 

By running the above code in a console app

image

So our service is up and running

on browsing the service at

http://localhost:8732/SeviceLibraryService/vehicles we will see

image

Since we have given uritemplate as vehicles the get request is sent in above url format and, we will see the above output which shows vehicles in the xml format ( default )

Testing in Fiddler

Now lets add a vehicle through fiddler and do the same get request as done above.

Steps to test in fiddler:

1> In fiddler select composer select POST request

2> In the url add http://localhost:8732/SeviceLibraryService/vehicles

3> In the request headers add Content-Type: text/xml

4> In the Request Body add sample xml like below to add vehicle

  1. <Vehicle>
  2.   <Id>123</Id>
  3.   <Model>2013</Model>
  4. </Vehicle>

Note:

In the datacontract of vehicle make sure namespace is empty else whatever the namespace is given add it in xml of Request body

image

Now on executing this request adds the vehicle and on making the GET request ( http://localhost:8732/SeviceLibraryService/vehicles ) in the browser we will see the vehicle added as shown below:

 

image


Leave a comment

ServiceKnownType and KnownType attribute in WCF

In this articles we will discuss about significance of ServiceKnownType and KnownType attribute in WCF.

Lets look at an example to understand this:

  1. [ServiceContract]
  2.     public interface IService
  3.     {
  4.         [OperationContract]
  5.         void AddVehicle( Vehicle v );
  6.     }

 

  1. [DataContract]
  2.     public class Vehicle
  3.     {
  4.         [DataMember]
  5.         public string VehicleName { get; set; }
  6.         [DataMember]
  7.         public int VehicleModel { get; set; }
  8.     }
  9.  
  10.     [DataContract]
  11.     public class Car : Vehicle
  12.     {
  13.         [DataMember]
  14.         public bool IsHatchBack { get; set; }
  15.     }

 

In the above example we see a a servicecontract which adds vehicle and takes vehicle as a parameter and looking at the datacontracts we have a class called Car inherited from Vehicle.

Now on referencing this service at client side we expect to see Car class generated at client’s proxy but NO client proxy will not be able to generate car class, Since Car is not part of contract DataContractSerializer fails to serialize.

To solve this problem decorate the method or contract with ServiceKnownType attribute as shown below:

  1. [ServiceContract]
  2.     public interface IService
  3.     {
  4.         [OperationContract]
  5.         [ServiceKnownType(typeof(Car))]
  6.         void AddVehicle( Vehicle v );
  7.     }

Alternatively we can use KnownType attribute at class level as shown below:

  1.     [DataContract]
  2.     [KnownType(typeof(Car))]
  3.     public class Vehicle
  4.     {
  5.         [DataMember]
  6.         public string VehicleName { get; set; }
  7.         [DataMember]
  8.         public int VehicleModel { get; set; }
  9.     }


1 Comment

Simple chat app using wsDualHttpBinding

First let us look at what needs to be done set up wsDualHttpBinding working.

Defining contracts at Service side:

  1. public interface IServiceCallBack
  2.     {
  3.         [OperationContract]
  4.         [FaultContract(typeof( FaultExceptionHandler))]
  5.         void CallBck( string str );
  6.     }
  7.  
  8.     [ServiceContract(CallbackContract=typeof(IServiceCallBack))]
  9.     public interface IService
  10.     {
  11.         [OperationContract]
  12.         void Message(string msg);
  13.         
  14.     }

We will be defining interface which will be our call back interface and implemented at client side.

Service contract needs to be addressed by adding a named parameter called CallBackContract as shown above

Service Implementation:

  1. [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
  2.     public class Service : IService
  3.     {
  4.  
  5.         void IService.Message(string msg)
  6.         {
  7.             IServiceCallBack cb = OperationContext.Current.GetCallbackChannel<IServiceCallBack>();
  8.             cb.CallBck(msg);
  9.  
  10.         }
  11.     }

Here we are simply sending the  message sent from client back to client again.

EndPoint:

  1. <endpoint address="" binding="wsDualHttpBinding" contract="WcfService.IService">
  2.         <identity>
  3.           <dns value="localhost"/>
  4.         </identity>
  5.       </endpoint>

Note:

1> Concurrency mode on the service behavior attribute should be Multiple otherwise we get a deadlock exception.

2> Binding should be wsDualHttpBinding

Client Side:

The service above is referenced as MyService at client side.

Implementing the callback contract at client side

  1.         public class ClsCallBack : MyService.IServiceCallback
  2.         {
  3.             void MyService.IServiceCallback.CallBck(string str)
  4.             {
  5.                 Console.WriteLine(str);
  6.             }
  7.         }

The above implementation writes the text to console.

Calling the service:

  1. static void Main(string[] args)
  2.         {
  3.             MyService.IServiceCallback c = new ClsCallBack();
  4.             InstanceContext ctx = new InstanceContext(c);
  5.             MyService.ServiceClient client = new MyService.ServiceClient(ctx);
  6.             string text = Console.ReadLine();
  7.             client.Message(text);
  8.  
  9.             Console.ReadLine();
  10.         }

 

Now let us make a simple chat app using this implementation

At service side we need to store all the client context whenever new connection is arrived

To make this possible we need to mark service implementation as Singleton

  1. [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]

and declare a List<IserviceCallBack> to store all client’s context

Initialize the list in the constructor of service

  1. public Service()
  2.         {
  3.             callBacksList = new List<IServiceCallBack>();
  4.         }

Since our service class is a singleton it is initialized only once and in our implementation of Message method store all client context as shown below

  1. void IService.Message(string msg)
  2.         {
  3.             IServiceCallBack cb = OperationContext.Current.GetCallbackChannel<IServiceCallBack>();
  4.             callBacksList.Add(cb);
  5.             foreach (IServiceCallBack c in callBacksList)
  6.             {
  7.                 c.CallBck(msg);
  8.             }
  9.         }

 

Now on calling the multiple clients we see the message is sent to all available client contexts as shown below:

2013-06-05_1445

In the above picture we can see the messages are shared among all clients.


Leave a comment

WCF Logging and basic v/s wshttpbinding

Hello All,

In this page we will discuss about logging messages that are passed b/w client and service in WCF, also about basic difference b/w basicHttpBinding and wsHttpBinding.

  • Logging messages:

To log messages that are exchanged between client and the service we need to add few lines in the config file of client

  1.   <system.diagnostics>
  2.     <sources>
  3.       <source name="System.ServiceModel.MessageLogging">
  4.         <listeners>
  5.           <add name="messages"
  6.           type="System.Diagnostics.XmlWriterTraceListener"
  7.           initializeData="messages.svclog" />
  8.         </listeners>
  9.       </source>
  10.     </sources>
  11.   </system.diagnostics>

Also under  <System.ServiceModel>

  1. <diagnostics>
  2.         <messageLogging
  3.              logEntireMessage="true"
  4.              logMalformedMessages="false"
  5.              logMessagesAtServiceLevel="true"
  6.              logMessagesAtTransportLevel="true"
  7.              maxMessagesToLog="3000"
  8.              maxSizeOfMessageToLog="2000"/>
  9.       </diagnostics>

By adding these lines we log the messages under current running directory of clint by file name: messages.svclog

  • Viewing messages:

Windows SDK provides a tool to view messages called Service Trace Viewer

To demonstrate the tool i am using this sample code:

  1. [ServiceContract]
  2.     public interface IService
  3.     {
  4.  
  5.         [FaultContract(typeof(FaultExceptionHandler))]
  6.         int GetData(int value);
  7.     }

In the service it is implemented as follows

  1.     int IService.GetData( int value )
  2.     {
  3.         return value + 1;
  4.  
  5.     }

So its a sample and simple code which is just incremented once and returned as response to client.

At client endpoint looks like this, which is a basicHttpBinding

  1. <client>
  2.         <endpoint address="http://localhost:3192/Service.svc" binding="basicHttpBinding"
  3.         bindingConfiguration="BasicHttpBinding_IService" contract="MyService.IService"
  4.         name="BasicHttpBinding_IService" />
  5.       </client>

On calling the GetData method from client like:

GetData(5)

Lets see the messages in Service Trace viewer tool

Untitled

As you see above the request from client to servive is issued and we can see the value that is sent

So lets check the response from service in the tool:

<MessageLogTraceRecord Time="2013-05-29T14:46:44.0738670+05:30" Source="TransportReceive" Type="System.ServiceModel.Channels.BufferedMessage" xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace"&gt;
<HttpResponse>
<StatusCode>OK</StatusCode>
<StatusDescription>OK</StatusDescription>
<WebHeaders>
<Connection>Close</Connection>
<Content-Length>189</Content-Length>
<Cache-Control>private</Cache-Control>
<Content-Type>text/xml; charset=utf-8</Content-Type>
<Date>Wed, 29 May 2013 09:16:44 GMT</Date>
<Server>ASP.NET Development Server/11.0.0.0</Server>
<X-AspNet-Version>2.0.50727</X-AspNet-Version>
</WebHeaders>
</HttpResponse>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt;
<s:Header></s:Header>
<s:Body>
<GetDataResponse xmlns="http://tempuri.org/"&gt;
<GetDataResult>6</GetDataResult>
</GetDataResponse>
</s:Body>
</s:Envelope>
</MessageLogTraceRecord>

The service response is highlighted as above, we see the result which is incremented by 1.

  • wsHttpBinding:

As discussed above we saw result is not encrypted, by changing the binding to wsHttpBinding we will see the result is encrypted as shown below.

<MessageLogTraceRecord Time="2013-05-29T15:21:21.6946083+05:30" Source="TransportReceive" Type="System.ServiceModel.Channels.BufferedMessage" xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace"&gt;
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope&quot; xmlns:a="http://www.w3.org/2005/08/addressing"&gt;
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue</a:Action&gt;
<a:RelatesTo>urn:uuid:1464ca31-0c2e-4e6c-8b54-8927aea3cb06</a:RelatesTo>
</s:Header>
<s:Body>
<t:RequestSecurityTokenResponse Context="uuid-fd903687-ba1d-412b-bce0-40e1e826d096-1" xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust&quot; xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"&gt;
<t:BinaryExchange ValueType="http://schemas.xmlsoap.org/ws/2005/02/trust/spnego&quot; EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">oYHaMIHXoAMKAQGhDAYKKwYBBAGCNwICCqKBwQSBvk5UTE1TU1AAAgAAAAwADAA4AAAANcKZ4pkpHbZCOv+f8NEmAgAAAAB6AHoARAAAAAYBsR0AAAAPQgBPAFMAVABPAE4AAgAMAEIATwBTAFQATwBOAAEAEgBJAE4AQgAtAFcAMAAwADQAMQAEAAwAZQBmAC4AYwBvAG0AAwAgAEkATgBCAC0AVwAwADAANAAxAC4AZQBmAC4AYwBvAG0ABQAMAGUAZgAuAGMAbwBtAAcACADG8wkTUlzOAQAAAAA=</t:BinaryExchange&gt;
</t:RequestSecurityTokenResponse>
</s:Body>
</s:Envelope>
</MessageLogTraceRecord>

So this is the basic difference between basicHttpBinding and wsHttpBinding where the message is by default encrypted.


6 Comments

MexHttpBinding v/s WSDL

Lets discuss about how the metadata is exchanged with client in WCF.

There are two ways to exchange metadata with client.

1> MexHttpBinding

2> WSDL

1> Enabling MexHttpBinding:

We can have the metadata exchanged through mexHttpBinding by adding endpoint in our config file like:

  1. <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

2> Enabling WSDL

In the Service Behaviors set httpGetEnabled="true"

  1. <serviceMetadata httpGetEnabled="false"/>

If both are added default will be WSDL

Example:

Lets assume we have simple service with IService as contract and web.config of service model looks like this

  1. <system.serviceModel>
  2.       <services>
  3.         <service name="WcfService.Service" behaviorConfiguration="WcfService1.Service1Behavior">
  4.           <endpoint address="" binding="basicHttpBinding" contract="WcfService.IService">
  5.             <identity>
  6.               <dns value="localhost"/>
  7.             </identity>
  8.           </endpoint>
  9.           <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  10.         </service>
  11.       </services>
  12.       <behaviors>
  13.         <serviceBehaviors>
  14.           <behavior name="WcfService1.Service1Behavior">
  15.             <serviceMetadata httpGetEnabled="true"/>
  16.             <serviceDebug includeExceptionDetailInFaults="false"/>
  17.           </behavior>
  18.         </serviceBehaviors>
  19.       </behaviors>
  20.     </system.serviceModel>

Since we have enabled both ( mex and wsdl ) preference will be always given to WSDL

On browsing the service:

2013-05-24_1227

Now we can see metadata is exchanged through WSDL when we add reference of this service to any project.

Disabling WSDL

By simply setting httpGetEnabled=false in Service behavior we can disable WSDl

On browsing service after disabling WSDL

2013-05-24_1231

Now we can see that metadata is exchanged with MexHttpBinding.

Create your own website, free on WordPress.com.Create your own website.
Start free