Tech blog

Solving problems

About
Contact

Archive for the ‘Silverlight/WPF’ Category

Three essential plugins for Expression Blend

leave a comment

When it comes to vector graphics in Windows applications XAML is the most advanced format to choose from. XAML is great because developer/designer has full control over the graphics. Hidden reference lines, or garbage shapes, or objects can be relatively easily detected and removed from the code as compared to those formats that entirely rely on GUI editor.

A XAML document can be created with plain Notepad but there are great apps like Visual Studio, Expression Blend and Kaxaml that simplify editing. What is missing in those apps is lack of XAML exporting support, like saving .xaml to .png file. Luckily there are plugins to do just that.

xbprint is printing plugin for Expression Blend 3 hosted on CodePlex. Installation of the utility must be perfomed manually by extracting files to the Addins folder in Expression Blend directory. But once the plugin is installed it is easy to use. Set margins, alignment, paper size and click Print.

xbprint screenshot

xbraster is xaml to raster image converting plugin, a close relative to xbprint. Installation and use is similar. xbraster can convert XAML to PNG, JPEG, TIFF, GIF or bitmap.

xbraster screenshot

xbsprite is a sprite image generating plugin. Input xaml files are rasterized and combined in one image with optional CSS and HTML output for use on a web page.

xbsprite screenshot

For advanced and professional use of XAML xbprint, xbraster and xbsprite are must-have plugins.

EDIT: xbprint, xbraster and xbsprite can run directly from desktop – no need to have
Expression Blend installed.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

July 5th, 2010 at 10:49 am

WriteableBitmap does not Render()?!

leave a comment

We spent quite some time working on a Silverlight deep zoom application. Like in other projects, a problem appears sooner or later. This time with the WriteableBitmap that couldn’t take screenshot of a basic shape.

//Simple ellipse (green circle)
Ellipse element = new Ellipse()
{
	Width = 50,
	Height = 50,
	Fill = new SolidColorBrush(Colors.Green)
};

//WriteableBitmap current = new WriteableBitmap(50, 50);
//current.Render(element, new MatrixTransform()); //DOES NOT WORK!!! - renders blank transparent image

//But with the constructor works fine
WriteableBitmap bitmap = new WriteableBitmap(element, new MatrixTransform());

//Ellipse captured as raster image painted on a panel's background
Grid grid = new Grid()
{
	Width = 50,
	Height = 50,
	Background = new ImageBrush() { ImageSource = bitmap }
};

Summary for the Render() method says: “Renders an element within the bitmap.”
Render() method didn’t output required result but using constructor instead of the method did do the job. Input parameters were the same.

Maybe Render() method do something else, maybe it is a problem with Vista 64-bit…

Anyway, WriteableBitmap is very useful in Silverlight 3, luckily it works.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

December 9th, 2009 at 5:36 pm

Silverlight: inherit a generic class from UserControl

leave a comment

Note! This blog post is just an idea than well tested solution, more a review that detailed description.
In Silverlight UserControl and Page classes are usually used with xaml. Root tags in xaml define the type, like so:

xaml
<UserControl x:Class="MyView">
...
</UserControl>

code-behind
namespace MyNamespace
{
  class MyView : UserControl
}

Sometimes, developers want to extend UserControl, i.e. as View by MVVM pattern.

xaml
<v:ViewBase x:Class="MyNamespace.MyView" xmlns:v="clr-namespace:MyNamespace">
...
</v:ViewBase>

code-behind
namespace MyNamespace
{
  class MyView : ViewBase /* ViewBase is a custom class */
}

Step further, every View should have it’s specialized model (ViewModel), thus base class could integrate a Model property. To avoid casting one should use generics, like ViewBase<MyViewModel>.

xaml
<!-- There's a problem, generics cannot be written in xaml. -->

code-behind
namespace MyNamespace
{
  class MyView : ViewBase<MyViewModel> /* ViewBase is a custom class */
}

Generics cannot be written directly in xaml? There is a workaround:
1. Use a wrapper, described here
2. Create a new non-generic class, like in this sample:

xaml
<v:MyViewBase x:Class="MyNamespace.MyView" xmlns:v="clr-namespace:MyNamespace">
...
</v:MyViewBase>

code-behind
namespace MyNamespace
{
  class MyView : MyViewBase
}

public abstract class MyViewBase : ViewBase<MyViewModel>
{
  /* non-generic class */
}

Appendix: ViewBase<TViewModel> class

public abstract class ViewBase<TViewModel> : UserControl, INotifyPropertyChanged where TViewModel : ViewModelBase, new()
{
	private TViewModel model;
	public TViewModel Model
	{
		get
		{
			if (this.model == null)
			{
				this.model = new TViewModel();
				base.DataContext = this.model;
			}
			return this.model;
		}
		set
		{
			if (this.model != value)
			{
				this.model = value;
				base.DataContext = this.model;
				OnPropertyChanged("Model");
			}
		}
	}
}

References:

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

November 30th, 2009 at 6:57 pm

How to focus window in WPF when it gets out of focus

one comment

Sometimes you want to have your WPF application in “kiosk” mode (fullscreen) and you can do this with this code:

Window w = new Window();
w.WindowStyle = WindowStyle.None;
w.WindowState = WindowState.Maximized;
w.TopMost = true;
w.ResizeMode=NoResize;
w.Show();

But, some system message (yellow balloon in system tray shows Taskbar in focus or any other Window system task) can get your application out of focus. In order to get it back to focus use this code:

//Interop.cs
using System.Runtime.InteropServices;
using System.Windows.Interop;

public class Interop
{
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

public static IntPtr GetWindowHandle(Window window)
{
return new WindowInteropHelper(window).Handle;
}
}

//Somewhere in main window
IntPtr window = Interop.GetWindowHandle(this);
IntPtr focused = Interop.GetForegroundWindow();
if (window != focused)
{
Interop.SetForegroundWindow(window);
}
VN:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

November 9th, 2009 at 11:48 am

Silverlight 2.0 – Invoke method with Reflection

one comment

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);
}

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

July 3rd, 2009 at 2:45 pm

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

one comment

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?

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

June 29th, 2009 at 9:59 am

Catching WPF Unhandled Exception

leave a comment

You can tell the debbuger to throw that exception.

1. In Visual Studio (checked in 2008) go to Debug/Exceptions.
2. Open tree of ‘Win32 Exceptions’
3. Check ‘Thrown’ checkbox in ‘c0000005 Access violation’ (the forth in my list)
4. Run your project in debug and the exception should be thrown in the line causing it.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

June 17th, 2009 at 6:49 pm

WPF Performance and Debugging Tools

leave a comment

Performance Profiling Tools for WPF
http://windowsclient.net/wpf/perf/wpf-perf-tool.aspx

Mole debugging tool
http://www.codeproject.com/KB/macros/MoleForVisualStudioEdit.aspx

Snoop tool
http://blois.us/Snoop/

CLR Profile tool
http://www.microsoft.com/downloads/details.aspx?familyid=86ce6052-d7f4-4aeb-9b7a-94635beebdda&displaylang=en

WinDebug tool
http://www.microsoft.com/whdc/devtools/debugging/default.mspx


VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

June 17th, 2009 at 6:20 pm

Catch Thread Exceptions in WPF

leave a comment

http://www.jimandkatrin.com/codeblog/2008/06/wpf-worker-thread-exceptions.html

What if you want to do global exception handling with worker threads? My scenario involves data methods that may be called synchronously, on the UI thread, or asynchronously on a worker. I would like to use the same global exception handling for both.

The problem with this scenario is that unhandled exceptions in the worker thread may cause the application to terminate; there’s no handler you can use or flag you can set to prevent this.

One way of handling this is explained as a side note in MSDN’s Application.DispatcherUnhandledExceptiondocumentation:

  1. Handle exceptions on the background thread.
  2. Dispatch those exceptions to the main UI thread.
  3. Rethrow them on the main UI thread without handling them to allow DispatcherUnhandledException to be raised.

I guess they thought the code was too obvious to bother providing an example…

That list is mentioned in the MSDN forums, where an example was promised, but not delivered.

try
{
    . . .
}
catch (Exception ex)
{
    . . . 

    // Are we not on the main UI thread?
    if (!Application.Current.Dispatcher.CheckAccess())
    {
        // Unhandled exceptions on worker threads will halt the application. We want to
        // use our global exception handler(s), so dispatch or "forward" to the UI thread.
        Application.Current.Dispatcher.Invoke(
            System.Windows.Threading.DispatcherPriority.Normal,
            new Action<Exception>(WorkerThreadException), ex);
    }
    else
    {
        throw;  // Already on UI thread; just rethrow the exception to global handlers
    }
}

The WorkerThreadException method simply re-throws the exception on the UI thread, where it is handled by any global exception handlers that have been defined:

private static void WorkerThreadException(Exception ex)
{
    throw ex;
}

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

June 17th, 2009 at 5:36 pm

Hosting Silverlight 2.0 applications on IIS

leave a comment

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/.

    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)