Solving development problems  |  About this blog

Archive for the ‘silverlight’ tag

Silverlight 2.0 – Invoke method with Reflection

When deciding whether to create a rich graphical web application with lots of animations either with Silverlight or ASP .NET, Silverlight definitely wins. But when deciding whether put a database in first place then server side scripts (i.e. ASP .NET) have the advantage.

Anyway, if you are accessing database from Silverlight you’ve probably came across WCF or other  web services. Let’s say you have 100 tables and want to use WCF. Each table has Select, Insert, Update and Delete methods generated like InsertUser(User item). Visual Studio 2008 can automatically generated WCF proxy classes in Silverlight which are asynchronous. Suddenly, handling application logic and database becomes complex for development.

Those methods have similarities - Select, Insert, Update and Delete are repeated but for different table names. Idea is to use System.Reflection to simply and minimize development time. What the Reflection classes do is they use run time variables (i.e. string, int, etc.) to dynamically invoke methods according to situation in run time (cannot be determined in design time while developing).

Let’s say you have a method InsertCustomer(Customer item) in WCF and Visual Studio generates InsertCustomerAsync(Customer item) for Silverlight. Application can generate “InsertCustomerAsync” as string on demand. Then a method invoke by string is needed:

using System.Reflection;

//MyWebService is WCF proxy class and Customer is data entity

MethodInfo methodInfo = typeof(MyWebService).GetMethod(“InsertCustomerAsync”, new Type[] { typeof(Customer) });

methodInfo.Invoke(con, BindingFlags.Public | BindingFlags.Instance, null, new object[] { this.item, }, null);

Then a “completed” event needs to be caught:

MethodInfo handlerInfo = typeof(ReflectionDemo<T>).GetMethod(“SaveHandler”, BindingFlags.NonPublic | BindingFlags.Instance);
EventInfo eventInfo = typeof(MyWebService).GetEvent(eventName);
eventInfo.AddEventHandler(con, Delegate.CreateDelegate(eventInfo.EventHandlerType, this, handlerInfo));

Putting all code together:

public class ReflectionDemo<T> where T : new()
{
private T item;

public bool IsUpdate
{
get;
set;
}

public void Save()
{
try
{
if (this.item != null)
{
//Get names
string methodName = (this.IsUpdate ? “Update” : “Insert”) + typeof(T).Name + “Async”; //e.g. UpdateCustomerAsync
string eventName = (this.IsUpdate ? “Update” : “Insert”) + typeof(T).Name + “Completed”; //e.g. UpdateCustomerCompleted
string eventArgsName = (this.IsUpdate ? “Update” : “Insert”) + typeof(T).Name + “CompletedEventArgs”; //e.g. UpdateCustomerCompletedEventArgs

//Create a connection
MyWebService con = new MyWebService();

//Attach an event handler in run time retrieved event (e.g. something like “con.UpdateCustomerCompleted += …” at design time)
MethodInfo handlerInfo = typeof(ReflectionDemo<T>).GetMethod(“SaveHandler”, BindingFlags.NonPublic | BindingFlags.Instance);
EventInfo eventInfo = typeof(MyWebService).GetEvent(eventName);
eventInfo.AddEventHandler(con, Delegate.CreateDelegate(eventInfo.EventHandlerType, this, handlerInfo));

//Invoke method in run time (e.g. something like “con.UpdateCustomerAsync(this.item);” at design time)
MethodInfo methodInfo = typeof(MyWebService).GetMethod(methodName, new Type[] { typeof(T) }); //From overloaded methods get the one with single parameter
methodInfo.Invoke(con, BindingFlags.Public | BindingFlags.Instance, null, new object[] { this.item, }, null); //Invoke the method immediately
}
}
catch (Exception ex)
{
//Exception may be thrown in various situations (e.g. method cannot be found)
//Insert breakpoint here while debugging
}
}

protected void SaveHandler(object sender, EventArgs args)
{

//Handle event logic here
//Sample how to cast to a derived EventArgs with known properties:

Type type = args.GetType();
Exception ex = type.GetProperty(“Error”).GetValue(args, null) as Exception ?? null;
Customer item = (Customer)type.GetProperty(“Customer”).GetValue(args, null);
}

Written by Avivo

July 3rd, 2009 at 2:45 pm

Silverlight 2.0 – Resolved issue: InitializeError #2103 – Invalid or malformed application

Intro

I am working on a project that includes ASP .NET MVC web site and Silverlight 2.0 application. Initialy a Visual Studio solution with both project types has been created. At the beginning, sample Silverlight application worked fine, then most of the time development was going on MVC side. Now, when development should continue on Silverlight side browser throws an error:

This blog post explains how the issue has been solved. Resolving issue step by step…

1.Check namespaces

App.xaml should have x:Class attributes formatted as “Namespace.ClassName” (e.g. “StudioBikini.ClientSide.App”).

Same namespace and class name should also appear in App.xaml.cs. Note that namespace and class name are separated in C# file while glued together in XAML.

2. Change project properties

When you change a namespace for App in either C# or XAML the Startup object value in properties still holds the previous value.
Right click on a project in Visual Studio and select Properties.
Click on the Startup object combobox should open a list of available startup object and select the Namespace.ClassName.

Also make sure that Generate Silverlight manifest file checkbox is checked and an existing manifest file is selected.

3. Check manifest file

Some text editors add 3 garbage bytes at the beginning of a file which represent encoding. Those three bytes are invisible by some editors and may cause xml parsing exception.
Remove Properties\AppManifest.xml file and create it again.

4. Other possibilities:

  • Try to set assembly name and default namespace in the project properties to the same value. Namespace in properties should be the same as namespace in App.
  • Try with relative or absolute uri or false uri – if .xap file cannot be found Silverlight plug-in returns error #2104, that is different than #2103. So #2103 indicates that file has been found.
  • Clear browser’s cache (downloaded data) and reload the page with Silverlight.
  • Turn off virus scanner, as some scanners block loading unknown or hidden extensions (I had problems with .xaml.js for Silverlight 1.0).
  • If you are using object tag in html to load .xap file, try to change height in pixels (in case it works on IE7 but not in Firefox 3.0).
  • There may be an old .xap build. Try to rebuild VS solution or delete bin and obj folders from all projects – those folders are generated again on next build.
  • AppManifest.xml file can be read-only, usually happens when under a source control system (e.g. sourcesafe, svn), so check it out first.
  • Finally, delete AppManifest.xml, create new one and paste next lines into the file:

<Deployment xmlns=”http://schemas.microsoft.com/client/2007/deployment”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”>
<Deployment.Parts>
</Deployment.Parts>
</Deployment>

Solution

It appears that file was under Visual SourceSafe, problem with locked file. Solution has been found progressively, step by step as described above.

Another time, another project, same error. Problem with an included assembly reference – a Silverlight Class Library project with web service reference and Silverlight Application project with reference System.ServiceModel… Resolved by commeting code that uses System.ServiceModel (code when calling web service generated classes). Alternative is to use  release settings instead of debug.

Any other suggestions?

Written by Avivo

June 29th, 2009 at 9:59 am

Hosting Silverlight 2.0 applications on IIS

http://www.shahed.net/post/Hosting-Silverlight-20-in-IIS.aspx

If you host Silverlight 2.0 application in IIS you might find that the silverlight object is not loading. If that’s the case, first thing you should check is the MIME type list. By default, the Silverlight package extension *.xap is not included.

To resolve that, go to IIS Manager, properties of your web site and check the “Http Headers” tab.

1

Then click the MIME Types button. You should see a list as bellow.

2

If the .xap extension is not in the list then click New… and add the following entry:

Extension: .xap
MIME type: application/x-silverlight-app

Now, check your site. You should get the silverlight objects properly.

http://weblogs.asp.net/mschwarz/archive/2008/03/07/silverlight-2-not-working-on-production-web-server.aspx

Silverlight 2 not working on Production Web Server

I got some questions about why is Silverlight 2 beta not working on my production Web server? Well, one of the most errors I found is the missing MIME type definition in IIS. Silverlight 2 doesn’t compile a DLL as the beta 1.1 did. The new file extension is .XAP. The only thing you have to do is following step:

  1. Open the Internet Information Services Manager (IIS Manager)
  2. Right-click on IIS and select Properties
  3. Click on the MIME-Types button
  4. Click on New… to add a new MIME-Type
  5. For file extension use .XAP and for the MIME-Type use Assembly application/x-silverlight
    (don’t miss the dot before XAP!!)

Now you are able to run your Silverlight 2 apps.

WindowClipping

If you cannot modify the MIME type you can simple rename the ClientBin file to .DLL. Note that you have to modify the source param, too.

Update: If you are using IIS7 yu can run following command. This will change the applicationHost.config in the subfolder config (section <staticContent/>):

“%systemroot%\System32\inetsrv\appcmd” set config /section:staticContent /+[fileExtension='.xap',mimeType='application/x-silverlight']

http://learn.iis.net/page.aspx/262/silverlight/

Configuring IIS for Silverlight Applications

Author: Walter Oliver

Published on December 06, 2007 by walterov

Updated on March 19, 2008 by walterov

Average Rating function SendRating(id, rating) { new Ajax.Request(‘/js/HelpfulHandler.ashx?command=rating’, { method:’post’, parameters: {contentid: id, vote: rating}, onSuccess: null, // function(transport){alert(transport.responseText);}, onFailure: function(){ alert(‘Something went wrong…’) } }); Element.show(‘thanks’); return false; } function login(url) { location.replace(url); // location.replace(‘/login.aspx’); } Rate It (0)

RSS

function incrementAndPrint() { new Ajax.Request(‘/js/HelpfulHandler.ashx?command=print’, { method:’post’, parameters: Form.serialize(‘aspnetForm’), onSuccess: null, // function(transport){alert(transport.responseText);}, onFailure: function(){ alert(‘Something went wrong…’) } }); window.print(); } function sentEmail() { new Ajax.Request(‘/js/HelpfulHandler.ashx?command=emailed’, { method:’post’, parameters: Form.serialize(‘aspnetForm’), onSuccess: null, // function(transport){alert(transport.responseText);}, onFailure: function(){ alert(‘Something went wrong…’) } }); }

Featured IIS 7.0 Web Hosting

Windows 2008/IIS 7.0 Hosting is Here!

Windows 2008/IIS 7.0 Hosting is Here!

  • Starting at $10/mo
  • Windows 2008 Servers w/ IIS7
  • Access to Microsoft IIS7 Manager
  • Trust Level Control
  • Pipeline Mode Selector Tool
  • ASP.NET 3.5/2.0
  • LINQ, AJAX, PHP5

Get 3 Months Free of IIS 7 Hosting Now

Introduction

Microsoft® SilverlightTM is a cross-browser, cross-platform plug-in for delivering the next generation of .NET based media experiences and rich interactive applications for the Web. Silverlight offers a flexible programming model that supports AJAX, VB, C#, Python, and Ruby, and integrates with existing Web applications. Silverlight supports fast, cost-effective delivery of high-quality video to all major browsers running on the Mac OS or Windows.

In most cases, hosters do not need to perform particular deployments to support Silverlight. However, check for the following basic items that could prevent Silverlight from functioning correctly.

MIME Types

In Windows Server 2008 IIS 7.0

All MIME types needed to support Silverlight are implemented by default in Windows Server 2008 IIS 7.0 and Windows Vista SP1.  Windows Vista RTM customers can add mime types by running “IIS Manager”, clicking on “Mime Types”, then clicking “add” and adding the following mime types:

  • .xap     application/x-silverlight-app
  • .xaml    application/xaml+xml
  • .xbap    application/x-ms-xbap

Alternatively, you can add the following mime types to your %windir%\system32\inetsrv\config\applicationHost.config file in the <staticContent> section.

<mimeMap fileExtension=”.xaml” mimeType=”application/xaml+xml” />
<mimeMap fileExtension=”.xap” mimeType=”application/x-silverlight-app” />
<mimeMap fileExtension=”.xbap” mimeType=”application/x-ms-xbap” />

In Windows Server 2003 IIS 6.0

To enable IIS 6.0 in Windows Server 2003 or IIS7 in Windows Vista RTM with the appropriate MIME Types, add:

  • .xap     application/x-silverlight-app
  • .xaml    application/xaml+xml
  • .xbap    application/x-ms-xbap

Here is a VBS script you could run to enable each of these types:

Const ADS_PROPERTY_UPDATE = 2

if WScript.Arguments.Count < 2 then
WScript.Echo “Usage: ” + WScript.ScriptName + ” extension mimetype”
WScript.Quit
end if

‘Get the mimemap object.
Set MimeMapObj = GetObject(“IIS://LocalHost/MimeMap”)

‘Get the mappings from the MimeMap property.
aMimeMap = MimeMapObj.GetEx(“MimeMap”)

‘ Add a new mapping.
i = UBound(aMimeMap) + 1
Redim Preserve aMimeMap(i)
Set aMimeMap(i) = CreateObject(“MimeMap”)
aMimeMap(i).Extension = WScript.Arguments(0)
aMimeMap(i).MimeType = WScript.Arguments(1)
MimeMapObj.PutEx ADS_PROPERTY_UPDATE, “MimeMap”, aMimeMap
MimeMapObj.SetInfo

WScript.Echo “MimeMap successfully added: ”
WScript.Echo “    Extension: ” + WScript.Arguments(0)
WScript.Echo “    Type:      ” + WScript.Arguments(1)

If you copy and paste the code above into a VBS file and save it as ADDMIMETYPE.VBS the syntax to add each type would be:

ADDMIMETYPE.VBS  .xap  application/x-silverlight-app ADDMIMETYPE.VBS  .xaml application/xaml+xmlADDMIMETYPE.VBS  .xbap application/x-ms-xbap

Using the IIS Manager User Interface in Windows Server 2003 IIS 6.0

1. Go to Start\Administrative Tools and run IIS Manager, see figure below:

2. Right click on the server name and select “Properties”, see figure below:

3. In the Properties Dialog, click on the “MIME Types” button, see figure below:

4. In the “MIME Types” Dialog, click the “New” button, see figure below:

5. In the “MIME Type” Dialog enter one MIME Type at the time:

  • .xap     application/x-silverlight-app
  • .xaml    application/xaml+xml
  • .xbap    application/x-ms-xbap
  • see figure below:

    For detailed information on Silverlight, visit http://silverlight.net/.

    System.Data.SqlServerCe.3.5 not installed

    SQL Compact is a great little database and highly recommended. However it was designed for use on small compact, hence its name, devices and that has some drawbacks. One of these is that it doesn’t run as a 64 bits application. And by default if you create a .NET application it is compile as “Any CPU” meaning it will run as a 64 bits application on a 64 bits version of Windows.

    I, or I should say Ron Jacobs, ran into that using my SqlCeWorkflowPersistenceService because the sample/test application  was set to the default of “Any CPU”. The result is that the LINQ provider cannot load the runtime and a InvalidOperationException with message “Cannot open ‘WorkflowPersistenceDatabase.sdf’. Provider ‘System.Data.SqlServerCe.3.5′ not installed.” is the result. Now the fix is rather easy but it has to be done in the main program and that is to compile it for X86 instead of Any CPU.

    X86

    Do this and any application using  SQL Compact 3.5 will happily run on Windows 64bit as a WOW Application.

    Enjoy!

    ArrayOfXElement not recognized by Silverlight 2.0

    Last weekend I was working on a Silverlight 2.0 game that loads and saves scores to an external database. Database is accessed via web service which has two methods: GetScore and SaveScore. GetScore returns DataSet and SaveScore returns nothing.

    Web service proxy is generated as usual – right click on the project node in VS2008, “Add Service Reference…”, enter url, proxy class is generated and the methods are accessible in the code. But when I tried to build the project an error occured: “The type or namespace name ‘ArrayOfXElement’ does not exist in the namespace” which means that ArrayOfXElement is unrecognized class for the compiler. Searching on the Google reveals that this happens when service method returns DataSet, so ArrayOfXElement is actually DataSet and DataSets are not supported in Silverlight 2.0.

    A quick solution is to replace all ‘ArrayOfXElement’ words with ‘object’. Project would build that way but the data would have no meaning.

    Another solution is to change the web service return type but this is not always editable by the client side developer.

    Finally, workaround idea is to get DataSet schema and convert it to a class. How to do this?
    1. Create a dummy WPF project.
    2. Add web service reference to the WPF project. Return type is DataSet instead of ArrayOfXElement.
    3. Write some code to call a web service methods that returns DataSet then extract xsd schema and save it to the disk. Build and run. Sample:
    GameServiceClient client = new GameServiceClient();
    DataSet ds = client.GetScore(1, “abc”, “”, DateTime.Now);
    ds.WriteXmlSchema(@”C:\Temp\Score.xsd”);
    4. So you have the xsd file. Now find ‘xsd.exe’ which is located in the same directory as ‘svcutil.exe’ (e.g. C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin). Run it with arguments:
    xsd C:\Temp\Score.xsd /c
    5. xsd tool generates Score.cs file which contains tables as classes and columns as properties. Include the generated file in the Silverlight project.
    6. Replace all ‘ArrayOfXElement’ words with ‘NewDataSet’ or other class name, depends on the retrieved DataSet name and generated code.

    Note that this is just an idea. So far the sample project builds fine but there is a problem with cross-domain security. Another story.

    Url to the web service in this example:
    http://www.silverlightclub.com/apps/GameService.asmx

    References:
    http://silverlight.net/forums/t/60518.aspx
    http://blogs.msdn.com/suwatch/archive/2009/01/21/wcf-silverlight-exception-and-serialization.aspx

    Written by Avivo

    March 21st, 2009 at 8:26 pm