<?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/"
	>

<channel>
	<title>David DeWinter</title>
	<atom:link href="http://davedewinter.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://davedewinter.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Tue, 09 Aug 2011 21:05:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
		<item>
		<title>Tip #22 – DynamicMethods in Partial Trust</title>
		<link>http://davedewinter.com/2010/11/21/tip-22-dynamicmethods-in-partial-trust/</link>
		<comments>http://davedewinter.com/2010/11/21/tip-22-dynamicmethods-in-partial-trust/#comments</comments>
		<pubDate>Sun, 21 Nov 2010 23:23:49 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[DynamicMethod]]></category>
		<category><![CDATA[partial trust]]></category>
		<category><![CDATA[Reflection.Emit]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/11/21/tip-22-dynamicmethods-in-partial-trust/</guid>
		<description><![CDATA[The DynamicMethod class is in a part of the .NET Framework that not many people touch, even less so in partial trust. You may ask, then, why I bother to cover it. I have two reasons: it is a lower-level &#8230; <a href="http://davedewinter.com/2010/11/21/tip-22-dynamicmethods-in-partial-trust/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx">DynamicMethod</a> class is in a part of the .NET Framework that not many people touch, even less so in partial trust. You may ask, then, why I bother to cover it. I have two reasons: it is a lower-level abstraction on which LINQ expression compilation is built (and therefore a building block for a future post), and enabling light-weight code generation in partial trust can be somewhat tricky.</p>
<p>DynamicMethods, as their name implies, are methods created at runtime that are associated with an existing module or type, or a transparent assembly provided by the framework (aka an anonymously hosted DynamicMethod). There are different considerations for each, so we&#8217;ll tackle them one at a time.</p>
<h3>Existing Module or Type</h3>
<p>DynamicMethods can be associated with existing .NET modules and types by using the appropriate constructor overload of DynamicMethod that accepts either a Module or a Type as an owner. Using one of these constructors allows you to create a method that is logically associated with that owner, which means it has access to any non-public members within that same scope. The <a href="http://msdn.microsoft.com/en-us/library/z84bd3st.aspx">MSDN documentation</a> has a great example of how to use this functionality.</p>
<p>Unfortunately, this example fails in medium trust because of one of the many security checks that DynamicMethods do in the case when there is an existing owner:</p>
<ol>
<li>If the DynamicMethod is associated with a Type, then if it is invoked from a Type that does not match the owner, then ReflectionPermission/MemberAccess is demanded. </li>
<li>If the DynamicMethod is associated with a Module, then if it invoked from an Assembly that does not match the owner Module&#8217;s Assembly, then ReflectionPermission/MemberAccess is demanded. </li>
<li>If the skipVisibility constructor parameter is set to true, then ReflectionPermission/MemberAccess is demanded. </li>
</ol>
<p>These restrictions make associating DynamicMethods with existing modules or types almost impossible in partial trust. But if you find that you still want to do this, you should find out about additional restrictions from Shawn&#8217;s <a href="http://blogs.msdn.com/b/shawnfa/archive/2006/10/05/using-lightweight-codegen-from-partial-trust.aspx">blog on the topic</a>. (For example, what stops me from associating methods with modules and types from .NET Framework assemblies?</p>
<h3>Anonymously Hosted</h3>
<p>The solution to the problems above is to place your DynamicMethods in an anonymously hosted security-transparent assembly provided by the .NET Framework. Doing this simply requires you not to specify an owner Module or Type in the constructor for the DynamicMethod.</p>
<p>This narrows down your constructor choice from eight to two; the only difference between them is a very interesting parameter called restrictedSkipVisibility.</p>
<p>When this parameter is set to false, the JIT compiler treats the DynamicMethod like any other method in your code; that is, it can access all public members in other assemblies. If the parameter is true, that means the DynamicMethod can access non-public members in other assemblies without using reflection. This feature is subject to the restriction that the accessed assemblies must have a trust level that is equal to or less than the trust level of the call stack that <strong><em>emits </em></strong>the dynamic method. This check is done only at JIT compilation time and not during subsequent invocations of the method.</p>
<p>If you&#8217;re familiar with ReflectionPermission/RestrictedMemberAccess this pattern of demand probably sounds familiar to you. In fact, the mechanism is largely the same with the interesting difference that the demand for the appropriate permission is done against the call stack that was present when the DynamicMethod was created. Let&#8217;s look at a couple of examples.</p>
<p>First, let&#8217;s look at the power of restrictedSkipVisibility. Below, I have declared an interface, ICalculator, with an internal implementation named PrivateCalculator.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:f0d8f5ee-b7b9-43ec-9ba0-e11eaaf5d06b" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
public interface ICalculator
{
    int Add(int left, int right);
}

internal class PrivateCalculator : ICalculator
{
    public int Add(int left, int right)
    {
        Console.WriteLine(&quot;Inside PrivateCalculator.Add.&quot;);
        return left + right;
    }
}
[/sourcecode]
</pre>
</div>
<p>So far, so good. Now let&#8217;s create a dynamic method that manufactures ICalculator instances.</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:83047e8f-d6fc-4e25-8e3a-4fd0ee67b4ed" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
public class Program : MarshalByRefObject
{
    static void Main(string[] args)
    {
        var ps = new PermissionSet(PermissionState.None);
        ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.Infrastructure));
        ps.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

        AppDomain d = AppDomain.CreateDomain(&quot;Sandbox&quot;, null, new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory }, ps);

        var x = (Program)d.CreateInstanceAndUnwrap(typeof(Program).Assembly.FullName, typeof(Program).FullName);
        x.PartialTrustMain();
    }

    public void PartialTrustMain()
    {
        var dm = new DynamicMethod(&quot;CreatePrivateCalculator&quot;, typeof(ICalculator), Type.EmptyTypes, restrictedSkipVisibility: true);
        var ilGenerator = dm.GetILGenerator();

        ilGenerator.Emit(OpCodes.Newobj, typeof(PrivateCalculator).GetConstructor(Type.EmptyTypes));
        ilGenerator.Emit(OpCodes.Ret);

        var createCalculator = (Func&lt;ICalculator&gt;)dm.CreateDelegate(typeof(Func&lt;ICalculator&gt;));
        Console.WriteLine(createCalculator().Add(5, 7));
    }
}

[/sourcecode]
</pre>
</div>
<p>I include Main for completeness, but the real code of interest is inside PartialTrustMain, where I create an anonymously hosted DynamicMethod with restrictedSkipVisibility set to true. The method&#8217;s body simply creates a new instance of PrivateCalculator and returns it. Notice I am simply using the IL necessary to call the C# equivalent of &quot;new PrivateCalculator(),&quot; and this compiles even though the method will not live in the same assembly as the PrivateCalculator class. If I removed the restrictedSkipVisibility parameter or set it to false, I would receive the following exception:</p>
<blockquote>
<p>Unhandled Exception: System.MethodAccessException: Attempt by method &#8216;DynamicClass.CreatePrivateCalculator()&#8217; to access method &#8216;CustomDynamicMethodSecurity.PrivateCalculator..ctor()&#8217; failed.<br />
    <br />&#160;&#160; at CreatePrivateCalculator() </p>
<p>&#160;&#160; at System.Func`1.Invoke() </p>
<p>&#160;&#160; at CustomDynamicMethodSecurity.Program.PartialTrustMain() </p>
<p>&#160;&#160; at CustomDynamicMethodSecurity.Program.PartialTrustMain() </p>
<p>&#160;&#160; at CustomDynamicMethodSecurity.Program.Main(String[] args) </p>
</blockquote>
<p>If we wanted to achieve the same thing without this parameter, we&#8217;d have to write the IL to generate calls against Activator.CreateInstance for the PrivateCalculator type, a verbose and error-prone set of lines to write by hand.</p>
<p>For the second example, let&#8217;s change the stakes a little bit. Let&#8217;s move ICalculator and PrivateCalculator to a separate assembly that is now fully trusted in the partial trust AppDomain. If we still try to create a PrivateCalculator using the DynamicMethod above, then we&#8217;ll encounter the same MethodAccessException that I pointed out earlier. Because PrivateCalculator is now in a fully trusted assembly, it requires full trust in order to create instances of PrivateCalculator from an anonymously hosted DynamicMethod. What else could we do?</p>
<p>Well it turns out we can move the creation of the DynamicMethod to a fully trusted assembly and then pass the delegate returned from DynamicMethod.CreateDelegate back to the console application to invoke. Let&#8217;s take a break here and look at the changes made to the code.</p>
<p>This is the console application:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:431dfdd3-3fb0-4124-b1a3-3b7ebf198595" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
public class Program : MarshalByRefObject
{
    static void Main(string[] args)
    {
        var ps = new PermissionSet(PermissionState.None);
        ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.Infrastructure));
        ps.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

        AppDomain d = AppDomain.CreateDomain(
            &quot;Sandbox&quot;,
            null,
            new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory },
            ps,
            typeof(CalculatorUtils).Assembly.Evidence.GetHostEvidence&lt;StrongName&gt;());

        var x = (Program)d.CreateInstanceAndUnwrap(typeof(Program).Assembly.FullName, typeof(Program).FullName);
        x.PartialTrustMain();
    }

    public void PartialTrustMain()
    {
        var createCalculator = CalculatorUtils.CreatePrivateCalculatorFactory();
        Console.WriteLine(createCalculator().Add(5, 7));
    }
}

[/sourcecode]
</pre>
</div>
<p>And this is the fully trusted assembly:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:c35523f1-4410-4ba1-b33d-5a9904816a1c" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
public static class CalculatorUtils
{
    public static Func&lt;ICalculator&gt; CreatePrivateCalculatorFactory()
    {
        var dm = new DynamicMethod(&quot;CreatePrivateCalculator&quot;, typeof(ICalculator), Type.EmptyTypes, restrictedSkipVisibility: true);
        var ilGenerator = dm.GetILGenerator();

        ilGenerator.Emit(OpCodes.Newobj, typeof(PrivateCalculator).GetConstructor(Type.EmptyTypes));
        ilGenerator.Emit(OpCodes.Ret);

        return (Func&lt;ICalculator&gt;)dm.CreateDelegate(typeof(Func&lt;ICalculator&gt;));
    }
}

public interface ICalculator
{
    int Add(int left, int right);
}

internal class PrivateCalculator : ICalculator
{
    public int Add(int left, int right)
    {
        Console.WriteLine(&quot;Inside PrivateCalculator.Add.&quot;);
        return left + right;
    }
}

[/sourcecode]
</pre>
</div>
<p>But even with this code we have a problem. The call stack present when the DynamicMethod was created has some partially trusted code in it from the console application. So the last thing we need to do is apply an assert to CalculatorUtils.CreatePrivateCalculatorFactory that stops the stack walk from going into that partially trusted code. The final outcome:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:111a4d2b-7fc5-4bb5-94ed-d84257fe9cd5" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp" padlinenumbers="true"]
public static class CalculatorUtils
{
    [SecuritySafeCritical]
    [ReflectionPermission(SecurityAction.Assert, MemberAccess = true)]
    public static Func&lt;ICalculator&gt; CreatePrivateCalculatorFactory()
    {
        var dm = new DynamicMethod(&quot;CreatePrivateCalculator&quot;, typeof(ICalculator), Type.EmptyTypes, restrictedSkipVisibility: true);
        var ilGenerator = dm.GetILGenerator();

        ilGenerator.Emit(OpCodes.Newobj, typeof(PrivateCalculator).GetConstructor(Type.EmptyTypes));
        ilGenerator.Emit(OpCodes.Ret);

        return (Func&lt;ICalculator&gt;)dm.CreateDelegate(typeof(Func&lt;ICalculator&gt;));
    }
}

[/sourcecode]
</pre>
</div>
</p>
</p>
<p>Now I should hope that it goes without saying but it&#8217;s very dangerous to pass around delegates created under an assert like this among class library boundaries. Treat them as radioactive if you must do this, and be sure to review your code for any possible exploitations where code might be able to invoke one of these delegates even though they should not be able to.</p>
<p>Next time, we&#8217;ll talk about expression compilation!</p>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2010/11/21/tip-22-dynamicmethods-in-partial-trust/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Persisting Collections of Scalar Properties in the Entity Framework</title>
		<link>http://davedewinter.com/2010/08/24/persisting-collections-of-scalar-properties-in-the-entity-framework/</link>
		<comments>http://davedewinter.com/2010/08/24/persisting-collections-of-scalar-properties-in-the-entity-framework/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 14:35:59 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Collections]]></category>
		<category><![CDATA[Navigation Properties]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[Scalars]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/?p=318</guid>
		<description><![CDATA[Our team has done a lot of work over the past few years to bring the Entity Framework up as an enterprise-ready ORM, but there is a still a lot of work for us to do going forward, particularly in &#8230; <a href="http://davedewinter.com/2010/08/24/persisting-collections-of-scalar-properties-in-the-entity-framework/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Our team has done a lot of work over the past few years to bring the Entity Framework up as an enterprise-ready ORM, but there is a still a lot of work for us to do going forward, particularly in the area of object flexibility. Even though with POCO entities we allow some customization when it comes to collection types, there are many more scenarios that we don&#8217;t support out of the box, at least without some workarounds.</p>
<p>One of these scenarios is to use a collection of scalar values (like ints or strings) to represent a relationship, instead of a collection of very simple entity types, each of which has that scalar property. The reason you&#8217;d want to do this is because you want to persist the scalar values to the database, but there isn&#8217;t any additional information associated with those values to justify a full-fledged entity type. The Entity Framework doesn&#8217;t support this today, but in this post I&#8217;ll take you through how you can simulate this with your entities.</p>
<p><a href="#attachments">Show me the code, already!</a></p>
<p>In this post I&#8217;m using the Database First approach to using EF, but I&#8217;m sure you can also achieve this same thing in <a href="http://blogs.msdn.com/b/efdesign/archive/2008/09/10/model-first.aspx">Model First</a> and <a href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx">Code First</a>.</p>
<h3>The Model</h3>
<p>The domain for this post focuses on albums and songs, and in this simplified model, we are only interested in the name of the song for a particular album.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/08/image2.png" width="273" height="326" /> </p>
<p>The conceptual model in EF does not look much different; the only difference from the default generation is that there is no navigation property from Song to Album—that is, there is no Album property on Song.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/08/image3.png" width="584" height="293" /> </p>
<p>Everything seems straightforward so far. We&#8217;ve decided, though, that since the only property of interest on the Song class is the SongTitle, that the Album class should have a collection of song titles instead of a collection of Songs. I&#8217;ll show how this works in the next step.</p>
<h3>The Model (Code)</h3>
<p>Now unfortunately because we are hacking around the way the Entity Framework works, we have to make some compromises when it comes to the API we expose on the Album class. Ideally, I would like to write something like this: </p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:9e021821-202e-46c9-9274-9a1014bdbf4b" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
public class Album
{
    public Album()
    {
        this.SongTitles = new HashSet&lt;string&gt;();
    }

    public int Id { get; set; }
    public string AlbumName { get; set; }

    public ICollection&lt;string&gt; SongTitles { get; private set; }
}
[/sourcecode]
</pre>
</div>
<p>Now for this to work with EF I have a couple of requirements:</p>
<ol>
<li>When I query for Albums, the SongTitles must be populated with titles from the related Song entities. </li>
<li>When I add or remove SongTitles from an Album that is attached to the ObjectContext, this must be processed as an Add or Delete during the call to SaveChanges. </li>
<li>Creating a new Album, populating the list of SongTitles, and then calling AddObject must also ensure that its SongTitles are added to the database when SaveChanges is called. </li>
</ol>
<p>Let&#8217;s take this one step at a time.</p>
<h3>Query</h3>
<p>When you issue a query to the database, the tuples of data that come back are converted into objects. This process is called <strong>materialization</strong>. EF4 allows us to use the ObjectMaterialized event to discover when objects are materialized, and we can use this to load the song titles for an album when any Album instance is materialized. Before we get started, though, we need a Song class to query for and a derived ObjectContext class.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:cb709a3c-f5a7-4824-bc2c-d7ae52b08018" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
public class Song
{
    public int AlbumId { get; set; }
    public string SongTitle { get; set; }
}

[/sourcecode]
</pre>
</div>
</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3b64c5b1-f4e7-4eb9-b65d-67e07bc912c7" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
public class ScalarCollectionsContext : ObjectContext
{
    public ScalarCollectionsContext() :
        base(&quot;name=EFScalarCollectionEntities&quot;)
    {
    }

    public ObjectSet&lt;Album&gt; Albums
    {
        get { return this.CreateObjectSet&lt;Album&gt;(); }
    }

    public ObjectSet&lt;Song&gt; Songs
    {
        get { return this.CreateObjectSet&lt;Song&gt;(); }
    }
}

[/sourcecode]
</pre>
</div>
<p>Since the ObjectMaterialized event is exposed on the ObjectContext, we can subscribe to that event from within the ScalarCollectionsContext constructor. The implementation is fairly straightforward—once an Album is materialized, query for the Songs that are associated with that Album and add all of the song titles in the results to the Album&#8217;s SongTitles collection.</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:53a046bb-38d2-492f-a1ff-6b68d41acee1" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
private void OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
{
    var album = e.Entity as Album;
    if (album != null)
    {
        foreach (var songTitle in this.Songs.Where(s =&gt; s.AlbumId == album.Id).Select(s =&gt; s.SongTitle))
        {
            album.SongTitles.Add(songTitle);
        }
    }
}

[/sourcecode]
</pre>
</div>
<p>One step done.</p>
<h3>Adding/Removing SongTitles Processed during SaveChanges</h3>
<p>The second step is to make sure that any time we add, remove, or change an item in the SongTitles collection, the corresponding add or delete occurs in the data store. Now you could do this by taking a snapshot of the collection when you query for it and then diffing it with the collection when you save changes, but to make things a little simpler we will instead leverage an <strong>ObservableCollection&lt;string&gt; </strong>for the SongTitles collection.</p>
<p>Each Album instance can then subscribe to the <strong>CollectionChanged</strong> event of that collection and register the changes as adds or removes against a private navigation property for Songs. We use the navigation property to make it easier to bridge the gap between our objects and the change tracking capabilities built into the Entity Framework. If that&#8217;s unclear, I&#8217;ve included the new version of the class below. Note that the SongTitles collection is now an ObservableCollection whose changes update the private Songs collection.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:524206dd-cdd6-4852-a391-09a52703b3ed" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp" padlinenumbers="true"]
public class Album
{
    public Album()
    {
        this.Songs = new HashSet&lt;Song&gt;();
        this.SongTitles = new ObservableCollection&lt;string&gt;();
        this.SongTitles.CollectionChanged += OnSongTitlesChanged;
    }

    public int Id { get; set; }
    public string AlbumName { get; set; }

    public ObservableCollection&lt;string&gt; SongTitles { get; private set; }
    private ICollection&lt;Song&gt; Songs { get; set; }

    private void OnSongTitlesChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach (string title in e.NewItems)
            {
                this.Songs.Add(new Song() { AlbumId = this.Id, SongTitle = title });
            }
        }

        if (e.OldItems != null)
        {
            foreach (string title in e.OldItems)
            {
                var song = this.Songs.SingleOrDefault(s =&gt; s.SongTitle == title);
                this.Songs.Remove(song);
            }
        }

        if (e.Action == NotifyCollectionChangedAction.Reset)
        {
            this.Songs.Clear();
        }
    }
}

[/sourcecode]
</pre>
</div>
<p>It would seem that we are done. When we query for Albums, their related SongTitles are populated, which also populates the Songs collection since it is an observable collection. Any changes to the SongTitles collection will update the corresponding Songs collection, and the Entity Framework will use that for assessing what changes to the database need to be made. Finally, because we subscribe to the CollectionChanged event from within the Album&#8217;s constructor, if we create an Album outside of the context and then add/attach it, its corresponding children will be added or attached as well.</p>
<p>But, there are a couple of problems:</p>
<ol>
<li>Marking the Songs collection private will not work in medium trust. </li>
<li>When the SongTitles are populated after querying for Albums, <em>completely new</em> Songs are added to the Songs collection, instead of the existing Songs that were materialized as part of the LINQ query. This means when SaveChanges is called, the Entity Framework thinks that it needs to INSERT all the existing songs as new songs, causing a primary key violation in Songs table. </li>
</ol>
<p>While the first problem is not something we can fix outside of the framework today, the second one is, and it requires a few changes to the code we have for the <strong>ObjectMaterialized</strong> event.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:be49861d-46ee-4448-b5ef-9e10bb190f59" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
private void OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
{
    var album = e.Entity as Album;
    if (album != null)
    {
        EntityCollection&lt;Song&gt; songs = (EntityCollection&lt;Song&gt;)this.ObjectStateManager
            .GetRelationshipManager(album)
            .GetRelatedEnd(&quot;EFScalarCollectionModel.FK_Song_Album&quot;, &quot;Song&quot;);
        foreach (var song in songs.CreateSourceQuery())
        {
            album.SongTitles.Add(song.SongTitle);
        }
    }
}

[/sourcecode]
</pre>
</div>
<p>Welcome to the nasty side of the Entity Framework, where magic strings abound. <img src='http://davedewinter.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  This code does a couple of very useful things to help us achieve our goal, so let&#8217;s break it down step-by-step:</p>
<p>First we retrieve the EF-centric view of the collection of Songs for the Album that was just materialized. This is an EntityCollection&lt;Song&gt;, a class you may recognize if you have used the Entity Framework with the default code generation in the past. The first magic string passed to GetRelatedEnd method is the namespace-qualified Association name of the relationship between Song and Album; the second is the name of the Role that signifies which &quot;end&quot; of the relationship you want to retrieve. You can find this in the CSDL section of your EDMX file:</p>
</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:78a3424f-bd7a-402e-9114-d74f04c04ee7" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="xml"]
&lt;AssociationSet Name=&quot;FK_Song_Album&quot; Association=&quot;EFScalarCollectionModel.FK_Song_Album&quot;&gt;
  &lt;End Role=&quot;Album&quot; EntitySet=&quot;Albums&quot; /&gt;
  &lt;End Role=&quot;Song&quot; EntitySet=&quot;Songs&quot; /&gt;
&lt;/AssociationSet&gt;

[/sourcecode]
</pre>
</div>
<p>Next we iterate over all the Songs in the collection after calling CreateSourceQuery; this allows us to both to load the Songs collection in the Album instance and to populate the SongTitles collection in the same Album instance.</p>
<p>One last problem—we now have duplicate Songs in the collection because SongTitles.Add triggers the CollectionChanged event. But we can fix this simply by ensuring that we don&#8217;t add duplicates in the OnCollectionChanged handler. Note the addition of the Where filter on the NewItems collection.</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:0ab4f4f3-3ed0-4d80-ac10-ac4bde266a71" class="wlWriterEditableSmartContent">
<pre>
[sourcecode language="csharp"]
if (e.NewItems != null)
{
    foreach (string title in e.NewItems.Cast&lt;string&gt;().Where(t =&gt; !this.Songs.Any(s =&gt; s.SongTitle == t)))
    {
        this.Songs.Add(new Song() { AlbumId = this.Id, SongTitle = title });
    }
}

[/sourcecode]
</pre>
</div>
<p>And that&#8217;s it. This is one way to keep collection of scalars in your POCO entities but project something entirely different to the Entity Framework. Theoretically, this would also work with collections of complex types, although I have not tried it.</p>
<h3>Results</h3>
<p>If you&#8217;re really concerned about a clear separation of concerns, this probably isn&#8217;t the greatest solution for you, since there are a lot of concerns that bleed from the Album entity because of the Entity Framework. Granted, the extra properties and methods are all private, but it&#8217;s still code you need to wade through every time you make changes to that part of the model.</p>
<p>Now, I have not tried this due to a lack of time, but there <em>might </em>be a way to remove the Songs navigation property entirely if you don&#8217;t care about the Song entities being in the state manager at all. If I wanted to do this, I would keep the following things in mind.</p>
<ul>
<li>As a consumer of the Album class, all I care about are the SongTitles, so I can make any changes I want to them, including adds, removes, and changes. </li>
<li>When I call SaveChanges on the ObjectContext, I would need a way to replay changes made to the SongTitles collection against the ObjectContext in terms it understands i.e. the Song entities. </li>
<li>This means that it would be useful to have a collection that had an initial state and a log of all the changes made to it. </li>
<li>The initial state is different for Albums created by users versus those created by the Entity Framework due to queries. </li>
</ul>
<p>There are also some limitations with this approach; for example, Song cannot have any other scalar properties or associations.</p>
<p>I have attached a solution with the final code in both C# and Visual Basic, along with a small number of acceptance tests that verify the requirements I laid out at the beginning of the post. If you decide to implement the alternative where there is no navigation property from Albums to Songs, then you can use these acceptance tests to help you get started.</p>
<p>If there are any other types of &quot;hacks&quot; you&#8217;d like to see with the Entity Framework let me know in a comment!</p>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2010/08/24/persisting-collections-of-scalar-properties-in-the-entity-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Viewing Generated Proxy Code in the Entity Framework</title>
		<link>http://davedewinter.com/2010/04/08/viewing-generated-proxy-code-in-the-entity-framework/</link>
		<comments>http://davedewinter.com/2010/04/08/viewing-generated-proxy-code-in-the-entity-framework/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 17:16:35 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[proxies]]></category>
		<category><![CDATA[Reflection.Emit]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/?p=304</guid>
		<description><![CDATA[This is one post that&#8217;s been on my to-do list for a while, and since I&#8217;ve seen some questions relating to it in our forums, I thought it appropriate to get it out the door before .NET 4 officially releases. &#8230; <a href="http://davedewinter.com/2010/04/08/viewing-generated-proxy-code-in-the-entity-framework/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This is one post that&#8217;s been on my to-do list for a while, and since I&#8217;ve seen some <a href="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/75a07036-6450-4128-8ad0-c30c9390c5b4">questions</a> relating to it in our forums, I thought it appropriate to get it out the door before .NET 4 officially releases.</p>
<p>As you may know, the Entity Framework supports mapping database information to POCO (Plain Old CLR Objects) classes in .NET 4. Normally, giving you control over your classes would mean we lose out on a few benefits on controlling the classes ourselves, such as lazy loading and change tracking capabilities. However, if your classes meet a few <a href="http://msdn.microsoft.com/en-us/library/dd468057%28VS.100%29.aspx">requirements</a>, then we can dynamically create an assembly at runtime which contains classes that inherit from your POCO types. Today these classes add additional behavior such as lazy loading and change tracking, but in future releases we could potentially augment them to add more features. Typically we refer to these dynamic classes as POCO proxies.</p>
<p>The Entity Framework uses the features in the <a href="http://msdn.microsoft.com/en-us/library/3y322t50.aspx">Reflection.Emit</a> namespace to generate these classes. If you check out Reflector, you can see that the System.Data.Objects.Internal.EntityProxyFactory.GetDynamicModule starts this process by calling <a href="http://msdn.microsoft.com/en-us/library/bs22fky4.aspx">AppDomain.CurrentDomain.DefineDynamicAssembly</a> with the AssemblyBuilderAccess specified in the s_ProxyAssemblyBuilderAccess field. During normal execution, s_ProxyAssemblyBuilderAccess is AssemblyBuilderAccess.Run and will never change, but we added this field as a test hook for other purposes. As a result, you can also save the assembly to disk by setting the s_ProxyAssemblyBuilderAccess field to AssemblyBuilderAccess.RunAndSave with reflection.</p>
<p>You can&#8217;t just save the assembly right away, since we lazily emit new types into the dynamic assembly as they&#8217;re requested. You&#8217;ll need to force the Entity Framework to create proxy types by calling <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.createproxytypes(VS.100).aspx">ObjectContext.CreateProxyTypes</a> with a list of all POCO types for which you want proxies generated. Then you can save the assembly to disk by calling AssemblyBuilder.Save on the dynamic assembly. If that sounds complicated, don&#8217;t worry. We&#8217;ll walk through some code to make these steps more concrete. Please note that you&#8217;ll need to run in full trust or at least have ReflectionPermission with ReflectionPermissionFlag.MemberAccess to run the code below.</p>
<p>I&#8217;ve attached a solution to this post that shows the code in more detail, but let&#8217;s walk through the major parts. To set up, I&#8217;ve created an Entity Data Model based on the Northwind database, and I&#8217;ve used our <a href="http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx">POCO templates</a> to create classes that the Entity Framework will create proxy types for. The first step is to set the s_ProxyAssemblyBuilderAccess field via reflection.</p>
<ul>
<p><strong>C#</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: #2b91af">Type</span> entityProxyFactoryType = <span style="color: #2b91af">Type</span>.GetType(</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #a31515">&quot;System.Data.Objects.Internal.EntityProxyFactory, &quot;</span> + <span style="color: blue">typeof</span>(<span style="color: #2b91af">ObjectContext</span>).Assembly.FullName);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">const</span> <span style="color: #2b91af">BindingFlags</span> bindingFlags = <span style="color: #2b91af">BindingFlags</span>.NonPublic | <span style="color: #2b91af">BindingFlags</span>.Static;</p>
<p style="margin: 0px">entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ProxyAssemblyBuilderAccess&quot;</span>, bindingFlags)</p>
<p style="margin: 0px">&#160;&#160;&#160; .SetValue(<span style="color: blue">null</span>, <span style="color: #2b91af">AssemblyBuilderAccess</span>.RunAndSave);</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Dim</span> entityProxyFactoryType <span style="color: blue">As</span> <span style="color: #2b91af">Type</span> = <span style="color: #2b91af">Type</span>.GetType(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #a31515">&quot;System.Data.Objects.Internal.EntityProxyFactory, &quot;</span> + <span style="color: blue">GetType</span>(<span style="color: #2b91af">ObjectContext</span>).Assembly.FullName)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">Const</span> bindingFlags <span style="color: blue">As</span> <span style="color: #2b91af">BindingFlags</span> = BindingFlags.NonPublic <span style="color: blue">Or</span> BindingFlags.Static</p>
<p style="margin: 0px">entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ProxyAssemblyBuilderAccess&quot;</span>, bindingFlags) _</p>
<p style="margin: 0px">&#160;&#160;&#160; .SetValue(<span style="color: blue">Nothing</span>, <span style="color: #2b91af">AssemblyBuilderAccess</span>.RunAndSave)</p>
</p></div>
</ul>
<p>Next, we need to force the creation of proxy types. Here we&#8217;re using a variable context that represents an ObjectContext we&#8217;re interested in generating proxies for. (Its instantiation is not shown.) Fortunately, the CreateProxyTypes method ignores any types that are not represented by the model, so we can call the method passing all types in the current assembly.</p>
<ul>
<p><strong>C#</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">context.CreateProxyTypes(<span style="color: #2b91af">Assembly</span>.GetExecutingAssembly().GetTypes());</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">context.CreateProxyTypes(<span style="color: #2b91af">Assembly</span>.GetExecutingAssembly().GetTypes())</p>
</p></div>
</ul>
<p>Finally, we need to access the AssemblyBuilder using a bit of reflection and call its Save method.</p>
<ul>
<p><strong>C#</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">var</span> moduleBuilders = (<span style="color: #2b91af">IDictionary</span>&lt;<span style="color: #2b91af">Assembly</span>, <span style="color: #2b91af">ModuleBuilder</span>&gt;)</p>
<p style="margin: 0px">&#160;&#160;&#160; entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ModuleBuilders&quot;</span>, bindingFlags).GetValue(<span style="color: blue">null</span>);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">var</span> pocoProxyModule = moduleBuilders[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NorthwindEntities</span>).Assembly];</p>
<p style="margin: 0px"><span style="color: blue">var</span> pocoProxyAssembly = (<span style="color: #2b91af">AssemblyBuilder</span>)pocoProxyModule.Assembly;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">pocoProxyAssembly.Save(<span style="color: #a31515">&quot;EntityProxyModule.dll&quot;</span>);</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Dim</span> moduleBuilders = <span style="color: blue">DirectCast</span>(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ModuleBuilders&quot;</span>, bindingFlags).GetValue(<span style="color: blue">Nothing</span>),&#160; _</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">IDictionary</span>(<span style="color: blue">Of</span> <span style="color: #2b91af">Assembly</span>, <span style="color: #2b91af">ModuleBuilder</span>))</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">Dim</span> pocoProxyModule = moduleBuilders(<span style="color: blue">GetType</span>(<span style="color: #2b91af">NorthwindEntities</span>).Assembly)</p>
<p style="margin: 0px"><span style="color: blue">Dim</span> pocoProxyAssembly = <span style="color: blue">DirectCast</span>(pocoProxyModule.Assembly, <span style="color: #2b91af">AssemblyBuilder</span>)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">pocoProxyAssembly.Save(<span style="color: #a31515">&quot;EntityProxyModule.dll&quot;</span>)</p>
</p></div>
</ul>
<p>After the preceding code runs, you&#8217;ll be left with a file named EntityProxyModule.dll in the current directory, which you can easily pop into Reflector to view the code for the proxies. As you can see the names of the generated types are quite long. <img src='http://davedewinter.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Since proxies today are tied to the metadata of the ObjectContext by which they were created, we use a hash of the metadata in the proxy&#8217;s type name to correlate the proxy type with that ObjectContext. If we need to use the same CLR type for an ObjectContext with different metadata, we will create a new proxy type.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Proxy assembly in Reflector" border="0" alt="Proxy assembly in Reflector" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/04/image.png" width="644" height="445" /> </p>
<p>I&#8217;m not going to dive deep into the proxy code, since it resembles code from the default code generation in some ways (e.g. change tracking, relationship management). There is one interesting piece that I&#8217;ll point out and that is how we override navigation properties.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/04/image1.png" width="644" height="395" /> </p>
<p>Our overrides are very simple—usually we delegate to the base implementation, but if lazy loading is enabled we will call into a delegate (ef_proxy_interceptor…), which is where we will load the navigation property into memory if it&#8217;s not there already. Of course, in the proxy code there is nothing specific to lazy loading; we just call a delegate that could do any number of things in future.</p>
<p>I encourage you to download the solution and play around with the code. Let me know here or on our <a href="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/threads">forums</a> if you have any additional questions!</p>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2010/04/08/viewing-generated-proxy-code-in-the-entity-framework/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Tip #20 – Opting Out of Security Changes in .NET 4 in ASP.NET and Custom AppDomains</title>
		<link>http://davedewinter.com/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/</link>
		<comments>http://davedewinter.com/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 15:53:01 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[CAS Policy]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/</guid>
		<description><![CDATA[Legacy CAS Policy in ASP.NET In a previous tip I discussed how you could re-enable CAS policy in applications running in .NET 4 by adding a switch to the application configuration file. However, Constantin Baciu brought up that even when &#8230; <a href="http://davedewinter.com/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3>Legacy CAS Policy in ASP.NET</h3>
<p><a href="http://blogs.rev-net.com/ddewinter/2009/05/20/opting-out-of-security-changes-in-net-4/">In a previous tip</a> I discussed how you could re-enable CAS policy in applications running in .NET 4 by adding a switch to the application configuration file. However, <a href="http://blogs.rev-net.com/ddewinter/2009/05/20/opting-out-of-security-changes-in-net-4/#comment-17758">Constantin Baciu</a> brought up that even when using this configuration switch in a web.config, ASP.NET still threw the SecurityException:</p>
<blockquote><p>This method explicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see <a href="http://go.microsoft.com/fwlink/?LinkID=155570">http://go.microsoft.com/fwlink/?LinkID=155570</a> for more information.</p>
</blockquote>
<p>Definitely a confusing error message, since you already added the NetFx40_LegacySecurityPolicy configuration switch. The problem is that in order for this switch to actually work, it must be in the executable&#8217;s application configuration file. Putting in the web.config has no effect; the switch must be in the configuration file for the server executable, like IIS or Visual Studio&#8217;s local web server. Since just about all web hosts I know of won&#8217;t let you modify the configuration file for the server, we need a different option.</p>
<p>Fortunately, ASP.NET does support enabling CAS policy in .NET 4, but it&#8217;s with a different switch in the web.config. Enter the new <a href="http://msdn.microsoft.com/en-us/library/dd984947%28VS.100%29.aspx">legacyCasModel attribute</a> of the <a href="http://msdn.microsoft.com/en-us/library/dd984947%28VS.100%29.aspx">trust element</a>. This is the same element that allows you to configure the trust level of the application.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">trust</span><span style="color: blue"> </span><span style="color: red">legacyCasModel</span><span style="color: blue">=</span>&quot;<span style="color: blue">true</span>&quot;<span style="color: blue">/&gt;</span></p>
</p></div>
<p>This enables you to get past the SecurityException above, but keep the following things in mind:</p>
<ul>
<li>You will be using the legacy security configurations from .NET 3.5 when using ASP.NET. These permission sets are kept in the runtime directory&#8217;s Config folder and have names like legacy.web_mediumtrust.config and legacy.web_minimaltrust.config. </li>
<li>Security asserts are no longer required when only full trust code is on the call stack. This is because ASP.NET will still set up a fully trusted AppDomain, because it relies on CAS Policy to apply specific permissions to assemblies. In .NET 4 ASP.NET sets up a <a href="http://blogs.rev-net.com/ddewinter/2009/05/22/how-to-host-a-partial-trust-sandbox/">sandbox AppDomain</a> by default, which means that even if only fully trusted code is on the call stack, as soon as a permission demand occurs, the stack walk will fail once it hits the AppDomain boundary. </li>
<li>Of course, CAS Policy is now enabled, which means the machine&#8217;s policy configuration affects what permissions an assembly has.</li>
</ul>
<h3>Legacy CAS Policy at the AppDomain Level</h3>
<p>When you specify the legacyCasModel attribute in the web.config, ASP.NET uses that information to set up an AppDomain that has legacy CAS policy enabled. The good news is that by using some lower-level APIs, you can do the same thing.</p>
<p>You may ask &quot;why would you want to do this?&quot; One scenario I can think of is for an existing application that uses AppDomains to isolate other pieces of code (e.g. for add-ins), but some of these old pieces of code use the older security APIs that are obsolete in .NET 4.</p>
<p>The key API is <a href="http://msdn.microsoft.com/en-us/library/system.appdomainsetup.setcompatibilityswitches%28VS.100%29.aspx">AppDomainSetup.SetCompatibilitySwitches</a>; remember that when setting up an AppDomain you can optionally use an instance of the AppDomainSetup class to initialize the AppDomain. The code example below shows how this is done.</p>
<h4>C#</h4>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">var</span> setup = <span style="color: blue">new</span> <span style="color: #2b91af">AppDomainSetup</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; ApplicationBase = <span style="color: #2b91af">Environment</span>.CurrentDirectory</p>
<p style="margin: 0px">};</p>
<p style="margin: 0px">setup.SetCompatibilitySwitches(<span style="color: blue">new</span>[] { <span style="color: #a31515">&quot;NetFx40_LegacySecurityPolicy&quot;</span> });</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: #2b91af">AppDomain</span> casPolicyEnabledDomain = <span style="color: #2b91af">AppDomain</span>.CreateDomain(<span style="color: #a31515">&quot;CAS Policy Enabled Domain&quot;</span>, <span style="color: blue">null</span>, setup);</p>
</p></div>
<h4>VB</h4>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Dim</span> setup = <span style="color: blue">New</span> <span style="color: #2b91af">AppDomainSetup</span> <span style="color: blue">With</span> {.ApplicationBase = <span style="color: #2b91af">Environment</span>.CurrentDirectory}</p>
<p style="margin: 0px">setup.SetCompatibilitySwitches(<span style="color: blue">New</span> <span style="color: blue">String</span>() {<span style="color: #a31515">&quot;NetFx40_LegacySecurityPolicy&quot;</span>})</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">Dim</span> casPolicyEnabledDomain <span style="color: blue">As</span> <span style="color: #2b91af">AppDomain</span> = <span style="color: #2b91af">AppDomain</span>.CreateDomain(<span style="color: #a31515">&quot;CAS Policy Enabled Domain&quot;</span>, <span style="color: blue">Nothing</span>, setup)</p>
</p></div>
<p>And that&#8217;s all there is to it. <img src='http://davedewinter.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>We&#8217;re Hiring! Test Positions Open on Entity Framework and WCF Data Services (Astoria) Teams</title>
		<link>http://davedewinter.com/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/</link>
		<comments>http://davedewinter.com/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 16:33:14 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/</guid>
		<description><![CDATA[With work on Visual Studio 2010 winding down, both the Entity Framework and Astoria teams have test engineer positions open. Here are the job postings: Astoria Entity Framework Note: If the job descriptions above still say you need C/C++ experience, &#8230; <a href="http://davedewinter.com/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>With work on Visual Studio 2010 winding down, both the Entity Framework and Astoria teams have test engineer positions open. Here are the job postings:</p>
<ul>
<li><a href="https://careers.microsoft.com/JobDetails.aspx?ss=&amp;pg=0&amp;so=&amp;rw=1&amp;jid=11878&amp;jlang=EN">Astoria</a> </li>
<li><a href="https://careers.microsoft.com/JobDetails.aspx?ss=&amp;pg=0&amp;so=&amp;rw=1&amp;jid=11877&amp;jlang=EN">Entity Framework</a> </li>
</ul>
<p><strong><em>Note: If the job descriptions above still say you need C/C++ experience, this is not true. If you don&#8217;t have experience in these areas, don&#8217;t let that discourage you from applying! </em></strong>In fact, I didn&#8217;t have C/C++ experience upon arriving here…</p>
<p>Now, I know what you&#8217;re thinking—&quot;ugh, test, you mean those guys who sit on the other side of the building and click on things all day?&quot; And actually, when I first joined as a tester, I had a bit of the same mentality. That&#8217;s why I wanted to find out for myself what testers actually do. I have worked at Microsoft for a year now as a tester on the Entity Framework team and have learned a lot about the discipline of test, but I know I have only scratched the surface. Also, I should clarify that these positions are opening on the <em>runtime</em> team, so you won&#8217;t be clicking on things that much, if at all. <img src='http://davedewinter.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>My background as a .NET developer has really helped me excel as a test engineer. The challenges that we face are very diverse and as a result I think there are many more opportunities for growth in the test discipline than in other disciplines. In a sense, we are developers ourselves; we don&#8217;t ship code (typically), but we must have the ingenuity and creativity to verify the code that does ship meets a high quality bar. Test can be a very demanding discipline, especially for those people who have a background in development.</p>
<p>If you want to know more about my experiences feel free to contact me using the contact form page, and I hope you consider applying if you&#8217;re looking for a challenging job.</p>
<p>P.S. I should note that the Astoria job description is missing an important sales pitch—you get to work with Pablo Castro! Yes, <a href="http://blogs.msdn.com/pablo/">that Pablo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>POCO Templates for Entity Framework v4 Beta 2 Released</title>
		<link>http://davedewinter.com/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/</link>
		<comments>http://davedewinter.com/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 20:02:31 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[POCO]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/</guid>
		<description><![CDATA[Today we have finally released an update to the POCO Templates that is compatible with Visual Studio 2010 Beta 2. Official announcement on the ADO.NET team blog. One thing I will highlight is that the templates won&#8217;t be released with &#8230; <a href="http://davedewinter.com/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Today we have finally released an update to the POCO Templates that is compatible with Visual Studio 2010 Beta 2. <a href="http://blogs.msdn.com/adonet/archive/2010/01/25/announcing-the-entity-framework-poco-template-update-for-visual-studio-2010-beta-2.aspx">Official announcement on the ADO.NET team blog.</a></p>
<p>One thing I will highlight is that the templates won&#8217;t be released with the final version of Visual Studio 2010. Instead we will continue to push releases through the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/">Visual Studio Extension Gallery</a>. This means you can easily download the POCO Templates using Visual Studio&#8217;s Extension Manager (accessed through the Tools menu).</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="Extension Manager menu item" border="0" alt="Extension Manager menu item" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image_thumb.png" width="613" height="534" /></a> </p>
<p>Once in the Extension Manager, click the Online Gallery tab on the left side of the window and use the search box (top right) to type in &quot;POCO template.&quot; After a few seconds you should see the POCO template extensions appear. There are two extensions, one for C# and one for Visual Basic.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image1.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image_thumb1.png" width="640" height="342" /></a> </p>
<p>After you install the extension, you&#8217;ll have a new item template for C# projects or Visual Basic projects (depending on which you installed) that will allow you to generate POCO entities from an Entity Framework model. For more in depth information on how to use the POCO templates, have a look at the <a href="http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx">POCO Template Walkthrough</a>.</p>
<p>As always we are interested in your feedback so feel free to request features or report bugs through the <a href="https://connect.microsoft.com/VisualStudio/content/content.aspx?ContentID=12362">Microsoft Connect web site</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CAS Policy on 64-bit Machines &#8211; #19</title>
		<link>http://davedewinter.com/2010/01/10/cas-policy-on-64-bit-machines-19/</link>
		<comments>http://davedewinter.com/2010/01/10/cas-policy-on-64-bit-machines-19/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 04:43:04 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[CAS Policy]]></category>
		<category><![CDATA[caspol.exe]]></category>
		<category><![CDATA[permissions]]></category>
		<category><![CDATA[policy]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/10/cas-policy-on-64-bit-machines-19/</guid>
		<description><![CDATA[Well it’s been quite a while since my last post. I hope you all had a happy holiday season! Today I’m going to talk about an issue I saw recently with a 64-bit machine and the partial trust tests for &#8230; <a href="http://davedewinter.com/2010/01/10/cas-policy-on-64-bit-machines-19/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Well it’s been quite a while since my last post. I hope you all had a happy holiday season!</p>
<p>Today I’m going to talk about an issue I saw recently with a 64-bit machine and the partial trust tests for the Entity Framework. Even though .NET 4 <a href="http://blogs.rev-net.com/ddewinter/2009/05/20/whats-new-with-security-in-net-4/">disables CAS policy</a>, it is more interesting for the Entity Framework to test with CAS policy enabled, because this allows us to configure security permissions on a per-assembly basis instead of per-AppDomain. The workflow for the tests is similar to the following:</p>
<ol>
<li>Enable CAS policy. </li>
<li>Use the System.Security.Policy APIs to configure the correct set of permissions for the test assemblies. (Some have ReflectionPermission, some don’t, etc.) This is a separate EXE from the next step. </li>
<li>Initialize the test harness and run the test cases. </li>
</ol>
<p>When running in our lab recently, a few test cases failed for reasons I could not explain. Further analysis revealed that the tests were running in full trust, and so these negative test cases failed because the expected exceptions were not thrown. How did this happen?</p>
<h3>Diagnosis</h3>
<p>The first thing I did was to experiment with the command line switches of caspol.exe. I started a new command prompt and ran the following command. The –rsp switch stands for <strong>r</strong>e<strong>s</strong>olve <strong>p</strong>ermission set. System.Data.Test.PartialTrust.Caller.dll is the name of one of the assemblies that needs a custom permission set.</p>
<p><strong>caspol.exe –rsp System.Data.Test.PartialTrust.Caller.dll</strong></p>
<blockquote><p>Microsoft (R) .NET Framework CasPol 4.0.21006.1      <br />Copyright (c) Microsoft Corporation.&#160; All rights reserved. </p>
<p>WARNING: The .NET Framework does not apply CAS policy by default. Any settings      <br />shown or modified by CasPol will only affect applications that opt into using       <br />CAS policy. </p>
<p>Please see <a href="http://go.microsoft.com/fwlink/?LinkId=131738">http://go.microsoft.com/fwlink/?LinkId=131738</a> for more information. </p>
<p>Resolving permissions for level = Enterprise      <br />Resolving permissions for level = Machine       <br />Resolving permissions for level = User </p>
<p>Grant =      <br /><strong>&lt;PermissionSet class=&quot;System.Security.PermissionSet&quot;        <br />version=&quot;1&quot;         <br />Unrestricted=&quot;true&quot;/&gt;</strong> </p>
<p>Success</p>
</blockquote>
<p>This had at least confirmed my suspicions that the tests were running in full trust. I looked back at the original executable code that configures the policy for the assemblies. It did not seem out of the ordinary, and besides, it had worked in many previous test runs.</p>
<p><strong>C#</strong></p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">static</span> <span style="color: blue">void</span> SetPermissions()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Find the machine policy level</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">PolicyLevel</span> machinePolicyLevel = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">IEnumerator</span> ph = <span style="color: #2b91af">SecurityManager</span>.PolicyHierarchy();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">while</span> (ph.MoveNext())</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">PolicyLevel</span> pl = (<span style="color: #2b91af">PolicyLevel</span>)ph.Current;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (pl.Label == <span style="color: #a31515">&quot;Machine&quot;</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; machinePolicyLevel = pl;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">break</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">NamedPermissionSet</span> ps = <span style="color: blue">new</span> <span style="color: #2b91af">NamedPermissionSet</span>(<span style="color: #a31515">&quot;CallerPermSet&quot;</span>, <span style="color: #2b91af">PermissionState</span>.None);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Add permissions (omitted)</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">StrongNamePublicKeyBlob</span> key = <span style="color: blue">typeof</span>(<span style="color: #2b91af">Caller</span>).Assembly.Evidence</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160; .OfType&lt;<span style="color: #2b91af">StrongName</span>&gt;().First().PublicKey;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">IMembershipCondition</span> mc = <span style="color: blue">new</span> <span style="color: #2b91af">StrongNameMembershipCondition</span>(key, <span style="color: blue">null</span>, <span style="color: blue">null</span>);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Create the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">PolicyStatement</span> policy = <span style="color: blue">new</span> <span style="color: #2b91af">PolicyStatement</span>(ps, <span style="color: #2b91af">PolicyStatementAttribute</span>.Exclusive);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">CodeGroup</span> codeGroup = <span style="color: blue">new</span> <span style="color: #2b91af">UnionCodeGroup</span>(mc, policy);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Description = <span style="color: #a31515">&quot;Permissions for PT Caller&quot;</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Name = <span style="color: #a31515">&quot;CallerGroup&quot;</span>;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Add the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; machinePolicyLevel.RootCodeGroup.AddChild(codeGroup);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Save changes</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">SecurityManager</span>.SavePolicy();</p>
<p style="margin: 0px">}</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Sub</span> SetPermissions()</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Find the machine policy level</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> machinePolicyLevel <span style="color: blue">As</span> PolicyLevel = <span style="color: blue">Nothing</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> ph <span style="color: blue">As</span> IEnumerator = SecurityManager.PolicyHierarchy()</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">While</span> ph.MoveNext()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">Dim</span> pl <span style="color: blue">As</span> PolicyLevel = <span style="color: blue">DirectCast</span>(ph.Current, PolicyLevel)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">If</span> pl.Label = <span style="color: #a31515">&quot;Machine&quot;</span> <span style="color: blue">Then</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; machinePolicyLevel = pl</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">Exit</span> <span style="color: blue">While</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">End</span> <span style="color: blue">If</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">End</span> <span style="color: blue">While</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> ps <span style="color: blue">As</span> NamedPermissionSet = <span style="color: blue">New</span> NamedPermissionSet(<span style="color: #a31515">&quot;CallerPermSet&quot;</span>, PermissionState.None)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Add permissions (omitted)</span></p>
<p style="margin: 0px"><span style="color: green"></span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> key <span style="color: blue">As</span> StrongNamePublicKeyBlob = <span style="color: blue">GetType</span>(Caller).Assembly.Evidence _</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .OfType(<span style="color: blue">Of</span> StrongName)().First().PublicKey()</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> mc <span style="color: blue">As</span> IMembershipCondition = <span style="color: blue">New</span> StrongNameMembershipCondition(key, <span style="color: blue">Nothing</span>, <span style="color: blue">Nothing</span>)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Create the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> policy <span style="color: blue">As</span> PolicyStatement = <span style="color: blue">New</span> PolicyStatement(ps, PolicyStatementAttribute.Exclusive)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">Dim</span> codeGroup <span style="color: blue">As</span> CodeGroup = <span style="color: blue">New</span> UnionCodeGroup(mc, policy)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Description = <span style="color: #a31515">&quot;Permissions for PT Caller&quot;</span></p>
<p style="margin: 0px">&#160;&#160;&#160; codeGroup.Name = <span style="color: #a31515">&quot;CallerGroup&quot;</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Add the code group</span></p>
<p style="margin: 0px">&#160;&#160;&#160; machinePolicyLevel.RootCodeGroup.AddChild(codeGroup)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">&#8216; Save changes</span></p>
<p style="margin: 0px">&#160;&#160;&#160; SecurityManager.SavePolicy()</p>
<p style="margin: 0px"><span style="color: blue">End</span> <span style="color: blue">Sub</span></p>
</p></div>
<p>My next plan of attack was to determine whether the changes to security policy were really being made. Even though no exceptions were thrown, I couldn’t understand why caspol –rsp would tell me that the framework would run our test assembly in full trust. i tried listing all the code groups from caspol under the Machine level:</p>
<p><strong>caspol –m –lg</strong></p>
<blockquote><p>Microsoft (R) .NET Framework CasPol 4.0.21006.1     <br />Copyright (c) Microsoft Corporation.&#160; All rights reserved. </p>
<p>WARNING: The .NET Framework does not apply CAS policy by default. Any settings     <br />shown or modified by CasPol will only affect applications that opt into using      <br />CAS policy. </p>
<p>Please see <a href="http://go.microsoft.com/fwlink/?LinkId=131738">http://go.microsoft.com/fwlink/?LinkId=131738</a> for more information. </p>
<p>Policy change prompt is ON </p>
<p>Level = Machine </p>
<p>Code Groups: </p>
<p>1.&#160; All code: Nothing     <br />&#160;&#160; 1.1.&#160; Zone &#8211; MyComputer: FullTrust      <br />&#160;&#160;&#160;&#160;&#160; 1.1.1.&#160; StrongName &#8211; 00240000048000009400000006020000002400005253413100040      <br />0000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE      <br />79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E82      <br />1C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8      <br />A12436518206DC093344D5AD293: FullTrust      <br />&#160;&#160;&#160;&#160;&#160; 1.1.2.&#160; StrongName &#8211; 00000000000000000400000000000000: FullTrust      <br />&#160;&#160; 1.2.&#160; Zone &#8211; Intranet: LocalIntranet      <br />&#160;&#160;&#160;&#160;&#160; 1.2.1.&#160; All code: Same site Web      <br />&#160;&#160;&#160;&#160;&#160; 1.2.2.&#160; All code: Same directory FileIO &#8211; &#8216;Read, PathDiscovery&#8217;      <br />&#160;&#160; 1.3.&#160; Zone &#8211; Internet: Internet      <br />&#160;&#160;&#160;&#160;&#160; 1.3.1.&#160; All code: Same site Web      <br />&#160;&#160; 1.4.&#160; Zone &#8211; Untrusted: Nothing      <br />&#160;&#160; 1.5.&#160; Zone &#8211; Trusted: Internet      <br />&#160;&#160;&#160;&#160;&#160; 1.5.1.&#160; All code: Same site Web      <br />Success</p>
</blockquote>
<p>The custom code groups weren’t there! But if I inspected the code groups in code after running the setup executable, then they did appear.</p>
<h3>Resolution</h3>
<p>Eventually I just got frustrated and pulled out <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx">procmon</a> to figure out what caspol.exe was doing under the covers. I saw it reading and writing from configuration files in the .NET Framework directory, and that’s when it hit me. The setup executable that writes to security policy was compiled as AnyCPU and thus any security policy edits were flushed to the configuration files in the %WINDIR%Microsoft.NETFramework64 directory. Our test harness was erroneously running as a 32-bit application on a 64-bit machine, which means the security policy it read was actually from the %WINDIR%Microsoft.NETFramework directory!</p>
<p><strong>There are two versions of caspol.exe on 64-bit machines! </strong>One is for 32-bit applications, and the other is for 64-bit. As you can probably infer, I was incorrectly using the 32-bit one in my diagnosis above, which is why I never saw any of the custom code groups added to security policy.</p>
<p>It took a couple hours to figure this out, so I hope this post can help save you some time if you ever run into a similar situation!</p>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2010/01/10/cas-policy-on-64-bit-machines-19/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Asserting for Permissions in .NET 4 – #18</title>
		<link>http://davedewinter.com/2009/06/25/asserting-for-permissions-in-net-4/</link>
		<comments>http://davedewinter.com/2009/06/25/asserting-for-permissions-in-net-4/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 14:35:24 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/25/asserting-for-permissions-in-net-4/</guid>
		<description><![CDATA[Security asserts are a way to tell the CLR to stop checking for permissions past a certain point in the call stack. Of course, not all code is allowed to assert, or we&#8217;d have some big security problems to worry &#8230; <a href="http://davedewinter.com/2009/06/25/asserting-for-permissions-in-net-4/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Security asserts are a way to tell the CLR to stop checking for permissions past a certain point in the call stack. Of course, not all code is allowed to assert, or we&#8217;d have some big security problems to worry about. Specifically, partial trust code and security transparent code cannot assert for permissions. You may ask why asserting is useful, then, when only fully trusted code can do it.</p>
<p>One use case where asserts are beneficial is in testing products in partial trust. Say we have some test code that runs in partial trust and calls LINQ to SQL to test that a certain scenario still works in a medium trust environment. However, the test framework that the test uses requires permissions that are not granted in medium trust for some operations. Since the test framework knows that its callers won&#8217;t do anything malicious, it can assert for the permissions it needs to run these privileged operations. To do this, however, the test framework must be fully trusted.</p>
<p>Let&#8217;s say I have a test that runs in medium trust and calls some code in LINQ to SQL to verify that that code path works under medium trust. However, during some part of the test, the test framework itself needs to read an environment variable to determine which version of SQL Server to execute the test against (e.g. SQL Server 2000, SQL Server 2005, or SQL Server 2008).</p>
<p>Here&#8217;s the beginning of a test. (Keep in mind that this code is just an example. It doesn&#8217;t represent real types that we use in the LINQ to SQL test code, but it does demonstrate security assertions, which is something we do in the test framework.)</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">void</span> TestMediumTrust()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">DataContext</span> context = <span style="color: #2b91af">DataContextFactory</span>.CreateDataContext();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// &#8230;</span></p>
<p style="margin: 0px">}</p>
</p></div>
<p>And here&#8217;s the code in the test framework that the test above calls.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">DataContextFactory</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: #2b91af">DataContext</span> CreateDataContext()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">string</span> sqlVersion = ReadSqlVersion();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// &#8230;</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// Return the correct data context.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">SecuritySafeCritical</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">EnvironmentPermission</span>(<span style="color: #2b91af">SecurityAction</span>.Assert, Read = <span style="color: #a31515">&quot;SQLVERSION&quot;</span>)]</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">string</span> ReadSqlVersion()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: #2b91af">Environment</span>.GetEnvironmentVariable(<span style="color: #a31515">&quot;SQLVERSION&quot;</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>The TestMediumTrust method resides in a test assembly, while the DataContextFactory resides in another assembly which is part of the test framework. When we <a href="http://blogs.rev-net.com/ddewinter/2009/05/22/how-to-host-a-partial-trust-sandbox/">set up the medium-trust sandbox</a> in which to run the test, we tell the CLR to fully trust the test framework assembly. Full trust implies two things: (1) that SafeCritical and Critical annotations are respected and (2) we can assert for permissions. Remember that security transparent code cannot assert for permissions; this is why the ReadSqlVersion method above must be SafeCritical.</p>
<p>Medium trust code does not have permission to read the SQLVERSION environment variable, so under normal circumstances calling Environment.GetEnvironmentVariable would throw a SecurityException. This is because the .NET Framework itself will do a full Demand for the EnvironmentPermission to read the SQLVERSION variable. Permission Demands walk the entire call stack to ensure that every frame in the stack has the relevant permissions; since the test code runs in medium trust, the CLR will throw once it checks the TestMediumTrust method.</p>
<p>Asserts are a way to tell the CLR to stop checking for permissions past a particular stack frame. Thus with the assert in place on the ReadSqlVersion method, the EnvironmentPermission check stops prematurely and the permission Demand will succeed. To put that graphically…</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/06/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/06/image-thumb1.png" width="813" height="149" /></a> </p>
<p>So what changes in .NET 4? The recommended guidance is now to assert for full trust instead of for a specific permission. This advice seems to contradict the principle of least privilege, but in reality, if you layer your transparent and critical code appropriately, then security transparency can help you realize least privilege much more effectively. A second reason is that asserting for a specific permission causes a dependency on the underlying implementation. (This is a less convincing argument for me personally.) So the ReadSqlVersion method above now becomes…</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">SecuritySafeCritical</span>]</p>
<p style="margin: 0px">[<span style="color: #2b91af">PermissionSet</span>(<span style="color: #2b91af">SecurityAction</span>.Assert, Unrestricted = <span style="color: blue">true</span>)]</p>
<p style="margin: 0px"><span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">string</span> ReadSqlVersion()</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: #2b91af">Environment</span>.GetEnvironmentVariable(<span style="color: #a31515">&quot;SQLVERSION&quot;</span>);</p>
<p style="margin: 0px">}</p>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2009/06/25/asserting-for-permissions-in-net-4/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to Build APIs with Transparency in Mind – #17</title>
		<link>http://davedewinter.com/2009/06/23/how-to-build-apis-with-transparency-in-mind/</link>
		<comments>http://davedewinter.com/2009/06/23/how-to-build-apis-with-transparency-in-mind/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 13:08:50 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[API Design]]></category>
		<category><![CDATA[security transparency]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/23/how-to-build-apis-with-transparency-in-mind/</guid>
		<description><![CDATA[In the .NET Framework there are a few types which expose both &#34;safe&#34; and &#34;unsafe&#34; equivalents of the same method. Both methods achieve the same goal e.g. BinaryFormatter.Deserialize and BinaryFormatter.UnsafeDeserialize will both deserialize a stream into a .NET object, but &#8230; <a href="http://davedewinter.com/2009/06/23/how-to-build-apis-with-transparency-in-mind/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In the .NET Framework there are a few types which expose both &quot;safe&quot; and &quot;unsafe&quot; equivalents of the same method. Both methods achieve the same goal e.g. BinaryFormatter.Deserialize and BinaryFormatter.UnsafeDeserialize will both deserialize a stream into a .NET object, but the safe variant will do a full Demand for the appropriate permissions. This ensures that callers without proper permissions will fail when trying to call the safe method. The unsafe variant, on the other hand, ensures only that the <em>immediate</em> caller has the necessary permissions. Previous versions of the .NET Framework enforce these invariants with Demands and LinkDemands, as shown in the example below. (Note that this isn&#8217;t exactly what you&#8217;ll see for these methods in the BinaryFormatter class if you examine them in Reflector, but the permission Demand and LinkDemand are present.)</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">SecurityPermission</span>(<span style="color: #2b91af">SecurityAction</span>.Demand, SerializationFormatter = <span style="color: blue">true</span>)]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">object</span> Deserialize(<span style="color: #2b91af">Stream</span> serializationStream)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160; <span style="color: blue">return this</span>.UnsafeDeserialize(serializationStream);</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">[<span style="color: #2b91af">SecurityPermission</span>(<span style="color: #2b91af">SecurityAction</span>.LinkDemand, SerializationFormatter = <span style="color: blue">true</span>)]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">object</span> UnsafeDeserialize(<span style="color: #2b91af">Stream</span> serializationStream)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Method body</span></p>
<p style="margin: 0px">}</p>
</p></div>
<p>The reason for the two different versions is that a permission Demand is expensive because it has to check the permissions of every frame in the call stack. If you <strong>know</strong> that you aren&#8217;t introducing a security hole by calling an unsafe method, then you can skip the permission Demand and avoid the performance hit. </p>
<p>In .NET 4 under the Level 2 security rules, LinkDemands have been replaced by the SecurityCriticalAttribute, which means the UnsafeDeserialize will look similar to this.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">[<span style="color: #2b91af">SecurityCritical</span>]</p>
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">object</span> UnsafeDeserialize(<span style="color: #2b91af">Stream</span> serializationStream)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Method body</span></p>
<p style="margin: 0px">}</p>
</p></div>
<p>Methods annotated with LinkDemands should migrate to use the SecurityCriticalAttribute because the whole purpose of <a href="http://blogs.rev-net.com/ddewinter/2009/05/28/introduction-to-security-transparency-in-net-4/">security transparency</a> is to promote this kind of safe/unsafe API layering. When a method is decorated with the SecurityCriticalAttribute, the CLR ensures that no security transparent code can call that method. When you consider that all code running in partial trust is security transparent, the SecurityCriticalAttribute is effectively the same as a LinkDemand for full trust.</p>
<p>Be careful though! This API layering works for the .NET Framework because the assemblies are installed in the GAC and are therefore fully trusted, even in a partial trust sandbox. If the assembly you create is loaded into a partial trust sandbox but is <strong>not</strong> fully trusted, then the SecurityCriticalAttribute will not enforce anything. Remember, all partial trust code is security transparent, even code annotated with the SecurityCriticalAttribute.</p>
<p>Finally, if your assembly is not intended for partially trusted callers, then do you don&#8217;t need to worry about any of this. <img src='http://davedewinter.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Check out the <a href="http://msdn.microsoft.com/en-us/library/3ky50t49(VS.100).aspx">.NET 4 documentation on Demands vs. LinkDemands</a> for more information.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:7844ae8a-04c2-4b99-a58f-1e0527229cc5" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/.NET+Framework" rel="tag">.NET Framework</a>,<a href="http://technorati.com/tags/API+Design" rel="tag">API Design</a>,<a href="http://technorati.com/tags/.NET+4" rel="tag">.NET 4</a>,<a href="http://technorati.com/tags/security+transparency" rel="tag">security transparency</a></div>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2009/06/23/how-to-build-apis-with-transparency-in-mind/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mixing Level 1 and Level 2 Transparency Rules – #16</title>
		<link>http://davedewinter.com/2009/06/09/mixing-level-1-and-level-2-transparency-rules/</link>
		<comments>http://davedewinter.com/2009/06/09/mixing-level-1-and-level-2-transparency-rules/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 12:56:40 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Security Tips]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[Level 1]]></category>
		<category><![CDATA[Level 2]]></category>
		<category><![CDATA[partial trust]]></category>
		<category><![CDATA[SecurityRulesAttribute]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/06/09/mixing-level-1-and-level-2-transparency-rules/</guid>
		<description><![CDATA[Today&#8217;s tip addresses how assemblies using different transparency rules (CLR v2 and CLR v4) interact with each other in the same AppDomain. Remember you can use the SecurityRulesAttribute to specify which level of security rules your assemblies adhere to. The &#8230; <a href="http://davedewinter.com/2009/06/09/mixing-level-1-and-level-2-transparency-rules/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s tip addresses how assemblies using different transparency rules (<a href="http://blogs.rev-net.com/ddewinter/2009/05/18/using-transparency-in-clr-2/">CLR v2</a> and <a href="http://blogs.rev-net.com/ddewinter/2009/05/28/introduction-to-security-transparency-in-net-4/">CLR v4</a>) interact with each other in the same AppDomain. Remember you can use the <a href="http://blogs.rev-net.com/ddewinter/2009/06/08/the-securityrulesattribute/">SecurityRulesAttribute</a> to specify which level of security rules your assemblies adhere to. The default in .NET 4 is level 2.</p>
<p>There are only two cases here—a level 1 assembly calling a level 2 assembly, and a level 2 assembly calling a level 1 assembly. Let&#8217;s take them one at a time.</p>
<p><strong>Level 2 Assembly Calls Level 1 Assembly</strong></p>
<p>Transparency rules are not enforced across assembly boundaries under the level 1 rules, but they are under the level 2 rules. When a level 2 assembly calls a level 1 assembly, transparency violations are <strong>not</strong> enforced—that is, if level 2 transparent code calls a level 1 critical method in another assembly, the call succeeds.</p>
<p><strong>Level 1 Assembly Calls Level 2 Assembly</strong></p>
<p>You might think that transparency is enforced across the assembly boundary since the roles are now reversed, but the CLR acts a bit more interestingly than that. If <em>partial-trust</em> code from a level 1 assembly tries to call a critical method in a level 2 <em>full-trust</em> assembly, then the call fails. Level 1 assemblies, which use the CLR v2&#8242;s transparency semantics, have no way to interpret a public security critical method as it exists in level 2; such a concept didn&#8217;t exist back in the second version of the CLR. Because of this, the CLR goes to great lengths to make everything appear as level 1 to the calling assembly. To do this the CLR transforms the method marked SecurityCritical into a LinkDemand for FullTrust. Thus the call to a public critical method from partial trust code fails.</p>
<p>In the CLR v4, methods that were marked with LinkDemands for FullTrust are now marked SecurityCritical, which is a stronger enforcement mechanism because it prevents all partial-trust code <em>and</em> all transparent code from calling it. It is not a stretch to see that the CLR will transform the SecurityCritical annotation back into a LinkDemand for FullTrust to make everything appear as level 1 to the level 1 assembly.</p>
<p>This means that transparent code in a level 1 assembly <strong>can</strong> call public critical code in a level 2 assembly if the level 1 assembly is fully trusted. The rule states only that partial trust code in a level 1 assembly cannot call fully trusted security critical code in a level 2 assembly.</p>
<p>Furthermore, partial trust code is always security transparent and thus can never call security critical code.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:74d9ec77-c2b8-46a9-ba35-c0fc3c6c7987" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/.NET" rel="tag">.NET</a>,<a href="http://technorati.com/tags/security+tips" rel="tag">security tips</a>,<a href="http://technorati.com/tags/SecurityRulesAttribute" rel="tag">SecurityRulesAttribute</a>,<a href="http://technorati.com/tags/Level+1" rel="tag">Level 1</a>,<a href="http://technorati.com/tags/Level+2" rel="tag">Level 2</a>,<a href="http://technorati.com/tags/partial+trust" rel="tag">partial trust</a>,<a href="http://technorati.com/tags/.NET+4" rel="tag">.NET 4</a></div>
]]></content:encoded>
			<wfw:commentRss>http://davedewinter.com/2009/06/09/mixing-level-1-and-level-2-transparency-rules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

