Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Monday, August 22, 2011

Adding custom EndPoint Behavior at client side ServiceReferences.ClientConfig

A custom Endpoint behavior which implements IEndpointBehavior can be added for many purposes. That depends upon your requirements and the nature of the application you are working on. But interesting thing is you cannot add the EndpointBehavior through config in Silverlight 4. But supports addition of custom Endpoint Behaviors through code .ie after creating the proxy you may add the behavior to the Endpoint.Behaviors collection of proxy.As you know, here proxy is a derived class of ClientBase<T> and this class has the property Endpoint.

Passing ClientBase<T> objects as method arguments
Next question comes how to make the code to add end point more generic in order to reuse the code for all the WCF service proxies.ie we need to write a method which accepts ClientBase<T>.This is little tricky at first look .But please don’t go for dynamic keyword or object where we have a typed way.Here is the small code snippet to use ClientBase<T> as method parameter type in C#.

private void CreateProxy()
{
TestServiceReference.TestServiceClient client = new TestServiceReference.TestServiceClient();
AddMyEndpointBahavior < TestServiceReference.ITestService>(client);
}
private void AddMyEndpointBahavior<T>(ClientBase<T> client) where T :class
{
client.Endpoint.Behaviors.Add(new MyEndpointBehavior());
}




For VB.Net version see my general coding blog where I posted this first since it is more related to generics.


Monday, August 15, 2011

Changing Application.RootVisual at runtime

If you are a Silverlight Island programmer, this will not applicable to you because you will never face a situation which demands to change the Application.RootVisual property. Don’t confuse the word Island programmer ,it simply refers to the programmers who are creating small sized Silverlight applications mainly with some animations to fit into a small portion of HTML page which may be static or emitted by technologies such as ASP.Net or PHP.

Sometimes I feel that the Silverlight is more suited to Island programs than full window business apps. There are so many reasons.One is its rich user interface capabilities.This is more needed for glazy island apps than business apps. When we talk about great user experience there is always some cost attached to it which reduces performance. The performance is more important when we come to business apps than the user interface. In some of the tests we could see that the UI rendering takes more time than the WCF service in the whole display cycle. This happens when the data elements are huge in number but small and has complex data templates.

Ok.Coming back to changing Application.RootVisual multiple times at runtime. There may be scenarios where you need to show your authentication UI first and then load your application XAPs and the actual UI pages. In this case you need to change the RootVisual for sure.But this is not supported by the Silverlight runtime. First of all if you simply change, it will not change.You will get the below exception when you try to set null first and assign another visual after that.

Invalid value set for application's RootVisual

ie the below code will result into System.InvalidOperationException' in System.Windows.dll

'This will result in System.InvalidOperationException occurred in System.Windows.dll
Application.Current.RootVisual = Nothing
Application.Current.RootVisual = New TextBox With {.Text = "changed"}




So what is the simple solution.Keep a ContentControl as your RootVisual and set your Login UI and Application UI pages as its content.In the Application_Startup event set a ContentControl as your RootVisual then add initial UI to that. Later cast the RootVisual as ContentControl and change its Content property.


Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
'Initial UI.Here its button
Dim btnChangeRootVisual As New Button() With {.Content = "Change RootVisual"}
AddHandler btnChangeRootVisual.Click, AddressOf btnChangeRootVisual_Click

'ContentControl as RootVisual
Me.RootVisual = New ContentControl() With {.Content = btnChangeRootVisual}
End Sub
Private Sub btnChangeRootVisual_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
'Get the ContentControl and assign new UI to its content property
Dim rootContentControl As ContentControl = DirectCast(Application.Current.RootVisual, ContentControl)
rootContentControl.Content = New TextBox With {.Text = "changed"}
End Sub




This is just a hack for real business application programmers of Silverlight.

Saturday, March 20, 2010

Creating WCF proxy without reference

The problem : Creating WCF proxy in Silverlight without using the add service reference and it’s auto generated code

It was a debate that whether we can call a WCF service from Silverlight without using “Add Service Reference” menu item.In WPF or in the other .Net environments it is easy.We just need to refer the contracts dll and write a class which inherits from ClientBase.But this is Silverlight - A different runtime.

A Normal WCF service reference with all the generated code files

There were 3 opinions.Not at all possible,Possible with less amount of code,Possible if we create all those classes by our own.Just avoid the last one because that doesn’t give us any benefit as it is just making the process manual.

One of my Colleagues started research on that and was able to achieve the same.I am just sharing the idea.

Solution : We can achieve the same using contract interface,proxy class and a custom eventargs class

First of all there are no changes at the server side.Only 3 types we are going to write at client side which will be present in the reference.cs file if you create the proxy using “Add Service Reference” Dialog.

There will be a question for sure.Why are we writing the code which is being auto generated ? Why don’t we create a reference using the dialog and copy paste the reference.cs code?

The answer for both the questions is same.You can create reference using the dialog and get the code from reference.cs.That is enough.

Advantages

  • Can avoid huge amount of code which is auto generated.
  • This is acting as a separate layer and can encapsulate operations here in future.

Implementation steps

Lets take example of implementing a DataService with one method GetData which returns a string.Don’t bother about the server side.Use the same.Below are the steps to perform at client side ie Silverlight side.

  1. Create interface IDataService
    1. Decorate with ServiceContract attribute.
    2. Add method BeginGetData.Decorate it with OpertionContract and Set AsyncPattern to True.
    3. Add Method EndGetData.
      Imports System.ServiceModel

      <ServiceContract()> _
      Public Interface IDataService
      <OperationContract(AsyncPattern:=True)> _
      Function BeginGetData(ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
      Function EndGetData(ByVal result As System.IAsyncResult) As String
      End Interface





  2. Create eventArgs class deriving from System.ComponentModel.AsyncCompletedEventArgs


    1. Add required properties to pass values.

      Public Class GetDataCompletedEventArgs
      Inherits System.ComponentModel.AsyncCompletedEventArgs

      Private results() As Object

      Public Sub New(ByVal results() As Object, ByVal exception As System.Exception, ByVal cancelled As Boolean, ByVal userState As Object)
      MyBase.New(exception, cancelled, userState)
      Me.results = results
      End Sub

      Public ReadOnly Property Result() As String
      Get
      If Me.results IsNot Nothing Then
      Return CType(Me.results(0), String)
      End If
      Return Nothing
      End Get
      End Property
      End Class




  3. Create class DataServiceProxy derived from ClientBase which Implements IDataService.Write constructors.Implement methods.Write delegates and event which communicate back to the caller.



Public Class DataServiceProxy
Inherits ClientBase(Of IDataService)
Implements IDataService
#Region " Constructors"
Public Sub New()
MyBase.New()
End Sub

Public Sub New(ByVal endpointConfigurationName As String)
MyBase.New(endpointConfigurationName)
End Sub

Public Sub New(ByVal endpointConfigurationName As String, ByVal remoteAddress As String)
MyBase.New(endpointConfigurationName, remoteAddress)
End Sub

Public Sub New(ByVal endpointConfigurationName As String, ByVal remoteAddress As System.ServiceModel.EndpointAddress)
MyBase.New(endpointConfigurationName, remoteAddress)
End Sub

Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress)
MyBase.New(binding, remoteAddress)
End Sub
#End Region

#Region "GetData"
Private onBeginGetDataDelegate As BeginOperationDelegate
Private onEndGetDataDelegate As EndOperationDelegate
Private onGetDataCompletedDelegate As System.Threading.SendOrPostCallback
Public Event GetDataCompleted As System.EventHandler(Of GetDataCompletedEventArgs)

Public Function BeginGetData(ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult Implements ServiceContracts.IDataService.BeginGetData
Return MyBase.Channel.BeginGetData(callback, asyncState)

End Function

Public Function EndGetData(ByVal result As System.IAsyncResult) As String Implements ServiceContracts.IDataService.EndGetData
Return MyBase.Channel.EndGetData(result)
End Function

Private Function OnBeginGetData(ByVal inValues() As Object, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
'Dim engID As String = CType(inValues(0), String)
'Dim libraryID As String = CType(inValues(1), String)
'Dim folderName As String = CType(inValues(2), String)
'Dim parentFolder As PathInfo = CType(inValues(3), PathInfo)
'Dim folderGeneralProperties As FolderGeneralProperties = CType(inValues(4), FolderGeneralProperties)
'Dim additionalProperties As System.Collections.Generic.Dictionary(Of String, String) = CType(inValues(5), System.Collections.Generic.Dictionary(Of String, String))
Return CType(Me, IDataService).BeginGetData(callback, asyncState)
End Function

'Private Function GetData() As String Implements IDataService.GetData
'Return MyBase.Channel.GetData()
'End Function

Private Function OnEndGetData(ByVal result As System.IAsyncResult) As Object()
Dim retVal As String = CType(Me, IDataService).EndGetData(result)
Return New Object() {retVal}
End Function

Private Sub OnGetDataCompleted(ByVal state As Object)
'If Not (GetDataCompleted Is Nothing) Then
Dim e As InvokeAsyncCompletedEventArgs = CType(state, InvokeAsyncCompletedEventArgs)
RaiseEvent GetDataCompleted(Me, New GetDataCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState))
'End If
End Sub

Public Overloads Sub GetDataAsync()
If (Me.onBeginGetDataDelegate Is Nothing) Then
Me.onBeginGetDataDelegate = AddressOf Me.OnBeginGetData
End If
If (Me.onEndGetDataDelegate Is Nothing) Then
Me.onEndGetDataDelegate = AddressOf Me.OnEndGetData
End If
If (Me.onGetDataCompletedDelegate Is Nothing) Then
Me.onGetDataCompletedDelegate = AddressOf Me.OnGetDataCompleted
End If
MyBase.InvokeAsync(Me.onBeginGetDataDelegate, New Object() {}, Me.onEndGetDataDelegate, Me.onGetDataCompletedDelegate, Nothing)
End Sub
#End Region
End Class



Uploaded a sample which does the same.

Saturday, August 15, 2009

WCF service from Silverlight with Windows credentials

Last week this was our major research item.How to make Silverlight call a WCF service which needs Windows authentication?

In the ideal scenario ,if the user is already logged in with right windows credentials the system(here Silverlight) should not ask for user name and password again.Silverlight should recognize the user and pass those credentials automatically into the WCF service.We implemented the WCF service with Windows credentials and made the hosting ASP.Net application's authentication to Windows.But it was asking for the user name and password when we call the service from Silverlight.Really that dialog is ugly when comparing to the rich UI of Silverlight.The reason for this is under normal circumstances Silverlight can't access the windows credentials of user.

Avoiding the windows login dialog box

After a tough research, one of my colleague find out a solution to get rid of this windows authentication dialog.The solution is simple.Just add the name of website where the service is hosted, into trusted sites collection of browser.

But this solution has a draw back.The end user has to do this configuration in browser.We can't always expect them to do this setting.So the better way is to create a Silverlight authentication page which accept the windows credentials and call a login service to authenticate the user using the provided credentials.Once we get the user name and password we can easily authenticate the user by calling some native methods.

So if the user has setup the browser settings the Silverlight won't show the authentication dialog.Else show the Silverlight dialog and ask user to enter his windows login details again.

Again another question comes, whether the user will/can trust the website which asks for his windows credentials ? In that scenario forget the rich UI of Silverlight show them the native windows login dialog box...


Some references

Happy Independence day to all My Indians.

Friday, April 4, 2008

Silverlight 2.0 crossdomain programming

'Crossdomain' is a common word in Silverlight programming from the days of wpf/e itself.Actually what is 'crossdomain' ?
It's nothing but trying to access something located at different domains other than the silverlight application's domain.

These calls are blocked in silverlight.But we can't create a complete application without making these calls.for eg: if we need to access a database ,we should make these types of calls since Silverlight dont have direct database suppport.In such situations we do the following.

Create a proxy in the same domain of Silverlight application and route calls through that proxy.Proxy usually be a webservice or WCF service which dont have the crossdomain limitation.

There are so many things which we should take care of when using these methods.Some links are given below which helps you to improve your application's communication skill.

http://blogs.msdn.com/silverlightws/archive/2008/03/30/some-tips-on-cross-domain-calls.aspx
http://community.irritatedvowel.com/blogs/pete_browns_blog/archive/2008/03/19/WCF-Integration-in-Silverlight-2-Beta-1.aspx