Thursday, 20 December 2012

Connecting to a WCF RESTful service from a Windows 8 Store App: Part 2 Connecting to the WCF Service

Part 2 of this mini blog series which is simple example of how to connect a Windows 8 store app to a WCF RESTful service. In Part 1 I went and created a very simple WCF RESTful service that had one simple GET method that returned an object.

In the first Part I created a solution with 2 projects in it one a WCF Service Application and the other was a Windows 8 Store App. I decided to start with a blank XAML app and first things first I stuck in a quick bit of mark up to create a very simple user interface.


One thing I have included here is a nifty little thing I found which you now have to do compared to writing XAML for WPF. The highlighted line that sets the horizontal and vertical alignment on the control. This is because compared to the likes of WPF grid layout controls the content within them isn't set to fill the entire row or column by default. It auto sizes to the size of its content. However I prefer my grid controls to do the resize of its child controls for me if the window size changes and therefore this is why I have set them to stretch.

Anyway I digress once this is in place I created a button event that would do the call to the WCF RESTful service to get my data and then place it into a readonly TextBox

private void btnCall_Click(object sender, RoutedEventArgs e)
{
    CallService();
}

public async void CallService()
{
    HttpClient client = new HttpClient();
    string url = "http://localhost:59000/Goat/1";
    HttpResponseMessage response = await client.GetAsync(url);
    txtResponse.Text = await response.Content.ReadAsStringAsync();
}
The button calls another method that will do all the work to get JSON data back and place it into the TextBox. In the past I would have created a HttpWebRequest and set the headers and then created a HttpWebResponse for the response or use I would use the WebClient, however this isn't avalible for Windows RT so I had to use the new HttpClient object. In this very basic example all I do is create a HttpClient object I have the url for my service which is running on localhost as its in the same solution. I have however set the service to always run on port 59000.

The next thing that is happening is the client object fires the GetAsync method passing it the URL. The reason it is a GetAsync is because we are using the GET HTTP verb as that's what the WCF RESTful service created in part 1 is expecting. Now to use this method you require the async/await keywords and there is an good post that best describes these here

Now this is a simple example which is just showing the basics. Once I have had more time to play with this I may post a Part 3 to this blog which could contain other HTTP Verbs, Authentication and also look into what the method returns and doing more with the response.

Useful Links:
Part 1
Source Code

Wednesday, 19 December 2012

Connecting to a WCF RESTful service from a Windows 8 Store App: Part 1 Creating the WCF Service

Update:
Part 2: Creating the Windows 8 App Now Up

This is part 1 of a simple blog to give you guys a heads up on the best way to connect a Windows 8 store app to a WCF RESTful service. I had some problems trying to get this working for a project I am on at work so thought I would share. All the source code for this project is available from my GitHub here.

This project was designed to be a quick a simple example to help others that maybe having the same problem. I started but firstly creating a Windows 8 Store application (we will look at this in more detail in part 2). If you haven't already you will need to ensure that you have a developer licence which is really easy to set up, if you don't have one Visual Studio will ask you to sign in when trying to create this application type. Some help with acquiring a developer licence.

Once I had the solution created I then went and added an additional project of WCF Service Application.In the past when I have done this I have used a specific project type for WCF RESTful service template that you can add to Visual Studio, but for this example I didn't have that to hand.



By choosing this template I had to do some more work to get it working the way I wanted. First things first I added a Global.asax top the service project and this is because I wanted to take advantage of the routing in ASP.NET and also because I have done  previous WCF RESTful services this way and I like the way it works. I then added a new route to the route table in the Global.asax.

        private void RegisterRoutes()
        {
            RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Service1)));
        }

Note: When adding this you may need to add a reference to System.ServiceModel.Activation to allow for the new Service Route.

The next thing I did was to update the config file to include the bindings, endpoints and behaviorConfigurations. Below is a small snippet of the config service endpoint for the full config check the solution.

      
        
        
      

The final thing on the service I did was implement the Service and operation contract. For this example I created an additional layer that generated 3 Goat objects that I would then be able to return from the service depending on the id passed.

Service Contract:
[ServiceContract]
public interface IService1
{
    [WebGet (UriTemplate="Goat/{id}", ResponseFormat= WebMessageFormat.Json)]
    Goat GetGoatForId(string id);
}

Important things to note in the above code:
  • The use of WebGet on the method signature this is to specify the HTTP verb used for this method.
  • The URI template. This specifies the url you can use to access this method.
  • Note the type of the parameter in the signature. its string and this is because everything with URI's are string. however the id type of the object is an int, so we simple parse the id in the service method.
Service:
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    GoatService goatService = new GoatService();

    public Goat GetGoatForId(string id)
    {
        return goatService.GetGoatFromID(int.Parse(id));    
    }
}

A quick test in the browser to make sure that it is working with the URI template highlighted.


There we go a Simple WCF RESTful service ready and waiting for our Windows 8 Store app to consume, which I will follow up in Part 2 in the next few days.  

Quick Blog: Code Syntax Highlighting in blogs

Just found this little gem of a post

http://www.craftyfella.com/2010/01/syntax-highlighting-with-blogger-engine.html

Following the quick steps in here got everything working quickly and I can now provide useful code snippets instead of screenshots. For Example:


            
// Start of Code.

for (int i = 0; i < 10; i++)
{
    Console.Writeline("Value of i: " + i);
}

// End Of Code.

Wednesday, 12 September 2012

Fun Packed Free Weekend


I say fun packed and that is I guess a slight lie but still it was a good weekend and I did do a lot of things that I was able to do for free.

Firstly I guess we'll start with Friday mainly because for me it is the start of the weekend and we had, had a fairly decent week of work I managed to do some proof of concept work on HTML5 canvas which I will be blogging about shortly. After finishing work there was a colleagues leaving drinks that was in this bar called Thirsty Bear this bar/pub is according to their site "A Pub Revolutionised" and I was a little sceptical of this and wasn't quite sure on what to expect.

Basically they have pumps dotted around with an iPad that is linked to each and then they also have several other iPads around the tables as well. You leave your card behind the bar and get given a card with a magnetic strip that you swipe through a card reader attached to the iPad. The pumps are then unlocked for you to pour you own drinks. You can also order other drinks from the bar downstairs and food to be delivered to your table/iPad I thought this was an amazing use of technology and had to give it a go and to be fair it worked really well.

Anyway I digress on to the actual weekend Saturday I work up early and wasn't feeling to great so first things first to solve my problem I had a burger from Honest Burger.


Now I am now burger blogger (see these guys for that Hamburger-me / Burgerac) and I have been to Honest's burger joint in Brixton before and that was amazing but this was something else and it managed to sort me out completely.

My Saturday evening was then spent on London's South Bank watching the Burnout Punks a sort of Fire Circus thing preform outside the national theatre as part of the Thames Festival. These guys were amazing see the video below. They had everything from banter through to explosions. 



Sunday was going to be a restful day but I ended up doing a load of house work before working on a simple HTML5 canvas example getting a image to move across a background on the left and right arrow keyboard events and to jump when space is entered (again a post about this to follow) before heading back up to Waterloo Bridge to catch the end of the Thames Festival firework display. 









As the title states it was a busy weekend with a lot going on and I recommend Honest Burger to any burger fans out there and also to check what free stuff is going on in London as there is some stuff that is worth a watch.

Saturday, 8 September 2012

Flowers

Quick post of some photos I have taken off flowers over the years haven't had much chance to get out and take many photos recently, which is a shame.










Tuesday, 28 August 2012

WPF Resizing Inner DataGrid Problem

I started this post in December last year and I am only just getting round to completing it now. While I was working a colleague came to me with a WPF problem which I had to look into and sort as it was bothering me.

The Problem:
A WPF DataGrid with each row having its own row details and the template for this is another DataGrid. This is fine however the tricky part was getting the inner DataGrid width to resize along with its columns when the window resizes like the outer grid will as long you are using the correct layout and no width has been set.

Now I have been doing WPF for about 3 years and I am still finding out the ins and outs of the DataGrid control I find it can be very powerful yet at the same time stab you in the back and not work the way you want, sometimes when problems like this arise they are extremely frustrating.

After looking into this somewhat the best option that I could come up with to do this without any code behind (XAML based only) was to bind the width of the inner grid to the ActualWidth property of its parent grid. for example:



<DataGrid Name="dgrDetails" DataContext="{Binding XPath=Tracks}" 
          ItemsSource="{Binding XPath=Track}" AutoGenerateColumns="False"
          Style="{StaticResource DataGridStyle}" Margin="0" 
          RowDetailsVisibilityMode="Collapsed"
          Width="{Binding ElementName=dgrMain, Path=ActualWidth}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="No." Binding="{Binding XPath=No}" Width="*" />
        <DataGridTextColumn Header="Title" Binding="{Binding XPath=Title}" Width="*" />
        <DataGridTextColumn Header="Length" Binding="{Binding XPath=Length}" 
                            Width="*" />
    </DataGrid.Columns>
</DataGrid>


I will upload the full source for this problem along with some other useful data grid examples up to my GitHub in the next 2 weeks and will link it in here.

Wednesday, 22 August 2012

Sending files as a Base64 String to a WCF RESTful Service

I recently came across a problem at work which was so frustrating and took the total of 3 days to fix so I thought it was vital that I write this blog.

For a project I am working on at work we are using a WCF RESTful service as an endpoint to provide and revive data in JSON format to an iPad. It came to the point where we needed to get PDF's (not overly sized I might add) off the iPad and back up to the server using the WCF REST service. It was my job to create the methods on the service to allow this to happen. I did a quick Goggle as this was newish territory for me and from what I found it seemed like a relatively simple task to do. (Oh how I was wrong). Me and my colleague had decided that the best way to do this was to convert the file into a Base64 string and then send this up with in the JSON to the service.

So I created the method signature that took a DateTime for sync purposes and an object which would have a set of properties one of which being the Base64 string.

Example WCF RESTful Service PUT Signature

Once this was done I went on to use a quick C# test app that I have created to test the service before the iPad connects to it and in this I kept getting a 400 Bad Request HTTP response.

The problem was due to a setting in the configuration file it took me 3 days to come round to this and a whole world of hurt.

During the second day of pain and when I was getting ready to give up my colleague found an excellent post that was very helpful and it was in fact from this post that I got the working config needed.

http://www.codeproject.com/Articles/327420/WCF-REST-Service-with-JSON

Essentially in the example in the above link he sends a large byte array around the size of 10mb up to a WCF RESTful service. The key thing in his example though is the configuration file and that he is using a attribute called TransferMode and this was set to streamed request.

Transfer Mode Attribute Set To Streamed Request

After implementing his example I then began to move it over to our project and and everything seemed to be working, first a byte array and then a Base64 string however I came across one last problem and that is as follows. The WCF RESTful project we have created uses Basic Authentication to ensure that our traffic is encrypted and sent over SSL. The problem is this you can't have streamed request turned on with Basic Authentication. However upon removing this attribute form the config it started to work which lead me to believe there was something not set up correctly i nthe orriginal config which was causing the server to ignore the maxReceivedMessageSize, maxBufferSize, etc attributes in the config.

Configuration Settings for Binding and the Behaviors 

To summarise the two problems I faced were:

  1. The configuration settings not being set correctly
  2. The transferMode="StreamedRequest" attribute doesn't work with Basic Authentication.