WCF, Silverlight – Access WCF REST services with Silverlight

Windows Communication Foundation (WCF), part of the .NET Framework, provides the first unified programming model for rapidly building service-oriented applications. It enables the development of secure, reliable, transacted services that interoperate with current Microsoft investments and non-Microsoft platforms.

With the .NET Framework 3.5 release, WCF added support for building REST style services. REST, an architectural style for building distributed hypermedia driven applications, involves building resource-oriented services by defining resources that implement uniform interfaces using standard HTTP verbs (GET, POST, PUT, and DELETE), and that can be located/identified by a URI.

Continue reading WCF, Silverlight – Access WCF REST services with Silverlight

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.

WCF ServiceWeb Service
Windows Communication Foundation (WCF) provides .NET Framework class libraries, tools and hosting facilities for enabling software entities to communicate using any protocols, including those used by Web servicesASP.NET provides .NET Framework class libraries and tools for building Web services, as well as facilities for hosting services within Internet Information Services (IIS)
WCF provides tools that can be used when software entities must be made to communicate with one anotherASP.NET Web services tools are solely for building Web services
WCF supports sending messages by using HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ). More important, WCF can be extended to support additional transport protocolsASP.NET Web services only support sending messages by using the Hypertext Transfer Protocol (HTTP)
WCF provides much richer facilities for deploying and managing applications than ASP.NET Web services provides-
WCF offers a configuration editor, activity tracing from senders to receivers and back through any number of intermediaries, a trace viewer, message logging, a vast number of performance counters, and support for Windows Management InstrumentationASP.NET has a configuration system

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“.

Windows Phone – Use REST WCF Service

Today when I play around with development in Windows Phone 7. I would like to check if I can access WCF REST Service which I discussed before in this post http://hintdesk.com/wcf-silverlight-access-wcf-rest-services-with-silverlight/ . To start with the development in Windows Phone 7 you need to download set of development tools here http://www.microsoft.com/downloads/details.aspx?FamilyID=2338b5d1-79d8-46af-b828-380b0f854203&displaylang=en . This set contains of
– Visual Studio 2010 Express for Windows Phone CTP
– Windows Phone Emulator CTP
– Silverlight for Windows Phone CTP
– XNA 4.0 Game Studio CTP
This packet is about 350 MB and can be installed parallel with Visual Studio 2008 SP1 and .Net Framework 3.5. When I try to move the example of the old post to Windows Phone 7, I think it must be very simple because the old example bases on Silverlight and Windows Phone 7 uses Silverlight as its default template and I am right. During the moving, I just need to copy and paste the code behind without needing to change anything. However some of components in normal Silverlight are not available, for example Label and DataGrid. The label can be easily replaced by a TextBlock but we need more work to make a control to replace DataGrid. I make a snapshot of available controls in image below

Continue reading Windows Phone – Use REST WCF Service

WCF – Generic List is converted to Array

As I discussed in my previous blogs I am developing a small tool for transferring files between computers in LAN. I decided to use WCF as my main technology in this application. During my developing I discovered that a data member whose type is a generic list, was changed when WCF service is exposed to client. The type was changed from a list to an array.

We pay attention to the data member “Files” whose type is a List of FileObject

    [DataContract]
    public class TransferObject
    {
        [DataMember]
        public QueryTypes QueryType { get; set; } // The action of the packet
        [DataMember]
        public string Name { get; set; } //Client name
        [DataMember]
        public string Id { get; set; } //Identification
        [DataMember]
        public List<FileObject> Files { get; set; } //the list of the file

        public TransferObject()
        {
            Files = new List<FileObject>();
        }

        public TransferObject(QueryTypes qtType) : this()
        {
            QueryType = qtType;
        }
    }

And this is the generated client code. We can recognize immediately that the type was changed to an array of FileObject.

 [System.Runtime.Serialization.DataMemberAttribute()]
        public Files_Over_LAN.FileServiceReference.FileObject[] Files {
            get {
                return this.FilesField;
            }
            set {
                if ((object.ReferenceEquals(this.FilesField, value) != true)) {
                    this.FilesField = value;
                    this.RaisePropertyChanged("Files");
                }
            }
        }

The reason for this converting is that “WCF Service are platform-agnostic, they need to use the most primitive data types“. Please consider two scenario below:
Scenario 1 :
What would happen if your web service would be consumed by a .NET 1.x application, where no generics are available?
Scenario 2 :
How would non .Net applications (J2ee or PHP) will consume the service, which doenst have the knowledge of .Net Generics?
The convertion happens because array is the lowest common denominator.

And what we should do if we still want to use generic list. It’s pretty simple. Right click on your service reference, choose “Configure Service Reference”.

At the combo box of collection type, we choose Generic List instead of Array

Now the client code will be exposed correctly as we expect.

WCF – Publish WCF Services in IIS 7 step by step for dummies

Today I would like a post about deploying WCF in IIS to help you avoiding nightmare from error given back by IIS 7 during installation. In the end of this post, you can host a wcf service in your localhost and call it like following

1. Install IIS 7 on your computer. Control Panel –> Programs and Features –> Turn Windows features on or off –> Navigate to “Internet Information Services” –> Select these options, then click on.

Continue reading WCF – Publish WCF Services in IIS 7 step by step for dummies