How To Post To A Remote Server From An ASP.NET Web Form

I recently came an across an interesting problem: I had to post an ASP.NET Web Form to a third party Web site. It turns out to be quite a tricky thing to do – so I thought I’d share my solution with you in case you ever need to do the same thing.

First off: why did I want to post on rather than back?

I am in the process of taking over responsibility for an existing Web site. The site integrates with a bank to take credit cards – and the data needs to be posted.

So why not just use HttpWebRequest?

Because the user has to leave the site, pay and then come back – bringing return parameters back with them.

Ok – so how did the current site work?

It cheated. It’s an ASP.NET Web Forms site, but the page that does the posting is actually PHP!

So – what exactly is the problem with just switching to an ASP.NET Web Form?

Actually, there are several:

  1. ASP.NET Web Forms post back to the same page (or, at a pinch, to other pages on the same server). They don’t post on to third party web sites.
  2. The remote server requires set names for the posted fields – and ASP.NET Web Forms changes these on the client. This problem had two sub-problems:
    1. I had to use runat=”server” controls because the values were dynamic, and
    2. It turns out that ClientIDMode=”Static” fixes IDs, but not names

Q: So how did I make it work?

A: By using jQuery

Here’s what I did:

  1. Added a label telling the user that they needed JavaScript to pay by credit card (or they could pay by bank instead)
  2. Hid the label using jQuery, then showed a button (input type=”button”, not submit) and set its click event to….
  3. Rewrite the form’s action so that it posted to the remote address
  4. Rewrite the control names so that they met the remote sites requirements.
  5. Remove the unwanted form elements such as __VIEWSTATE
  6. Submit the form

Then all I had to do was test it – which I did by creating a page to echo the newly posted values back to the (which also meant I had to set EnableViewStateMac=”false” on the test page).

Here is the JavaScript:

$(function () {
$(‘#needJavaScript’).hide();
$(‘#buttonSubmit’).show().click(function () {
$form = $(‘form:first’);
$form.attr(‘action’, “test.aspx”);
$(‘#__VIEWSTATE, #__EVENTTARGET, #__EVENTARGUMENT’).remove();
$(‘input:hidden’).each(function () {
var original = $(this).attr(‘name’);
var improved = original.substring(original.lastIndexOf(“$”) + 1, original.length);
$(this).attr(‘name’, improved);
});
$form.submit();
});
});

So there you have it – a way to post to a remote server from an ASP.NET Web Forms Web site.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building Web Applications with ASP.NET and Ajax

jQuery: A Comprehensive Hands-On Introduction

Integrating Knockout into a Page

In these posts, I’m working through a process that enables me to implement an MVC/MVVM design pattern in my JavaScript code. In my first post, I discussed why I care (primarily to create a testable application) and set up my server side test functions. In the following post, I started creating the client-side ModelView that wrapped up both the Customer data that I wanted to display and the function that would retrieve the data from the server. I also created the test page that would demonstrate that the client-side Javascript ViewModel worked correctly. Now that I know that code works, it’s time to integrate it into a real page. Again, I’m going to take a Test Driven Development approach.

Creating Server-side Resources

My ViewModel’s getCustomer function will use jQuery’s getJson function to retrieve a Customer object. However, the server-side method I accessed from my test page returned a mock Customer object. For the real application, I need a method that returns a real Customer object. I’ll need to test that new Action that returns an actual Customer object, of course, so I add a Test project to my solution with a reference to my ASP.NET MVC project. This test runs the Action method that will (eventually) return the Customer object, catches the result and, through a Dynamic variable, checks to see if it returned the right result:

[TestClass]
public class CustomerMVVM
{
   [TestMethod]
   public void TestRetrieveCustomer()
   {
    HomeController  hc = new HomeController();
     System.Web.Mvc.JsonResult  jres = (System.Web.Mvc.JsonResult)
        hc.CustomerById("ALFKI");
     dynamic res = jres.Data;
     Assert.AreEqual("Berlin", res.City, "Unable to retrieve customer");
   }
}

Eventually, the Action method in my Controller that passes the test looks like this:

publicActionResult CustomerById(string id)
{
 using (northwndEntities ne = new northwndEntities())
 {
  Customer cust = (from c in ne.Customers
                       where c.CustomerID == id
                    select c).FirstOrDefault();
  ne.Detach(cust);
  return this.Json(cust, JsonRequestBehavior.AllowGet);
  };
}

That’s all I need in my Controller for now, so I’ll return to working in my client.

Binding Data from the ViewModel to the Page

In my View, I need to add a reference to the JavaScript file I created that holds my ViewModel code. I don’t want to put this reference in my Layout View because I only need this code in a few pages. Fortunately, when I set up my Layout View, I added a RenderSection statement in its <head> element. So, in my Customer View, I just need to insert that section with the script reference that I need:

@section Header 
{
 <script src="@Url.Content("~/Scripts/CustomerViewModel.js")"
    type="text/javascript"></script>
}

In the page, I need to do two things to start using my ViewModel. First, I need to activate Knockout so that it will handle moving data from my ViewModel to elements on the page (and moving data from the elements on the page back to my ViewModel). I do that by instantiating my ViewModel and passing it to Knockout’s applyBindings method as soon as the page is fully loaded. I also set my controller variable so that I when I start accessing my client-side methods, the URL will point to the right controller:

<scripttype="text/javascript">
    controller = "Home";
    $(function () {
        var cust = new Customer();
        ko.applyBindings(cust);
    });
</script>

I now need to tie the properties on my ViewModel to elements on my page—in this case, I’ll tie most of my data to <input> elements. To make that happen I add the data-bind attribute to the <input> element specifying which of Knockout’s bindings I want to use and the name of the property I’m binding to. Knockout’s text binding is the most useful since it works with both input and span elements (I could also have used Knockout’s value binding). The one exception to tying my data to input elements is my Customer Id property—I don’t want to allow users to update the Customer Id property (at least, not in the initial display) so I use a span element to display it. The following markup ties three elements are to the CustomerId, CompanyName, and City properties on the ViewModel I passed to Knockout’s applyBindings function:

<p>Id: <spandata-bind="text: CustId" /> </p>
<p>Name: <inputtype="text" data-bind="text: CompanyName" /> </p>
<p>City: <inputtype="text" data-bind="text: City" /> </p>

Binding Functions in the ViewModel to the Page

But I’m not limited to binding properties to elements. I can also bind functions on my ViewModel to events fired in the browser. For instance, I want to have a button on the page that allows users to delete the currently displayed customer. First, in my ViewModel I add a new function that calls a server-side method to handle deletions. In this method, I use my controller variable and my ViewModel’s CustId property (through the self variable I set up earlier) to build the URL I use to access the server-side method:

this.deleteCustomer = function ()
   {
    $.getJSON("/" + controller + "/DeleteCustomerById/" +  self.CustId,
         null,
         function (flag)
              {
              if (flag)
               {
                 self.CompanyName = "";
                 self.City = "";
               }
               else
	       {
                 alert("delete failed");
               }
              }
             );
    };

Which means that I need to create a mock server-side method to test this method against:

publicActionResult DeleteCustomerById(string id)
{
  return this.Json(false, JsonRequestBehavior.AllowGet);
}

I also need another test function on my test page to test my client-side code:

asyncTest("Delete Customer", function () {
            stop();
            expect(2);
            controller = "Test";
            cust = new Customer();
            cust.getCustomer("ALFKI");
            setTimeout(

			function () {
                            equals(cust.CustId(),"ALFKI", "Customer retrieved");
                            cust.deleteCustomer("ALFKI");
                            setTimeout(

			function () {
                                    equals(cust.CustId(),"", "Customer not deleted");
                                    start();
                                },
                                1000);
                         start();
                        },
                        1000);
        }
        );

Once my client-side code has passed all my tests, I move on to the server to create the production version of the DeleteCustomerById method. In true TDD fashion, I first create a test for the server-side method:

[TestMethod]
public void TestDeleteCustomer()
{
 HomeController hc = new HomeController();
 System.Web.Mvc.JsonResult jres = (System.Web.Mvc.JsonResult)hc.DeleteCustomerById("ALFKI");
				dynamic res = jres.Data;
 Assert.AreEqual(false, res, "Unable to delete customer");
}

Using that test to prove my code works, I create the Action method to use in production:

public ActionResult DeleteCustomerById(string id)
{
  try
  {
    using (northwndEntities ne = new northwndEntities())
    {
      Customer cust = (from c in ne.Customers
                    where c.CustomerID == id
                    select c).FirstOrDefault();
      ne.DeleteObject(cust);
      returnthis.Json(true, JsonRequestBehavior.AllowGet);
    };
  }
  catch
 {
      return this.Json(false, JsonRequestBehavior.AllowGet);
  }
}

The last step is to bind my deleteCustomer function I’ve just added to my ViewModel to the click event of a button. As with binding data, I use the data-bind attribute but this time I use Knockout’s click binding specifying the function on my ViewModel that the button’s click event is to call:

<button type="button"
    data-bind='click: deleteCustomer'>Delete Customer</button>

However, while I can manipulate the Customer object on my page, I haven’t actually written the code to retrieve that Customer object. That’s in my next post.

Creating a Testable Client-side ViewModel with Knockout

In my previous post, I discussed why I a JavaScript MVC or MVVM framework is essential: It lets you prove, quickly and conveniently, that your code works so that you can assemble applications out of reliable components. In that post I also started on a project to show how one of those frameworks—Knockout—supports the MVVM design pattern. I also created the server-side methods that my application (an ASP.NET View that displays information for a customer selected by the user) would need. However, what I created were mock functions that I could use for testing. In this post, I’ll start to create the client-side resources my application would need while still focussing on testing the code.

Setting Up the Client

My first step on the client (after adding the Knockout library to my Scripts folder, of course) is to add the necessary script references to my layout page to support using Knockout. For testing purposes, I also include a RenderSection that will allow me to selectively add script references on a View-by-View basis. This basic set of references is used by every View:

<head> <meta charset="utf-8" />  
 <title>@ViewBag.Title</title>
 <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> 
 <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> 
 <script src="@Url.Content("~/Scripts/knockout-2.0.0.js")" type="text/javascript"></script>
 @RenderSection("Header",false)
</head> 

With those references in place I’m ready to start generating some client-side code. First, I add a Javascript file to my Scripts folder to hold the Customer ViewModel that I’ll developer. Again, to support testing, I add a variable called controller to the file that will let me redirect my server-side requests to my mock methods:

var controller = ""; 

Now I can (finally) start defining my ViewModel, beginning with the properties that hold the data my page will both display and allow users to update. I define those properties using Knockout’s observable function:

var Customer = function (custIdIn) {
 this.CustId = ko.observable(); 
 this.CompanyName = ko.observable(); 
 this.City = ko.observable(); 

Using the observable function gives me two-way databinding (the ViewModel automatically updates the View’s elements, the View’s elements automatically update the ViewModel). Other Knockout functions support handling arrays and computed values. I don’t have to use the observable function—if I only wanted the data to flow from my Customer ViewModel to the elements on my page, I could skip using the observable function.

I also define a variable to refer to the current value of this (my ViewModel). I’ll need a reference to my ViewModel later and defining self at this point in the ViewModel’s code bypasses any of the ways that this gets redefined:

var self = this; 

My next step is, still in my Customer ViewModel, to define a function that uses jQuery’s getJSON method to retrieve data from my server-side methods. I’m going to call this function getCustomer and have it retrieve the Customer object from my server-side methods. Once the JSON object is retrieved, the code updates my ViewModel’s properties from the JSON object’s properties. This is one of the places that I use the self variable I defined earlier to avoid problems with this being redefined. I also use my controller variable to define the URL used to access the service:

this.getCustomer = function (custId) {
  $.getJSON("/" + controller + "/CustomerById/" + custId, 
 null, 
 function (cust) {
 self.CustId(cust.CustomerID);
 self.CompanyName(cust.CompanyName);
 self.City(cust.City); } ); }; 

Because my CustId, CompanyName, and City properties are really Knockout observable functions, I must use the syntax shown here to update their values. This ensures, for instance, that changes to the CompanyName and City properties will automatically be reflected in any elements in my page that the properties are databound to.

Testing a JavaScript ViewModel

I’ve got enough functionality written at this point to begin testing (too much, actually, for a real TDD approach—I should have started writing my tests before I put any code in my getCustomer function). In my last post, I defined a controller (TestController) and an action method (CustomerViewModelTest) to use for testing. I can now create the View that will be called from that action method (CustomerViewModelTest.cshtml). I use QUnit for testing client-side code, so I need to add the files Qunit needs (a JavaScript file and a CSS file) to my application. However, I’d prefer not to download those files on every page so I don’t add those references my layout View. Instead, in my test View, I add the references to the Header section that my Layout View references. I also add a reference to the JavaScript file holding my Customer ViewModel that I want to test:

@{ ViewBag.Title = "Customer ViewModel Tests"; } 
@section Header { 
 <script src="@Url.Content("~/Scripts/CustomerVieModel.js")" type="text/javascript"></script>  
 <link href="@Url.Content("~/Content/Tests/qunit.css")" rel="stylesheet" type="text/css" />  
 <script src="@Url.Content("~/Scripts/qunit.js")" type="text/javascript"></script>  
} 

In the body of my page, I add in the headers that QUnit needs to execute and display test results:

<form action="/Test/index">
 <h1 id="qunit-header">Customer MVVM Tests</h1>
 <h1 id="qunit-bannder"></h1>
 <div id="qunit-testrunner-toolbar"></div>
 <h2 id="qunit-userAgent"></h2>
 <ol id="qunit-tests"></ol>
</form> 

I can now test my ViewModel using QUnit’s test function. I set my controller variable to direct all my getJson requests to the mock methods on my Test controller. I use jQuery to prevent my tests from running until the page is fully loaded:

controller = "Test"; $(function () { 

That test consists of instantiating my Customer ViewModel, calling its getCustomer method passing a customer Id, and checking to see if the ViewModel’s properties were updated correctly. Since I’m making an asynchronous server-side call, I can’t simply call my getCustomer method and check the property results—my test code might run faster than my server-side call and check the property before the result is returned. To get around that, I use QUnit’s asyncTest and JavaScript’s setTimeout functions to wait for one second before checking the result using QUnit’s equals function:

var cust; test("Get Customer",
 function () {
 stop();
 cust = new Customer("Test");
 cust.getCustomer("ALFKI"); 
 setTimeout( function () {
 equals(cust.City(), "Regina", "Customer not retrieved");
 start(); },
 3000); } ); 

I can now run my tests and see the results by calling my CustomerViewModel action method on my TestController (and, of course, my test passes the first time).

At this point I have a testable ViewModel but, of course, that’s not much good unless it supports a real page. That’s what I’m going to look at in my next post. But with this framework in place, I know that I’m building my page with something that works.

If you’re looking for a course with a good introduction to TDD in Visual Studio, Learning Tree’s Design Patterns and Best Practices in .NET course is a good choice. However, Learning Tree’s ASP.NET MVC course devotes a whole chapter to TDD with ASP.NET MVC.

Peter Vogel

Creating Testable Applications with a JavaScript MVC Framework

I love test driven development because, assuming that I’m going to test my code at all, the TDD frameworks make testing much easier and faster—much faster than running the whole application in order to test a few lines of code, for instance. The problem is that my usual JavaScript + jQuery coding practices defeat TDD.

My usual practice is to present users with a page where, for instance, they can select a customer from a dropdown list in order to see the information on that customer. In my JavaScript code, I use the customer Id from the dropdown list to access a service that returns the appropriate JSON object. I then start moving that data to the page using jQuery to select the elements that I want to update with data from the JSON object. And this is where the wheels fall off, at least as far as TDD goes: I can’t claim that I’ve tested my code unless I’ve tested the jQuery code and I can’t test my jQuery code without providing the page with the elements that my jQuery code is updating.

But this is exactly the problem that the Model-View-Controller design pattern is intended to solve: Have all the code/logic in the controller where it can be tested with TDD; have a separate View that is too simple to have much wrong with it and, as a result, doesn’t require testing. What I want, then, is an MVC framework that lets me put all my JavaScript code in a Controller that doesn’t need a View to be tested. Then, in my View, I want to integrate with my controller in a declarative “code-free/logic-free” way that doesn’t require testing. Oh, sure, in my View I can still have what I call “blunders” (e.g. misspelled text; the right data in the wrong place) but I can’t have logic errors that require debugging.

There are several frameworks that will do that. Lately, I’ve been using one of them—Knockout—on a project for one of my clients. Knockout implements the MVVM pattern which includes a ViewModel object that wraps up both the code and the data that drives your View creating, in the ViewModel, a very testable object. Knockout also provides declarative databinding to elements in my page to move data to my elements without code. In addition to Knockout’s basic functionality there’s lots to like about Knockout. For instance, it’s very easy to implement: download the Knockout library from knockoutjs.com, add it to your Scripts folder, and add a script reference to your page. Knockout also relatively agnostic about how you retrieve your data, making it easy to integrate with either WCF or ASP.NET MVC. I’m going to do this in easy stages, starting with this post that sets up my server-side resources.

Setting Up the Server

As an example, I’m going to walk through creating a page with Knockout using ASP.NET MVC. Since, with TDD, I begin with my tests, I first a controller called Test to my application, with an action method to support displaying a View that will let me test my client-side Customer ViewModel:

public class TestController : Controller {
 public ActionResult CustomerViewModel() {
 return View();
} 

My client-side Customer ViewModel is going to need to retrieve Customer objects from my server. Since I’m working in ASP.NET MVC, I’ll add an action method to my controller to support that. However, I’ll just return some mocked up objects for testing purposes. This ensures that, when I’m testing my Customer ViewModel, I really am only testing my Customer ViewModel and not my server-side code or database connection. That mock method looks like this:

public ActionResult CustomerById(string id) { 
 Customer cust = Customer.CreateCustomer(id, "PHVIS", null);
 cust.City = "Regina"; 
 return this.Json(cust, JsonRequestBehavior.AllowGet);
} 

Learning Tree has several excellent courses in this area. I get to teach both Learning Tree’s ASP.NET MVC course and its Design Patterns and Best Practices course. But Learning Tree also offers courses on JavaScript and jQuery.

Peter Vogel

Sending SMTP Email with Amazon SES and C#

For a while now I’d been meaning to add a ‘contact us’ page to www.cocktailsrus.com and I finally got around to it this week.

Sending SMTP email is very straightforward – but you do need to have access to an SMTP server. I suppose I could have just turned on the SMTP component in Windows 2008, but I’m hosting on Amazon’s Elastic Cloud Compute infrastructure and thought there had to be a better way… And there is: the Amazon Simple Email Service. And, as it turns out, you can use it even if you don’t host on EC2.

First, you have to go to amazon and sign up for the simple email service – which means signing up to use Amazon Web Services. Once you do so, you’re given a sandbox in which to play… or, in this case, send emails. You need to verify the email addresses you send from (to make sure that you’re not an evil spammer) and then you can send test messages either from the online interface or programmatically. Once you’re through with testing, you can ask for production access – and once that’s granted, you can send up to 2,000 emails a day (and up to 1GB of data transfer per month) for free. If you want to send more, then you will start incurring costs – but, as ever with EC2, those costs are more than reasonable.

So – the big picture: you get to send lots of emails for free, and someone else is responsible for maintaining and securing the SMTP server.

And best of all – it works when you’re testing on your development machine as well as on the live box. Nice.

The only remaining problem is that you can’t just change the server name in your existing .NET code :-( . Now that you’re using Amazon’s service, you need to download the AWS SDK (it’s available as a NuGet) and program against the Amazon objects. The following code relies on using statements for Amazon.SimpleEmail and Amazon.SimpleEmail.Model, and also the following keys in the Web.config:

<add key=FromEmailAddress value=[Enter verified email address here] />
<add key=AwsAccessKey value=[Enter your access key here] />
<add key=AwsSecretKey value=[Enter your secret key here] />

Once you have those set, the minimum code to send emails is along the following lines:

public static void SendEmail(EmailViewModel email, List toAddresses)
{
    AmazonSimpleEmailServiceConfig amazonConfiguration =
	new AmazonSimpleEmailServiceConfig();
    AmazonSimpleEmailServiceClient client =
	new AmazonSimpleEmailServiceClient(
		ConfigurationManager.AppSettings.Get("AwsAccessKey").ToString(),
                ConfigurationManager.AppSettings.Get("AwsSecretKey").ToString(),
                amazonConfiguration);
    Destination destination = new Destination();
    destination.ToAddresses = toAddresses;
    Body body = new Body() { Html = new Content(email.Body) };
    Content subject = new Content(email.Subject);
    Message message = new Message(subject, body);
    SendEmailRequest sendEmailRequest =
	new SendEmailRequest(
		ConfigurationManager.AppSettings.Get("FromEmailAddress"),
		destination,
		message);
    client.SendEmail(sendEmailRequest);
}

The secret key is sent securely by default, by the way, so you don’t need to worry about compromising it.  There are, of course, other things you can do (like checking the response to see if you had any problems sending the email) but the only complication I’ve had to deal with so far is the fact that I can’t just hit reply to emails from users.  The problem, of course, is that you can only send from verified addresses.  The solution is to add a mailto: inside the email. As problems go, it’s pretty trivial – and very much out-weighed by the benefits of not having to set up and use my own SMTP server.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building Web Applications with ASP.NET MVC

Building Web Applications with ASP.NET and Ajax

Cloud Computing Technologies: A Comprehensive Hands-On Introduction

Cloud Computing with Amazon Web Services

Visual Studio Tips – Wildcard Search and Replace

Ever wanted to do a wildcard Search and Replace in Visual Studio? I don’t just mean finding things using wildcards, but selectively replacing part of what you find while leaving other parts untouched. I came across an example recently where I needed to do just that – and since what I discovered saved me an inordinate amount of work, I thought I’d share it with you.

I was asked to look over the code for an ASP.NET Web Forms web site with a Sql Server back end. When I looked into the code, however, I discovered that the database was actually MySql… which I don’t support. I managed to migrate the database over to Sql Server, but then found that although the project used NHibernate, much of the data access code was written as inline SQL in the code-behind pages. And that code wouldn’t work with Sql Server.

The problem was primarily lots of code along these lines:

      rs.GetString(“ColumnName”)

Unfortunately, this code errors with the Sql Server driver because GetString() only accepts integers. I needed to keep the variable name, but change the code so that it was something like this:

     rs["ColumnName"].ToString();

And there were a huge number of column names and GetXXX() methods that needed changing.

So I did a little research, and discovered that there’s an option to use regular expressions in the Find and Replace dialog.

find options in find and replace dialog

Crucially, you can use Regular Expressions for both find and replace. So I was able to enter the following find string:

   rs.GetString\(“{.@}”\);

and the following replace string:

   rs["\1"].ToString();

And change all the GetStrings() for all of the columns in one simple Find and Replace – thus avoiding a great deal of tedious and repetitive work.  Here’s hoping I’ve saved you some of the same.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building Web Applications with ASP.NET MVC

Building Web Applications with ASP.NET and Ajax

Amazon Web Services Tools For Visual Studio

Recently I’ve been needing to make a few tweaks to the hosting for my cocktailsrus project. It’s hosted on Amazon EC2, and until now I have been logging on to the Amazon console whenever I need to make changes. That’s not a great hardship, as it is (unsurprisingly) a well constructured and user friendly interface.

But it turns out there’s a better way. Amazon have created a set of tools that integrate with Visual Studio. They make it easy to manage your instances directly through Visual Studio.

The tools give you a new set of project templates for working with Amazon Web Services (including EC2):

project templates dialog

And you also get a new set of tools for managing your instances. The AWS Explorer window is available via View | AWS Explorer.

View drop down

When you open it, you need to select the account and region you want to manage:

.account and region dropdowns

These only become available after you’ve clicked on the Add Account icon (highlighted in red above). The icon brings up a dialog allowing you to enter your credentials. If you don’t know your secret key, you can get it via the AWS console.

credentials dialog

Once you’ve completed the form, you can manage your instances (including security groups etc.) directly from inside Visual Studio.

Here’s the big picture view of a management screen:

Visual Studio with tools

And here’s a close up (with a few details snipped out for obvious reasons):

detail of Visual Studio tools

The toolkit integrates with both 2008 and 2010, and allows you to manage AWS through a familiar user-friendly Visual Studio interface – and without having to log on to the console every time you want to make a change.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Cloud Computing Technologies: A Comprehensive Hands-On Introduction

Cloud Computing with Amazon Web Services

Creating Web Services for the iPhone with .NET and WCF

Recently, I’ve been writing iPhone applications. The iPhone development tools are great and Objective-C is fun. Sooner or later though, an iPhone app will need to get data from a server. That’s where .NET and WCF come in.

WCF is a full-featured, highly automated way of creating Web services that run on Windows servers. However, if you are writing a service for the iPhone, there is one important thing to be aware of. In iOS, there is no built-in support for SOAP services which are the default type of services in WCF. So, your WCF services will need to be RESTful. Luckily, WCF makes this simple. I’ll walk you through the easiest way I know of to do this.

First, create a project with Visual Studio and choose the ASP.NET Empty Web Application template as shown below.

Once you have the project, select the Project | New Item menu. Then, choose AJAX-enabled WCF Service from the list of templates as shown below.

By choosing that template, the service is automatically configured as a RESTful service using the webHttpBinding binding and supports simple http get requests. An example Web.config file is shown below. Note the binding attribute in the endpoint configuration.

Now it’s time to write a service. Just create a function in the service’s code behind file and mark it with two attributes, OperationContract and WebGet. See the example code below.

[OperationContract]
[WebGet]
public string Square(string number)
{
double num;
double.TryParse(number, out num);
return (num * num).ToString();
}

One thing to note is the default return type when using the WebGet attribute is JSON. If you prefer to return XML, you can change the attribute as shown below.

[WebGet(ResponseFormat = WebMessageFormat.Xml)]

That’s it. Now you can invoke that service using a standard http request from Objective-C. If you want to learn how to do that though, you’ll need to come to Learning Tree’s course, iPhone® and iPad® Programming (this blog is about .NET programming after all).

Doug Rehnstrom

Dynamically Accessing Large Resource Files in XAML at Runtime

WPF provides ResourceDictionaries as a convenient way of adding resources like Styles to your application to be accessed when needed. However, if a non-executable resource gets very large and/or is used infrequently, resource files are a better choice than ResourceDictionairies.

With WPF applications you can incorporate any non-executable resources (including data files, images, audio, and video) into your application using a variety of schemes. You can even put XAML in a resource file so that you can download parts of your UI at runtime. However, if you’d like to avoid downloading/distributing the file until the user actually needs it, a site of origin resource file is your best choice. Site of origin files aren’t compiled into your application’s EXE or distributed with it (they’re not even copied to the location specified when you publish your application). Instead, they’re picked up at run time when your code accesses them.

Site of origin files are also a good choice in two other scenarios. First, if you have some content that is going to change frequently you can store the file on your website where you can update them as needed and let your applications pick them when they want them. Secondly, if your application is going to load different files depending on settings in the local configuration file, the identity of the local user, or any other basis for customization, you can put multiple versions of the file on your site and download them as needed.

Using site of origin files also avoids requiring your application to be granted full trust. In WPF you can often set properties (usually the Source property) on an element to a URI that points to a resource. For instance, you might use an Image element like this:

<ImageSource=http://www.phvis.com/DataFile.bmp />

However, this option requires that your application be granted full trust. Site of origin files require only partial trust.

Implementing Site of Origin Files

The first step in using a site of origin file is to add it, or smaller stand-in for it, to your project in Visual Studio. After adding the file (or its stand-in) to your application, select the file and set its Build Action to None (this prevents the file from being compiled into your application).

At run time, you can download your file with code when the file is actually needed. The first step is to create an Uri object passing the location of the file with the pack and siteoforigin prefix:

Dim sooUri As New Uri(
"pack://siteoforigin:,,,/MyGrid.xml", UriKind.Absolute)

Once you have created the Uri, you may be able to just set the Source property of the control you want to use your file to the URI. This sets the Source property on a Frame, for instance (and assumes that the xml file downloaded in the previous example contained valid XAML):

Me.Frame1.Source = sooUri

However, this approach forces the framework to do any type casting or conversions for you. If you’re willing to write a little more code, you can take control of the process and ensure that the conversion is done the way you want. The first step is to create a StremResourceInfo object by calling the Application object’s GetRemoteStream method, passing your Uri:

Dim info As StreamResourceInfo = Application.GetRemoteStream(soouri)

Your next step is create a read object object to process the file. You call the reader’s LoadAsync method, passing the stream property of your StreamResourceInfo object. You’ll need to cast the output of this method to the right type. Assuming that that I’m downloading a XAML file containing a Grid, I’d need to create a XamlReader and cast the output as Page, like this:

Dim xrdr AsNewSystem.Windows.Markup.XamlReader() 
Dim grd As Grid = CType(reader.LoadAsync(info.Stream), Page)
Me.Frame1.Content = grd 

After publishing your application, it’s just a matter of dropping the file into the folder with the setup.exe file and your application will download it when your code executes.

Peter Vogel

Fun With NuGet

I was teaching an ASP.NET MVC class just before Christmas, and was forcefully reminded of two things – 1) ASP.NET MVC Routing can be really tricky to get your head around, and 2) a surprising number of people still aren’t familiar with NuGets and don’t take advantage of them.

So this blog post is designed to kill two birds with one stone. I’m going to introduce NuGets and show you one in particular that helps you become familiar with the routing engine.

First up: what is NuGet?

NuGet is a mechanism to make the downloading and installing of useful .NET libraries transparent and easy. It comes with Visual Studio – but you may have an old version and need to uninstall it and install the latest version before you begin. Once you’ve done so, it’s very easy to install new packages. Here’s how you do it…

1. Open a project to which you want to add a NuGet (in this case, the routing debugger).

2. Go to Tools | Library Package Manager | Manage NuGet Packages

Screenshot of Menu

3. That brings up the NuGet dialog.

NuGet Dialog

4. You then search for the NuGet you’re after (in this case, the route debugger by Phil Haacked) and then click on the Install button once you’ve found it.

searching for NuGet Package

5. Now all you have to do is use it. In this case, that means running your application and using the useful debugging utility to see which of your routes matches the address in the browser. A great way to learn more about routes and test whether your routes really do what you think they’re doing….  (I’d advise using this one on a learn-routing project rather than a real site, by the way).

Route Debugger in action

NuGets – they’re easy to use, and there’s one out there that’s just what you need.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building Web Applications with ASP.NET MVC

Building Web Applications with ASP.NET and Ajax

Next Page »


Learning Tree International

.NET & Visual Studio Courses

Learning Tree offers over 245 Management and IT courses, including a full curriculum of over 15 .NET training options.

Free White Papers

Questions on current IT or Management topics? Access our Complete Online Resource Library of over 65 White Papers, Articles and Podcasts

Enter your email address to subscribe to this blog and receive notifications of new posts by e-mail.

Join 7 other followers

Follow Learning Tree on Twitter

Archives

Do you need a customized .NET training solution delivered at your facility?

Last year Learning Tree held nearly 2,500 on-site training events worldwide. To find out more about hosting one at your location, click here for a free consultation.
Live, online training

Follow

Get every new post delivered to your Inbox.