Windows Communication Foundation (WCF Service) vs Web Service

Before you read this post, I would like to admit that the content of this blog is not written by me but I copy it from many resources on internet. I always ask (review) myself why Microsoft must invent WCF Service. What are the advantages of WCF in compare to web services? I found many answers on internet and would like to archive them for myself. The source of these information I insert at the end of this post.

[table id=1 /]

Source : http://msdn.microsoft.com/en-us/library/ms730214.aspx

Windows Phone – Phone PC Connector through WCF service

Windows Phone OS is being developed and I do not know which protocol Microsoft use to allow users and developers to transfer data between PC and phone, may be USB, Wifi, Bluetooth, etc … Within these protocols I prefer using protocol based on IP therefore today I would like to write a small demonstration which lets me download/upload file from PC to phone/from phone to PC.
The Demo source code consists of 2 projects :
– The sever is a WPF application running on PC. When the server starts to run, a WCF service will be automatically executed and listens on specific port to request and gives response back to phone client.

– The client is a Silverlight application running on Windows Phone Emulator. The client requires information of the IP and opened port of server for building the connection and accessing the WCF service. These settings are stored in InsolatedStorageFile within AppSettings.xml file and can be edited by client.

Before I start to discuss a little about my demo, there are some requirements we should do so that it runs smoothly
– If you are running a firewall, you must register the server so that the firewall allows inbound and outbound traffic of server. This registration can be done with programming but I still don’t integrate it into program.


Server side

As I said above, the server will host a WCF service inside it and starts the service at the same time. This service will open an available port (which requires administrator right and access through firewall) and binds the service to that port.

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
	try
	{
		lblServer.Content = TCPClass.GetIPV4();
		CustomConfiguration.Port = TCPClass.GetAvailablePort();
		txtPort.Content = CustomConfiguration.Port.ToString();
		txtServiceUri.Text = "http://" + TCPClass.GetIPV4() + ":" + CustomConfiguration.Port + CustomConfiguration.ServiceName;
		txtTargetFolder.Text = Directory.GetCurrentDirectory();
		m_wcfsFileTransfer = new WCFService();
		m_wcfsFileTransfer.CreateService();
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
	}
}

ServiceHost uses BasicHttpBinding with TransferMode set on Streamed. “Setting the transfer mode to Streamed enables streaming communication in both directions. Streamed transfers can improve the scalability of a service by eliminating the need for large memory buffers. Whether changing the transfer mode actually improves scalability in practice depends on the size of the messages being transferred. Improvements in scalability should be most evident when large messages use streamed instead of buffered transfers.“. I already set the buffer size very large (64 MB) for sending large file.

public void CreateService()
{
	try
	{
		Uri uriTcpAddress = new Uri("http://" + TCPClass.GetIPV4() + ":" + CustomConfiguration.Port + CustomConfiguration.ServiceName);
		Uri[] uriBaseAddress = { uriTcpAddress };

		m_shHost = new ServiceHost(typeof(FileStreamingService), uriBaseAddress);

		BasicHttpBinding ntbBind = new BasicHttpBinding(BasicHttpSecurityMode.None);
		ntbBind.MaxBufferPoolSize = (int)67108864;
		ntbBind.MaxBufferSize = (int)67108864;
		ntbBind.MaxReceivedMessageSize = (int)67108864;
		ntbBind.SendTimeout = TimeSpan.FromSeconds(15);
		ntbBind.MaxReceivedMessageSize = 67108864;
		ntbBind.ReaderQuotas.MaxArrayLength = 67108864;
		ntbBind.ReaderQuotas.MaxStringContentLength = 67108864;
		ntbBind.TransferMode = TransferMode.Streamed;

		m_shHost.AddServiceEndpoint(typeof(IFileStreaming), ntbBind, "");

		ServiceMetadataBehavior smbBehavior = m_shHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
		if (smbBehavior == null)
		{
			smbBehavior = new ServiceMetadataBehavior();
			smbBehavior.HttpGetEnabled = true;

			m_shHost.Description.Behaviors.Add(smbBehavior);
		}

		m_shHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:" + (CustomConfiguration.Port - 1).ToString() + CustomConfiguration.ServiceName + "/mex");
		m_shHost.Open();
	}
	catch (Exception ex)
	{
		throw ex;
	}
}

After creating service, we can defines some operation contract so that the client can access and transfer data.
– GetStream : download file from PC to phone.
– UploadStream : upload file from phone (IsolatedStorageFile) to PC.
– GetStartUpFolder : get the folder where the server program locates.
– GetFolderInfo : get list of files and sub-folders of a specific folder.

[ServiceContract]
public interface IFileStreaming
{
	[OperationContract]
	System.IO.Stream GetStream(string data);
	[OperationContract]
	bool UploadStream(FileUpload stream);
	[OperationContract]
	string GetStartUpFolder();
	[OperationContract]
	List<ObjectInfo> GetFolderInfo(string Folder);
}

Client side
The mission of client is pretty simple. It just calls the service with appropriate data and receives data back. The operations of WCF services will be parsed in class ViewModel and used in client to browse, upload, download file in PC and phone.

void Explorer_Loaded(object sender, RoutedEventArgs e)
{
	string strType = "";
	NavigationContext.QueryString.TryGetValue("Type", out strType);
	if (strType == "PCExplorer")
	{
		btnUp.Visibility = System.Windows.Visibility.Visible;
		tbCurrentFolder.Visibility = System.Windows.Visibility.Visible;
		m_bUpload = false;
		vm.ReadConfiguration();
		vm.StartPCExplorer();
	}
	else
	{
		btnUp.Visibility = System.Windows.Visibility.Collapsed;
		tbCurrentFolder.Visibility = System.Windows.Visibility.Collapsed;
		m_bUpload = true;
		vm.ReadConfiguration();
		vm.StartPhoneExplorer();
	}
}

What we should make a concern about is that the operations should be called asynchronously and the stream type will be therefore automatically converted to byte array.

public void StartPCExplorer()
{
	try
	{
		fscClient.GetStartUpFolderCompleted += new EventHandler<GetStartUpFolderCompletedEventArgs>(fscClient_GetStartUpFolderCompleted);
		fscClient.GetStartUpFolderAsync();
	}
	catch (Exception ex)
	{
		throw ex;
	}
}

I am installing VS 2010 on my desktop and therefore I can not develop Windows Phone Application on my desktop. I must use my laptop to develop client. Hence the project contains 2 separated solutions. The complete source code you can download here “Windows Phone PC Connector“.

C# – Custom code editor

Did you ever need a code editor embedded in your program? When I am running around some forums and read articles about interesting library, I discovered a very useful library which allows me to have a code editor directly in my program. This code editor control is ScintillaNET and parses our code very beautifully as image below

The homepage of this .net control is http://scintillanet.codeplex.com/ . Just navigate to that website, download and add reference to it from project. You need to read the instructions for installing carefully otherwise the control can not be compiled. For example, if you meet the error “%1 is not a valid Win32 application” as in my case, you can read instructions here to fix it http://scintillanet.codeplex.com/WorkItem/View.aspx?WorkItemId=23101 . I just copy ScintillaNET DLL to folder of program, set to run only on 0x86 operating system and everything runs smoothly. We can adjust some settings so that we have a professional code editor. For example,

1. Enable syntax highlighting through define the language of source code

Syntax highlighting

2. Enable code line number

3. Enable folds to group and un-group block of code

For more advanced features you can read homepage of control. I built a running example which you can download here. “Custom code editor

There are of course some alternatives to ScintillaNET which I list below
– Actipro SyntaxEditor http://www.actiprosoftware.com/products/DotNet/WindowsForms/SyntaxEditor/Default.aspx
– AqiStar.TextBox http://www.aqistar.com/
– AvalonEdit http://wiki.sharpdevelop.net/%28X%281%29S%28sbe5bd45peye2m45jr4wka55%29%29/AvalonEdit.ashx

C# – Working with interlaced XML database

Today I read a thread on mycsharp.de asking about how man can work with a database whose type is a interlace XML. The XML file has following structure

<?xml version="1.0"  encoding="utf-8"?>
<xs:schema id="DatenbankSpiel" targetNamespace="http://Weltkarte/DantenbankAll" elementFormDefault="qualified" xmlns="http://Weltkarte/DantenbankAll.xsd" xmlns:mstns="http://Weltkarte/DantenbankAll.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Staedte">
    <xs:complexType>
		<xs:sequence>
			<xs:element name="Name" type="xs:string"/>
			<xs:element name="Fraktion" type="xs:int"/>
			<xs:element name="Position-X" type="xs:int"/>
			<xs:element name="Position-Y" type="xs:int"/>
			<xs:element name="Verteidigung-Anzahl">
				<xs:complexType>
				  <xs:sequence>
					<xs:element name="Anzahl" />
					<xs:element name="Typ" />
				  </xs:sequence>
				</xs:complexType>
			</xs:element>
		</xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Continue reading C# – Working with interlaced XML database

Windows Phone – Daily Horoscope Example

Do you believe on horoscope? I do not but my wife does. Sometimes she watches in Internet some predictions about her horoscope and tells me that they are not correct in her case. But in most of cases it was correct and she believes it a lot. She says me that everyone has his own fate and man can not change or something likes that. I always say she should be a fortuneteller. She will earn millions of dollars from this career. ^^. Although I do not believe on horoscope but today I decide to write a small application on Windows Phone to tell user his daily horoscope. With this application I would like to test if I can use DependencyObject to create a custom image button control. The result is ” I failed”. In WPF I can easily create a image button with RelativeSource and AncestorType but Silverlight and Windows Phone do not support it. There is work around with DependencyObject but I still do not know how to do it. So if you know how to make a custom image button control in Windows Phone then please tell me.

The application is very simple. It just fetches data from a RSS feed under XML format and gives information back to GUI. Because I failed with create a custom image button therefore my XAML file looks very terrible as following

<StackPanel Orientation="Vertical">
	<Rectangle Height="25"></Rectangle>
	<StackPanel Orientation="Horizontal">
		<StackPanel Style="{StaticResource CustomSPStyle}" Orientation="Vertical">
			<Image MouseLeftButtonDown="imgAries_MouseLeftButtonDown" x:Name="imgAries" Style="{StaticResource CustomImageStyle}" Source="Images/DuongCuu.jpg"></Image>
			<TextBlock Style="{StaticResource CustomTBStyle}" Text="Aries"></TextBlock>
		</StackPanel>
		<StackPanel Style="{StaticResource CustomSPStyle}" Orientation="Vertical">
			<Image MouseLeftButtonDown="imgTaurus_MouseLeftButtonDown" x:Name="imgTaurus" Style="{StaticResource CustomImageStyle}" Source="Images/KimNguu.jpg"></Image>
			<TextBlock Style="{StaticResource CustomTBStyle}" Text="Taurus"></TextBlock>
		</StackPanel>
		<StackPanel Style="{StaticResource CustomSPStyle}" Orientation="Vertical">
			<Image MouseLeftButtonDown="imgGemini_MouseLeftButtonDown" x:Name="imgGemini" Style="{StaticResource CustomImageStyle}" Source="Images/SongTu.jpg"></Image>
			<TextBlock Text="Gemini" Style="{StaticResource CustomTBStyle}"></TextBlock>
		</StackPanel>
	</StackPanel>
	...
</StackPanel>

You can see that I use StackPanel to store my custom control consisting of an image and a textblock. For each horoscope I add such StackPanel and it is really stupid to do that because when I want to apply style for textblock/image, I must apply it for every textblock/image through copying and pasting. Because I am stuck in creating such control like this http://blogs.msdn.com/mikehillberg/archive/2007/02/01/ParameterizedTemplates.aspx , this is current status. I will update the code if I find a solution. The remaining code is really easy. It is combination of navigating between pages, getting data from web client and parsing data,… etc. Nothing special.

private void imgLeo_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
	NavigationService.Navigate(new Uri("/Astrology.xaml?Horoscope=Leo", UriKind.Relative));
}
...
void wcTemp_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
	try
	{
		XDocument doc = XDocument.Parse(e.Result);
		var vGotArticle = (from s in doc.Descendants("item")
						   select new Horoscope
						   {
							   Title = s.Element("title").Value,
							   Description = TrimAndRemoveNewLine(s.Element("description").Value.ToString()),
						   });
		m_lstHoroscope = vGotArticle.ToList();

		if (m_lstHoroscope.Count > 0)
		{
			var vFound = (from h in m_lstHoroscope
							   where h.Title.IndexOf(m_strHoroscope) >= 0
							   select h).FirstOrDefault();
			HoroscopeImage = GetImageUri(m_strHoroscope);
			NotifyPropertyChanged("HoroscopeImage");
			HoroscopeDescription = vFound.Description;
			NotifyPropertyChanged("HoroscopeDescription");
		}

	}
	catch (Exception ex)
	{
		throw ex;
	}
}

The complete source code of this example you can download here “Windows Phone Horoscope