Thursday, July 17, 2008

A beginner's guide to WCF in XBAP

Contents

  1. Development Platform
  2. Introduction
  3. Prepare the stage
  4. Creating the projects and necessary files
  5. Configure the WCF for XBAP
  6. Consume WCF Service from XBAP
  7. Debugging WCF Service
  8. Deploying your solution
  9. Using the WsHttpBinding configuration
  10. A quick discussion on Data Transfer Limit
  11. Conclusion

Development Platform

  1. Visual Studio 2008
  2. Dot net framework 3.5
  3. IIS 5.1~7
  4. IE7/Firefox 2.x
  5. Asp.net 2.0
  6. Windows vista/xp

Introduction

Windows presentation foundation in short, wpf is Microsoft’s new user interface technology. Wpf introduced with the release of dot net framework 3.0. Wpf comes with lot of promises, for example, it can be used to show very rich graphics centric 2D and 3D models. WPF uses the client machines graphics capability to full extent. For more information about wpf please visit www.windowclient.net. In this article we will discuss about using wpf in web! It sounds a very strange wish to accomplish. But it’s true; wpf can be used in browser. This special browser centric package called WPF Browser Application. XBAP stands for XAML Browser Application which is the eventual output of WPF browser application. The main purpose of XBAP is to introduce a fat client application which runs on client side and provide the user an ease of desktop application in web. XBAP use the resources of client machine, that’s why .net framework must be installed in client machine to run WPF browser application. Even though XBAP uses client machine's resource and memory but it run in a sandbox environment, this mode of sandbox called the partial trust mode. XBAP in dot net 3.5 have few improvement over 3.0. Using WCF in partial trust mode is one of them. In this article we will see the implemention of WCF service in XBAP partial trust mode.

Prepare the stage

Learning by example is always a very good way of learning new things, that’s why we are going to develop a simple XAML browser application in which we will display a to-do list and notes of a user and of course going to use WCF to communicate with our data layer. Few things must be clear before jumped in to the stage. In partial trust mode XBAP can consume WCF service from the site of origin only. So we cannot use a cross domain WCF service from XBAP. Another restriction we have in case of WCF binding configuration, we can use only BasicHttpBinding and WSHttpBinding in partial trust mode. For retrieving, creating, deleting and updating tasks we will use BasicHttpBinding. On the other hand to retrieving, creating, deleting and updating notes we will use WsHttpBinding. Let’s go through the projects templates first. We will of course create a WPF Browser application Project, Next we are going to create a WCF Service Application Project and Finally we are going to develop a simple web site (web application project of vs2008) where our browser application will be hosted. We will use a SQL express edition database in data service layer that is a “tododata.mdf” we will construct our own user base and user validation. WPF browser application will forward all request to a WCF web service. WCF service will do business logic validation and retrieve data from data access layer. Bellow here is a simple diagram to presented how the application architecture will be.

XBAP-WCF.JPG

Creating the projects and necessary files

By now we already know that we are going to create three different projects. So let’s get started, we will start with creating a blank solution for our convenience. Go ahead and create a blank solution in vs2008 and save the solution to your convenient place with a convenient name. Now add a new WPF Browser application project to the solution. Then add a new WCF Service Application to the solution and lastly add a new web application project to the solution, that concludes the projects creation process. To save the data we will use sql express database, so let's go ahead and add a Sql server database file and name it to your convenient. Then create necessary tables for task, notes and users. Next we need a simple mechanism to retrieve, save and to modify data from the database, for this we are going to use LINQ. Add a dbml file to the wcf service project drag and drop the data tables from database explorer to the dbml. Next we have to define our service interfaces. We will have two services in the same wcf project one for notes (INoteService) and other one for tasks (ITaskService).

Projects.jpg

Configure the WCF for XBAP

If you are new to wcf I would like to suggest you to spend some time on msdn library learning wcf. So now we have our wcf service application “WcfService”. Now we are going to configure our wcf service so that our XBAP can consume this service. By default when users add a wcf service, visual studio automatically configure two end points for the service. We are going to modify the binding configuration for our service so that XBAP can communicate with it. Visual studio 2008 provides a nice tool to edit wcf service configurations, and the tool is “WCF Service Configuration Editor” we will edit service configurations with this tool, you can also modify the web.config manually to setup appropriate markup under service model section. By default when you right click on web.config of service no edit configuration tool is shown, to make it show first we have to run it from the tools menu of visual studio 2008. Click on the tools menu of the visual studio 2008 and click on wcf configuration menu. Now you can close the tool. Once you have opened the tool it will be available for the current session. Now right click on the web.config file of the wcf service project and select “Edit WCF configuration”. Configuration editor will pop up with the entire configuration that is defined in the web.config. In configuration editor on the left side you will find a tree with service information’s populated. Expand the services node and you will see a node named “Endpoints”. By default under endpoints node there are two pre-added endpoints, one endpoint configured with WsHttpBinding and another is configured with MaxHttpBinding. Now select the endpoint that is configured with WsHttpBinding. After selecting the endpoint, properties of that end point will be shown in property editor on the right side. Change the binding property to WsHttpBinding to BasicHttpBinding. Click on file and save and close the tool.

ServiceConfigurationEditor.jpg

Now it’s time to host the service to a location so that our application can consume it from a fixed location. When we added the wcf service application by default visual studio 2005/2008 configure the service to run on visual studio development server. We are going to modify this to run from IIS. For this right click on wcf service project and select properties. After project properties window popup, navigate to web tab and change the server configuration under servers section from “Use Visual Studio Development server” to “Use IIS Web server” after that you need to click on create virtual directory button to finish the process. Now save the project. And you are all done configuring the service for you xbap. If you are in windows vista you can encounter with few errors, to overcome the problems you must run visual studio with “run as administrator” mode.

Consume WCF Service from XBAP

The hard part is now over, just add a service reference like normal procedure i.e. right click on project select “add service reference “ after add service reference window popup, click on discover button. You will see the service will be found and URL will be added to the address textbox. Click okay and you are all done.
Because of the previous action that is performed appropriate mark up will be added in the app.config under service model configurations section. The markup that is added look like this


<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" 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="Text" 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://munna.kaz.com.bd/TODO.SERVICE/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
contract="TodoServiceReference1.IService1" name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>


Debugging WCF Service



While developing XBAP sometimes developers need to debug the
application. Developer may needs to investigate what data is received
to the service and what data is transmitted from the service. Well,
since WCF works in XBAP only in partial trust mode it’s become a little
bit difficult, but not yet that much difficult. While debug from visual
studio 2008 we can set the “trust mode” to full trust. You can set
trust mode to full trust from security tab of project properties. This
will enable your WPF Project to debug in application in development
environment. But while deployment you must change trust mode back to
partial trust otherwise you will encounter with trust not granted error.


Deploying your solution



First of all developer needs to set XBAP’s security mode to partial
trust. In publish wizard first step is to specify where you want to
publish the binary. Browse and select a folder as convenience. Click
next will guide the user to select next option which is selection of
how the user will install the application. In this screen developer
needs to select “from a web site” option and specify the location of
the web site. Browse or put down the location of the web site. While
deploying your solution you must be careful about the deployment URL
and the URL or the WCF service that is defined in the app.confiq of the
XBAP. In app.config let’s say you have an end point with
http://localhost/wcfservice you should also put your XBAP deployment
URL as http://localhost/xbaphost. If you in app.config you have
localhost but you browse as http://{pcname}/xbaphost things won’t work
and you will end up with a code access security violation exception. So
you must remain consistent about the URL of WCF Service, XBAP Host, and
the URLS.



PublishWizard.jpg


Using the WsHttpBinding Configuration



You can also use WsHttpBinding to communicate with the wcf also, but
few things need to configure to ensure that you don’t suffer from code
access security exception. If you want to use WsHttpBinding you don’t
have to create any new binding. Visual studio 2008 by default creates
two end points for a wcf service application one is WsHttpBinding and
another is MaxHttpBinding. What developer needs to do is to configure a
new binding configuration. To accomplish this edit the web.config of
WCF Service application. In default window you will see first endpoint
is configured with WsHttpBinding and under the endpoint a default
binding is configured, it should say “(Default) Click to Create” just
click to create new binding configuration and configure it not to use
reliable session and security mode to None. Bellow the service mode
configuration is provided for better understanding; eventually WCF
Configuration Editor will generate this sort of markup.




<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="NewBinding0" messageEncoding="Text">
<reliableSession enabled="false"/>
<security mode="None">
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="TESTWCF.Service1Behavior" name="TESTWCF.Service1">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="NewBinding0"
contract="TESTWCF.IService1">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TESTWCF.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove


the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below


to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>



Make sure that you set enable reliable session to “false” and set
security mode to “none” in both client endpoint and service’s endpoint
binding configuration. Otherwise XBAP can suffer from code access
security exception.


A quick discussion on Data Transfer Limit



XBAP to WCF communication data transfer have few limitations in data
transfer size. If you are transferring huge list of objects that
exceeds the size specified in max buffer size and max receive size in
web.config application will cause receive limit exceed exception. You
can increase the size of the maxBufferSize and maxReceivedMessageSize
from web.config in binding configuration section of service, but
increasing its size will cause the application suffer from code access
permission exception. So a very straight forward way to escape from
this issue is to make your service in such a way so that you don’t
return data that exceed the size limit. And if you have huge data to
transfer, change the service contract in such a way, so that you can
transfer data in multiple requests, and in every request size limit
should remain under the maxBufferSize.


Conclusion



In few cases you will see that service is taking a little bit time
to respond to your request, and that can cause your application to
become irresponsive for few seconds. To escape from this problem you
can use background process to call the WCF service, and display a wait
screen to the user and hide the wait screen after the process finished
execution. That concludes a beginner introduction to xbap to wcf
communication.

Sunday, June 22, 2008

Improved Resource file project template in vs2008

Visual Studio 2008 resource file project template is now more improved! and more usable.It has very user friendly and easy to edit environment, providing the user with the ease of managing resource better than ever. I have been using resource file since Visual Studio 2003. Previously I got to write code and use resource manager to pull the resources from the embedded resource file. And there are maintenance hassles to load a resource only once. We did lot of engineering previously to resolve the easy management and developer friendly architecture for resource accessibility. Now resource management with Visual Studio 2008 resource file template is a child's job.

 

What can be added in resource file

 

Now we can add different type of resource file just with few mouse click, isn't it great. Okay, here is the list of file type you can add as a resource file in resource file template.

  • String
  • Image
  • Icon
  • Audio
  • Files
  • Other(Virtually every thing!)

 

 

So there is lot to work with resource file. The magic is you can add these files with drag and drop from any location. Adding resources is that much easy. Still you have some traditional way of adding resource, you can add new resource and also add existing file from the disk. for this we have to click on "Add Recourse" button in Resource Management Window.

 

 

Access Modifier

 

Resource file and its type has few access modifier just like our class access modifier. If you set access modifier as "No code generation"  no designer generated code will be generated! ... this means now we don't have to write any manager class to manage and pull the resources from embedded resource file if we choose access modifier other than "No code generation". Here are the options we have in access modifier.

  • Internal
  • Public
  • No code generation

 

Visual Studio 2008 will automatically write a class and code for you so what you can access your files right way. This is one of the major improvement in resource file template of Visual Studio 2008. If you set access modifier as "Internal" your resource can only be accessed from the container project of the resource file, that implies what you can not access resources, that are marked as internal, from out side the project. So of course setting the access modifier to "Public" will made our resource accessible from any where.

 

I have used string file in in couple of my projects and did all custom codes to manage those. Now I use resource file right way because its so easy. Here is a view what designer generates for you.

 

 

Resource File "IntelliSense"

 

Since we have a designer generated code so we can use the class right way in our code and also enjoy the facility of intellisence. A very beautiful feature is that if we will get the object as typed object, means if we added string type it will give use string object, and if we have added image in our resource file it will return a Image Type object. so its pretty smart and we can bind it to a Image Control to display it.

 

 

Well another thing that I want to share, that, its has different type of view in resource manager window. we can switch to thumb nail mode if we are using image and easily locate which image we are looking for. Of Course we can also filter our resource using resource type selector.

NOTE: Each Resource is added against a key so. Key must be unique.

Thursday, May 8, 2008

Using Background Process in WPF

WPF applications often needs to call time consuming methods or processes, the time consuming methods or processes can be, huge time consuming calculation or perhaps a web service call. In case of WPF specially XBAP (wpf browser application) which run on remote client machines browser, this sort of calls can make your user interface unresponsive.  I am working with WPF for more than four month. Lot of things come in to way and dealt with nicely. Well in this post I am going to share a simple trick for avoiding unresponsiveness of user interface. We have already used this technique in many cases in our application, but this is for WPF.

The "Thread & Invoke"

BackgroundWorker is a very smooth and useful tool for our purpose of making more responsive UI(user interface). Before discussing more about BackgroundWorker lets take a flash back of legacy technique (which is pretty smart)  implementation of making  more responsive UI. Previously I used threading for implementing such kind of UI smoothness. What I did is to create a background thread and call expansive operation on that thread. When the job is finished use the "MethodInvoker" method to let know the UI thread that the job is finished. And this model is called asynchronous model. And this is quite smart model and rest of the models are based on this approach. Here is a quick code snippet for demonstration the technique.

//first start the method with tread
System.Threading.ThreadStart ts = new System.Threading.ThreadStart(ExpansiveMethod);
System.Threading.Thread t = new System.Threading.Thread(ts);
t.Start();
protected void ExpansiveMethod()
{
//Very expansive call will go here...
//after the job is finished call method to update ui
MethodInvoker updaterMI = new MethodInvoker(UpdateChange);
this.BeginInvoke(UpdateChange);
}
protected void UpdateChange()
{
//again back to main ui thread
}


 


The "Background Worker"


Okay, its time to use the BackgroundWorker. An amazing thing about background worker is, its simple to use.  First, lets see what a background worker is. "BackgroundWorker" is a class under "System.ComponentModel" which executes an operation on a separate thread. Which is introduced from dot net framework 2.0. Things are again pretty simple just like tread, All you have to do is instantiate a BackgroundWorker and subscribe its events, and call the "RunWorkerAsync()" method. Lets put a code snippet. Since we are programmers we understand code better.




void MyMethodToCallExpansiveOperation()
{
//Call method to show wait screen
BackgroundWorker workertranaction = new BackgroundWorker();
workertranaction.DoWork += new DoWorkEventHandler(workertranaction_DoWork);
workertranaction.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workertranaction_RunWorkerCompleted);
workertranaction.RunWorkerAsync();
}
void workertranaction_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Call method to hide wait screen
}
void workertranaction_DoWork(object sender, DoWorkEventArgs e)
{
//My Expansive call will go here...
}



As you can see in above code I have subscribed two event "DoWork" (which is the main function) and "RunWorkerCompleted", In dowork event handler we will put our expansive time consuming operations, as the name imply's RunWorkerCompleted event is fired when the work is finished . BackgroundWorker also has "ProgressChanged" event which is used to let the main UI thread know how much work is completed.


The "Dispatcher"


In few cases the BackgroundWorker needs to access the main UI thread. In WPF we can use "Dispatcher" which is a class of "System.Windows.Threading" and a delegate to access the main thread. First of all we have to declare a delegate for our candidate methods, and then use the delegate to call the method using Dispatcher. Dispatcher has few thread priority and you can use various priority from DispatcherPriority enum. "Send" has the highest priority in DispatcherPriority.




//delegate for our method of type void
public delegate void Process();
//and then use the dispatcher to call the method.
Process del = new Process(UpdateMyUI);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, del);
void UpdateMyUI()
{
//get back to main UI thread
}



For more reading about this Asynchronous Programming please visit the references.


Reference



Thursday, April 10, 2008

Wpf Image ,Working with Image Source

Hi after a long time I am back in my blog. In this post I will discuss few things about WPF image object. Recently I have been working in a project whose UI Layer is build entirely with windows presentation foundation.

Background

WPF has another way to display image. That is, using BitmapImage object. You can declare BitmapImage tag and in WPF XAML just like Image tag. But in case of BitmapImage the source property is a Uri name is UriSource. Luckily BitmapImage is the source property of Image. Here is a simple code segment of Image and BitmapImage.

ImageSource & BitmapImage

WPF has another way to display image. That is, using BitmapImage object. You can declare BitmapImage tag and in wpf xaml just like Image tag. But in case of BitmapImage the source property is a Uri name is UriSource. Luckily BitmapImage is the source property of Image. Here is a simple code segment of Image and BitmapImage

<Image Width="200" Margin="5" Grid.Column="1" Grid.Row="1" >
<Image.Source>
<BitmapImage UriSource="sampleImages/bananas.jpg" />
</Image.Source>
</Image>

Mouse hover effect

Bellow I have listed few lines of code when i change the image in mouse enter and mouse out of an image object. Of course I am using Uri to define the location of my image then using the Uri to make a new BitmapImage and finally use BitmapImage to assign Image.Source Property.


1: private void btnGoToHome_MouseEnter(object sender, MouseEventArgs e)


2: {


3: this.Cursor = Cursors.Hand;


4: Uri src = new Uri(@"C:/Images/DifferentTransaction_Icon_Active.png");


5: BitmapImage img = new BitmapImage(src);


6: btnGoToHome.Source = img;


7: }


8:


9: private void btnGoToHome_MouseLeave(object sender, MouseEventArgs e)


10: {


11: this.Cursor = Cursors.Arrow;


12: Uri src = new Uri(@"C:/Images/DifferentTransaction_Icon_Normal.png");


13: BitmapImage img = new BitmapImage(src);


14: btnGoToHome.Source = img;


15: }




That's it you are done




Reference




http://msdn.microsoft.com/en-us/library/system.windows.controls.image.aspx

Thursday, March 6, 2008

No Scroll content of wpf xbap in iframe

In my previous blog post i have discussed about how to hide the navigation ui of xbap while you hosting Xbap ( Xaml browser application) in iframe. Note that xbap can be accessed directly from browsers url address and can also be viewed in a iframe in existing web site. In both case user can have contents that requires scrolling.If user developed the xbap application in such a way that the application will be accessed directly form url address, user can archive the goal by adding a "scrollableview" element in your xmal page. bellow a code sample is provided.

   1:  <Page x:Class="CookieTest.Page1"

   2:        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:        Title="Page1">

   5:      <ScrollViewer>

   6:          <Grid>

   7:              <!--your content will go here–>-->

   8:          </Grid>

   9:      </ScrollViewer>

  10:  </Page>


Next case is if user hosted the xbap application in a iframe. In this case there is a good chance that user will be viewing two vertical scrollbar in user's browser if users existing site's page is long enough to cause view a vertical scroll bar, that is the browser's vertical scrollbar. Xbap host have a defined size, which generally as long and wide as the browser window. So if your content is longer than the size of xbap host, you can loose your content from viewable content area. or you will end up having two scrollbar.Well there is several solutions to this problem. Lets discuss with a simpler version. Make the iframe's height property as long as the xbap that is hosting the xbap. And make sure that your xbap will not grow larger than that. but if your xbap has variable content and has variable height and you got to keep the constant look you need to do some engineering to keep things smooth.Xbap do support get and set of cookie in the site of origin. so do calculate your height for your content in xbap and then set the height as a cookie, make sure you do set the height of the content as a cookie each time the content of xbap has changed, of course in case of the content that cause the xbap to change its size. here is a code example to set cookie for site from xbap.


Application.SetCookie(BrowserInteropHelper.Source, "HEIGHT=" + DemoHeight );


Now in the page, where you hosted your xbap in iframe read the cookie with javascript and the change the height of the iframe. that's it you will have a smooth operation of auto grow or shrink of your xbap and wont cause any extra scrollbar. for reading the cookie do a little engineering for example always track the height cookie with javascript timer based function.




   1:  <script language="javascript" type="text/javascript">

   2:  function getCookie(c_name)

   3:  {

   4:      if (document.cookie.length>0)

   5:      {

   6:        c_start=document.cookie.indexOf(c_name + "=");

   7:        if (c_start!=-1)

   8:          {

   9:          c_start=c_start + c_name.length+1;

  10:          c_end=document.cookie.indexOf(";",c_start);

  11:          if (c_end==-1) c_end=document.cookie.length;

  12:          return unescape(document.cookie.substring(c_start,c_end));

  13:          }

  14:      }

  15:      return "";

  16:  }

  17:  function InCreaseHeight()

  18:  {

  19:      var hight = getCookie('HEIGHT');

  20:      if(hight != "")

  21:      {

  22:          if(document.getElementById('framename')!=null)

  23:          {

  24:              if(hight<600)

  25:              {

  26:                  hight = 600;

  27:              }

  28:              document.getElementById('framename').height = hight;

  29:          }

  30:      }

  31:      setTimeout("InCreaseHeight()",250);

  32:  }

  33:  </script>


one more thing do call the javascript increase height function on body on load event of the page to kick start the process.




   1:  <body onload="InCreaseHeight();">


Reference:


http://www.w3schools.com/js/js_cookies.asp
http://msdn2.microsoft.com/en-us/library/ms750478.aspx#Cookies



Thursday, February 7, 2008

Hide Navigation UI (back, forward button) of Xbap application

Xbap application can be used directly in browser or can be used in a iframe in a web page. when you use directly in browser, browsers nagivation ui is used as xbap navigation UI . But if you use xbap in a iframe xbap host automatically add two back forward button and add a navigation header to your xbap application. if you are using the xbap in a existing web page and in a iframe this cause a little bit problem.

but we can hide the navigation ui very easyly... all we have to do is to set the wpf page object's ShowsNavigationUI property to false... thats all... you are done. But if you are using an "user control" as startup object there is no way to set the property. This works only in case of WPF Page project item template.

But you can still hide the navigation UI... on application's contractor subscribe the navigated event ..

public App()
{
this.Navigated += new NavigatedEventHandler(App_Navigated);
}

void App_Navigated(object sender, NavigationEventArgs e)
{
NavigationWindow ws = (e.Navigator as NavigationWindow);
ws.ShowsNavigationUI = false;
}