Posts Tagged '.NET programming'

How to Use ViewModels Without Sacrificing Encapsulation

I have been using ASP.NET MVC extensively over the past year, and the more I use it, the more I like it. However, there remain a couple of things that bug me. One is the fact that the built-in validation doesn’t work with repeating forms. The other is the “best practice” of placing Data Annotations on a ViewModel class.

For me, validation rules belong on the business object itself, not on the ViewModel. One of the key benefits of encapsulation is that we reduce code duplication. If we don’t encapsulate the validation rules inside the object, then we are doomed to repeat them once for every presentation layer. Data Annotations in an MVC ViewModel are not available to a WPF UI. Not only does this lead to redundancy, it increases the risk of inconsistencies cropping up between UI.

So no problem, you might think. All we have to do is add the Data Annotations to the Model itself, and then add the Model as a property of the ViewModel.

Okay, let’s try that.

Here is the Model:

BasicClass simple C# class

And here is the ViewModel:

The ViewModel class

This looks straightforward enough. But look at what happens when we ask Visual Studio to scaffold the View:

View scaffolding

What happened to our “Basic” Model property? It’s not there. The scaffolding only seems to work for simple properties.

Okay, so let’s add the details of the Model to the View. In fact, let’s cheat. We’ll get Visual Studio to scaffold the inner Model for us. First we’ll create a throwaway View. Then we copy the contents of the form and paste it into the View that’s typed to the ViewModel. All we have to do then is change the lambda expressions to point at model.Basic rather than just model:

Full scaffolding

Problem solved. The View now contains the data we need and also respects our data annotations…

This means we can pass the ViewModel through to a Controller method and pick up the Model we need via the ViewModel’s “Basic” property. There’s only one problem:  How do we use the UpdateModel() method when we’re only interested in a property on the object passed to the method, rather than the whole object? Fortunately, Microsoft anticipated the need and there’s an overload on UpdateModel() that allows us to specify a prefix. In this case, not surprisingly, the HTML helpers have inserted the prefix “Basic”:

UpdateModel() with second argument

As you can see, the Model has successfully been bound, so we now have a mechanism for taking advantage of ViewModels without sacrificing encapsulation.

Kevin Rattan

For related information, check out Building Web Applications with ASP.NET MVC from Learning Tree.

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

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

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

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

Preparing for ASP.NET MVC 4 Mobile Development

ASP.NET MVC 4 will include a neat little feature allowing you to create mobile views very easily. All you will have to do to mobile-enable a view is add ‘mobile’ to its name and then customize it for mobiles. How you customize it is up to you – but the built in Visual Studio MVC 4 templating will be using jQuery mobile (hurray!).

If you have a file called “index.cshtml”, you would copy it and create the new file “index.mobile.cshtml”. If you have “index.aspx” then you would create “index.mobile.aspx”. These then sit side-by-side with your standard views. Internally, ASP.NET MVC will detect that a mobile device is being used and direct the request to the appropriate view.

Sounds good, doesn’t it?

Wouldn’t it be nice if you could get a head start on developing your apps this way using the ASP.NET MVC3? Well, thanks to Scott Hanselman, you can. He’s created a NuGet that works the same way, and made it available for you to download and integrate into your projects. It includes both C# and VB code,

vb and csharp files

so after you’ve installed it, you need to go in and remove whichever you’re not using:

Csharp files

But once you’re done that, you have a mechanism for developing mobile apps in a forwards-compatible way. In the example below, I created a separate mobile master using jQuery mobile, which I then tied into the mobile version of the page using the Layout property:

code sample

Then I ran the application in Internet Explorer, and also in Firefox using the User Agent Switcher add on. The application automatically delivered the appropriate views:

Here is IE acting as a normal browser:

Web site

And here is Firefox pretending to be iPhone 3:

mobile web site

All in all, a useful little NuGet which sets you up for developing mobile apps in ASP.NET MVC 4.

Kevin Rattan

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

Building Web Applications with ASP.NET MVC

jQuery: A Comprehensive Hands-On Introduction

Understanding Windows 8 Metro-Style Apps and WinRT

I’ve heard some misconceptions surrounding Windows 8 development. The first one is Microsoft is killing Silverlight. The second is Microsoft is favoring HTML 5 and JavaScript for developing Windows 8 applications over XAML and C#. The third is Microsoft is replacing the .NET Framework with a new framework called WinRT.

Understanding Windows 8 Metro Apps

Windows 8 will include a new Start screen similar to Windows Phones. The Start screen will have tiles that represent programs. Clicking on a tile will start the program. The thing that makes a tile different from an icon is a tile can contain live information. For example, the tile for an e-mail program might include the number of messages in the in-box. Tiles are also big. This allows them to not only contain live information, but also makes them optimized for touch screens.

When a tile is selected, a traditional Windows application or a Metro-style application might start. Traditional Windows applications will run on the Windows desktop. Metro-style apps will run in full screen, like an application on a phone or tablet. Metro-style apps will also have their own controls and idioms optimized for touch. Microsoft has claimed that in a couple years nearly all computers will have touch-enabled screens.

Understanding WinRT

WinRT is the framework used to build Windows 8 Metro-style apps. It is a native Windows API that is optimized for Windows 8 Metro-style UIs, and not a part of the .NET Framework. Metro-style apps can be created using WinRT three ways: with XAML and unmanaged C++, with XAML and C# (or VB), or with HTML and JavaScript. For the third option, Microsoft has created a JavaScript API that allows access to WinRT and some custom HTML tags that understand the WinRT controls.

So, let’s clear up the misconceptions

First, Microsoft is not “killing” Silverlight. Silverlight will be used where appropriate. For example, when a program needs to run on both a PC and a Mac.

Second, by allowing Web developers to use languages they are comfortable in (namely HTML and JavaScript), it doesn’t mean Microsoft intends that to be the development platform of choice. The strength of HTML and JavaScript is support for any platform. Once an application uses the WinRT JavaScript library, it’s a Windows app, not a Web app. I suspect most developers will choose XAML and C#, as it will be more productive.

Third, the .NET Framework is not going away. WinRT applications will still need to access services, write to databases, and not all applications will be Metro-style applications.

Getting Ready for Windows 8 Development

Windows 8 and Metro-style apps offer exciting new opportunities for developers. Whether you are a C++, Web or .NET developer, you will be able to leverage your existing skills to create great new applications for you users. If you want to learn more about developing Windows applications using XAML come to Learning Tree course 975: WPF and Silverlight Introduction: Hands-On.

Doug Rehnstrom


Learning Tree International

.NET & Visual Studio Courses

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

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 29 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

%d bloggers like this: