ObservableDeveloper - Leonid Sorokin's Blog

.NET, Silverlight, ASP.NET, Web Services, SQL Server, Cloud Computing, and much more...

About the author

I am a .NET Software Developer, Consultant, and Trainer from Toronto, Canada specializing in web development with Rich Internet Applications on the Microsoft development tool chain.

My Photo

Microsoft Certified Professional Developer

Reusing .NET Framework 3.5 code in Silverlight 3

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.


Permalink | Comments (0) | Post RSSRSS comment feed

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

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!


Permalink | Comments (2) | Post RSSRSS comment feed

How to pass arbitrary data in a Message object using WCF

I was searching all over the Internet, and yet I could not find any information about this seemingly simple task. Suppose you have an arbitrary string that you would like to return from a WCF (Windows Communication Foundation) service.

You can do one of the following on the service contract:

  1. Create a method/operation with a string return type
  2. Create a method/operation with a Stream return type in order to have full control over how serialization is performed. You can find a good explanation @ http://blogs.msdn.com/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx 

However, you may find yourself in a situation where you cannot return a Stream type because you are sending the response somewhere deep inside the WCF stack and you only have the System.ServiceModel.Message type to work with. Here is the documentation of the Message class I am talking about - http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.message.aspx

Aside: If you have ever worked with RIA (Rich Internet Applications) such as Flash or Silverlight you will most likely be familiar with cross-domain policy files, such as crossdomain.xml (Flash) or clientaccesspolicy.xml (Silverlight). I am not going to go into why they are needed, but needless to say, I had to return one of these files depending on the request made from the client. Both of these files contain perfectly valid XML.

If you look carefully at the Message.CreateMessage method you will see it has many overloads. At first, I tried this:

Message reply = Message.CreateMessage(MessageVersion.None, "", XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes("[XML goes here]"))));

This works fine as long as the XML you are passing to XmlReader does not contain DTD definitions. For some security reason having a DTD in the XML causes an exception on the XmlReader.Create call. I was able to avoid an exception by setting the ProhibitDtd property on XmlReaderSettings to false, but WCF decided I was performing evil deeds, and independently decided to emit my XML without the DTD definition.

If you look at the overloads of Message.CreateMessage you will quickly realize that you must serialize as XML. In my case, the DTD in the crossdomain.xml caused the headache, but what if you want to pass an arbitrary string such as "Hello World" back from the service as-is, what do you do then? Anything you may try will cause the default DataContractSerializer to kick in and serialize your object. The catch is, you do not actually want serialization.

Here is the code that you need in order to return arbitrary text using WCF's Message class.

/// <summary>
/// Necessary to write out the contents as text (used with the Raw return type)
/// </summary>
public class TextBodyWriter : BodyWriter
{
        byte[] messageBytes;

        public TextBodyWriter(string message)
            : base(true)
        {
            this.messageBytes = Encoding.UTF8.GetBytes(message);
        }

        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("Binary");
            writer.WriteBase64(this.messageBytes, 0, this.messageBytes.Length);
            writer.WriteEndElement();
        }
}

// ....

// Here is sample code that does the magic of returning raw text to the client...
string response = "Hello World!";
Message reply = Message.CreateMessage(MessageVersion.None, null, new TextBodyWriter(response));
reply.Properties[WebBodyFormatMessageProperty.Name] = new WebBodyFormatMessageProperty(WebContentFormat.Raw); // very important - forces WCF to serialize the message body contents as "Raw" which effectively means no serialization
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; // can also be "application/xml" or anything you prefer


Permalink | Comments (0) | Post RSSRSS comment feed

To throw or not to throw Exceptions - that is the question

Today I had to make a decision whether I should be throwing an exception or not.

In my data access layer I had to have a SaveUser method that saves a user object by calling a corresponding SaveUser method on a REST web service.  The question arose regarding the return value of the method in my data access layer. Logically the return value should be a boolean, either the SaveUser operation succeeded or not.

Here is one possible method signature:

bool SaveUser(User user); // not such a good approach

However, this is not a good solution. Why? The return value should always be true, and false only in exceptional circumstances. 

In general, when saving data, it is much better to return nothing, and let exceptional situations be handled by the best candidate - exceptions.

Therefore, the SaveUser method should have the following signature:

void SaveUser(User user); // much better approach

If the web service returns an error, the data access layer should raise an exception and set the InnerException propety to the exception text returned by the web service. 

This is a much cleaner solution than returning true/false from the SaveUser method.


Categories: C# | .NET
Permalink | Comments (0) | Post RSSRSS comment feed

My blog is finally on the web!

I have managed to make my blog visible on the Internet. I am using discountasp.net as my host provider, and so far, I am very pleased with them.

I plan on writing, for the most part, about Silverlight. For those of you who don't know, Silverlight is Microsoft's new RIA (Rich Internet Application) platform, and it is about to compete with Adobe Flash (Flex, AIR), Java FX, and Google Gears, just to name a few.

My own interests lie with RIA technologies, and since I am a Microsoft developer (and have been since around 1999), I will touch on other technologies only in passing and in comparison.

I plan to discuss everything about and around Microsoft Silverlight. For example, my next blog posts will deal with the following topics (in no particular order).

Silverlight + IoC (Inversion of Control)

Silverlight + Windows Azure (Cloud)

Silverlight + Control Communication (via Javascript)

Silverlight + Expression Blend

Silverlight + UI/UX

Silverlight + Security

Hopefully, you will find my posts useful and informative. I will attempt to write a post once a week, and will try to focus on quality posts only.

I am a firm believer that the age of traditional operating systems (as we know it) is coming to a timely end. RIA technologies, with Silverlight at its helm, are bound to transform the way we view the O/S and the Web Browser.

 Enjoy!


Categories: .NET
Permalink | Comments (0) | Post RSSRSS comment feed