<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="www.w3.org/2005/Atom" xmlns:sy="purl.org/rss/1.0/modules/syndication/" xmlns:dc="purl.org/dc/elements/1.1/" xmlns:content="purl.org/rss/1.0/modules/content/" xmlns:wfw="wellformedweb.org/CommentAPI/" xmlns:slash="purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>compiler padawan</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/dsimmons/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/dsimmons/feed.xml</link>
    <description>My adventures learning how to build compilers.</description>
    <lastBuildDate>Tue, 16 Apr 2019 05:04:44 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Coo coo ca choo ... back to the big 'ol blue</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/coo-coo-ca-choo-back-to-the-big-ol-blue</link>
      <pubDate>Fri, 02 Oct 2015 15:59:23 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2015/10/02/coo-coo-ca-choo-back-to-the-big-ol-blue/</guid>
      <description><![CDATA[...monster that is.

I'm back at Microsoft.&nbsp; I had a great time outside the company including...]]></description>
      <content:encoded><![CDATA[<p>...monster that is.</p>
<p><a href="gapingvoid.com/blog/microsoftbizcard219border.jpg" rel="lightbox[3189]"><img src="gapingvoid.com/blog/microsoftbizcard219border.jpg" alt="microsoftbizcard219border.jpg" width="400" height="247" border="0" /></a></p>
<p>I'm back at Microsoft.&nbsp; I had a great time outside the company including working for several years with my brother on a startup, but now I'm excited to be back.&nbsp; I've now joined the Azure Information Management and Machine Learning organization, and I'm working on a cool technology called program synthesis.&nbsp; More details soon.</p>
<p>- Danny</p>]]></content:encoded>
    </item>
    <item>
      <title>compiler padawan moves on</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/compiler-padawan-moves-on</link>
      <pubDate>Wed, 01 Feb 2012 14:35:13 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2012/02/01/compiler-padawan-moves-on/</guid>
      <description><![CDATA[After nearly 15 years at Microsoft I've decided to leave the company and explore some programming...]]></description>
      <content:encoded><![CDATA[<p>After nearly 15 years at Microsoft I've decided to leave the company and explore some programming adventures elsewhere.&nbsp; This Friday, February 3, 2012, will be my last day at Microsoft.&nbsp; It has been an absolutely GREAT experience, I have worked with some wonderful people and learned a lot, but I'm excited for a change.</p>
<p>If you are interested in following my adventures as I step out of the reality distortion bubble surrounding 1 Microsoft Way and enter some new form of reality distortion bubble, I'm now going to blog at <a href="blogs.the-simmons.net/danny">blogs.the-simmons.net/danny</a></p>
<p>&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>system.data.objects dev guy becomes a compiler padawan</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/system-data-objects-dev-guy-becomes-a-compiler-padawan</link>
      <pubDate>Thu, 02 Dec 2010 15:46:22 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/12/02/system-data-objects-dev-guy-becomes-a-compiler-padawan/</guid>
      <description><![CDATA[More than 5 years ago I joined what became the Entity Framework team and started an awesome...]]></description>
      <content:encoded><![CDATA[<p>More than 5 years ago I joined what became the Entity Framework team and started an awesome adventure which taught me a lot and has given me many memories which I will treasure: Everything from a room of MVPs yelling at me (so much that one of them later apologized on his blog) and a certain well-publicized “vote” … to the v2^2 t-shirts and talk about magic unicorns, and that’s just the public stuff.&#160; I won’t mention the crazy antics that went on behind closed doors just like pretty much any other hard-driving software team, or the experience of being part of a high-profile, at times controversial project in the world’s largest software company.&#160; It wasn’t all fun and games, but it has been great, and I’ve had the honor of working with an outstanding group of people both inside and outside Microsoft.</p>  <p>One of the best parts about working at Microsoft is the opportunity it gives you to explore a variety of things and work on multiple different projects without the impact on the rest of your life associated with changing companies.&#160; So I’ve decided the time has come for me to take advantage of this unique employment situation and explore some new challenges elsewhere in the company.&#160; Thankfully, I know that I’m leaving the EF in very good hands and that it has a wonderfully bright future ahead of it.</p>  <p>In case you are wondering where I’m going, I’m joining an incubation team which is in charge of, among other things, the phoenix project.&#160; Specifically I’ll be working on ahead-of-time compilation for c# in order to solve some really challenging problems in system programming.&#160; One of the things that has come out of the last several years for me is a real love of programming in c#, and this project has the potential to help extend the use of c# into domains where it can’t be used today.&#160; The team I’m joining faces some challenges which will benefit from my past experience, and at the same time there is a vast new domain to learn about where I have no experience (compilers).</p>  <p>So today I lay down my claim to the title “system.data.objects dev guy”, and take up the mantle of “compiler padawan.”&#160; (My wife asks if I’m going to grow a small padawan braid at the back of my head, but I really don’t think anyone wants to see that, so I suppose I’ll pass.)</p>  <p>- Danny</p>]]></content:encoded>
    </item>
    <item>
      <title>Simple WPF 2D Graphics: DrawingVisual</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/simple-wpf-2d-graphics-drawingvisual</link>
      <pubDate>Sat, 27 Nov 2010 18:47:35 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/11/27/simple-wpf-2d-graphics-drawingvisual/</guid>
      <description><![CDATA[And now for something completely different…&#160; Over the last little while I’ve been working on a...]]></description>
      <content:encoded><![CDATA[<p>And now for something completely different…&#160; Over the last little while I’ve been working on a side project just for fun which involves some simple 2D graphics using WPF.&#160; Because I’m calculating the image I want to draw rather than it being a static thing, one of my criteria for the basic approach is that it will all be code oriented.&#160; I’m not by any means opposed to xaml, and there are places in this program where I could use some xaml, but it would only be for the most basic top-level windows and such.&#160; So I decided to just do the whole thing in C# and avoid any xaml to keep all my code in one place and to force myself to learn how all the pieces go together.</p>  <p>For my first attempt I did the easiest thing (and the one most frequently shown in simple WPF graphics demos) which is to use a Canvas and create on it a series of Line objects.&#160;&#160; The result looked like this:</p>  <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: true; ruler: false; smart-tabs: true; tab-size: 4; toolbar: false;">[STAThread]
public static void Main()
{
    var app = new Application();
    var window = new Window();
    var canvas = new Canvas();

    window.Content = canvas;
    canvas.Children.Add(new Line
        {
            X1 = 0,
            Y1 = 0,
            X2 = 400,
            Y2 = 400,
            Stroke = Brushes.Black
        });
    canvas.Children.Add(new Line
        {
            X1 = 0,
            Y1 = 400,
            X2 = 400,
            Y2 = 0,
            Stroke = Brushes.Black
        });

    app.Run(window);
}</pre>

<p>While this approach worked for my initial drawings and was quite easy, I became concerned when I wanted to introduce some animation because I had cases where I wanted to animate a figure made up of a large number of lines as though it was one thing, and it began to get a bit ugly to setup.&#160; In addition I started to worry a bit about perf, and even though I didn’t have the full program running yet so I wasn’t able to actually measure the perf, my reading on the net led me to think those worries were justified.</p>

<p>One fairly commonly recommended alternative approach is to use a DrawingVisual which as I understand it is basically a lower level construct which allows you to compose a number of drawing commands as though they were a single control in the visual hierarchy.&#160; Rather than each part of the drawing being full-fledged controls with their own events and everything, you create a series of drawing commands and put them inside a single object that is the only thing which has events and such.&#160; This is supposed to be faster, and it’s also supposed to allow you to use things like DrawingGroup which can cause all its contents to animate together as one thing—just what I wanted!</p>

<p>When I started to try this, though, everything I did seemed to just display a blank screen.&#160; My app would start, and the window would come up, but the graphics weren’t drawn into it.&#160; I looked at several samples—many of which were all in xaml—and you’d think that they would convert easily to code since xaml is just a straightforward mapping onto object creation after all, but I just couldn’t make it work.&#160; After much banging my head on the wall and searching on the net I eventually discovered that one of the main places I was looking, MSDN, had a sample with code shown on the help page that was incomplete.&#160; There was a small link to another page where you could go download the full sample, which worked fine.&#160; So a fair amount of scratching my head and trial and error later led me to the discovery of what was in that sample which was missing from my code.&#160; Hopefully this post will help some other poor wpf graphics programmer figure out their problem sooner.</p>

<p>It turns out that the key to my whole mess was creating the “visual host” control which would contain my drawing.&#160; This control inherits from FrameworkElement and provides the infrastructure for event handling and other things.&#160; It plays a role much like the canvas in the sample above except that with the canvas, each child is also something that inherits from FrameworkElement whereas when using a VisualDrawing this is the only thing that does that and all of its children are just simple drawing components.&#160; In addition to inheriting from FrameworkElement, the visual host needs to contain a VisualCollection object which is a container for its children.&#160; That much I had working.&#160; The part that had escaped me was that you are also required to override a property and a method from FrameworkElement.&#160; The property is VisualChildrenCount.&#160; It needs a getter and it should just return the count value from the VisualCollection.&#160; The method is GetVisualChild and it just returns the child with the specified index from the VisualCollection.</p>

<p><strong><em>Unfortunately these aren’t abstract so the compiler won’t catch the issue and tell you that you must override them, but if you don’t, then the framework never becomes aware of your child objects and the result is that nothing is displayed.</em></strong></p>

<p>Once over that hurdle, everything works great.&#160; The final program (equivalent to the one above) looks like this:</p>

<pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: true; ruler: false; smart-tabs: true; tab-size: 4; toolbar: false;">[STAThread]
public static void Main()
{
    var app = new Application();
    var window = new Window();
    var host = new MyVisualHost();

    window.Content = host;
    app.Run(window);
}

public class MyVisualHost : FrameworkElement
{
    private VisualCollection children;
        
    public MyVisualHost()
    {
        children = new VisualCollection(this);

        var visual = new DrawingVisual();
        children.Add(visual);

        using (var dc = visual.RenderOpen())
        {
            dc.DrawLine(new Pen(Brushes.Black, 1), new Point(0, 0), new Point(400, 400));
            dc.DrawLine(new Pen(Brushes.Black, 1), new Point(0, 400), new Point(400, 0));
        }
    }

    protected override int VisualChildrenCount
    {
        get { return children.Count; }
    }

    protected override Visual GetVisualChild(int index)
    {
        if (index &lt; 0 || index &gt;= children.Count)
        {
            throw new ArgumentOutOfRangeException();
        }

        return children[index];
    }
}</pre>

<p>As you can see, the structure of the program is very similar to the first sample except that instead of creating a canvas and then adding child line objects to that canvas, I create a new “MyVisualHost” object which in its constructor creates a DrawingVisual, uses that object to get a DrawingContext and then calls methods on the DrawingContext to draw lines.&#160; Everything but the last two methods is fairly easy to find in samples on the net, but if you omit them, your program will compile—it just won’t work.&#160; Lovely.</p>

<p>- Danny</p>]]></content:encoded>
    </item>
    <item>
      <title>EF FAQ Relocation and Overhaul</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/ef-faq-relocation-and-overhaul</link>
      <pubDate>Mon, 08 Nov 2010 14:21:53 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/11/08/ef-faq-relocation-and-overhaul/</guid>
      <description><![CDATA[It has been quite some time since I last updated the EF Frequently Asked Questions which makes them...]]></description>
      <content:encoded><![CDATA[<p>It has been quite some time since I last updated the EF Frequently Asked Questions which makes them dramatically less useful to everyone.&#160; At its core, I think the reason for this delay is not just that I have been busy doing other things but rather that the way the FAQ was setup and posted made it difficult for others to help keep it up to date.&#160; To have any hope of continuing to be a great and useful resource in the long run, I believe this needs to be a community effort rather than one run by a single individual or by the EF team.</p>  <p>In an attempt to improve matters, I’ve spent some time over the last few weeks relocating the FAQ to <a href="www.ef-faq.org">www.ef-faq.org</a> (a domain that I registered personally, not something officially owned or maintained by Microsoft) and changing its source format into a series of text files with simple wiki-like markup maintained under mercurial-based source control at the codeplex project <a href="effaq.codeplex.com/">effaq.codeplex.com/</a>.&#160; In addition, some folks on the EF team have put a lot of effort into adding additional questions and answers and updating things based on EF4 so hopefully the FAQ is in a better place than it has been for a while.</p>  <p>Now my hope is that some of you will take a few minutes to help me out in the following ways:</p>  <ol>   <li>Look over the FAQ—maybe you will learn something. </li>    <li>Next time you have a question or answer a question, check the FAQ, and if the answer is already there publish a link so that others can more easily find and benefit from it.&#160; Every question has a fragment name based on the section and question #.&#160; So if you want a link, for instance to Code Generation Question 12.2 (“Is there any way to use public, easily modifiable templates for EF code generation?”), the link would be <a href="www.ef-faq.org/code-generation.html#12.2">www.ef-faq.org/code-generation.html#12.2</a> </li>    <li>If the question you have is NOT answered in the FAQ, and you think it is something others may also run into.&#160; Please, PLEASE, take the time to enlist in the codeplex project, edit the source, make a fork and send a pull request so that we can incorporate your change and push it up to the site.&#160; This is designed to be a pretty easy process, and it can really benefit your fellow programmers. </li> </ol>  <p>For the curious, here’s a little background about how the new EF FAQ site is put together: After casting about for a bit, I decided that I wanted to have a static site with pretty simple HTML so that it is simple, quick and search-engine friendly.&#160; I wanted more formatting than I could get from strict plain text, but I wanted something simpler and more constrained/uniform than what I could get out of word or something like that.&#160; In the end I decided to take the <a href="blog.stackoverflow.com/2009/12/introducing-markdownsharp/" target="_blank">markdownsharp</a> library (thanks Jeff and others), extend it a little bit to add the concept of “sections” and “questions” which get auto-numbered, have some specific HTML markup and help to produce an auto-generated index of sections for navigation.&#160; I also wrote a simple program to wrap the generated content HTML in a high-level template so that every page gets a header, footer and navigation bar and to manage the workflow of turning the various source files into all the HTML for the site.&#160; You can find the source for my “faqbldr” app as part of the codeproject as well, and soon I hope to push my extensibility hooks for markdownsharp back into its repository so that I can remove its source from the codeplex project and just check in a binary nuget-style.</p>  <p>By the way, if you are an HTML and CSS guru with a strong stomach, you might want to take a look at template.html in the codeplex project where I have created a horrendous mess that no doubt violates every rule of good HTML design but somehow seems to have landed in a place where the site works and looks OK as long as I don’t touch it any more (If I do I’m pretty sure the whole house of cards will come tumbling down).&#160; Someone who wasn’t such an awful html hacker like me could no doubt make it cleaaner, nicer looking and faster.</p>  <p>One last comment, while the FAQ has originally been produced by members of the EF team (and likely some EF team members will continue to contribute to it), it is definitely my intention that this not just be a Microsoft effort.&#160; This isn’t official documentation.&#160; Ideally it should be a helpful resource that contains whatever info you need to help get your tasks programming with the EF done (or more frequently pointers to where to find the more complete details on what you need).&#160; This means that if you have negative comments about the EF in some area or positive comments about some other product that you would use in conjunction with the EF or instead of it in some scenario, those belong here as well—as long as they are constructive and help achieve the goal of making people successful at building great software.&#160; Happily <a href="blogs.teamb.com/craigstuntz/" target="_blank">Craig Stuntz</a> has agreed to start contributing to the project, and it’s my hope that we’ll have others join in soon.</p>  <p>- Danny</p>  <p>P.S. If you visit the site in the next day or two, you will find that the bing search box in the upper left isn’t fully working yet because the site is so new and bing hasn’t indexed it, but that should fix itself in the next few days.</p>]]></content:encoded>
    </item>
    <item>
      <title>EF Query Tuning</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/ef-query-tuning</link>
      <pubDate>Thu, 22 Jul 2010 17:31:23 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/07/22/ef-query-tuning/</guid>
      <description><![CDATA[Continuing on the topic of application performance tuning, let’s turn our attention specifically to...]]></description>
      <content:encoded><![CDATA[<p>Continuing on the topic of application performance tuning, let’s turn our attention specifically to the EF and take a look at some of what’s going on under the covers with EF queries.</p>  <h3>Question #1: Where is the hot path?</h3>  <p>The first thing to think about in broad terms is where is the time really going.&#160; Often it’s relatively easy to introduce a few counters or make some other small hack to find the worst offender in your application.&#160; My first bit of advice to you on this front is: <strong><em>Don’t be afraid to make temporary changes to your code.</em></strong>&#160; You can sometimes get great results by making a fresh enlistment in your source control system, checking out a bunch of files and hacking on the code in ways that you would never ship but which help to isolate things so you can figure out what’s really going on.</p>  <p>My next suggestion is: <strong><em>Get a profiler and figure out how to use it.&#160; </em></strong>Visual studio has a great profiler if you have a sufficiently advanced version, and that’s what I use, but there are other products on the market.&#160; There are even some profilers specifically aimed at working with applications built on top of the EF.&#160; In any case, if you care about perf, a profiler is hugely important.&#160; I’m no expert on any of these, but you can find some great resources on the web.&#160; Some of the the articles I’ve found useful for working with the VS profiler are: <a href="https://msdn.microsoft.com/en-us/magazine/cc337887.aspx">msdn.microsoft.com/en-us/magazine/cc337887.aspx</a> and <a href="www.wintellect.com/CS/blogs/jrobbins/archive/2009/10/19/vs-2010-beta-2-sampling-and-instrumentation-profiling-in-depth-first-look.aspx">www.wintellect.com/CS/blogs/jrobbins/archive/2009/10/19/vs-2010-beta-2-sampling-and-instrumentation-profiling-in-depth-first-look.aspx</a>.</p>  <p>However you decide to measure things, the first level of investigation which I’d recommend when you are looking at an EF-based application is to determine where your biggest bottleneck is: </p>  <ul>   <li>your application </li>    <li>EF one-time startup </li>    <li>EF query code </li>    <li>network transmission </li>    <li>or the database </li> </ul>  <p>If you can figure this out, then you can much more quickly home in on where to investigate further and what experiments you might want to try to improve performance.</p>  <h3>What happens during the execution of an EF query?</h3>  <p>In order to get to the next level of your investigation, it can help a lot to have a general idea of what all is happening and in what order when you execute an EF query.&#160; To that end, here’s a rough list:</p>  <ul>   <li>Startup: When you first create an ObjectContext, it will load metadata describing your model.&#160; The first time a context is created in an app domain, that metadata is loaded either from resources in your assemblies or from files on disk.&#160; On subsequent context creations the data is loaded from an in-memory cache making it much faster.      <br />&#160; </li>    <li>Startup: The first time you execute a query on the first ObjectContext instance for an app-domain, the EF will generate an in-memory structure (called the query views) which it uses for query translation.&#160; For every query after that, it will simply retrieve the views from an in-memory cache.&#160; This view generation step can be very time consuming—especially for large, complex models.      <br />&#160; </li>    <li>Query: Next the query is translated from LINQ or ESQL into your backend database command (TSQL in the case of SQL Server) and the results assembly plan is created.      <br />&#160; </li>    <li>Query: The connection is opened if it isn’t already.&#160; By default the EF will open the connection before each operation and close it when the operation is complete.&#160; If you open the connection manually, though, the EF will leave it alone so it can be kept open if you are performing multiple operations in a row, and this can sometimes be a significant perf win.      <br />&#160; </li>    <li>Query: If a TransactionScope is active, then the connection is enlisted in the transaction.&#160; The effect of this depends on the ado.net provider—for sql server 2008 this is usually cheap, but for earlier versions of sql server if the connection has been previously opened and closed and was just opened again all within the same transaction (or for any provider if more than one transaction participant is involved), then the transaction is promoted to a distributed transaction which can be very expensive.      <br />&#160; </li>    <li>Network: Send query to the database.&#160; Typically this part of the process is inexpensive because the amount of data required to send the query to the database is usually small.&#160; Network time is more of a factor when results come back later.      <br />&#160; </li>    <li>Database: Execute the query.&#160; What this entails obviously depends on the complexity of the query, the indexes that are configured and the particular database server involved among other things.&#160; Most modern databases have their own fairly sophisticated query optimization system as well as execution plan caches and other mechanisms to help here.&#160; In the case of sql server, the complexity of the query being executed is only one of the tools available for tuning, indexes and statistics can be added to the database and even plan guides can be used to give the database hints about how to execute the query efficiently.      <br />&#160; </li>    <li>Network: Return results from the database.&#160; This can become a significant factor if your query returns extra data which isn’t actually needed by the app.&#160; In addition, things like eager loading can help perf by reducing the number of network round trips, but they can also hurt performance by causing redundant data to be returned since the way entities from different tables are returned is through the use of a join which often causes some data to be repeated—this repeated data is accounted for during the result assembly process so you end up with accurate results, but there is still overhead in the data returned over the network.      <br />&#160; </li>    <li>Query: Check the ObjectStateManager by key to see if the entity in question is already present (unless MergeOption is NoTracking).      <br />&#160; </li>    <li>Startup: The first time a particular entity type / query result shape is returned, dynamic code is generated which extracts the relevant data from the DataReader, constructs the object and initializes it with data (called materialization).      <br />&#160; </li>    <li>Query: Objects are actually materialized.      <br />&#160; </li>    <li>Query: Objects are added to the ObjectStateManager (unless MergeOption is NoTracking).      <br />&#160; </li>    <li>Query: Relationships between entities are fixed up.      <br />&#160; </li>    <li>Application: Results are processed potentially causing additional queries (especially through lazy loading, etc.) </li> </ul>  <p>OK.&#160; Now you know what goes on under the covers, and you’ve found something that seems to be taking more time than necessary.&#160; That brings us to…</p>  <h3>What can be done to improve EF query perf?</h3>  <p>Here’s a general rule-of-thumb checklist for EF query perf tuning in the order I would tend to investigate (since this is usually the order of highest bang-for-the-buck).</p>  <p>DANGER!&#160; DANGER!&#160; DANGER!&#160; If you read my post about perf tuning philosophy, all kinds of bells should be going off in your head about now.&#160; You should be saying something like, “I thought perf was a science and I should measure what exactly is the issue, create my own prioritization and then do a series of carefully controlled experiments.”&#160; Of course all those things are true.&#160; You SHOULD measure the reality in your particular situation.&#160; That said, I get asked these kinds of questions quite often, and some of these issues show up frequently enough that it if it’s not too expensive to try one of these fixes, you might just try them and measure the results—this could be cheaper to try than deep profiling or the like.</p>  <ol>   <li><strong>Pre-compiled views.&#160; </strong>Usually a very easy to implement change is to turn on pre-compiled views.&#160; This will move the time of generating views from the first query in your app-domain to design time.       <br />&#160; </li>    <li><strong>Avoid distributed transactions.</strong>&#160; If your app is triggering distributed transactions, getting rid of that can be a MAJOR perf win.&#160; So even though this can be more involved, it’s worth looking for.&#160; If you are using SQL Server 2000 or 2005, this can be caused just by opening and closing the connection more than once inside the same transaction, and if that’s the case the fix is as simple as explicitly opening the connection before the first operation inside the transaction and then either explicitly closing it when the transaction is done or letting it be closed when the context is disposed.       <br />&#160; </li>    <li><strong>Avoid extra connection opens.</strong>&#160; Even if you aren’t getting distributed transactions, if you have a number of operations all in a row, just opening the connection can be expensive.&#160; As with the best case of distributed transactions, it can be easily addressed by explicitly opening the connection before the first operation.       <br />&#160; </li>    <li><strong>Reduce database round trips.</strong>&#160; Eager loading through the Include method can cause graphs of related entities to be retrieved in a single round trip rather than several.&#160; This can be an especially big win if you are using lazy loading to retrieve a graph of related entities across a 1-many relationship like a set of customers and their orders.&#160; With lazy loading this will take one round trip for the customers + one round trip for each order, while lazy loading could return the entire set in a single round trip.&#160; Be careful, though, to balance the cost of round trips against the cost of extra network traffic and query complexity.&#160; If you have a large graph of related entities (across several relationships), using eager loading to retrieve the whole thing may not be the most efficient.&#160; Often the best answer is a combination with some eager loading and some lazy loading or some other combination.&#160; The only way to tell is to try things and measure.       <br />&#160; </li>    <li><strong>Retrieve less data.</strong>&#160; Often this is the first thing your DBA will tell you: Quit retrieving data that you don’t actually use in your app.&#160; If you only want to display a list of customers and their zip codes, then retrieving the entire customer object might be a bad idea.&#160; On the other hand, it may be that querying for the customer object up front will allow you to avoid later queries for the rest of the data, so it’s a balance and you have to try things and measure.       <br />&#160; </li>    <li><strong>Reduce post DB-query client processing costs.</strong>&#160; Often the simplest way to do this is to set the MergeOption of the query to NoTracking.&#160; When you do this the EF will no longer check the ObjectStateManager to see if the entity is already present there, and after the objects are constructed, it will not add the entity to the ObjectStateManager.&#160; This can often produce a significant perf improvement, but you have to keep in mind the side effects this will cause since entity change tracking and identity resolution will no longer happen, etc.       <br />&#160; </li>    <li><strong>Reduce pre DB-query client processing costs.</strong>&#160; If you only execute this particular query once, then there’s really not much you can do, but if you execute the same query multiple times and you use ESQL, then the EF will automatically cache the translated query.&#160; For LINQ, though, the EF doesn’t automatically cache the query which is where LINQ compiled queries come in.&#160; They allow you to explicitly do the translation ahead of time, hold onto a token representing the query and then use that token to execute it each time.       <br />&#160; </li>    <li><strong>Reduce complexity of the DB query.</strong>&#160; You may find opportunities to do this by adjusting the shape of the LINQ or ESQL that you write in your application.&#160; More often, though, you should look for ways to adjust the model shape.&#160; Deep inheritance hierarchies with lots of relationships, and especially if they use TPC-style inheritance tend to create complex queries.&#160; If you can reduce the depth of your inheritance hierarchy, write queries that return fewer different types in a single query, or switch from TPC to TPH or something like that, the result will tend to be less complex.&#160; While the EF often does a great job in the database queries that it generates, occasionally it will produce a query which is less than ideal.&#160; If you determine this is your bottleneck and you know how to hand-write a better query, then you can consider writing the query by hand as a stored procedure and calling that in order to take complete control over the query rather than letting the EF generate it. </li> </ol>  <p>- Danny</p>]]></content:encoded>
    </item>
    <item>
      <title>Application Performance Tuning Philosophy</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/application-performance-tuning-philosophy</link>
      <pubDate>Thu, 22 Jul 2010 17:01:35 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/07/22/application-performance-tuning-philosophy/</guid>
      <description><![CDATA[I’m in the process of embarking on some investigation and discussion with folks about performance...]]></description>
      <content:encoded><![CDATA[<p>I’m in the process of embarking on some investigation and discussion with folks about performance tuning EF apps (in particular I’m going to dive into a critical area or two on my <a href="https://code.msdn.com/d3/">D3 project</a>), and the more I thought about this, the more convinced I became that there is a fair amount of background that needs to be set out before diving into the heart of the matter.&#160; At least for me, there are a number of things about perf tuning that just weren’t obvious when I first began considering it.&#160; To be successful at this endeavor, just as with any other, we need to really know what we’re about and something of the underlying ideas that lead to a workable approach.&#160; So here’s my off the cuff description of the way I think about performance.</p>  <h3>There Are Two Ways to Improve Performance</h3>  <p>In my opinion, there are basically two different ways to actually improve the performance of an application (improving the performance of a framework or a server overlaps a lot but each has some unique challenges that I’m not going to consider today).&#160; The first technique is all about your application design, and the second is a matter of tuning individual operations.&#160; </p>  <p>Without a doubt the biggest wins come from making good design decisions up front.&#160; What I’m talking about here are coarse-grained things that affect the entire way your app works.&#160; Getting these right is generally either a measure of understanding your problem space well through a lot of experience, being lucky or writing your application, discovering what you got wrong and then completely re-writing large portions of it.&#160; An example of this kind of issue would be the difference between a client-server application where the client is essentially just a dumb terminal that requires every single key-stroke to travel to the server to be handled and one where you have a smarter client that does a fair amount of display, validation and other logic on the client giving great responsiveness and then just sends larger batch operations to the server.&#160; If you happen to choose the first approach, you might discover huge perf problems, and if that happens it will be a major issue to redesign your application to the second approach.</p>  <p>While the first approach is largely about forecasting where you are going and making sure you create an architecture that leads you down the right path for your largest decisions, the second approach looks at how to improve much finer-grained individual scenarios.&#160; The techniques you use for this approach are much different than those used for the first one.&#160; In fact, often if you try to think carefully and optimize your fine grained operations up front in the way you do for the overall architecture, you will introduce a ton of complexity which makes your application much harder to develop, test and maintain and even after all that experience shows that most often you will not have actually improved the performance in a way that has a meaningful positive effect on the end user experience—you may actually have made it worse.</p>  <p>So while design is very important, tuning is also critical to get a great experience from your app.</p>  <h3>Tuning is Experimental Science</h3>  <p>While lots of what we do as software developers is very different from experimental science (resembling something closer to craftsmanship involving a mix of art &amp; science, engineering &amp; design), performance tuning done right is ALL SCIENCE.&#160; We need to have an understanding of the underlying concepts, to have some intuition about what will and will not work, but just like an experimental scientist we have to train ourselves to thoroughly harness that intuition and slave it to a process that will lead us to results we can prove and depend on.</p>  <p>I like to tell developers on my team, “If you think you know what will improve the perf, you are almost certainly wrong.”&#160; As developers we often have that feeling that we just know what is wrong with the code, and we want desperately to dive in and implement our fix.&#160; In practice, though, often we’re wrong.&#160; Oh sure, we will improve the performance of some part of the code, but unless we’ve done a very careful investigation first we may have made an improvement in an area of the code that is already so fast it doesn’t matter while ignoring or maybe even making worse the hot path (the thing that is the current slowest part which has the most effect on the user experience).&#160; Further, we often have a tendency to take a shotgun approach and make a lot of changes before measuring again with the result that if the perf gets better, worse or stays approximately the same we have no way to know what change we made is responsible.</p>  <p>The only real answer is to make a baseline measurement, look at the data, create a hypothesis and then make the smallest possible change to test that hypothesis.&#160; Further, it’s super important that we carefully prioritize our experiments.&#160; We want to go after the lowest hanging fruit.&#160; That is to tackle those problems which will have the biggest impact on the end user experience for the lowest possible cost in terms of development cost and final code complexity.&#160; Obviously this means we have a tendency to look for the hot path through the application as the first step, but we also have to apply a complexity filter since it may be that the hot path is something that would be very hard to change, while there may be 2 or 3 other things that are almost as significant as the hot path but much easier to change.&#160; Just always remember: measure, measure, measure.&#160; When we’re done we want to KNOW the app will be faster and that we’ve gotten there as quickly and easily as possible.</p>  <h3>Tuning Improvements Tend to be the Enemy of Clean Code</h3>  <p>To add further strength to the comment that we want to make the cheapest possible changes, I’ll point out that while top-level architecture design style perf improvements can often make your application even cleaner and easier to understand and work with at the same time that they improve performance, the kinds of changes you make when tuning tend to have the opposite effect.&#160; So you want to start with the simplest, cleanest possible implementation for every part of your app.&#160; Remember: You never know in advance where the tuning will really be needed so wait until you can measure and find out where you have to introduce the hacks rather than putting them in up front.</p>  <p>One example of this principle comes to mind from when I used to work on Excel a number of years ago.&#160; Excel is a product that has been around for a LONG time in software years, and it’s been through a lot of changes.&#160; When I worked on the product it had already been around a long time so there was a lot of legacy.&#160; One aspect of this legacy was a perf optimization they had put into the product back when it was being used on MUCH slower systems than we have today.&#160; There was this code which was used to interpret the core data structures representing cells in the spreadsheet.&#160; The structure itself was highly optimized to make cells take as little memory as possible with the result that the bytes in memory could have one of several meanings so the code would look at a few bits up front to figure out how to interpret the rest.&#160; Not only was this data structure very complicated, but to make matters worse the code for interpreting the structure was repeated all over the code base.&#160; They went to great lengths to make sure it stayed the same everywhere, but nevertheless it was repeated.&#160; They had done this for very good reasons.&#160; At the time it was first done that way, the cost of calling to a single central routine to interpret the structure in all the many places that needed to interact with it was just too high.&#160; If they had to make that jump every time and then return, recalcs would take forever.&#160; The problem was that by the time I was working on the project, there really wasn’t anyone left on the team who knew every place that might have a copy of that code, and when we wanted to introduce a change to the data structure, the cost was astronomical to hunt down every case and fix it and then to test the product like maniacs to make sure we hadn’t missed anything.&#160; At about the same time, a related small project rewrote the core spreadsheet engine from scratch in a small component designed for plugging into web pages.&#160; Since this was written from scratch in an era where computers had sped up considerably, this little component was able to centralize its code for the same task with the result that it had more features in some areas than the big brother excel product for several years until excel could finally be updated.</p>  <p>The moral of the story? Start clean, measure carefully, tune in biggest-bang-for-the-buck order.&#160; Stop tuning as soon as you can.&#160; (Which implies that you need to know just how fast is fast enough.)</p>  <p>- Danny</p>]]></content:encoded>
    </item>
    <item>
      <title>D3: Implementing the WCF Service</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/d3-implementing-the-wcf-service</link>
      <pubDate>Thu, 22 Jul 2010 16:08:50 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/07/22/d3-implementing-the-wcf-service/</guid>
      <description><![CDATA[D3 release 0.1322 is now available.&#160; The work that went into this release is all about building...]]></description>
      <content:encoded><![CDATA[<p><a href="https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=d3&amp;ReleaseId=4664" target="_blank">D3 release 0.1322</a> is now available.&#160; The work that went into this release is all about building out the WCF service which D3 will use as the interface between our mid-tier and the client.&#160; I encountered a grab bag of issues along the way, so here’s a list of tips &amp; tricks as well as random thoughts on the topic of building a WCF service with the EF.</p>  <h3>Authentication</h3>  <p>Somewhere along the way between the last D3 release and this one I had knee surgery.&#160; My recovery was actually pretty quick, but I did end up spending most of a week sitting at home with my knee in the air and a computer on my lap.&#160; I spent a frighteningly large amount of time trying to read up on ways to do authentication using WCF for the D3 project.&#160; One of the best blog posts I found was this:</p>  <p><a href="blogs.infosupport.com/blogs/alexb/archive/2009/10/02/silverlight-3-securing-your-wcf-service-with-a-custom-username-and-password-authentication-mechanism.aspx">blogs.infosupport.com/blogs/alexb/archive/2009/10/02/silverlight-3-securing-your-wcf-service-with-a-custom-username-and-password-authentication-mechanism.aspx</a></p>  <p>The overall approach really seemed to match my general goals in the sense that I want the service to be essentially secure and WCF to handle that security in a relatively transparent way, but I also want to have my own username and password tracking in my EF model (I don’t want to create windows accounts on a domain controller for every user of D3 or something like that).&#160; The issue that drove me nuts is the fact that this approach absolutely requires SSL and at the time I was working on it there really wasn’t a good way to get SSL running (even with just a test cert) inside of VS because Cassini (the mini-webserver built into VS) doesn’t support it.&#160; </p>  <p>Since then the IISExpress project seems to have gotten off the ground, and it may well be the right long-term answer, but after much banging of my head against this particular wall, I decided that for the current interim release I would completely fake all of this in a hacky way that would leave us setup for the right thing but be clear to implement now.&#160; What I did was to add a username and password parameter to every method on the service.&#160; We’ll return to this in a later release and make things more secure and nicer to use.</p>  <h3></h3>  <h3>Service Contract Design</h3>  <p>As I have written in other places (such as this short series of MSDN Magazine Articles: <a href="https://msdn.microsoft.com/en-us/magazine/dd882522.aspx">Anti-Patterns To Avoid In N-Tier Applications</a>, <a href="https://msdn.microsoft.com/en-us/magazine/ee321569.aspx">N-Tier Application Patterns</a> &amp; <a href="https://msdn.microsoft.com/en-us/magazine/ee335715.aspx">N-Tier Apps and the Entity Framework: Building N-Tier Apps with EF4</a>), there are lots of patterns/approaches that can and should be considered when designing a service.&#160; While especially typical intranet line-of-business applications will benefit from the developer productivity and simplicity of an approach like self-tracking entities or RIA services, in this case my goal is to create a game that will run over the internet which means that I’d like to take more control over the contract.&#160; </p>  <p>That led me to the decision that D3’s service should be fairly strictly SOA—at least for the most commonly used methods (issuing commands from the client and retrieving events from the server).&#160; For these two core commands, I decided that the service should neither accept entities as parameters nor return them as results.&#160; We just want the simplest, most basic possible interface, and the result is the following two method signatures:</p>  <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: true; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">[OperationContract, FaultContract(typeof(CommandFault)), ApplyProxyResolver]
void ExecuteCommand(string userName, string password, int playerId, string command);

[OperationContract]
Tuple&lt;IEnumerable&lt;string&gt;, int&gt; GetEventMessages(string userName, string password, 
                                                 int playerId, int lastSeenEventId);</pre>

<p>Ignoring the authentication parameters (which as discussed above should go away in a later release), the first method takes a player ID and a string representing the command that the player wants to execute—typically this will be something like “go north”, “get fancy sword” or “attack purple snorklewacker”.&#160; You’ll notice that this method does not return any results—the only interesting result is if the command is invalid in which case the service will return a CommandFault with the error message.</p>

<p>The way the service returns the results of commands as well as the observable actions of others in the game is through the GetEventMessages method.&#160; It also takes a player ID to determine the perspective of the player from which the events are observed, and it takes the ID of the last event which was returned by a previous call to GetEventMessages.&#160; This method returns a tuple which contains an enumerable of strings which are messages to display on the client plus the ID of the last event which produced a member of that last event of messages.</p>

<p>The idea is that the client will have two asynchronous UI interaction streams going on.&#160; First, at any time the player can type a command and send it to the server, and assuming the command was valid the server will process the command using its business logic and create events representing the result of that command.&#160; The second thing going on is that the client will periodically poll the server for new event messages observed by the player.&#160; The events which produce these messages are both those created as a part of processing this player’s commands as well as events caused by everyone else in the game.&#160; Each time the client calls the GetEventMessages method, it will get back any messages that it hasn’t yet seen plus an ID used in the next call to the method to indicate the “high-water mark” of what it has already seen.</p>

<p>Obviously the GetEventMessages method will be the most frequently called top-level method in the entire application (every client will poll it frequently in order to maintain its UI).&#160; So it will be very perf sensitive.&#160; In subsequent blog posts, I’ll take a look at the topic of tracking and tuning the perf of this method.</p>

<h3>Unit Testing vs. Integration Testing</h3>

<p>If you’ve been reading my blog, you probably know by now that I’m a huge fan of unit testing, and I’ve been putting a lot of work into appropriately unit testing D3 as we go.&#160; This has led to finding and fixing a lot of bugs early on, increasing my confidence in my ability to refactor the project frequently without much risk of introducing new subtle bugs and generally a better overall structure for the project.&#160; Unit testing, though, isn’t everything.&#160; When unit testing we try to isolate small parts of the application so we can focus what we test on a very small piece to make it fast and make sure we know what is responsible when a test fails (so it’s easy to fix).&#160; Sometimes, though, you’ve got to move to a coarser granularity and make sure that you have some tests to verify that all the units go together properly.&#160; </p>

<p>This lesson came home to me in a big way when I decided to write a small integration test that would simulate the most common client / service interactions.&#160; I had been unit testing various parts including directly calling the service method implementations, etc., but I hadn’t yet put it all together and run it through WCF.&#160; The code I wanted to get working wasn’t exactly huge or hugely complicated.&#160; It looked like this:</p>

<pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: true; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">[TestMethod]
public void KickoffScenario_Works()
{
    using (var svc = new PlayerServiceClient(
        new BasicHttpBinding(), 
        new EndpointAddress(&quot;localhost:9999/PlayerService&quot;)))
    {
        svc.CreateUser(&quot;simmdan&quot;, &quot;password&quot;);

        var id = svc.CreatePlayer(&quot;simmdan&quot;, &quot;password&quot;, &quot;joe&quot;);
        svc.GetPlayers(&quot;simmdan&quot;, &quot;password&quot;).Single(p =&gt; p.Id == id);
        var logOnEventId = svc.LogOn(&quot;simmdan&quot;, &quot;password&quot;, id);

        svc.ExecuteCommand(&quot;simmdan&quot;, &quot;password&quot;, id, &quot;get item1&quot;);
        var eventMessages = svc.GetEventMessages(&quot;simmdan&quot;, &quot;password&quot;, id, logOnEventId);

        var message = eventMessages.Item1.Single();
        Assert.AreEqual(&quot;You pick up the Item1.\n&quot;, message);
    }
}</pre>

<p>As I discovered, though, there were a surprising number of issues that came up including some things that were quick and easy to find and some others that were pretty subtle and took a fair amount of hunting.&#160; Along the way, one thing I found very helpful was this post about turning on WCF tracing: <a title="www.c-sharpcorner.com/UploadFile/shivprasadk/6876788978904302009095012AM/68767889789.aspx" href="www.c-sharpcorner.com/UploadFile/shivprasadk/6876788978904302009095012AM/68767889789.aspx">www.c-sharpcorner.com/UploadFile/shivprasadk/6876788978904302009095012AM/68767889789.aspx</a>&#160; Following the directions on that site I added the following XML to the app.config file in D3.Web.Tests:</p>

<pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: true; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">&lt;system.diagnostics&gt;
  &lt;sources&gt;
    &lt;source name=&quot;System.ServiceModel&quot; switchValue=&quot;Information, ActivityTracing&quot;&gt;
      &lt;listeners&gt;
        &lt;add name=&quot;log&quot; type=&quot;System.Diagnostics.XmlWriterTraceListener&quot; initializeData=&quot;c:\Traces.svclog&quot; /&gt;
      &lt;/listeners&gt;
    &lt;/source&gt;
  &lt;/sources&gt;
&lt;/system.diagnostics&gt;</pre>

<h3>Common Issues When Using the EF &amp; WCF Together</h3>

<p>So all of that leads me to the following short list of the most common issues I encounter in my own code or when talking with others specific to using the EF and WCF together.</p>

<ol>
  <li><strong>Not understanding the basic design patterns involved.</strong>&#160; This is by far and away the most common issue.&#160; For this I recommend the magazine articles I referred to in the Service Contract Design section above.&#160; <br />

    <br /><em>(Side Note: It used to be that at least as common as this one was the issue of trying to figure out how EF’s disconnected APIs work—even if you did understand the basic patterns, it could be very hard to implement them correctly with the EF.&#160; Happily, since EF4 shipped the APIs are much easier to use, so this is not so common any more.)</em> 

    <br />&#160; </li>

  <li><strong>Disposing the context before enumerating a query which is returned from the service method.</strong>&#160; This one will get you almost every time.&#160; The general recommended pattern is that each service method should create a context instance in a using block so that it (and its underlying connection) will be disposed properly as soon as possible to free up precious server resources.&#160; If you have a method that returns an enumerable of some type which comes from a query to the database, though, you have to make sure that you fully enumerate that query before the context is disposed.&#160; If you just return the query itself, in a regular CLR method call where the context lifetime is managed some other way, that query would be cast to IEnumerable and the CLR would lazily evaluate it when the results were actually needed.&#160; This is simple and efficient, but in a case where the context is being disposed before the method returns, though, the query results won’t be enumerated until the WCF service’s serializer attempts to process things after the method returns, and in that case the context will first be disposed and then later the query will be enumerated, and it will throw an exception because its connection to the database will be gone.&#160; The fix?&#160; Just call .ToList() on your query before returning. 

    <br />&#160; </li>

  <li><strong>Using POCO without thinking through WCF’s requirements for objects it serializes.</strong>&#160; If you have a WCF service which accepts entities as parameters or returns them as results and you use POCO entities (maybe by using the POCO T4 template or maybe just writing them by hand), then you have to think about WCF’s requirements for its objects because your POCO objects can be almost anything and they may well not be setup properly to work with WCF.&#160; The three ways this comes up most commonly for me are if you have dynamic proxies (either just for lazy loading or for full change tracking), if you have inheritance in your model which the DataContract serializer is unaware of, or if you want to return entire graphs of entities which have cycles.&#160; You can read about the first two issues (and how to address them) here: <a title="blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx" href="https://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx">blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx</a> the key concepts are the DataContractResolver and KnownTypes.&#160; For the last issue, the answer is in the IsReference=true parameter to the DataContract attribute.&#160; This is a feature that was added in .Net 3.5sp1 which makes the DataContract serializer smarter about graphs of related objects.&#160; You can read more about that here: <a title="zamd.net/2008/05/20/datacontract-serializer-and-isreference-property/" href="zamd.net/2008/05/20/datacontract-serializer-and-isreference-property/">zamd.net/2008/05/20/datacontract-serializer-and-isreference-property/</a>&#160; <br />

    <br />One thing to watch out for is that if you have POCO entities with no DataContract attributes, the DataContract serializer will handle them fine up to a point, but if you start having more advanced scenarios like graphs of related entities or dynamic proxies, then the default conventions which the DataContract serializer uses will no longer work, and in that case the answer is to add the attributes.&#160; If you are using the POCO template to generate your entities, for instance, it’s pretty easy to hack these into the T4 template which is what I did for D3.&#160; If you are using the default codegen, then all of these things are taken care of for you automatically, but of course there are other advantages to POCO—it’s all a matter of tradeoffs. </li>
</ol>

<p>OK.&#160; I suppose that’s enough for now.&#160; Happy WCF-service building.</p>

<p>- Danny</p>]]></content:encoded>
    </item>
    <item>
      <title>EntityRoots – An EF Extensibility Exercise</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/entityroots-an-ef-extensibility-exercise</link>
      <pubDate>Sun, 11 Jul 2010 23:21:00 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/07/11/entityroots-an-ef-extensibility-exercise/</guid>
      <description><![CDATA[A little while back I was working on a project for one of the other teams in the Data and Modeling...]]></description>
      <content:encoded><![CDATA[<p>A little while back I was working on a project for one of the other teams in the Data and Modeling Group where we were building an EDM which was not huge but nevertheless had a number of entity sets, and I was trying various strategies to make the model more usable and easier to understand.&nbsp; It occurred to me that one thing which would help would be to remove some of the entity sets which would normally be exposed as ObjectSet properties on the context since it was very unusual to want to reference those sets directly at the top level&mdash;normally all queries and other operations would be initiated using other sets/types.&nbsp; Those types effectively were the &ldquo;roots&rdquo; of interaction with the model.&nbsp; This concept is certainly weaker but somewhat reminiscent of aggregate roots as defined by practitioners of domain driven design.</p>
<p>This is not all that different from some samples we have put together before.&nbsp; Sanjay, for instance, wrote <a target="_blank" href="https://blogs.msdn.com/b/adonet/archive/2008/01/24/customizing-code-generation-in-the-ado-net-entity-designer.aspx">a post</a> quite some time ago showing how to enable an extension which would cause code generation to add an arbitrary attribute to classes or properties.&nbsp; The core capability of adding <a target="_blank" href="https://msdn.microsoft.com/en-us/library/ee473438.aspx">annotations to the conceptual model metadata</a> as described in that post is still the same.&nbsp; Since EF4 has shipped, however, we have some additional options which make the overall task a whole lot easier than it was before.&nbsp; First off, this seemed like a great opportunity to play a bit with the <a target="_blank" href="https://code.msdn.microsoft.com/DesignerExtStartKit">EDM Designer Extension Starter Kit</a> which I had not previously given the time that it deserves.&nbsp; Of course this is a perfect application for T4 templates which make it much easier to customize code generation (I&rsquo;ll not give a link for that since we have talked about it a lot in the past&mdash;you can easily find more info with a quick search), and the VS2010 <a target="_blank" href="https://msdn.microsoft.com/en-us/vstudio/vextend.aspx">VSIX extension format</a> makes it easy to wrap all of this up in a neat package and manage installation and versioning of it.</p>
<p>The final result of this effort is a <a target="_blank" href="www.the-simmons.net/EntityRoots.vsix">VSIX package I call EntityRoots</a> which adds an extension to the designer making it possible to set in the properties for an entity type whether or not it is a root which will then show up as an annotation in the CSDL for that entity type as well as a new T4 code generation item template which looks at that annotation in order to decide whether or not to output an ObjectSet property for that type.&nbsp; In addition to just downloading and using the VSIX package, if you want you can download the <a target="_blank" href="www.the-simmons.net/entityroots.zip">solution I use to build it</a>.</p>
<p>For the designer extension, the exercise was mostly just a matter of removing parts of the starter sample that do other things than just adding a property to entity types and renaming things, so I won&rsquo;t spend much time describing how to do it.&nbsp; You can follow the example and easily adapt it to whatever other scenario you might have.&nbsp; Happily the starter kit also automatically creates a VSIX project to install the extension without much effort.&nbsp; The more interesting part (although also pretty easy) is creating the T4 template, turning it into a VS item template and adding it to the VSIX package.&nbsp; To do that, my first step was to decide that I wanted to base my template on the POCO template.&nbsp; You could, of course, do the same thing with the default code gen template, the self-tracking entities template or any other EF code gen template you might have.&nbsp; </p>
<p>I created a small sample project, added the POCO template, and then just added a few lines to the portion of the template which outputs the ObjectSet properties:</p>
<pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: false; highlight: [1,2,3,4,5,8,9,10,11,12,13,25]; html-script: false; light: true; ruler: false; smart-tabs: true; tab-size: 4; toolbar: false;">        var entityRootsExist = container.BaseEntitySets.OfType&lt;EntitySet&gt;()
            .Where(s =&gt; s.ElementType.MetadataProperties
                .Contains("blogs.msdn.com/dsimmons/schemas/EntityRoot:EntityRoot"))
            .Any();

        foreach (EntitySet entitySet in container.BaseEntitySets.OfType&lt;EntitySet&gt;())
        {
            if (!entityRootsExist || (entitySet.ElementType.MetadataProperties
                .Contains("blogs.msdn.com/dsimmons/schemas/EntityRoot:EntityRoot") &amp;&amp;
                ((XElement) entitySet.ElementType
                .MetadataProperties["blogs.msdn.com/dsimmons/schemas/EntityRoot:EntityRoot"].Value).Value == "True"))
            {
#&gt;

    &lt;#=Accessibility.ForReadOnlyProperty(entitySet)#&gt; ObjectSet&lt;&lt;#=code.Escape(entitySet.ElementType)#&gt;&gt; &lt;#=code.Escape(entitySet)#&gt;
    {
        get { return &lt;#=code.FieldName(entitySet) #&gt;  
                    ?? (&lt;#=code.FieldName(entitySet)#&gt; = CreateObjectSet&lt;&lt;#=code.Escape(entitySet.ElementType)#&gt;&gt;("&lt;#=entitySet.Name#&gt;")); }
    }
    private ObjectSet&lt;&lt;#=code.Escape(entitySet.ElementType)#&gt;&gt; &lt;#=code.FieldName(entitySet)#&gt;;
&lt;#

            }
        }</pre>
<p>Essentially we just check to see if any of the entity sets have the annotation.&nbsp; If so, then we only output an ObjectSet if that set has the annotation and it is set to true.</p>
<p>I then put the modified templates into a project which creates a VS item template (which is just a zip file with the T4 template files plus a vstemplate file giving information about how the templates should be added to the project).&nbsp; In order to make this item template show up in the EF designer&rsquo;s add code generation item dialog, the vstemplate file&rsquo;s name must begin with &ldquo;ADONETArtifactGenerator_&rdquo;.&nbsp; You can read more about VS item templates <a target="_blank" href="https://blogs.msdn.com/b/pedrosilva/archive/2009/06/03/creating-an-item-template-extension-part-1.aspx">here</a>.</p>
<p>- Danny</p>]]></content:encoded>
    </item>
    <item>
      <title>Generating Business Logic “Hooks” for EF4 Entities</title>
      <link>https://docs.microsoft.com/archive/blogs/dsimmons/generating-business-logic-hooks-for-ef4-entities</link>
      <pubDate>Thu, 22 Apr 2010 15:30:18 GMT</pubDate>
      <dc:creator><![CDATA[simmdan]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/dsimmons/2010/04/22/generating-business-logic-hooks-for-ef4-entities/</guid>
      <description><![CDATA[Once again a question in the EF MSDN Forum has prompted a blog post where I can give a more complete...]]></description>
      <content:encoded><![CDATA[<p>Once again a <a href="https://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/e4724ad5-5840-4fca-9424-2cf00bbe1b36/" target="_blank">question in the EF MSDN Forum</a> has prompted a blog post where I can give a more complete answer.&#160; If I understand things correctly, the person asking the question wanted a simple way to add business logic hooks to their entities which would be called whenever they did SaveChanges.&#160; In EF4 we made available the basic building blocks for this kind of thing, but unfortunately it’s not quite as easy and discoverable as it ought to be.</p>  <p>Since I’m stuck sitting at home with my knee elevated as I recover from minor knee surgery, I thought I’d take a little time today to create something which should make this much easier.&#160; You can find the result <a href="www.the-simmons.net/entityhooks.vsix" target="_blank">here</a>.&#160; It’s a visual studio extension file (VSIX) which installs a new T4 item template called EntityHooks.&#160; If you right click on the EF designer background and choose “Add Code Generation Item…”, you should see a new EF EntityHooks Code Generator in the list of templates.&#160; If you choose that option, it will add a new TT file to your project that implements the hooks.</p>  <p>It’s important to realize that this complements whatever other code generation you have going on—it doesn’t replace it.&#160; So if you have already added a code generation item, this will just add another one which generates partial classes that add functionality to your existing partial classes.&#160; Unfortunately, if this is the first code gen artifact you have added to your project, the designer doesn’t realize it doesn’t generate the full entities so it turns off the default codegen, and you will either need to add another codegen artifact or in the properties for your EDMX file set the codegen strategy property from None back to default.</p>  <p>Once this is done you can write your own partial class for any of your entities and implement any or all of the OnAdded, OnModified and OnDeleted partial methods.&#160; These methods will be called whenever an instance of that entity type is in the appropriate state at the time SaveChanges is called, and the call will happen before the framework does any other part of SaveChanges.&#160; So, if your method throws an exception, no save will happen.&#160; This also means that you can modify other entities if you want, or cancel an operation on the particular entity by calling AcceptChanges on its ObjectStateEntry (which is passed as an argument to the partial method).</p>  <p>Here’s a simple example I used to test out the extension.&#160; It’s a hook which takes Customer entities marked for deletion and instead of deleting them just prepends “D:” to the front of the company name as a signal that they are deleted but you still want to keep them around for historical info or something like that:</p>  <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: false; html-script: false; light: true; ruler: false; smart-tabs: true; tab-size: 4; toolbar: false;">public partial class Customer
{
    partial void OnDeleted(System.Data.Objects.ObjectStateEntry entry)
    {
        entry.ChangeState(EntityState.Modified);
        CompanyName = &quot;D:&quot; + CompanyName;
    }
}</pre>

<p>With this class in place, any attempt to delete a Customer will instead become just a modification.</p>

<p>The extension should work with whatever code generation strategy (default, self-tracking, poco, any custom strategy you create) as long as you generate partial classes both for your entities and your context.&#160; You will notice, though, that it introduces a dependency on the EF since the partial methods receive an ObjectStateEntry argument.&#160; if you want this kind of thing with a truly POCO experience, then you would need to create some other type to abstract away this dependency.&#160; For this exercise I just took the shortcut of passing a state entry because it makes it easy to change the state of the entity or perform other actions in a general way.</p>

<p>The way I implemented this was to output an IEntityHooks interface which declares three methods OnAddedHook, OnModifiedHook and OnDeletedHook, plus a partial class for each entity which implements the interface by having those methods call the corresponding OnAdded, OnModified or OnDeleted partial method which the partial class also declares (can’t have a partial method implement an interface method because the compiler will completely optimize away the partial method if no one implements it), and finally a partial class for the context which overrides the SaveChanges virtual method.&#160; The new SaveChanges method retrieves entries from the ObjectStateManager which represent entities in the various states, casts the entities to the interface and then executes the appropriate hook.</p>

<p>If you want more details, install the VSIX file linked above, add the hook template to one of your projects and have a look.&#160; Pretty straight-forward really.&#160; Let me know if you have any questions.</p>

<p>- Danny</p>]]></content:encoded>
    </item>
  </channel>
</rss>