<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Pure silver</title>
	<atom:link href="http://puremsil.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://puremsil.wordpress.com</link>
	<description>removing impurities</description>
	<lastBuildDate>Wed, 04 Jan 2012 16:48:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='puremsil.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Pure silver</title>
		<link>http://puremsil.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://puremsil.wordpress.com/osd.xml" title="Pure silver" />
	<atom:link rel='hub' href='http://puremsil.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Glow effect in Silverlight</title>
		<link>http://puremsil.wordpress.com/2010/05/16/glow-effect-in-silverlight/</link>
		<comments>http://puremsil.wordpress.com/2010/05/16/glow-effect-in-silverlight/#comments</comments>
		<pubDate>Sun, 16 May 2010 13:39:37 +0000</pubDate>
		<dc:creator>Stefan Dragnev</dc:creator>
				<category><![CDATA[Silverlight and .NET]]></category>

		<guid isPermaLink="false">http://puremsil.wordpress.com/?p=65</guid>
		<description><![CDATA[Ever wondered how you can achieve in Silverlight that nice silhouette effect that FarmVille uses to highlight pointed objects? Probably not. On a related note, folks at Stack overflow however have wondered how you can achieve glow/halo effects on text. Apparently it&#8217;s easy to do in Flash &#8211; you just use the glow filter. Silverlight [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=65&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Ever wondered how you can achieve in Silverlight that nice silhouette effect that FarmVille uses to highlight pointed objects? Probably not.</p>
<p>On a related note, folks at <a href="http://stackoverflow.com/questions/408406/silverlight-2-text-glow-effect">Stack overflow</a> however have wondered how you can achieve glow/halo effects on text.</p>
<p>Apparently it&#8217;s easy to do in Flash &#8211; you just use the <a href="http://www.entheosweb.com/flash/glow_effect.asp">glow filter</a>. Silverlight unfortunately doesn&#8217;t have one out of the box. So, I decided to try put in one. Presenting:</p>
<p><a href="http://puremsil.files.wordpress.com/2010/05/glows.jpg"><img class="alignnone size-full wp-image-72" title="Glows" src="http://puremsil.files.wordpress.com/2010/05/glows.jpg" alt="" width="399" height="399" /></a></p>
<p>Check out the <a href="http://savage-dreams.net/static/glow/GlowTestPage.html">full sample</a> and get the <a href="http://savage-dreams.net/static/glow/GlowSrc.zip">source code</a>.</p>
<p>A few notes:</p>
<ul>
<li>this is more of a proof-of-concept effect. It might have some bugs as is. It also needs a few features on top.</li>
<li>to compile the shader with DirectX&#8217;s effect compiler use the following command :
<pre>fxc /T ps_2_0 /Vd /Fo GlowEffect.pso GlowEffect.ps</pre>
</li>
<li>the presented effect is for outer glow only &#8211; it doesn&#8217;t implement  knockout or inner glow. Those won&#8217;t be hard to implement on top of this  code, though. Maybe a bit of conditional compilation.</li>
<li>the glow radius is <strong>fixed</strong> at 4 pixels. This is a limitation of the approach used &#8211; PS 2.0 doesn&#8217;t support loops. The compiler demands that all syntactic loops be unrolled at compile time. The shader has a constant for the glow radius &#8211; increasing it will increase the glow radius after recompiling the shader. The problem is that the shader compiler takes more and more time as the radius increases &#8211; currently it takes 1-2s to compile. I have actually no idea how e.g. the stock BlurEffect was implemented to support an arbitrary blur radius. The shader can be enhanced to take an arbitrary radius though, that still must be smaller than the &#8216;max radius&#8217; in the shader. Note that if you change the glow radius, you must also increase the Padding used in the GlowEffect class.</li>
<li>&#8220;approximately 193 instruction slots used (49 texture, 144 arithmetic)&#8221; which is well over the limit of PS 2.0 (32 tex, 64 arith) &#8211; case in point that silverlight isn&#8217;t bound by standard limitations.</li>
<li>the sample is built against Silverlight 4.0, although there is no reason for the code to not work on older versions.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/puremsil.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/puremsil.wordpress.com/65/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/puremsil.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/puremsil.wordpress.com/65/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/puremsil.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/puremsil.wordpress.com/65/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/puremsil.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/puremsil.wordpress.com/65/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/puremsil.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/puremsil.wordpress.com/65/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/puremsil.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/puremsil.wordpress.com/65/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/puremsil.wordpress.com/65/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/puremsil.wordpress.com/65/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=65&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://puremsil.wordpress.com/2010/05/16/glow-effect-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/594a687459af9dcb554e6dd03f0c702d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tailsu</media:title>
		</media:content>

		<media:content url="http://puremsil.files.wordpress.com/2010/05/glows.jpg" medium="image">
			<media:title type="html">Glows</media:title>
		</media:content>
	</item>
		<item>
		<title>Migrating from Silverlight 3 to 4 &#8211; hicks along the road</title>
		<link>http://puremsil.wordpress.com/2010/05/12/migrating-from-silverlight-3-to-4-hicks-along-the-road/</link>
		<comments>http://puremsil.wordpress.com/2010/05/12/migrating-from-silverlight-3-to-4-hicks-along-the-road/#comments</comments>
		<pubDate>Wed, 12 May 2010 12:35:29 +0000</pubDate>
		<dc:creator>Stefan Dragnev</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://puremsil.wordpress.com/?p=59</guid>
		<description><![CDATA[The migration for me was almost painless. Every now and then however there are some wrinkles to iron out. In today&#8217;s installment a tester called that there was a problem connecting to the server-side. Investigation showed that the problem was that the plugin thought there was no cross-domain policy in place. Incidentally the tester opened [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=59&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The migration for me was almost painless. Every now and then however there are some wrinkles to iron out.</p>
<p>In today&#8217;s installment a tester called that there was a problem connecting to the server-side. Investigation showed that the problem was that the plugin thought there was no cross-domain policy in place. Incidentally the tester opened the client application without omitting the www. part, which lead to the need to use cross-domain access policy. Moving along, the problem only appeared on IE &#8211; Chrome and Firefox work fine.</p>
<p>The problem turned out to be an old Silverlight.js that was generated by the SL3 wizard for ASP.NET SL test pages.</p>
<p>I downloaded the latest Silverlight.js from <a href="http://code.msdn.microsoft.com/silverlightjs/Release/ProjectReleases.aspx?ReleaseId=4148">MSDN</a></p>
<p>&#8230;and problem solved.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/puremsil.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/puremsil.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/puremsil.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/puremsil.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/puremsil.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/puremsil.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/puremsil.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/puremsil.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/puremsil.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/puremsil.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/puremsil.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/puremsil.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/puremsil.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/puremsil.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=59&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://puremsil.wordpress.com/2010/05/12/migrating-from-silverlight-3-to-4-hicks-along-the-road/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/594a687459af9dcb554e6dd03f0c702d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tailsu</media:title>
		</media:content>
	</item>
		<item>
		<title>How to work around the limitation of 64 instructions in pixel shader model 2.0 in Silverlight shader effects</title>
		<link>http://puremsil.wordpress.com/2010/05/06/how-to-work-around-the-limitation-of-64-instructions-in-pixel-shader-model-2-0-in-silverlight-shader-effects/</link>
		<comments>http://puremsil.wordpress.com/2010/05/06/how-to-work-around-the-limitation-of-64-instructions-in-pixel-shader-model-2-0-in-silverlight-shader-effects/#comments</comments>
		<pubDate>Thu, 06 May 2010 19:46:56 +0000</pubDate>
		<dc:creator>Stefan Dragnev</dc:creator>
				<category><![CDATA[Silverlight and .NET]]></category>
		<category><![CDATA[effect]]></category>
		<category><![CDATA[pixel shader]]></category>
		<category><![CDATA[shader]]></category>
		<category><![CDATA[shader model]]></category>
		<category><![CDATA[ShaderEffect]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://puremsil.wordpress.com/?p=37</guid>
		<description><![CDATA[In the wish list for Silverlight 4 people asked that SL support at least ps_2_b for compiling shader effects. The main reason is the amount of shader instructions supported &#8211; while ps_2_0 (which is the currently supported shader model in SL) supports 64 instructions, ps_2_b supports a whopping 512. Many effects, especially ones that sample [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=37&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the wish list for Silverlight 4 people asked that SL support at least ps_2_b for compiling shader effects. The main reason is the amount of shader instructions supported &#8211; while ps_2_0 (which is the currently supported shader model in SL) supports 64 instructions, ps_2_b supports a whopping 512. Many effects, especially ones that sample a lot of pixels around its target pixel (think blurs), quickly blow through the 64 instructions limit &#8211; the ps_2_b shader model would give a breath of fresh air in this situation.</p>
<p>The main point of confusion about this is that people think that there is some inherent limitation in PS2.0 to support more instructions. There actually isn&#8217;t &#8211; the shader model is just a specification of the minimum of supported features in *hardware*. If a video card supports PS2.0, then it guarantees that it can meet at least the requirements for PS2.0. In fact, modern hardware will probably run ps_2_0-targeted shaders with more than 64 instruction even though they are technically non-standard (it&#8217;s actually just a driver issue). The same shaders will almost certainly be incompatible with video cards that support only up to ps_2_0, though.</p>
<p>Now, Silverlight shaders are (to some extent &#8211; unfortunately) run on the CPU. They&#8217;re, in a sense, interpreted. As such, there really are no hardware-specific limitations that would prohibit Silverlight to render non-standard (in the sense of instruction count) shaders &#8211; in fact, it just works! There is nothing to stop you to compile a million instruction shader! (save for DirectX SDK&#8217;s effect compiler&#8217;s bogus performance on slightly larger shaders)</p>
<p>Well, enough exposition &#8211; I guess by now you just want to know how to compile long shaders for Silverlight effects. Normally you compile shaders with the following command or a variation thereof:<br />
<code>&gt; fxc /T ps_2_0 /Fo effect.pso effect.ps</code></p>
<p>To enable long shaders, just append the <code>/Vd</code> option to the command line. It just disables shader model compatibility validation and lets you deal eventually with potential incompatibilities.</p>
<p>Now that you&#8217;ve handled the issue of instruction count, prepare to weep because of the code generator&#8217;s imperfections&#8230; good luck.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/puremsil.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/puremsil.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/puremsil.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/puremsil.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/puremsil.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/puremsil.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/puremsil.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/puremsil.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/puremsil.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/puremsil.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/puremsil.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/puremsil.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/puremsil.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/puremsil.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=37&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://puremsil.wordpress.com/2010/05/06/how-to-work-around-the-limitation-of-64-instructions-in-pixel-shader-model-2-0-in-silverlight-shader-effects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/594a687459af9dcb554e6dd03f0c702d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tailsu</media:title>
		</media:content>
	</item>
		<item>
		<title>Generic weak event handlers</title>
		<link>http://puremsil.wordpress.com/2010/05/03/generic-weak-event-handlers/</link>
		<comments>http://puremsil.wordpress.com/2010/05/03/generic-weak-event-handlers/#comments</comments>
		<pubDate>Sun, 02 May 2010 23:29:45 +0000</pubDate>
		<dc:creator>Stefan Dragnev</dc:creator>
				<category><![CDATA[Silverlight and .NET]]></category>

		<guid isPermaLink="false">http://puremsil.wordpress.com/?p=23</guid>
		<description><![CDATA[If you’ve grown to need really generic weak event handlers and weak delegates, then I assume you have at least tried using existing non-entirely-generic ones. Dustin Campbell has a great article detailing the implementation of a weak event handler that can be used for any EventHandler&#60;&#62; parameterization, which is great for most practical purposes. Unfortunately, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=23&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you’ve grown to need really generic weak event handlers and weak delegates, then I assume you have at least tried using existing non-entirely-generic ones.<br />
Dustin Campbell has a <a href="http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx">great article</a> detailing the implementation of a weak event handler that can be used for any EventHandler&lt;&gt; parameterization, which is great for most practical purposes.<br />
Unfortunately, there seems to be no way to create a single generic class that can act as a weak proxy for all possible delegate types. It appears to be an inherent .NET limitation –generic type parameters that are in fact delegates cannot be used for invocation or anything delegate-related. It would have been possible if you could spell it as a type constraint, e.g. <code>class Foo&lt;T&gt; where T : delegate {};</code>. Oh well, no biggie – let’s just write a separate class for each possible delegate type. However, let’s be smart about it!<br />
By now you should’ve guessed that we’ll just use code generation – we’ll just generate an exact replica of the code in Campbell’s article, with the only difference being the delegate’s type.  I’m giving you the entire code below.</p>
<p><pre class="brush: csharp; wrap-lines: false;">
    /// &lt;summary&gt;
    /// Weak delegates are useful where you don't want the lifetime of a delegate target
    /// to be bound to the delegate's lifetime.
    ///
    /// The WeakDelegateFactory is used for the the same purpose as WeakEventHandler, but
    /// can work for any delegate type. Is uses Reflection.Emit to create an exact replica
    /// of the WeakEventHandler class, but for the specific delegate type.
    /// &lt;/summary&gt;
    public static class WeakDelegateFactory
    {
        private static AssemblyBuilder theDelegatesAsm;
        private static ModuleBuilder theModuleBuilder;

        public static TDelegate Create&lt;TDelegate&gt;(TDelegate targetDelegate, Action&lt;TDelegate&gt; unregisterDelegate) where TDelegate : class
        {
            EnsureBuildersCreated();

            var type = targetDelegate.GetType();

            if (type.GetMethod(&quot;Invoke&quot;).ReturnType != typeof(void))
                throw new ArgumentException(&quot;Weak delegates can only be created for delegates with void return type.&quot;, &quot;targetDelegate&quot;);

            // create the class builder that will give birth to this weak delegate class
            var className = &quot;WeakDelg-&gt;&quot; + GetPrettyName(type);
            var classType = theModuleBuilder.GetType(className)
                            ?? CreateWeakDelegateClass(targetDelegate, type, className);

            var ctor = classType.GetConstructors()[0];
            var weakDelg = ctor.Invoke(new object[] { targetDelegate, unregisterDelegate });
            return (TDelegate) (object) Delegate.CreateDelegate(type, weakDelg, classType.GetMethod(&quot;Invoke&quot;));
        }

        private static Type CreateWeakDelegateClass&lt;TDelegate&gt;(TDelegate targetDelegate, Type type, string className) where TDelegate : class
        {
            var classBuilder = theModuleBuilder.DefineType(className, TypeAttributes.Class | TypeAttributes.Public);

            // create the class fields for the unbound delegate, the weak reference to the delegate's target and an unregister callback
            var weakRefFld = classBuilder.DefineField(&quot;myWeakRef&quot;, typeof(WeakReference), FieldAttributes.Private);

            MethodBuilder unboundDelgInvoke;
            var unboundDelgType = CreateUnboundDelegateType(classBuilder, targetDelegate, out unboundDelgInvoke);
            var unboundDelgFld = classBuilder.DefineField(&quot;myUnboundDelg&quot;, unboundDelgType, FieldAttributes.Private);

            var unregisterDelgFld = classBuilder.DefineField(&quot;myUnregisterDelg&quot;, typeof(Action&lt;TDelegate&gt;), FieldAttributes.Private);

            // create constructor
            DefineConstructor&lt;TDelegate&gt;(type, classBuilder, unboundDelgType, weakRefFld, unboundDelgFld, unregisterDelgFld);

            // create the method that implements the weak delegate calling
            DefineInvokeMethod(targetDelegate, classBuilder, weakRefFld, unboundDelgFld, unregisterDelgFld, unboundDelgInvoke);

            unboundDelgType.CreateType();
            return classBuilder.CreateType();
        }

        private static void DefineConstructor&lt;TDelegate&gt;(Type delegateType, TypeBuilder classBuilder, TypeBuilder unboundDelgType, FieldBuilder weakRefFld, FieldBuilder unboundDelgFld, FieldBuilder unregisterDelgFld)
        {
            var target = delegateType.GetProperty(&quot;Target&quot;);
            // create the constructor; it initializes the unbound delegate and the weak reference
            var constructor = classBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis,
                                                             new[] { delegateType, typeof(Action&lt;TDelegate&gt;) });
            var ctorIl = constructor.GetILGenerator();

            // call object.ctor()
            ctorIl.Emit(OpCodes.Ldarg_0);
            ctorIl.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[] { }));

            // store a WeakReference to the delegate's target into a field
            ctorIl.Emit(OpCodes.Ldarg_0);
            ctorIl.Emit(OpCodes.Ldarg_1);
            ctorIl.Emit(OpCodes.Callvirt, target.GetGetMethod());
            ctorIl.Emit(OpCodes.Newobj, typeof(WeakReference).GetConstructor(new[] { typeof(object) }));
            ctorIl.Emit(OpCodes.Stfld, weakRefFld);

            // create an unbound delegate type from the given delegate's method
            ctorIl.Emit(OpCodes.Ldarg_0); // for stfld
            ctorIl.Emit(OpCodes.Ldtoken, unboundDelgType);
            ctorIl.Emit(OpCodes.Call, typeof(Type).GetMethod(&quot;GetTypeFromHandle&quot;, new[] { typeof(RuntimeTypeHandle) })); // first parameter; load the unbound delegate's type
            ctorIl.Emit(OpCodes.Ldnull); // second parameter; no instance given, i.e. treat it as a static method
            ctorIl.Emit(OpCodes.Ldarg_1); // third parameter to CreateDelegate
            ctorIl.Emit(OpCodes.Callvirt, typeof(Delegate).GetProperty(&quot;Method&quot;).GetGetMethod());
            ctorIl.Emit(OpCodes.Call, typeof(Delegate).GetMethod(&quot;CreateDelegate&quot;, new[] { typeof(Type), typeof(object), typeof(MethodInfo) }));
            ctorIl.Emit(OpCodes.Castclass, unboundDelgType);
            ctorIl.Emit(OpCodes.Stfld, unboundDelgFld);

            // store the unregister callback
            ctorIl.Emit(OpCodes.Ldarg_0);
            ctorIl.Emit(OpCodes.Ldarg_2);
            ctorIl.Emit(OpCodes.Stfld, unregisterDelgFld);

            ctorIl.Emit(OpCodes.Ret);
        }

        private static void DefineInvokeMethod&lt;TDelegate&gt;(TDelegate targetDelegate, TypeBuilder classBuilder, FieldBuilder weakRefFld, FieldBuilder unboundDelgFld, FieldBuilder unregisterDelgFld, MethodBuilder unboundDelgInvoke) where TDelegate : class
        {
            var targetType = ((Delegate) (object) targetDelegate).Target.GetType();
            var unregisterDelgType = typeof(Action&lt;TDelegate&gt;);
            var delegateType = targetDelegate.GetType();
            var delegateSignature = delegateType.GetMethod(&quot;Invoke&quot;);
            var delgParamTypes = GetParameterTypes(delegateSignature);
            var invoker = classBuilder.DefineMethod(&quot;Invoke&quot;, MethodAttributes.Public, delegateSignature.ReturnType, delgParamTypes.ToArray());
            var invokerIl = invoker.GetILGenerator();

            var targetLocal = invokerIl.DeclareLocal(targetType);

            var endLabel = invokerIl.DefineLabel();
            var targetIsNullLabel = invokerIl.DefineLabel();

            // get Target from weak reference
            invokerIl.Emit(OpCodes.Ldarg_0);
            invokerIl.Emit(OpCodes.Ldfld, weakRefFld);
            invokerIl.Emit(OpCodes.Callvirt, typeof(WeakReference).GetProperty(&quot;Target&quot;).GetGetMethod());
            invokerIl.Emit(OpCodes.Isinst, targetType);
            invokerIl.Emit(OpCodes.Castclass, targetType);
            invokerIl.Emit(OpCodes.Stloc, targetLocal);
            invokerIl.Emit(OpCodes.Ldloc, targetLocal);
            invokerIl.Emit(OpCodes.Brfalse_S, targetIsNullLabel);

            // the target is not null - call the unbound delegate
            invokerIl.Emit(OpCodes.Ldarg_0);
            invokerIl.Emit(OpCodes.Ldfld, unboundDelgFld);
            invokerIl.Emit(OpCodes.Ldloc, targetLocal);
            invokerIl.Emit(OpCodes.Ldarg_1);
            invokerIl.Emit(OpCodes.Ldarg_2);
            invokerIl.Emit(OpCodes.Callvirt, unboundDelgInvoke);
            invokerIl.Emit(OpCodes.Ret);

            invokerIl.MarkLabel(targetIsNullLabel);
            // target was null, call unregister
            invokerIl.Emit(OpCodes.Ldarg_0);
            invokerIl.Emit(OpCodes.Ldfld, unregisterDelgFld);
            invokerIl.Emit(OpCodes.Brfalse_S, endLabel); // check if unregister is null
            invokerIl.Emit(OpCodes.Ldarg_0);
            invokerIl.Emit(OpCodes.Ldfld, unregisterDelgFld);
            invokerIl.Emit(OpCodes.Ldarg_0);
            invokerIl.Emit(OpCodes.Ldftn, invoker);
            invokerIl.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) })); // create delegate from invoke
            invokerIl.Emit(OpCodes.Callvirt, unregisterDelgType.GetMethod(&quot;Invoke&quot;)); // call unregister
            invokerIl.Emit(OpCodes.Ldarg_0);
            invokerIl.Emit(OpCodes.Ldnull);
            invokerIl.Emit(OpCodes.Stfld, unregisterDelgFld); // nullify unregister
            invokerIl.MarkLabel(endLabel);

            invokerIl.Emit(OpCodes.Ret);
        }

        private static void EnsureBuildersCreated()
        {
            if (theDelegatesAsm == null)
            {
                theDelegatesAsm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(&quot;WeakDelegates&quot;), AssemblyBuilderAccess.Run);
                theModuleBuilder = theDelegatesAsm.DefineDynamicModule(&quot;WeakDelegates&quot;);
            }
        }

        /// &lt;summary&gt;
        /// Creates an unbound delegate type from the type of a normal delegate
        /// &lt;/summary&gt;
        private static TypeBuilder CreateUnboundDelegateType(TypeBuilder parentClass, object boundDelegate, out MethodBuilder outInvokeMethod)
        {
            var invokeMethod = boundDelegate.GetType().GetMethod(&quot;Invoke&quot;);
            var targetType = ((Delegate) boundDelegate).Target.GetType();
            return CreateDelegateType(parentClass, invokeMethod.ReturnType, new[] { targetType }.Concat(GetParameterTypes(invokeMethod)).ToArray(), out outInvokeMethod);
        }

        private static IEnumerable&lt;Type&gt; GetParameterTypes(MethodInfo mi)
        {
            return from p in mi.GetParameters() select p.ParameterType;
        }

        /// &lt;summary&gt;
        /// Basically does what the compiler does when it has to compile a delegate statement.
        /// Creates the delegate as a nested type.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;A class derived from System.MulticastDelegate that can be called with the given parameters&lt;/returns&gt;
        private static TypeBuilder CreateDelegateType(TypeBuilder parentClass, Type returnType, Type[] parameters, out MethodBuilder outInvokeMethod)
        {
            // from Joel Pobar's CLR weblog
            // Creating delegate types via Reflection.Emit
            // http://blogs.msdn.com/joelpob/archive/2004/02/15/73239.aspx

            var delgTypeBuilder = parentClass.DefineNestedType(&quot;UnboundDelegate&quot;, TypeAttributes.Class | TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));
            var constructorBuilder = delgTypeBuilder.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(object), typeof(IntPtr) });
            constructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            outInvokeMethod = delgTypeBuilder.DefineMethod(&quot;Invoke&quot;, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, returnType, parameters);
            outInvokeMethod.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            return delgTypeBuilder;
        }

        private static string GetPrettyName(Type t)
        {
            if (t.IsGenericType)
            {
                return t.Namespace + '.' + t.Name + '(' + String.Join(&quot;;&quot;, (from p in t.GetGenericArguments() select p.Name).ToArray()) + ')';
            }
            else
            {
                return t.FullName;
            }
        }
    }

</pre></p>
<p>Note that we use Reflection.Emit to do the onerous code generation – we could’ve used CSharpCodeProvider to the same effect, so why didn’t we? Well, CSharpCodeProvider isn’t available in Silverlight, so there. This code works in Silverlight as it does in .NET. The only inherent limitation in Silverlight (as with the code in Campbell&#8217;s article) is that the bound method must be public enough &#8211; otherwise trying to create an unbound delegate from the delegate target throws a SecurityException.</p>
<p>The code probably works &#8211; it&#8217;s more of a proof of concept than anything else. I&#8217;ve used it in production code, so there aren&#8217;t any train-wrecking problems in it. There is probably more stuff needed to make it work in all cases, however.</p>
<p>This is how you use it:</p>
<p><pre class="brush: csharp;">
        public event Action&lt;int&gt; SomeEvent;

        private void Register()
        {
            SomeEvent += WeakDelegateFactory.Create(new Action&lt;int&gt;(Sink), e =&gt; SomeEvent -= e);
        }

        private void Sink(int foo)
        {}
</pre></p>
<p>It would have been great if methods were implicitly usable as delegates. You could then write (with an appropriate extension method) <code>SomeEvent += Sink.ToWeak(e=&gt;SomeEvent-=e);</code></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/puremsil.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/puremsil.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/puremsil.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/puremsil.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/puremsil.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/puremsil.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/puremsil.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/puremsil.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/puremsil.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/puremsil.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/puremsil.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/puremsil.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/puremsil.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/puremsil.wordpress.com/23/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=23&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://puremsil.wordpress.com/2010/05/03/generic-weak-event-handlers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/594a687459af9dcb554e6dd03f0c702d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tailsu</media:title>
		</media:content>
	</item>
		<item>
		<title>Using PointAnimation to move an object over a Canvas</title>
		<link>http://puremsil.wordpress.com/2010/05/03/using-pointanimation-to-move-an-object-over-a-canvas/</link>
		<comments>http://puremsil.wordpress.com/2010/05/03/using-pointanimation-to-move-an-object-over-a-canvas/#comments</comments>
		<pubDate>Sun, 02 May 2010 22:54:03 +0000</pubDate>
		<dc:creator>Stefan Dragnev</dc:creator>
				<category><![CDATA[Silverlight and .NET]]></category>

		<guid isPermaLink="false">http://puremsil.wordpress.com/?p=7</guid>
		<description><![CDATA[Imagine a situation where an object needs to animate its position on a Canvas. You know where it is, you know where it needs to be. As you know, the position on a Canvas is specified by the Canvas.Left and Canvas.Top dependency properties. We could simply use two DoubleAnimation instances, one for the Left and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=7&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Imagine a situation where an object needs to animate its position on a Canvas. You know where it is, you know where it needs to be. As you know, the position on a Canvas is specified by the Canvas.Left and Canvas.Top dependency properties. We could simply use two DoubleAnimation instances, one for the Left and another for the Top property. But wouldn’t it be nice if we could move it with a single timeline?<br />
PointAnimation is a class that can animate the value of a Point property. Unfortunately for us, the canvas position is specified by two distinct double values, not a single Point. Here’s how we work around this issue – first, we’ll define a proxy dependency property; next, I’ll show you how to use it.</p>
<p>This is our proxy property – it uses a property change callback to translate position changes into Canvas.Left and Canvas.Top property changes.<br />
<pre class="brush: csharp; wrap-lines: false;">
    public class CanvasServices
    {
        public static readonly DependencyProperty CanvasPositionProperty =
            DependencyProperty.RegisterAttached(&quot;CanvasPosition&quot;, typeof (Point), typeof (CanvasServices),
                                                new PropertyMetadata(new Point(), CanvasPositionChanged));

        private static void CanvasPositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var position = (Point) e.NewValue;
            d.SetValue(Canvas.LeftProperty, position.X);
            d.SetValue(Canvas.TopProperty, position.Y);
        }

        public static void SetCanvasPosition(DependencyObject d, Point position)
        {
            d.SetValue(CanvasPositionProperty, position);
        }

        public static Point GetCanvasPosition(DependencyObject d)
        {
            return (Point) d.GetValue(CanvasPositionProperty);
        }
    }

</pre><br />
Now, let’s use it to create a simple animation:<br />
<pre class="brush: xml; wrap-lines: false;">
    &lt;Canvas x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;Ellipse Height=&quot;44&quot; HorizontalAlignment=&quot;Left&quot; Stroke=&quot;Black&quot;
                 StrokeThickness=&quot;1&quot; VerticalAlignment=&quot;Top&quot; Width=&quot;58&quot;
                 x:Name=&quot;myElli&quot;/&gt;
        &lt;Canvas.Resources&gt;
            &lt;Storyboard x:Name=&quot;myStory&quot;&gt;
                &lt;PointAnimation From=&quot;20,20&quot; To=&quot;200,200&quot; Duration=&quot;0:0:3&quot;
                    Storyboard.TargetName=&quot;myElli&quot; x:Name=&quot;myAnim&quot;/&gt;
            &lt;/Storyboard&gt;
        &lt;/Canvas.Resources&gt;
    &lt;/Canvas&gt;
</pre><br />
Now, a problem with custom attached properties is that they don’t play nice with the property path syntax in XAML. This forces us to set the animation target in code, which is actually not that hard:<br />
<pre class="brush: csharp;">
Storyboard.SetTargetProperty(myAnim, new PropertyPath(CanvasServices.CanvasPositionProperty));
myStory.Begin();
</pre></p>
<p>That&#8217;s it. As you can see, custom attached properties can be used to change the way existing SL properties are aggregated in objects and used with animations.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/puremsil.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/puremsil.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/puremsil.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/puremsil.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/puremsil.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/puremsil.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/puremsil.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/puremsil.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/puremsil.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/puremsil.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/puremsil.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/puremsil.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/puremsil.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/puremsil.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=7&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://puremsil.wordpress.com/2010/05/03/using-pointanimation-to-move-an-object-over-a-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/594a687459af9dcb554e6dd03f0c702d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tailsu</media:title>
		</media:content>
	</item>
		<item>
		<title>What do the numbers in the upper-left corner mean when EnableGPUAcceleration and EnableFramerateCounter are both set to true?</title>
		<link>http://puremsil.wordpress.com/2010/05/02/4/</link>
		<comments>http://puremsil.wordpress.com/2010/05/02/4/#comments</comments>
		<pubDate>Sun, 02 May 2010 21:06:39 +0000</pubDate>
		<dc:creator>Stefan Dragnev</dc:creator>
				<category><![CDATA[Silverlight and .NET]]></category>

		<guid isPermaLink="false">http://puremsil.wordpress.com/?p=4</guid>
		<description><![CDATA[As taken from MSDN: If EnableGPUAcceleration is true AND EnableFrameRateCounter is true, an additional frame counter displays in the upper-left corner as an overlay within the Silverlight content area. The format of this frame rate counter is as follows: frameRate videoMemoryUsed GPUEnabledSurfaces intermediateSurfaces videoMemoryUsed is in KB. intermediateSurfaces refers to surfaces implicitly created to represent the software-rendered parts [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=4&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As taken from <a href="http://msdn.microsoft.com/en-us/library/cc838171(v=VS.95).aspx">MSDN</a>:</p>
<p>If <a href="http://msdn.microsoft.com/en-us/library/dd833062%28v=VS.95%29.aspx">EnableGPUAcceleration</a> is true AND EnableFrameRateCounter is true, an additional frame counter displays in the upper-left corner as an overlay within the Silverlight content area. The format of this frame rate counter is as follows:</p>
<p>frameRate videoMemoryUsed GPUEnabledSurfaces intermediateSurfaces</p>
<p>videoMemoryUsed is in KB. intermediateSurfaces refers to surfaces implicitly created to represent the software-rendered parts of the application on the GPU.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/puremsil.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/puremsil.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/puremsil.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/puremsil.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/puremsil.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/puremsil.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/puremsil.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/puremsil.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/puremsil.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/puremsil.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/puremsil.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/puremsil.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/puremsil.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/puremsil.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=puremsil.wordpress.com&amp;blog=13441395&amp;post=4&amp;subd=puremsil&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://puremsil.wordpress.com/2010/05/02/4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/594a687459af9dcb554e6dd03f0c702d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tailsu</media:title>
		</media:content>
	</item>
	</channel>
</rss>
