Chris SellsThis article assumes you're familiar with C #, Windows Forms, and .NETLevel of Difficulty 1 2 3 SUMMARY Windows Forms applications solve many of the problems inherent in building Web applications the old fashioned way-with HTML. To demonstrate the use of Windows Forms over the Web, the author takes his existing app, Wahoo !, and ports it to Windows Forms. In doing so, he discusses versioning, linked files, security, storage isolation, the deployment model, and everything else you need to get started Building your owne windows forms apps for the web ..
hen compared with Visual Basic®, MFC, or even Win32®, HTML is woefully inadequate for building applications. Do not get me wrong. I love the Web. HTML, plug-ins, and browsers have all but eliminated the need for many print, video, and audio media in my life. However, you can not use HTML to build full-featured applications that are optimized for heavy usage. The user interfaces are, by nature, primitive to use and difficult to implement and maintain. and the blame does not rest solely with HTML and JScript®. Building stateful applications on top of the Web's highly concurrent, stateless infrastructure is just hard. You would have thought that long ago people would have given up building HTML applications, at least for situations like the corporate intranet where the client environment is tightly controlled, but so far, HTML still has the mindshare.The problem, of course, is that darn deployment model. When an IT manager sees that updating a Web site automatically gives users the new versi on, it's hard to get them to go back to the painstaking process of making sure that all desktops in a corporation have been updated to the latest version of HR452.EXE. Only a technology that provided a deployment as compelling as HTML would stand a chance of unseating it.Taking up this challenge, .NET marries the latest version of the forms engine that made Visual Basic a corporate development mainstay with the kind of deployment model that turns an IT manager's head. The engine is called Windows Forms and the deployment model IS Built Right Into .Net. Here, I'll Focus on The Elements of Windows Forms Deployment Itself. for more details on The Implementation of Windows Forms, See The MSDN® Magazine Article
Windows Forms: A Modern Day Programming Model for Writing GUI Applications "by Jeff Prosise.Just like a Web application, a Windows Forms application can be deployed on a Web server and executed by merely surfing to a URL To see for yourself just how easy. it is, stop reading and try the following in Visual Studio®.Using the New Project dialog, choose either a C # or a Basic Windows application and call it DeploymentFun. Drag and drop some controls from the toolbox, but before going too far, compile your application. In the shell explorer, navigate to your DeploymentFun / bin folder, right-click on the Debug folder, and choose Properties. Choose Web Sharing and turn it on, using DeploymentFun as the name of the share. Now surf to your Windows Forms app using Start | Run and the following URL: http: //localhost/DeploymentFun/DeploymentFun.exe After basking in the glory of deploying a smart client-a real Windows application over the Web-stop playing around and read the rest of. This Article.f igure 1 Wahoo! Using HTMLTo test this deployment model, I ported an HTML application to Windows Forms. The application is an implementation of the game of Wahoo! The HTML implementation is shown in Figure 1, while the .NET implementation is shown in Figure 2 .!. Any similarity to any other very popular games that you may already be familiar with is purely intentional.Figure 2 Wahoo Using .NETBoth implementations offer identical play In the Windows Forms version, I wanted to:
Make a real Windows-based executable-Wahoo.exe-complete with menu bar, status bar, function key handling, and no browser frame. I wanted it to be downloadable from a Web server. Split the client area into a separate assembly, WahooControl .dll, because you never know when you're going to need a game plugged into your application. Save user settings, such as window size and position, between sessions. Provide access to a Web Service for reporting and retrieving high scores. Cache high score lists on the client hard drive and retrieve them later for viewing.With the exception of running outside of the browser, these were all features that I could probably have added to my HTML application, given enough time and effort. Frankly, though, I was happy just to get the HTML version running at all. As it was, I had to mandate the use of Internet Explorer 5.0 for the HTML version because I needed a feature that was not present in earlier versions (VML support, specifically). In Fact, Although THIS is a pretty simple application, it took quite a bit of effort to get the limited object-oriented facilities of JScript and the limited UI facilities of HTML to bend to my will. I'm sure it's no surprise that the better UI, including all of the features mentioned, was easier to implement in Windows Forms. What may be surprising is the small download size of each application. The HTML version (Wahoo.htm plus sblogo.gif) was approximately 58KB while Windows Forms (Wahoo.exe plus WahooControl .dll) WAS Not Much Larger at 60kb.i don '
t know if I could have implemented the extra features in JScript and HTML in two kilobytes, but I do know that it was a whole lot easier to do it in Windows Forms. (Of course, the 20MB .NET Framework runtime could be counted too , but then so should the average Internet Explorer install of 17MB.) Application DownloadDeployment of a .NET application on the server is achieved by simply dropping the app into a virtual directory so that the Web server can hand out the bits on demand. The. NET runtime is not required on the server; nor are Microsoft Internet Information Services (IIS) or Windows On the client, things are a bit more interesting When you feed Internet Explorer a URL likehttp: //localhost/foo/foo.exeit.. Forms an http request for the foo.exe file to be streamed back to the client: get /foo.exe http / 1.1
Accept: * / *
Accept-language: EN-US
Accept-encoding: Gzip, deflate
User-agent: mozilla / 4.0 (compatible; msie 6.0; windows NT 5.1;
Q312461; .NET CLR 1.0.3705)
Host: Localhost
Connection: Keep-alive
The response from the server is just a stream of bytes: http / 1.1 200 ok
Server: Microsoft-IIS / 5.1
Date: fri, 01 feb 2002 02:11:29 GMT
Content-Type: Application / OcTet-stream
Accept-ranges: Bytes
Last-Modified: Fri, 01 Feb 2002 01:41:16 GMT
ETAG: "50AAE089C1AAC11: 916"
Content-Length: 45056
<< stream of bytes from foo.exe >>
Besides the bytes the the assebly is used to form a request each subsser ipsequent time triass
Accept: * / *
Accept-language: EN-US
Accept-encoding: Gzip, deflate
IF-modified-Since: Fri, 01 Feb 2002 01:41:16 GMT
IF-NONE-MATCH: "50AAE089C1AAC11: 916"
User-agent: mozilla / 4.0 (compatible; msie 6.0; windows NT 5.1; Q312461; .NET CLR 1.0.3705)
Host: Localhost
Connection: Keep-alive
The If-Modified-Since header is kept in the Internet cache and sent back with each request so that if the bits on the server have not changed, the server can respond with a header that indicates that the cache is still good, reducing the PayLoad That Needs to Be Downloaded to the Client.http / 1.1 304 Not Modified
Server: Microsoft-IIS / 5.1
Date: fri, 01 feb 2002 02:42:03 GMT
ETAG: "A0FA92BC8AAC11: 916"
Content-Length: 0
The bytes themselves are cached in two places:. The Internet cache managed by the browser and the .NET download cache The contents of the download cache can be examined using gacutil.exe / ldl and cleared using gacutil.exe / cdl If, during. your testing, you'd like to ensure that a download happens, make sure to clear out the Internet cache using the Internet control panel, as well as the download cache using gacutil.VersioningWhile I'm on the subject of caching and downloading the latest . version, you may be curious about how actual versions affect things As you may know, you can tag a signed .NET assembly with a specific version using the AssemblyVersion attribute: // Strong naming is required when versioning
[Assembly: AssemblyKeyFileAttribute ("wahoo.key")]]]
[Assembly: AssemblyVersionattribute ("1.2.3.4")]]]]
So, if an assembly is versioned, does this version affect the caching and downloading Well, sometimes.When you request http:? //Localhost/foo/foo.exe, the runtime does not have any idea which version you'd like , so it's just going to ask the Web server for the latest version (as indicated by the If-Modified-Since header sent along with the HTTP request). If the runtime already has the latest version, no download takes place. If the server has a newer binary (based on the date / time stamp on the file), even if that binary is of a lower version number (based on the AssemblyVersion attribute), the lower version will be loaded. In other words, the AssemblyVersion plays no role in what the server considers the latest version of the assembly to be.But sometimes an assembly may reference other assemblies, either implicitly as part of the manifest or explicitly via the Assembly.Load method. For example, Wahoo.exe references WahooControl.dll The Version of Wahoocontrol.dll That Wahoo.exe Compiles against will be the version that the assembly resolver (the part of the .NET runtime responsible for finding code) expects to find at run time. If that version of WahooControl.dll is found in the cache, the assembly resolver will not cause a request To the Web Server Asking if IT Has A NEWER VERSION. of Course, this Means That if you'd Like The Client To Have A Newer Version of a Reference Assembly, you '
ll need to post the updated EXE assembly that refers to it.Related FilesAs I just mentioned, assemblies may reference other assemblies. If a referenced assembly is already present in the Global Assembly Cache (GAC), for example System.Windows.Forms, then the assembly will be loaded from the GAC. If the assembly is not in the GAC, the download cache is checked. If the download cache does not contain the assembly, the assembly resolver goes back to the originating server using the application base of the . assembly (often called the AppBase) The AppBase is the directory from which the initial assembly was loaded, such as c: / foo or http:. // localhost / foo / foo / The AppBase is available using the GetData function of the currently Executing Application Domain (AppDomain), Like So: String AppBase = Appdomain.currentDomain.basedirectory;
For example, when Wahoo.exe needs WahooControls.dll and it's not present in the GAC or the download cache, the assembly resolver will go back to the originating Web server, as you've already seen. Referenced assemblies, however, are not the only files that the assembly resolver will look for when an executable is loaded. In fact, on my machine when I surf to the initial version of the signed Wahoo.exe after the caches have been cleared, 35 requests are made for files, as listed in Figure 3.The first request makes sense, of course, as it's the assembly I asked for originally. The second request is for a .config file, which is where assembly-specific settings can be set, for example, version mapping and additional probing paths. This is a handy file if you'd like to tailor the resolution policy of your assembly's AppDomain. I recommend the online documentation for more information about just what can go into this file.The third request is for the WahooControl.dll assembly That Wahoo.exe references, as you'd expect. The next request is for a resources assembly called Wahoo.resources. This assembly is used to resolve resource requests on a per culture basis (which is why the assembly resolver is looking in the subdirectory for the current culture on my machine-United States English). Since the resources assembly is not found where the assembly resolver first looks, it continues to look for this assembly with other names and in other subdirectories over the next 31 requests.In situations where the latest Wahoo. Exe and Wahoocontrol.dll Are Aleady Cached on My Machine, I '
ve seen these additional requests take more than 75 percent of the load time. In a WAN environment, this may not seem like a good idea, but what's happening is actually worthwhile. If I have resources in my application, such as a background image, pulling the resource out of the file requires the use of a resource manager, as shown in the Windows Forms Designer-generated InitializeComponent method: private void InitializeComponent () {System.Resources.ResourceManager resources =
New system.resources.resourceManager (Typeof);
•••••
THIS.GAME.BACKGROUNDIMAGE = ((System.drawing.bitmap)
(Resources.getObject ("Game.BackgroundImage"))))))
•••••
}
When the resource manager is created, it looks in 32 places for the corresponding culture-specific resources before settling on the resources bundled with the assembly This allows a zero touch model of localization;. As you port your application's resources to other cultures, you can drop the assembly.resources.dll into an appropriately named culture directory and these resources will preempt the culture-neutral resource bundled with the assembly. In a LAN or file system environment, this is exactly what you want.In a WAN environment, these extra round-trips can make for a very poor user experience, especially when the culture-neutral resources are the only resources for your application. In this case, you have a couple of options, one of which is to avoid using the Windows Forms Designer to SUCH As the BackgroundImage So That The Designer-Generated Code Doesn't Create a Resource Manager. Then, To Load Resources, You Write The Code Yourself in a Cultur e-neutral way like this: public mainform () {
// let the designer-generated code runinitializecomponent ();
// init cost-neutral Properties
THIS.GAME.BACKGROUNDIMAGE = New Bitmap (Typeof (Mainform),
"SBLOGO.GIF"); // Warning: Case Sensitive
}
This approach is handy for resources that you know are culture-neutral and that you never want to localize, but it's inconvenient if you've grown attached to the Windows Forms Designer, as I have. For those of you who share my addiction, the resource manager supports an optimization that makes this kind of hand-written code unnecessary in many cases. The NeutralResourcesLanguage attribute is an assembly-level attribute that marks the resources bundled in your application as culture-specific, so that they will be found first without the Round-trips to the Web Server When Launched from That Culture: [Assembly: NeutralResource "]]
This attribute reduces the number of requests from 34 to two when the assembly is launched from a machine with the culture of the assembly, improving load times considerably. If you'd like to let the designer generate the code and reduce round-trips for cultures other than that in which you're writing the application, you can put zero-length files in the first places that the resource manager looks-en-US / appname.resources.dll and en / appname.resources.dll for the US- but this is somewhat of a hack.If you'd like to reduce the number of requests by one more, you can put up a .config file (although this involves some special entries in your Web.config file if you're serving up Your .NET Applications Via an ASP.NET Site-See The Code Download for An Example). The Following Is The Smallst Legal .config File:
Once the .config file has been cached, the .NET v1.0.3705 assembly resolver will not ask for it again, even if there is a newer version on the server. Unfortunately this means that you'd better be darn happy with your application's. config file because the client's Internet cache must be cleared before the .config file will be downloaded again.Of course, the ultimate reduction of requests is to use no requests at all. By putting Internet Explorer into offline mode (via the File menu), surfing to a smart client will work completely from the cache. If there is no connection, there are no Web Services, but isolated storage (discussed later) is a good place to cache Web Services calls to be made when a connection is reestablished.Security ZonesAs Keith Brown pointed out in his excellent MSDN Magazine article "Security in .NET: Enforce code Access Rights with the Common Language Runtime,"., .NET brings with it a new security model for deployed code Instead of an assembly getting the permiss ions of the process running the code (which, let's face it, would give all code full admin rights on most machines), the .NET Code Access Security (CAS) model grants code permissions based on where it's obtained. To view the current permission Settings on Your Machine, Use The Microsoft .NET Framework Configuration Tool (Available In Your Administration Tools Menu). Drilling Into the Permission Sets for the machine '
s runtime security policy shows a number of entries, including FullTrust, LocalIntranet, Internet, and so on. Figure 4 compares the LocalIntranet permission set to the Internet permission set.Assemblies are associated with a permission set in any number of ways, including the publisher , the site, the strong name, and the security zone. Most of the default code groups associate code with a zone. For example, the My_Computer_Zone is associated with the FullTrust permission set and the Local_Intranet_Zone is associated with the LocalIntranet permission set. In release 1.0 of .NET, the Internet_Zone was associated with the Internet permission set, but as of Service Pack 1 of the .NET runtime, code from the Internet_Zone is associated with the Nothing permission set by default. Someday Microsoft may loosen permissions on code from the Internet, But untenil dam (As you'll see later) .The zone an assembly is from is determined by the shell and / or the assembly resolver based on the path used to find the assembly, as shown in Figure 5. If an assembly needs to know the zone IT's Running In, IT CAN Access The Zone Via The Zone Class in System.Security.Policy: Using System.Security; Using System.security.Policy;
SecurityZone Zone =
Zone.createFromurl (AppBase) .securityzone;
By default, the loaded assembly will get the union of the permissions from all of the code groups to which it belongs and must live within the confines of those permissions. Any attempt to perform an action for which the assembly does not have permission will result in a security exception. The Wahoo and WahooControl assemblies, for example, are designed to work within the restricted set of Internet permissions, which means that it was difficult to implement the functionality I wanted. The challenging areas I encountered included remembering and restoring user preferences, communicating with Web Services, saving and opening files, and hosting the signed WahooControl.dll in Wahoo.exe.Isolated StorageOf course, one of the hallmarks of a good application in Windows is that it remembers the preferences set the last time a user ran it ............................ .. egistry because it handles per-user settings under HKEY_CURRENT_USER relatively well. The Registry is so overused that it's becoming a maintenance issue, so Windows now has special per-user folders where applications can keep their settings. Unfortunately, applications outside of the MyComputer zone don 't have permission to access the file system without user interaction and the Internet permission set does not allow an application to write to the file system at all, making the special folders inaccessible to restricted smart clients. For this reason, Microsoft provides isolated storage .Isolated storage is expected via the system.io.isolatedStorage namespace. It '
sa special place on the hard drive where even Internet applications can read and write files and directories. The location can not be known to the application and the size of this area can be restricted (10MB by default in the Internet permission set), but for storing user preferences or medium-sized files, it's fine.Isolated storage can be segregated into many stores based on the assembly, the AppDomain, and the user, but the only store that Internet applications has permission to access is the user store for the AppDomain. Using this store, the assembly can open or create a file via a stream for reading or writing, as shown in Figure 6.Once the isolated storage stream is open, the assembly can use it for whatever it likes. The Wahoo assembly, for example , uses the stream to cache and restore window size and position (see Figure 7). The ReadSetting and WriteSetting functions in Figure 7 are helpers for converting simple types to and from strings using TypeConverters (see Figure 8) .Typ eConverters are easy to use, but only suitable for simple data. If you'd like to serialize more complicated data, you can send all of the public fields of an object into a stream using the XML serializer defined in the System.Xml.Serialization namespace. If you want protected and private fields serialized too, I would normally point you to the [Serializable] attribute and the formatters in the System.Runtime.Serialization namespace, but that serialization model is unavailable to restricted assemblies. While this can be inconvenient , the unrestricted ability to set an object '
s protected or private variables is a security hole large enough to give a restricted assembly ownership of the machine.Communicating with Web ServicesCommunicating with the user is not the only job of a smart client. Very often they're going to need to communicate to the outside world as well. In the restricted zones, this communication is limited to talking back only to the originating site and only via Web Services. luckily, the originating site is often what you want to talk to anyway (if that's not the case, you can easily build shims redirecting requests to other servers), and Web Services are flexible enough to handle most communication needs.In addition to being flexible, Web Services provide a much more manageable model for separating server-side and client-side code. Instead of MAINTAINING Client State on The Server Like A Web Application Offers, Web Services Typically Provide A Stateless Endpoint That Receives For Service. these Requests Are Usually Large-Graine d and atomic to reduce requests and to let the client maintain its own state.Assuming the Web Service itself was implemented in .NET, generating the client-side proxy code necessary to talk to a Web Service is as easy as adding a Web Reference to your project by pointing Visual Studio .NET at the URL for the Web Service's WSDL. Calling it is tricky as you need to make sure that the URL, which is hardcoded into the generated proxy code, points at the originating server. you can do this By Replacing The Site in The Hardcoded Url with The Site That You Discover Dynamically Using The Appdomain's AppBase (See Figure 9) .reading and Writing Filesonce I '
D gotten the current wahoo! high scorers via the Web Service, i Found That I Wanted to Be Able To Cache The The BRIEF MOTED WHEN I WAS AT TOP). .NET MAKES It Very Easy to Read and write files and to show the File Save and File Open dialogs. Unfortunately, only a limited subset of that functionality is available in restricted zones. in the Intranet zone, files can be read and written, but not without interaction with the user. Unrestricted access to the file system is, of course, a security hole on par with buffer overflows and fake password dialogs. to avoid this problem but still allow an application to read and write files, a file can only be opened via the File Save or File Open dialogs. Instead of using these dialogs to obtain a file name from the user, the dialogs themselves are used to open the file (see Figure 10) .Notice in Figure 10 that instead of opening a stream using the SaveFileDialog.FileName property after the user Has Chosen A File, I Cal l the OpenFile method directly. This gives me an open stream while preventing a restricted program from opening a file without user intervention.While an application with Intranet permissions can use this technique for both reading and writing files, applications with Internet permissions can only read files IF you '
d like your application to dynamically downgrade its capabilities based on what permissions it has, check the permissions by creating a permission object and demanding that permission and catch the security exception if the demand fails. For example, to check whether your application is allowed to show the FileSaveDialog, you use an instance of the FileDialogPermission from the System.Security.Permissions namespace, as shown in Figure 11.If you wonder what permission you need for a specific call, you should start with the security exception itself, if you can discern the problem from that. Unlike most other exceptions in .NET, the information provided with a security exception is somewhat terse to prevent people with evil intentions from learning too much about an application's implementation. This does tend to make debugging security exceptions a bit harder, THOUGH. In There Cases, I Check The Documentation, Which IS surprisingly Good About Telling You What permissions Are Needed and when.PermissionsHowever, sometimes the documentation is not enough. Because of the ever-increasing focus on security by Microsoft, the .NET team spent the two months before the release of .NET (and several more months after that) just tuning and testing security settings. Unfortunately, some of those tunings resulted in documentation changes that are not in the documentation included with the initial release of the product but are available on the Microsoft MSDN site.One example of this is a permission that an assembly needs to grant to Allow it to be called by restrictage assembly. this permission is caled allowpartiallytrustedCaller (APTC) and it '
S Applied to Assemblies Via An Assembly-Level Attribute, Like So: [Assembly: AllowPartiallytrustedCallersattribute]
This permission is only checked once an assembly is signed (which you should always do), but if it is not set, then attempting to use that assembly from an assembly with restricted permissions will cause a security exception. For example, the WahooControl assembly is marked with this attribute to allow it to be hosted by Wahoo. Just remember, it can be very dangerous to mark a signed assembly with the APTC attribute (unsigned assemblies never need to mark themselves APTC). Only a few of the assemblies that come with the .NET are thus marked and those without it can not be called from restricted zones. If you mark yourself as APTC, you are now taking responsibility for making sure that your assembly can not be used for evil purposes from restricted zones.Obviously, debugging and working around security-related issues are the trickiest aspects of smart-client deployment. If you launch a smart client via a URL, you may have noticed that there are no processes running with that name. Instead , Each application launched via a URL will get its own copy of IEExec.exe, the process responsible for setting up the appropriate security environment for the application to run in.The undocumented usage for IEExec.exe is shown in Figure 12, and one common usage of these settings is shown in Figure 13. Notice that the Debug Mode has been set to Program (it defaults to Project), that the Start Application has been set to the full path to IEExec.exe, and that the Command Line Arguments have Been set to a url hosted on the local machine along with a trailing zero to indicate That I need no special flags. if you use 127.0.0.1 to get to the local machine, you '
ll get default Internet zone permissions when you debug. Likewise, if you use localhost, you'll get default LocalIntranet zone permissions instead.Figure 13 Debug SettingsIf you'd like to debug without hosting your application in a virtual directory, you can do so . using a file URL and an appropriate flags argument For example, to launch wahoo.exe from the file system using Internet permissions, you can do the following: C: /> ieexec.exe file: // c: / wahoo / deploy / Wahoo.exe 3 3 00
While it's certainly possible to build full-featured applications that run within the confines of a reduced permission set, these restrictions can easily be avoided by granting well-known assemblies increased or even unrestricted permissions. This is especially useful in a corporate Intranet where client machines are configured by the same staff deploying the smart-client applications.There are a number of ways to increase permissions for an assembly. for example, if you're unhappy with the changes that where made in .NET 1.0 SP1, you can increase or decrease permissions for any zone as a whole using the Adjust .NET Security wizard (available through the Microsoft .NET Framework Wizards item on the Administration Tools menu) as shown in Figure 14.Figure 14 Risky Internet Security SettingsTo be a little less sweeping in your Security Changes (Which I Heartily Recommend), You Can Decide To Trust All Assemblies from a Specific Site Via The Internet Control Panel (See Figure 15). Obviously if you were to choose the full-trust Internet security options that were shown in Figure 14, you'd be putting your systems at risk! Figure 15 Add Trusted SitesIf you'd like to adjust permissions for a specific assembly, you can set up a custom code group using the Microsoft .NET Framework Configuration tool or you can use the Trust an Assembly Wizard shown in Figure 16.Figure 16 .NET WizardsThis tool creates a code group named Wizard_N, where the N varies with how many times you run the Wizard. When You Run this Tool, You'll Be Able To Enter the Url To Trust, Such as http: //trustedmachine/hr452/hr452.exe