Reusing .NET Framework 3.5 code in Silverlight 3

by Leo 1. September 2009 05:22

Over the past couple of days, I have been trying to port pieces of .NET code that I have written to the Silverlight runtime.

First, I have to clarify what I mean by reusing. In this case, reusing simply means using C# code from the full .NET Framework verbatim in Silverlight.

I want to simply be able to add a file as a link in Visual Studio 2008 – this will enable me to re-use .NET Framework code in Silverlight hassle-free.

Here are a few suggestions that you may find useful, if, for example, the code that you are re-using in Silverlight is not compiling. All of the suggestions below make it necessary for you to go back to your “server” code (i.e. .NET Framework code), and alter it so that it compiles under Silverlight.

  1. Make the problematic class a partial class. As such, you can port only a part of that class and leave out that portion of the class that would not be necessary in Silverlight.
  2. Use extension methods. Extension methods allow you to easily re-use bits of code while maintaining clarity. For example, I was using a .NET Framework method ConvertAll that was missing in Silverlight. I decided to create an extension method with slightly different parameters than the .NET Framework-based method, and changed my “server” code to use the extension method.
  3. Use partial methods. Although I rarely use partial methods, you can definitely use them when reusing code. However, many methods cannot be made partial (such as if a method does not return void, or if it has the override keyword. Because of these severe restrictions, partial methods are not always appropriate.
  4. Finally, if all else fails, you can use the good ol’ #IF…#ENDIF preprocessor directive to tell the compiler to include/exclude source code at compile time. For example, you can set the conditional compilation symbol on the “server” – so that when compiling under Silverlight, the bits of code that are only server bound will not get compiled.

Hope this helps.

Tags: ,

.NET | Silverlight

Unit Test Framework for Silverlight 3 uses port 8000

by Leo 14. August 2009 22:34

It appears that the Silverlight Unit Test Framework automatically calls http://localhost:8000/… when you load the Silverlight control in the web browser.

If Port 8000 is already in use, you will receive an error message from the Silverlight control stating that it received a 404 error page when it issued a web request (or something similar – I don’t remember the exact error message).

Bottom line, make sure that no web service or other application is using Port 8000 on your machine. Furthermore, note that Fiddler will not display any outgoing requests to “localhost”, so you will not see this particular request in Fiddler.

Unfortunately, I cannot explain why the Silverlight Unit Test Framework uses Port 8000 but just keep this mind! If you want to know why ask Jeff Wilcox.

Happy Unit Testing!

Tags: ,

Silverlight

How to run Visual Studio as administrator on Vista (with UAC)

by Leo 13. August 2009 00:11

I just ran into a strange problem on Windows Vista that touches upon Visual Studio 2008 and IIS 7.

I created a WCF Service Application project and in the properties I set it up to use the Local IIS Web Server (i.e. not Cassini). So far so good.

However, when I opened my solution file later on, Visual Studio complained that I was not running it under an Administrator account, and failed to load that project.

It turns out that if UAC (User Access Control) is enabled, Visual Studio does not run under an admin account automatically, and as such I had three choices:

  • Disable UAC on Windows Vista (I know it’s annoying but it does do a good job at protecting your machine)
  • Run Visual Studio as Administrator explicitly (really annoying…what if I forget? Besides, I usually like to open my .sln files by double-clicking via Windows Explorer)
  • Setup Visual Studio to run as administrator automatically (I think this is the best option)
    • Go to C:\Program Files\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe and C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe (could be different depending on your version), right-click on each one, and go to Properties. Under the Compatibility tab, make sure to choose Run as Administrator. Now when you run Visual Studio, it will automatically prompt you with the UAC, which is really what you want. Of course, this approach will work with any other program and not just Visual Studio. If you encounter any further issues, read http://www.pluralsight.com/community/blogs/matt/archive/2007/05/21/47446.aspx.

Now back to work…

Tags: ,

Visual Studio 2008

Visualizing LINQ Expression Trees for In-Memory data sources

by Leo 2. June 2009 02:45

Have you ever encountered the need to see how Expression Trees are built but you are working with a collection of memory objects and not LINQ to SQL?

First, you should try to download the Expression Tree Visualizer for Visual Studio. You can find a nice post about it @ http://blogs.msdn.com/charlie/archive/2008/02/13/linq-farm-seed-using-the-expression-tree-visualizer.aspx

You can also try LINQPad, since it has a pretty good Expression Tree Visualizer. You can download LINQPad from http://www.linqpad.net/. LINQPad allows you to create code-snippets (very useful for creating temporary ad-hoc queries to try stuff out).

Now back to my original question…

After you have set up the Expression Tree Visualizer for Visual Studio, you can see the expression tree for a LINQ to SQL query in the debugger – cool. Now, you write a LINQ to Objects query and attempt to view the expression tree in the debugger – oh, oh, there is no expression tree visible!

The simplified explanation is that LINQ to SQL uses IQueryable as the data source while LINQ to Objects uses IEnumerable. Therefore, in order to fix this issue, all you need to do is call the extension method AsQueryable() on your in-memory data source. Now, when you use the debugger, you will be able to see the expression tree that was generated!

Happy LINQin’ :)

Tags: ,

Visual Studio 2008 | LINQ

How to configure Subversion (SVN) Source Control with Visual Studio 2008 Professional

by Leo 14. May 2009 05:08

If you find yourself working with Visual Studio 2008 Professional, but you are not a millionaire, yet, and you are in desperate need of source control, I have the following to say to you:

Consider downloading VisualSVN Server, TortoiseSVN, and AnkhSVN.

Well, it’s Free!

  • VisualSVN Server is analogous to Microsoft Team Foundation Server
  • AnkhSVN is analogous to Team Explorer for Visual Studio
  • TortoiseSVN has nothing comparable in the Microsoft world, but it’s great. You can basically check-in, check-out, merge, diff, etc, directly from Windows Explorer

Underneath, all of them are running Subversion as the “brain”, which is a really good source control system. I am using this configuration with two networked computers and it works rather well.

Based on my experience, I recommend you setup VisualSVN Server to use custom users and groups. If you use Windows Authentication you may run into strange problems when you start to have many computers networked together.

All in all, I have used Subversion for about two weeks, and I am quite happy with it. It is definitely comparable to Team System, and I would highly recommend it in replace of Team System for small teams.

You can find a really thorough “getting started” guide @ http://www.codeproject.com/KB/dotnet/VistaVisualSourceControl.aspx

Tags: ,

Visual Studio 2008

Solving cross domain issues with Silverlight 2

by Administrator 1. May 2009 02:28

We all know that Silverlight and Flash follow a similar security model and run in the browser sandbox. These RIA platforms essentially request a cross domain policy file when a request is sent from the RIA application to a web service. If the policy file is not present or does not list your domain as an allowed domain then you have three choices:

  • Call, write, and ask the company/person to list your domain (i.e. the domain from which your Silverlight application is downloaded) as an allowed domain in the client policy file (clientaccesspolicy.xml or crossdomain.xml) – may not be very reasonable
  • Create your own proxy – the proxy will sit on your domain, and will make calls to the external domain. Hence, your Silverlight app will call the proxy on the same domain, so the Silverlight runtime will avoid asking for the cross domain policy file. Your proxy will simply call the external service and pass the response back to the Silverlight application
  • Use a 3rd party proxy service instead of rolling your own – such as Yahoo Pipes @ http://pipes.yahoo.com/pipes or the Google AJAX Feed API @ http://code.google.com/apis/ajaxfeeds
  • Trick the browser and avoid using any proxy whatsoever. This only works if the Silverlight application can access the Html Bridge and inject a JavaScript element into the head tag of the page. Also, you need to understand how to pass the response into a Silverlight control. If you don’t know how this can be accomplished then this approach will not work for you. This is the option I will discuss further, since the other ones are self explanatory

I am not sure if I would recommend using such an approach because it feels like a hack, but it does indeed work. This approach may not work at all, if, for example, you are loading your Silverlight application XAP file from a different domain than the web page that is hosting the Silverlight content. I am not sure if the Silverlight control will be able to modify the head Html element of the host page.

Here is the most important snippet of code you need in order to implement this trick:

HtmlElement head = HtmlPage.Document.GetElementsByTagName("head")[0] as HtmlElement;
HtmlElement javascriptContent = HtmlPage.Document.CreateElement("script"); 
javascriptContent.SetProperty("type", "text/javascript"); 
javascriptContent.SetProperty("src", "http://aWebServiceSomeWhere"); 
head.AppendChild(javascriptContent);

Do you see the trick? The browser’s javascript engine will say, “oh, look, we have a new script element that has been added to the header, and it has a URL as the src property – I need to download and then execute that javascript!” Since the request is made from the browser’s DOM and has no relevance to any RIA technology, all outbound requests will succeed an no cross domain policy file is requested. After the javascript is returned, it is necessary to pass the results back to the Silverlight control. Clearly, the only reasonable way to do it is to force the javascript to contain a method call into your Silverlight control. For instance, Twitter allows you to specify a callback=YourJavascriptFunction in the request, and the resulting JavaScript returned from the Twitter service will contain YourJavascriptFunction in the response.

Bryant Likes wrote a Silverlight Twitter control that demonstrates using this trick, and a fall-back mechanism that uses Yahoo Pipes. Have a look @ http://blogs.sqlxml.org/bryantlikes/archive/2009/01/23/twilight-a-silverlight-twitter-badge.aspx and http://www.codeplex.com/Twilight

By the way, I am currently using Bryant’s excellent Silverlight Twitter badge on my blog. 

 

Tags: ,

CodeProject | Silverlight

Architecting Silverlight 2 Applications with Prism (Composite Application Guidance)

by Administrator 17. April 2009 02:36

Many people who have worked with enterprise applications over the years have realized that building maintainable applications that naturally evolve over time is quite challenging. If the application consists of many modules, it is paramount that each module be as self-contained and decoupled from other modules as possible. Otherwise, over time, the modules become more and more tightly-coupled which generally results in spaghetti code.

Prism is a codename for the Composite Application Guidance package which consists of libraries (DLLs) that you can reference in your Silverlight/WPF projects. As such, Microsoft Patterns & Practices is providing documentation, written tutorials, videos, etc., in order for software developers to get up to speed with it. You can check out the CodePlex site for Prism @ http://www.codeplex.com/CompositeWPF

Prism empowers developers to create modules that encapsulate a certain piece of functionality. Each module would be responsible for emitting a view, which would then be injected into a particular region that is present inside a containing shell. The bootstrapper is responsible for initializing the shell and enumerating the available modules in the ModuleCatalog. There is also an EventAggregator that essentially acts as a Mediator, and all event publishers and subscribers use the EventAggregator to publish and subscribe to events. As such, one module may fire an event, and a multitude of subscribers may handle that event. Therefore, the modules are truly decoupled from each other. In addition each module uses a Model-View-ViewModel (M-V-VM) architecture to separate the View from the underlying model using data binding and the Command pattern. I have previously blogged about a fully unit-tested sample application that showcases the M-V-VM pattern and the Ninject (Inversion of Control) IoC container @ http://www.leonidsorokin.com/blog/post/Architecting-Designing-Silverlight-2-Applications.aspx. By the way, Prism includes the Unity IoC (Inversion of Control) container out-of-the-box although you are free to plug-in other IoC containers in replace of Unity.

In my opinion, the real power of the Prism framework is that it uses a large number of popular design patterns, with the hope that the composite applications that you build as a developer are as maintainable and scale well over time. In most documents, design patterns are presented in isolation, but the beauty of Prism is that it amalgamates these design patterns in a form of libraries, reference implementation (Stock Trader WPF application), and written guidance documentation. You can find an excellent introductory series of screencasts that showcase Prism @ http://compositewpf.codeplex.com/Wiki/View.aspx?title=Learn%20Prism

On a side note, I have found another framework that Microsoft appears to be developing with the developer community, although so far it is only in a preview state - it called MEF (Managed Extensibility Framework). As far as I understand, this framework will ship with .NET Framework 4.0. I believe MEF is some kind of grandiose Publish/Subscribe & component discovery mechanism which by decorating properties/methods with Import/Export attributes enables a developer to basically dump a bunch of modules in a folder and have them discover other modules during run-time and not during design time, and actually use them. Also, unlike Prism, which relies of WPF, MEF has no requirement on XAML, so theoretically, it can be used with other-non WPF stacks, such as Windows Forms. MEF is still early in its development but it feels rather promising. Hopefully, MEF will be ported over to Silverlight at some point. You can check out MEF on CodePlex @ http://mef.codeplex.com

Tags: ,

Silverlight

Using the "Cumberland" .NET Mapping Framework with SQL Server 2008

by Administrator 7. April 2009 04:23

As you may have heard, SQL Server 2008 now comes with two additional data types for spatial data, "Geometry" and "Geography". Thus, it is now possible to query spatial data using standard SQL syntax. You can find out more about the spatial capabilities of SQL Server 2008 @ http://www.microsoft.com/sqlserver/2008/en/us/spatial-data.aspx

Many people already have spatial data stored in proprietary file formats, but would like to use the power of a full-fledged database to query that data. So the question becomes, "how to we load such data into a database?"

There are two .NET Mapping Frameworks that can do this for you, and yes, there are tools that can do it for you as well, such as Morten Nielsen's shape2sql tool. You can download Morten's shape2sql application free of charge from his blog @ http://www.sharpgis.net/page/Shape2SQL.aspx

However, I prefer to use the open-source Mapping Frameworks for the simple reason that I can see the code, and alter it in case something does not work as it should.

The two .NET Mapping Frameworks I am familiar with are

SharpMap is a veteran compared to the new Cumberland framework, though I believe these frameworks complement each other. Both have data adapters that can work with spatial data in SQL Server 2008, ESRI Shapefiles, etc. In addition, Cumberland can generate Virtual Earth or Google Maps raster tiles or even KML data for Google Earth.

If you try Cumberland, please be aware that some applications may fail with a "proj.dll not found" error message. This may occur if you are running Windows Vista. This occurs because the proj.dll is actually an unmanaged DLL. It is responsible for setting projection information and you can find out more about the Proj.4 Cartographic Projection Library @ http://trac.osgeo.org/proj. It turns out that this DLL actually has a dependency on another DLL that is supposed to ship with Windows, but newer operating systems do not have it (such as Windows Vista). This special DLL is named msvcr71.dll. I recommend you download it from http://www.dll-files.com/dllindex/dll-files.shtml?msvcr71

After you download it, just make sure both proj.dll and msvcr71.dll are in the same folder, and everything should work just fine. If you are curious how I got it to work, I highly recommend Dependency Walker which is a free tool that allows you to examine any Windows library/executable and see the dependencies it has on other libraries (whether the dependencies are on system libraries or not). Dependency Walker can be downloaded for free from http://www.dependencywalker.com

Have Fun!

 

Tags: ,

.NET | GIS | SQL Server 2008

Persisting state during asynchronous calls

by Administrator 30. March 2009 04:07

When using Silverlight you are pretty much forced to use asynchronous requests to web services. In most cases, this is not a problem, but sometimes you may need to be aware of the "context" of the response. In other words, in your callback event handler, you process the response from the server but you need that extra bit of information so you know what do to with the response.

Suppose you have a tree-view control. Every time a user selects a tree-view item you make an asynchronous web request, and when the response arrives you would like to pop-up a balloon over that selected tree-view item with the response (perhaps a detailed explanation of that tree-view item). Sounds simple right? Well, it is. Except that by the time the response has been received, the user may have already selected another tree-view item. Clearly, when the response is received, it is necessary to know who the response is for. In our case, the response event handler needs to receive the tree-view item reference, or better yet, the appropriate data-bound object if you are using data binding.

In Silverlight you can use the WebClient class or the more advanced HttpWebRequest class for making HTTP calls. Either way, when you make the call, you need to pass in an object reference, and when the response is received, that same object can be accessed.

For instance, WebClient has a method named DownloadStringAsync that is used to download non-stream data with two overloads. The difference between them is that one of them takes a userToken object. Here is the method signature:

public void DownloadStringAsync(Uri address, Object userToken)


You can access the user token in the response via the UserState property of the response object. The same mechanism exists for the HttpWebRequest class.

Now you should be able to successfully work with asynchronous requests in Silverlight and the .NET Framework.

Tags: ,

Silverlight

ASP.NET MVC 1.0 Highlights

by Leo 22. March 2009 18:05

I decided to write this post after reading the first chapter of an upcoming book on ASP.NET MVC entitled "Professional ASP.NET MVC 1.0" published by Wrox.

You can find an introductory post on ASP.NET MVC by Scott Guthrie @ http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx. You will be pleased to realize that the first chapter is absolutely free and it is written by Scott Guthrie himself. It is quite a lengthy read (approximately 190 pages), but the content is excellent.

ASP.NET MVC is not only plumbing code - it is basically a guidance package that enables developers to build/test/maintain ASP.NET web applications in an architecturally sound way. MVC is an acronym for Model-View-Controller, which is a very famous design pattern. You can find more information about it @ http://en.wikipedia.org/wiki/Model-view-controller

Do not confuse the MVC design pattern with the M-V-VM (Model-View-ViewModel) design pattern which is a little different, and is mainly utilized in WPF client-side applications such as Silverlight.

ASP.NET MVC 1.0 is very RESTful and extremely "clean". Everything is done with good design/architecture in mind and separation of concerns is strictly enforced. Yes, you can customize it, but by default, even folder names and class names should follow the designated conventions in order to be used effectively.

While reading the chapter, I noticed a few new concepts that I did not know before. I have decided to list them here. I hope you find them useful. The quotes are from Scott Guthrie, and the explanations are mine.

  • "LINQ to SQL will automatically handle escaping SQL values for you when using strings - so you don't
    need to worry about SQL injection attacks when using it." Of course, all of us lose sleep over SQL injection attacks. What, you don't?Surprised
  • "Partial classes can be used to add methods/properties/events to classes maintained by a VS designer (like the Dinner class generated by the LINQ to SQL designer) and help avoid the tool from messing with our code." I am sure you already know about partial classes, but the next one is new to me...
  • "The OnValidate() partial method is a hook that LINQ to SQL provides that allows us to be notified
    anytime the Dinner object is about to be persisted within the database." Partial methods are especially useful as a way to customize generated code. You can read about partial classes and methods @ http://msdn.microsoft.com/en-us/library/wa80x488.aspx
  • "Why differentiate via HTTP verbs?" The two most used verbs with the HTTP protocol are HTTP GET and HTTP POST. When a crawler crawls your website (for indexing purposes) it follows links which are HTTP GET, and it should not make any HTTP POST requests to the site. First, you should make sure that no HTTP GET requests actually change server state - we have HTTP POST for that. As well, bookmarking a page and sending it to others to use will also use HTTP GET. Suppose you are editing your profile on a website. You have requested to edit your profile with the following URL (HTTP GET): http://site.com/UserProfile/Edit/[id]. After you are finished editing it, you will need to submit the form to the server. You can either submit the form using HTTP POST to the same URL, such as http://site.com/UserProfile/Edit/[id] or use a different URL such as http://site.com/UserProfile/Save/[id]. Which one is better? In either case you are performing an HTTP POST. However, if you use the http://site.com/UserProfile/Save/[id] URL for saving and a form validation error occurred with one of the form fields, the browser will re-display the form. Now, if the user decided at this point to bookmark the URL and send it to his friend, his friend will not be able to access that page, since he/she will be performing an HTTP GET on a URL that does not support HTTP GET requests. On the other hand if we used the same URL such as http://site.com/UserProfile/Edit/[id] for both HTTP GET and HTTP POST, upon a validation error the form will be redisplayed with same URL. The user can go ahead and bookmark it and even send to his friend. His friend should have no problem accessing the URL. The bottom line is: The user can bookmark a URL at any time, so make sure the URLs you use are always valid HTTP GET URLs. On a side note, Silverlight 3 promises to have excellent support for SEO (Search Engine Optimization), and the user should have no problem navigating Silverlight 3 content using the browser's back/forward buttons.
  • "The IQueryable<Dinner> object returned by our FindUpcomingDinners() method encapsulates a query
    to retrieve Dinner objects from our database using LINQ to SQL." Basically, IQueryable<T> encapsulates a LINQ query. This query is not executed until you call ToList() on it, or iterate on it using a foreach statement. Therefore, if a method returns an IQueryable<T> you can actually chain additional queries on top of it, and thus modify the query. With LINQ you can query relational data, XML data, and even POCOs (Plain Old CLR Object), with a unified query syntax. I recommend you get familiar with LINQ since it is very useful and may save you hours or even days on querying functionality you had to write yourself before.

As you can see ASP.NET MVC 1.0 is much more down-to-the-metal than the traditional ASP.NET framework. You are actually forced to think about raw HTTP GET/POST requests and how you handle them. This offers a lot of flexibility, but you must be careful not to abuse this added responsibility. The only thing Scott Guthrie fails to address in his first chapter is how we can use the myriad of existing ASP.NET server controls with ASP.NET MVC. However, I am sure this will be covered in subsequent chapters.

Enjoy the read!

Tags: ,

ASP.NET

About the author

I am a software engineer from Toronto, Canada passionate about web development and XAML on the Microsoft tool chain.

I am always looking for consulting projects, so drop me a line.

Me     Microsoft Certified Professional Developer

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.