<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Eric Erhardt</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/eric_erhardt/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/eric_erhardt/feed.xml</link>
    <description>I work on the Visual Studio LightSwitch team.  This is a personal blog where I will share tips, tricks and coding information mostly about Visual Studio LightSwitch and anything else that comes to mind.</description>
    <lastBuildDate>Wed, 17 Apr 2019 03:41:27 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Building the LightSwitch Twitter Control</title>
      <link>https://docs.microsoft.com/archive/blogs/eric_erhardt/building-the-lightswitch-twitter-control</link>
      <pubDate>Tue, 25 Feb 2014 16:57:17 GMT</pubDate>
      <dc:creator><![CDATA[Eric Erhardt]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/eric_erhardt/2014/02/25/building-the-lightswitch-twitter-control/</guid>
      <description><![CDATA[This is the second part of my LightSwitch Twitter Feed Control series.&#160; For an introduction to...]]></description>
      <content:encoded><![CDATA[<p>This is the second part of my LightSwitch Twitter Feed Control series.&#160; For an introduction to the control and how it can be used in your applications, please see the <a href="https://blogs.msdn.com/b/eric_erhardt/archive/2014/02/07/integrating-a-twitter-feed-into-a-lightswitch-application.aspx">first part</a> of this series.</p>  <h1>Twitter Embedded Timelines</h1>  <p>Twitter embedded timelines are a great, interactive way to bring tweets into any webpage.&#160; You can read about them on Twitter’s <a href="https://dev.twitter.com/docs/embedded-timelines">developer documentation for embedded timelines</a>.&#160; In the “Creating an Embeddable Timeline” section, you can see that using the embedded timelines involves two pieces:</p>  <ul>   <li>An HTML anchor “&lt;a /&gt;” tag that contains:</li>    <ul>     <li>a special “twitter-timeline” class</li>      <li>a list of “data-“ attributes that provide input into the control, for example the widget id.</li>   </ul>    <li>Some JavaScript that loads the “platform.twitter.com/widgets.js” script</li> </ul>  <p>When the widgets.js script is loaded it looks through your HTML document and will replace any anchor elements that are marked with class=“twitter-timeline” with an iframe.&#160; The iframe hosts the actual timeline.&#160; The HTML inside the iframe is created by Twitter itself, and is outside the scope of this article to explain.&#160; Just know that whatever HTML is created in the iframe will show the specified tweets correctly.</p>  <p>The last piece to understand about Twitter embedded timelines is how to update them once they have already been loaded.&#160; There is a <a href="https://dev.twitter.com/docs/intents">Twitter JavaScript API</a> that will search through your HTML document and convert any anchor tags with the class=”twitter-timeline” into iframes.&#160; This API hangs off the global “twttr” object: twttr.widgets.load().&#160; Optionally, you can pass a DOM element, and only that DOM element and its descendants will be searched.</p>  <p>Now, you should be able to see the strategy that will be used in order to create a reusable Twitter embedded timeline control.&#160; All that is needed is to generate an anchor tag with the appropriate attributes.&#160; Then call the twttr.widgets.load() function, which will turn the anchor into the appropriate iframe with the necessary HTML that shows the Twitter feed.&#160; When data on the screen is changed:&#160; remove the old iframe, put in a new anchor tag with updated “data-“ attributes, and call twttr.widgets.load() again.</p>  <h1>Creating a Custom LightSwitch HTML Control</h1>  <p>One goal I had for my custom control was to be as simple as possible for a LightSwitch developer to use.&#160; Ideally, I wish the LightSwitch developer wouldn’t have to write any code at all to use the control.&#160; However, I couldn’t find a way around needing at least one line of code.&#160; To use it, a developer creates a “Custom Control” in the LightSwitch screen designer, clicks the “Edit Render Code” link and writes:</p>  <pre class="code"><span style="background: white; color: black;">    TwitterControl.render(element, contentItem);</span></pre>
<a href="https://11011.net/software/vspaste"></a>

<p>The TwitterControl’s render function gets passed the two parameters that are passed to the developer’s render function:</p>

<ul>
  <li>element – an HTML DOM element, the &lt;div&gt; where a custom control can add new content</li>

  <li>contentItem – the LightSwitch view model object that provides the context to the control</li>
</ul>

<p>I feel this is an acceptable solution in order to get this reusable control in an application.&#160; Maybe someday custom HTML controls can be registered as extensions to Visual Studio LightSwitch and a developer would see “Twitter Feed” as an option to when adding new controls in the screen designer.&#160; Maybe I am just wishful thinking.</p>

<p>Another goal I had was that any input value could be changed at any time and this would cause the control to update automatically.&#160; The Twitter Feed Control depends on the LightSwitch runtime for its data binding functionality.&#160; This functionality comes from the LightSwitch “ContentItem” objects.&#160; ContentItem objects have a “stringValue” property.&#160; According to <a href="https://blogs.msdn.com/b/lightswitch/archive/2012/12/06/custom-controls-and-data-binding-in-the-lightswitch-html-client-joe-binder.aspx">Joe Binder’s excellent custom control blog</a>, “The string value is a formatted string representation of the underlying property value.”&#160; This is the property the Twitter control is using to get the current values for the “data-“ attributes in the anchor tags.&#160; In order to get notified when this value is changed, there is a ‘dataBind’ function on a ContentItem that registers a callback function to be invoked whenever the value is changed.&#160; So the Twitter control calls </p>

<pre class="code"><span style="background: white; color: black;">    </span><span style="background: white; color: black;">contentItem.dataBind(</span><span style="background: white; color: rgb(163, 21, 21);">'stringValue'</span><span style="background: white; color: black;">, loadFeed);</span></pre>

<p>This tells the LightSwitch runtime to invoke the loadFeed function when the contentItem.stringValue changes.&#160; The loadFeed function gets the current values, rebuilds the anchor tag and calls twttr.widgets.load().</p>

<p>Now here is where a design decision was made.&#160; The Twitter Feed doesn’t just take a single value as an input.&#160; Instead there are 17 possible inputs:</p>

<ul>
  <li>widgetId (required)</li>

  <li>width</li>

  <li>height</li>

  <li>userId</li>

  <li>theme</li>

  <li>etc&#160; (you can get the full list in the <a href="https://blogs.msdn.com/b/eric_erhardt/archive/2014/02/07/integrating-a-twitter-feed-into-a-lightswitch-application.aspx">first part</a> of this series)</li>
</ul>

<p>In a lot of cases, a custom control will display a single value.&#160; Using the built in “Specify the data for the new custom control” dialog</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/0456.image_380772AF.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/0456.image_5F00_380772AF.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/8204.image_thumb_574A1982.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/8204.image_5F00_thumb_5F00_574A1982.png" width="426" height="141" /></a> </p>

<p>to bind to a single value is great when you only need a single value, or all your inputs comes from a single source.&#160; However, I wanted to be flexible enough that the widgetId could come from one place (like a data property directly on the LightSwitch screen) and the userId could come from another (like the “TwitterId” property on an “Author” entity).</p>

<p>In order to be this flexible, I needed a way for the developer to tell the control where to get the data for each input.&#160; Ideally, all 17 inputs would show up in the “Properties” sheet in Visual Studio.&#160; A developer could bind each property to its source as appropriate.&#160; However, since there is no custom control registration for HTML controls, there is no way to customize the Properties sheet when a developer puts one of these controls on his/her screen.</p>

<p>So the technique I devised was to use the same approach as any other “Group” control and inspect the child items under the current control.&#160; If the control finds a child ContentItem with a name that looks like one of its inputs, it uses that child ContentItem for the input value.&#160; Looking at the child ContentItems is pretty simple in JavaScript:</p>

<pre class="code"><span style="background: white; color: black;">    </span><span style="background: white; color: green;">// find the child ContentItem based on a naming convention
    </span><span style="background: white; color: black;">contentItem.children.forEach(</span><span style="background: white; color: blue;">function </span><span style="background: white; color: black;">(e) {
        </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">name = e.name.toLowerCase();

        </span><span style="background: white; color: green;">// inspect the child's name to see if it should be used as an input</span></pre>

<pre class="code"><span style="background: white; color: green;">        </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(name.indexOf(inputName.toLowerCase()) &gt;= 0) {</span></pre>
<a href="https://11011.net/software/vspaste"></a>

<pre class="code"><span style="background: white; color: green;">
        </span><span style="background: white; color: black;">...
    });</span></pre>
<a href="https://11011.net/software/vspaste"></a>

<p>When a ContentItem is found to match an input, it gets its “stringValue” registered for data binding.&#160; When any of the bound values change, the feed is rebuilt.</p>

<p>This technique works great when the input value can be changed dynamically.&#160; However, I found many cases where I wanted to hard code a static value to be passed to the control.&#160; Most often this was the most important input value: the widgetId.&#160; When using a “User Timeline” feed where the user being displayed is dynamic, you only need one widget registered with Twitter.&#160; In that case, you want to just say widgetId = 12345, and not mess around with ContentItems.&#160; Although I could have forced a developer to add a screen data item, and hard code the value during “screen.created” function, this was breaking my first goal of making this control as simple as possible.</p>

<p>In order to support easily providing static information to the control, I added an optional parameter to the TwitterControl.render function: “options”.&#160; This options object can contain any of the 17 input values in properties that have the same name as the input.&#160; So, if a developer wanted to statically define the width and height input values, the code they would write would simply be:</p>

<pre class="code"><span style="background: white; color: black;">    TwitterControl.render(element, contentItem, {
        width: 450,
        height: 600
    });</span></pre>
<a href="https://11011.net/software/vspaste"></a>

<p>Internally to the control, these static input values are placed in “FakeContentItem” objects, which allows the rest of the control code to handle both real ContentItem objects and these static values in the same way.&#160; Sometimes this is the best feature of JavaScript and sometimes it is the worst feature: having such a loose typing system.&#160; In this case, it really worked out great.&#160; I didn’t need to try using the real ContentItem “class” for something it wasn’t designed to do.&#160; But I didn’t need to write an “adapter” layer that could support both real and fake ContentItem objects.&#160; My code just uses two things from a ContentItem: the stringValue property and the dataBind function.&#160; So the fake objects just need to expose these two things, and they act like a real ContentItem to the rest of the system.&#160; Obviously there are plenty of cases where you can “shoot yourself in the foot” doing something like this.&#160; But when used at appropriate times, this really simplifies JavaScript coding.</p>

<p>The rest of the Twitter Feed code is pretty self-explanatory.&#160; It uses jQuery to create an anchor tag, add the necessary attributes, and then calls twttr.widgets.load() on the DOM element passed into the render function.</p>
<a href="https://11011.net/software/vspaste"></a>

<h1>Creating the NuGet Package</h1>

<p>I don’t think I can sing my praises of NuGet loud enough to describe how much value I think it adds to the development community.&#160; It is such a simple, yet powerful platform to share components.&#160; Just having a searchable catalogue of things you can use in your applications adds immeasurable value.&#160; But to be able to install them correctly in your Visual Studio projects with a click of a button seriously blows me away.&#160; It is like the first time I experienced a mobile device’s “app store”.&#160; There was no wizard asking me where to install the app.&#160; There wasn’t an archaic README.txt file explaining how to set the app up.&#160; I just searched for an app, clicked a button and I was using the application in seconds.</p>

<p>So deciding to distribute the Twitter Feed control over NuGet was a non-decision.&#160; It was a given.</p>

<p>However, I had never done it before and I was willing to learn.&#160; <a href="https://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package">NuGet has a great set of documentation</a> explaining how to download NuGet.exe, create a NuGet package, and publish it to a NuGet repository.</p>

<p>A question I have gotten asked is “How do you get the twitterControl.js script registered in the default.htm page automatically?”&#160; This relates back to one of my goals above: making this control as simple as possible to use.&#160; Even adding a &lt;script /&gt; line in the default.htm page seemed like too much work for me.</p>

<p>To get the script file automatically added to the application’s HTML, I used a feature that the LightSwitch HTMLClient project uses itself.&#160; During build time, the LightSwitch HTMLClient project looks for all .js files under the “UserCode” folder.&#160; It creates a generated ‘usercode.js’ file under the hidden “GeneratedArtifacts” folder.&#160; This usercode.js file looks like following:</p>

<pre class="code"><span style="background: white; color: black;">    </span><span style="background: white; color: green;">// Warning: AutoGenerated file, Don't edit.
    </span><span style="background: white; color: black;">document.writeln(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;&lt;script type=\&quot;text/javascript\&quot; src=\&quot;UserCode/twitterControl.js\&quot;&gt;&lt;/script&gt;&quot;</span><span style="background: white; color: black;">);
    document.writeln(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;&lt;script type=\&quot;text/javascript\&quot; src=\&quot;Screens/ViewEmployee.lsml.js\&quot;&gt;&lt;/script&gt;&quot;</span><span style="background: white; color: black;">);
</span></pre>

<p><a href="https://11011.net/software/vspaste"></a>The usercode.js file gets added to the DOM by a file named “generatedAssets.js”.&#160; A script tag for the “Scripts/Generated/generatedAssets.js” file is in the default.htm file.&#160; This is how the Twitter Feed control “automatically” gets registered in the application’s default.htm file.&#160; Since it is placed in the “UserCode” folder of a LightSwtich HTMLClient project, LightSwitch will automatically load this .js file at runtime.</p>

<p>Now, will this feature be supported forever?&#160; I don’t know.&#160; Someday there might not be a “UserCode” folder in a LightSwitch HTMLClient project.&#160; Or, the generatedAssets.js file might not get created anymore.&#160; So, just because I used this “hack” doesn’t mean that it is a publicly supported feature.&#160; It could change in a future release.&#160; However, knowing this, I still decided to take advantage of this functionality in order to support my above goals.</p>

<p>To get the .js file installed to the UserCode folder by NuGet, a NuGet package author just needs to put the .js file under “Content\UserCode” in their NuGet folder structure.&#160; When the NuGet package gets installed on an HTMLClient project, the .js file will automatically be put in the project’s “UserCode” folder.</p>

<p>A drawback to this approach is that I don’t ship both a full version and a minified version of the code.&#160; Adding both to the “UserCode” folder would cause problems because they both would be automatically registered in an app.&#160; I didn’t tackle this problem, but if there is enough feedback (probably like one person asking for it) I would ship a minified version of the Twitter Feed control and then have to address this issue.</p>

<h1>Conclusion</h1>

<p>That’s all for now.&#160; I hope this gives someone insight into how I built the Twitter Feed control.&#160; Feel free to <a href="https://www.nuget.org/packages/Erhardt.LightSwitch.Twitter/">download the code from NuGet</a> and look through it yourself.&#160; Maybe it will give you ideas on how you can build a reusable control for yourself and the rest of the LightSwitch developers out there.</p>

<p>Eric</p>]]></content:encoded>
    </item>
    <item>
      <title>Integrating a Twitter Feed into a LightSwitch Application</title>
      <link>https://docs.microsoft.com/archive/blogs/eric_erhardt/integrating-a-twitter-feed-into-a-lightswitch-application</link>
      <pubDate>Fri, 07 Feb 2014 17:39:23 GMT</pubDate>
      <dc:creator><![CDATA[Eric Erhardt]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/eric_erhardt/2014/02/07/integrating-a-twitter-feed-into-a-lightswitch-application/</guid>
      <description><![CDATA[Twitter is a very popular social networking site.&#160; There are times when you want to integrate...]]></description>
      <content:encoded><![CDATA[<p><a href="https://twitter.com/">Twitter</a> is a very popular social networking site.&#160; There are times when you want to integrate this site into your application.&#160; Some examples I can think of are:</p>  <ul>   <li>Your application maintains a list of people and your users want to see the tweets sent by each of those people.</li>    <li>Your application has a list of items and your users want to see any tweets about those items.</li> </ul>  <p>You get the idea.&#160; Of course, your application could build up hyperlinks to twitter and your users could just click on the link to view this information.&#160; But wouldn’t it be better to display that information directly in your application?</p>  <p>In this article I am going to show you how you can integrate a Twitter feed directly into your Visual Studio LightSwitch application.&#160; I’ve built a reusable Twitter Feed control for LightSwitch HTML projects.&#160; I’ll show you how you can use this control in your application.&#160; This is the first article in a two part series.&#160; In the <a href="https://blogs.msdn.com/b/eric_erhardt/archive/2014/02/25/building-the-lightswitch-twitter-control.aspx">next article</a>, I’ll discuss the internals of the control.&#160; For now, I’ll just show you how you can use the control.</p>  <h1>Get the Control from NuGet</h1>  <p>First, you need to get the control’s JavaScript code from NuGet.&#160; You can do this by using the Package Manager Console from Tools –&gt; NuGet Package Manager –&gt; Package Manager Console.&#160; Set the Default project to your application’s HTMLClient project and type “Install-Package Erhardt.LightSwitch.Twitter”.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/8132.image_09C0A68A.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/8132.image_5F00_09C0A68A.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/5516.image_thumb_1B310762.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/5516.image_5F00_thumb_5F00_1B310762.png" width="560" height="150" /></a> </p>  <p>Or optionally, you can right-click your application’s HTMLClient project, select “Manage NuGet Packages” and search for a package named “LightSwitch Twitter Feed Control”.</p>  <h1>Create a Twitter Widget</h1>  <p>In order to embed a Twitter feed into an HTML page, someone needs to create a Twitter Widget.&#160; This is easily done by</p>  <ul>   <li>Logging into <a href="https://twitter.com">https://twitter.com</a></li>    <li>At the top right click the “cog” icon and select “Settings”</li> </ul>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/6746.image_46E2C3E0.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/6746.image_5F00_46E2C3E0.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/2870.image_thumb_383817FB.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/2870.image_5F00_thumb_5F00_383817FB.png" width="180" height="280" /></a> </p>  <ul>   <li>On the left side, select “Widgets”</li>    <li>Click the “Create new” button</li> </ul>  <p>On the “Create a user widget” page, you are given options on the different types of widgets you can create.&#160; At the top of the page is a link to the <a href="https://dev.twitter.com/docs/embedded-timelines">developer documentation</a> which explains the types of widgets.&#160; The LightSwitch Twitter Feed Control supports all types, but the easiest one to start with is the “User timeline” widget.&#160; Type in the Username of the person whose Tweets you want displayed.&#160; (Don’t worry about which user you pick.&#160; This can be changed later at runtime, as I’ll demonstrate.)&#160; Click the “Create widget” button and you are done.</p>  <p>Now that you have created a widget, you need one very important piece of information – the widget id.&#160; There are two ways to get the widget id:</p>  <ol>   <li>In the address bar of the browser, the URL will look like:&#160; https://twitter.com/settings/widgets/<em><strong>&lt;widgetId&gt;</strong></em>/edit…</li>    <li>At the bottom of the page there is an HTML snippet.&#160; Parse that HTML for the “data-widget-id” attribute.</li> </ol>  <p>Save this widget id, you’ll need it in the next step.</p>  <h1>Put the Twitter Feed Control on a Screen</h1>  <p>Now we can get to the fun part – actually using the control.&#160; In your LightSwtich HTML application, add a new Screen and name it “TwitterScreen”.&#160; In the screen designer:</p>  <ul>   <li>Add a “New Group” control</li>    <ul>     <li>Optionally name it “TwitterFeed”</li>   </ul>    <li>Change the group control from a “Rows Layout” to a “Custom Control”</li>    <li>In the Properties sheet, click the “Edit Render Code” link for your new custom control</li>    <li>Add the following line of code to the render method:</li> </ul>  <pre class="code"><span style="background: white; color: black;">myapp.TwitterScreen.TwitterFeed_render = </span><span style="background: white; color: blue;">function </span><span style="background: white; color: black;">(element, contentItem) {
    TwitterControl.render(element, contentItem, { widgetId: </span><span style="background: white; color: rgb(163, 21, 21);">&quot;123456&quot; </span><span style="background: white; color: black;">});
};</span></pre>

<p>Make sure you replace 123456 with the widget Id number you saved above.</p>

<p>That’s it, now F5 your application and your screen will show all the tweets by the user you specified when you created the widget.</p>

<p>I used the “twitterapi” user name and my screen looks like the following:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/1512.image_28A93B33.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/1512.image_5F00_28A93B33.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/7318.image_thumb_4E9EEB89.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/7318.image_5F00_thumb_5F00_4E9EEB89.png" width="447" height="562" /></a> </p>

<h1>Client Side Customizations</h1>

<p>Now that you have a Twitter feed showing in your application, it is time to customize it.&#160; There are a number of different options on how you can customize it.&#160; See Twitter’s <a href="https://dev.twitter.com/docs/embedded-timelines">developer documentation</a> for all the different options under “Customization Options”.&#160; To start, I’ll show you how to statically customize the feed.&#160; First, let’s change which user is displayed.&#160; To do this, change the line of code in the TwitterFeed_render function to also pass in a “userId”:</p>

<pre class="code"><span style="background: white; color: black;">myapp.TwitterScreen.TwitterFeed_render = </span><span style="background: white; color: blue;">function </span><span style="background: white; color: black;">(element, contentItem) {
    TwitterControl.render(element, contentItem, {
        widgetId: </span><span style="background: white; color: rgb(163, 21, 21);">&quot;123456&quot;</span><span style="background: white; color: black;">,
        userId: </span><span style="background: white; color: rgb(163, 21, 21);">&quot;microsoft&quot;
    </span><span style="background: white; color: black;">});
};</span></pre>

<p>When you F5 your application, you will see that instead of twitterapi’s tweets being shown, you will see tweets by the official Microsoft account.</p>

<p>Now, say you want to change the size of the feed.&#160; You can easily do this by specifying “width” and “height” properties:</p>

<pre class="code"><span style="background: white; color: black;">myapp.TwitterScreen.TwitterFeed_render = </span><span style="background: white; color: blue;">function </span><span style="background: white; color: black;">(element, contentItem) {
    TwitterControl.render(element, contentItem, {
        widgetId: </span><span style="background: white; color: rgb(163, 21, 21);">&quot;123456&quot;</span><span style="background: white; color: black;">,
        userId: </span><span style="background: white; color: rgb(163, 21, 21);">&quot;microsoft&quot;</span><span style="background: white; color: black;">,
        width: 250,
        height: 200
    });
};</span></pre>

<p>Here is a list of the supported properties that can be specified.&#160; See Twitter’s developer documentation on embedded timelines for the explanation of each.&#160; Note that the only required property is the “widgetId” property.</p>

<ul>
  <li>widgetId</li>

  <li>userId</li>

  <li>theme</li>

  <li>linkColor</li>

  <li>width</li>

  <li>height</li>

  <li>chrome</li>

  <li>borderColor</li>

  <li>language</li>

  <li>tweetLimit</li>

  <li>related</li>

  <li>ariaPolite</li>

  <li>showReplies</li>

  <li>customTimelineId</li>

  <li>favoritesId</li>

  <li>listOwnerId</li>

  <li>listId</li>
</ul>

<h1>Binding to Data Dynamically</h1>

<p>I can just hear the conversation happening in your head right now, “This is all well and fine, Eric, but I have a <u>list</u> of people in the application.&#160; Am I supposed to hard code the list of people in my JavaScript code?”&#160; </p>

<p>Luckily the answer is, “Of course not.”&#160; Each one of the properties listed above can also be bound to data in LightSwitch.&#160; So you can dynamically change the feed based on the current data in the running application.</p>

<p>The pattern to do this is simple.&#160; Remember how you first created a “Group” control, and then changed it to a “Custom” control afterwards?&#160; This allows you to add other items underneath your TwitterFeed control.&#160; The TwitterControl.render method looks at all the children directly below the contentItem being passed into it.&#160; If it finds a child whose name contains a property listed above, it binds that property to the data of that child content item.&#160; In other words, it gets the property values from the child content items, and as those values change, the feed is automatically updated with the new data.</p>

<p>So to illustrate this, I have created a simple Table in LightSwitch named “Person”.&#160; A Person has a string Name and a string TwitterUserId.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/2047.image_46A74927.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/2047.image_5F00_46A74927.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/2475.image_thumb_71137A44.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/2475.image_5F00_thumb_5F00_71137A44.png" width="567" height="281" /></a> </p>

<p>I then created a Browse Data Screen on the Person table.&#160; On the Browse screen, I added a “New Group” control, and changed it to a “Custom” control.&#160; I then dragged the “TwitterUserId” property underneath the Custom Control.&#160; This added a new child content item named “People_selectedItem_TwitterUserId” to my TwitterFeed control.&#160; (Notice that the name of the content item contains “UserId” – which means it should bind to the userId property.)</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/7380.image_7E798D4A.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/7380.image_5F00_7E798D4A.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/3580.image_thumb_76EE1DDD.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/3580.image_5F00_thumb_5F00_76EE1DDD.png" width="575" height="302" /></a> </p>

<p>&#160;</p>

<p>And finally, I clicked on the “Edit Render Code” link in the Properties sheet and added the necessary code:</p>

<pre class="code"><span style="background: white; color: black;">myapp.BrowsePeople.TwitterFeed_render = </span><span style="background: white; color: blue;">function </span><span style="background: white; color: black;">(element, contentItem) {
    TwitterControl.render(element, contentItem, { widgetId: </span><span style="background: white; color: rgb(163, 21, 21);">&quot;123456&quot; </span><span style="background: white; color: black;">});
};</span></pre>

<p>Now when I run my application, the currently selected Person’s tweets are shown in the Twitter feed.</p>

<p>&#160;</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/1263.image_441E1769.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/1263.image_5F00_441E1769.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/0317.image_thumb_5C4181C4.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/0317.image_5F00_thumb_5F00_5C4181C4.png" width="523" height="575" /></a> </p>

<p>&#160;</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/2783.image_5449DF62.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/2783.image_5F00_5449DF62.png"><img title="image" style="display: inline;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/0576.image_thumb_0C88567B.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/0576.image_5F00_thumb_5F00_0C88567B.png" width="525" height="581" /></a> </p>

<p></p>

<p>You can mix and match any number of properties – some can be statically defined and some can be bound to data.&#160; To bind the data dynamically, remember that your child content item’s name needs to contain the associated property’s name.&#160; If a property is both statically defined and bound to a content item, the statically defined value always wins.&#160; And remember that you always need to specify a widgetId (either static or bound).</p>

<h1>Conclusion</h1>

<p>I hope you are getting wonderful ideas about how you can use an embedded Twitter feed in your application(s).&#160; If so, I’d love to hear them.&#160; Just drop me a comment explaining how you plan to use this control.&#160; Or leave any other feedback you’d like to give.&#160; It is always appreciated.</p>

<p>&#160;</p>

<p>Eric</p>]]></content:encoded>
    </item>
    <item>
      <title>Updating Records in LightSwitch using Stored Procedures</title>
      <link>https://docs.microsoft.com/archive/blogs/eric_erhardt/updating-records-in-lightswitch-using-stored-procedures</link>
      <pubDate>Thu, 19 Apr 2012 13:05:55 GMT</pubDate>
      <dc:creator><![CDATA[Eric Erhardt]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/eric_erhardt/2012/04/19/updating-records-in-lightswitch-using-stored-procedures/</guid>
      <description><![CDATA[Since stored procedures provide benefits over directly using TSQL commands, a lot of database...]]></description>
      <content:encoded><![CDATA[<p>Since <a href="https://msdn.microsoft.com/en-us/library/aa214299(SQL.80).aspx">stored procedures provide benefits</a> over directly using TSQL commands, a lot of database administrators like to completely hide database tables from applications.&#160; Instead, they will expose a View to read data from the table, and then create stored procedures to allow inserting, updating and deleting records in the table.</p>  <p>The problem is, Visual Studio LightSwitch doesn’t understand how to call stored procedures to insert, update and delete records out of the box.&#160; Thus, any database that only allows stored procedures to update records seems like it is unusable in LightSwitch.</p>  <p>However, LightSwitch can still support these databases, but it just needs a little more work to get it hooked up.&#160; I’ll show you a simple way to manipulate these records in LightSwitch.</p>  <h1>General Approach</h1>  <p>To work with stored procedures in our data model, we are going to use one of my favorite features in LightSwitch: attaching to a custom WCF RIA Service.&#160; The reasons this is one of my favorite features is because it provides you the flexibility you need to bring any data into your application.&#160; If you have data stored in a text file, a spreadsheet, out on the web, or wherever, you can write a WCF RIA Service to expose that data and LightSwitch will seamlessly work with that data.</p>  <p>Overall, the approach will be:</p>  <ul>   <li>Create an Entity Framework .edmx model that can write using the database’s stored procedures </li>    <li>Create a WCF RIA Service that talks to the Entity Framework model</li>    <li>Import the WCF RIA Service into LightSwitch and use it as a normal data source </li> </ul>  <h1>Prerequisites</h1>  <p>The stand alone VS LightSwitch 2011 doesn’t have an Entity Framework designer in it.&#160; In order to build the Entity Framework .edmx model, you will need one of the following:</p>  <ul>   <li><a href="https://www.microsoft.com/visualstudio/11/en-us/downloads">Visual Studio 11 Beta</a> or later </li>    <li><a href="https://www.microsoft.com/visualstudio/en-us/buy">Visual Studio 2010</a> Professional or higher </li>    <li><a href="https://www.microsoft.com/express">Microsoft Visual Studio 2010 Express</a> (I used Visual Web Developer 2010 Express) </li> </ul>  <p>&#160;</p>  <p>I will use the standard <a href="https://www.microsoft.com/downloads/en/details.aspx?FamilyId=06616212-0356-46A0-8DA2-EEBC53A68034">Northwind</a> database for this article.&#160; However, I will add 3 standard stored procedures to it: InsertCustomer, UpdateCustomer, and DeleteCustomer.&#160; These will be simple stored procedures that call INSERT, UPDATE, and DELETE TSQL commands respectively.&#160; See the appendix at the end of this article or the <a href="https://code.msdn.microsoft.com/Updating-Records-in-c88c7997">MSDN Code Gallery: Updating Records in LightSwitch using Stored Procedures</a> sample for this article for the stored procedures’ definitions.</p>  <h1>Entity Framework Model</h1>  <p>First start by creating a new Class Library in Visual Studio (not the stand alone Visual Studio LightSwitch, but Visual Studio Pro or Visual Studio Express), name it “NorthwindService”.&#160; In the Solution Explorer, right-click the “NorthwindService” project and select “Add” –&gt; “New Item…”.&#160; Select “ADO.NET Entity Data Model” and name it “Northwind.edmx”.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/3808.image_5603E81A.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/3808.image_5F00_5603E81A.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/6786.image_thumb_420A5584.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/6786.image_5F00_thumb_5F00_420A5584.png" width="562" height="311" /></a></p>  <p>Select “Generate from database” and enter the connection information to your Northwind database and click “Next”.&#160; Expand the “Tables” node and select “Customers”.&#160; (Note: you could have selected a view if the table isn’t exposed.)&#160;&#160;&#160; Also expand the “Stored Procedures” node and select “InsertCustomer”, “UpdateCustomer”, and “DeleteCustomer”.&#160; (Note these stored procedures don’t exist in a default Northwind database.&#160; They need to be added.&#160; See the <a href="https://code.msdn.microsoft.com/Updating-Records-in-c88c7997">gallery sample</a> for the commands to create them.)&#160; </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/5074.image_04BBC3A0.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/5074.image_5F00_04BBC3A0.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/1106.image_thumb_2E4F8ED3.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/1106.image_5F00_thumb_5F00_2E4F8ED3.png" width="472" height="449" /></a></p>  <p>Click Finish.&#160; This generates you an entity model that contains the Customer entity in it.&#160; We want to insert, update and delete through our stored procedures.&#160; So we need to tell the Entity Framework how to do that.&#160; Right-click the Customer entity and select “Stored Procedure Mapping”.&#160; At the bottom of the screen, you will see a windows with three grid rows:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/4401.image_224D9E9F.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/4401.image_5F00_224D9E9F.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/6557.image_thumb_61AB522F.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/6557.image_5F00_thumb_5F00_61AB522F.png" width="606" height="282" /></a></p>  <p>Click on each of these dropdowns and select the corresponding stored procedure for each action.&#160; The Entity Framework will automatically hook up the parameter mapping if the names match.&#160; If the names don’t match, you can easily map each property to the corresponding parameter.&#160; When you are finished your mapping screen should look like:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/3733.image_79CEBC8A.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/3733.image_5F00_79CEBC8A.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/5556.image_thumb_392C701B.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/5556.image_5F00_thumb_5F00_392C701B.png" width="607" height="283" /></a></p>  <p>You now have an Entity Framework data model that will insert, update and delete records using your stored procedures.</p>  <h1></h1>  <h1>Creating the WCF RIA Service</h1>  <p>The next thing we need is a way for LightSwitch to consume this Entity Framework model.&#160; That is where WCF RIA Services fits into the picture.&#160; There are two ways to create a WCF RIA Service.&#160; If you have a Visual Studio Professional installation, you can right-click the project in the Solution Explorer and “Add” –&gt; “New Item…” and select “Web” –&gt; “Domain Service Class”.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/7026.image_66415CE9.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/7026.image_5F00_66415CE9.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/7028.image_thumb_5E49BA87.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/7028.image_5F00_thumb_5F00_5E49BA87.png" width="596" height="366" /></a></p>  <p>Name the file “NorthwindService.cs” (or .vb) and click “Add”.&#160; In the “Add New Domain Service Class” dialog, accept the defaults and click OK.</p>  <p>If you are working with Visual Studio Express, you can do all the steps the above Add New Item template does by hand:</p>  <ul>   <li>Add References to the following .NET assemblies:      <ul>       <li>System.ComponentModel.DataAnnotations </li>        <li>System.ServiceModel.DomainServices.EntityFramework (Look in %ProgramFiles(x86)%\Microsoft SDKs\RIA Services\v1.0\Libraries\Server if it isn’t under the .Net tab) </li>        <li>System.ServiceModel.DomainServices.Server (Look in %ProgramFiles(x86)%\Microsoft SDKs\RIA Services\v1.0\Libraries\Server if it isn’t under the .Net tab) </li>     </ul>   </li>    <li>Create a new Code File by “Add” –&gt; “New Item…” and select “Code File” named “NorthwindService” </li> </ul>  <p>No matter which route you take, copy and paste the following code into your NorthwindService.cs file:</p>  <p><strong>C#:</strong></p>  <pre class="code"><span style="color: blue">using </span>System.Data;
<span style="color: blue">using </span>System.Linq;
<span style="color: blue">using </span>System.ServiceModel.DomainServices.EntityFramework;
<span style="color: blue">using </span>System.ServiceModel.DomainServices.Server;

<span style="color: blue">namespace </span>NorthwindService
{
    <span style="color: blue">public class </span><span style="color: #2b91af">NorthwindService </span>: <span style="color: #2b91af">LinqToEntitiesDomainService</span>&lt;<span style="color: #2b91af">NorthwindEntities</span>&gt;
    {
        [<span style="color: #2b91af">Query</span>(IsDefault = <span style="color: blue">true</span>)]
        <span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Customer</span>&gt; GetCustomers()
        {
            <span style="color: blue">return this</span>.ObjectContext.Customers;
        }

        <span style="color: blue">public void </span>InsertCustomer(<span style="color: #2b91af">Customer </span>customer)
        {
            <span style="color: blue">if </span>((customer.EntityState != <span style="color: #2b91af">EntityState</span>.Detached))
            {
                <span style="color: blue">this</span>.ObjectContext.ObjectStateManager.
                    ChangeObjectState(customer, <span style="color: #2b91af">EntityState</span>.Added);
            }
            <span style="color: blue">else
            </span>{
                <span style="color: blue">this</span>.ObjectContext.Customers.AddObject(customer);
            }
        }

        <span style="color: blue">public void </span>UpdateCustomer(<span style="color: #2b91af">Customer </span>currentCustomer)
        {
            <span style="color: blue">this</span>.ObjectContext.Customers.AttachAsModified(currentCustomer,
                <span style="color: blue">this</span>.ChangeSet.GetOriginal(currentCustomer));
        }

        <span style="color: blue">public void </span>DeleteCustomer(<span style="color: #2b91af">Customer </span>customer)
        {
            <span style="color: blue">if </span>((customer.EntityState != <span style="color: #2b91af">EntityState</span>.Detached))
            {
                <span style="color: blue">this</span>.ObjectContext.ObjectStateManager.
                    ChangeObjectState(customer, <span style="color: #2b91af">EntityState</span>.Deleted);
            }
            <span style="color: blue">else
            </span>{
                <span style="color: blue">this</span>.ObjectContext.Customers.Attach(customer);
                <span style="color: blue">this</span>.ObjectContext.Customers.DeleteObject(customer);
            }
        }
    }
}</pre>


<p><strong>VB:</strong></p>

<pre class="code"><span style="color: blue">Imports </span>System.ComponentModel.DataAnnotations
<span style="color: blue">Imports </span>System.ServiceModel.DomainServices.EntityFramework
<span style="color: blue">Imports </span>System.ServiceModel.DomainServices.Server

<span style="color: blue">Public Class </span><span style="color: #2b91af">NorthwindService
    </span><span style="color: blue">Inherits </span><span style="color: #2b91af">LinqToEntitiesDomainService</span>(<span style="color: blue">Of </span><span style="color: #2b91af">NorthwindEntities</span>)

    &lt;<span style="color: #2b91af">Query</span>(IsDefault:=<span style="color: blue">True</span>)&gt;
    <span style="color: blue">Public Function </span>GetCustomers() <span style="color: blue">As </span><span style="color: #2b91af">IQueryable</span>(<span style="color: blue">Of </span><span style="color: #2b91af">Customer</span>)
        <span style="color: blue">Return Me</span>.ObjectContext.Customers
    <span style="color: blue">End Function

    Public Sub </span>InsertCustomer(<span style="color: blue">ByVal </span>customer <span style="color: blue">As </span><span style="color: #2b91af">Customer</span>)
        <span style="color: blue">If </span>((customer.EntityState = <span style="color: #2b91af">EntityState</span>.Detached) = <span style="color: blue">False</span>) <span style="color: blue">Then
            Me</span>.ObjectContext.ObjectStateManager.
                ChangeObjectState(customer, <span style="color: #2b91af">EntityState</span>.Added)
        <span style="color: blue">Else
            Me</span>.ObjectContext.Customers.AddObject(customer)
        <span style="color: blue">End If
    End Sub

    Public Sub </span>UpdateCustomer(<span style="color: blue">ByVal </span>currentCustomer <span style="color: blue">As </span><span style="color: #2b91af">Customer</span>)
        <span style="color: blue">Me</span>.ObjectContext.Customers.AttachAsModified(currentCustomer,
            <span style="color: blue">Me</span>.ChangeSet.GetOriginal(currentCustomer))
    <span style="color: blue">End Sub

    Public Sub </span>DeleteCustomer(<span style="color: blue">ByVal </span>customer <span style="color: blue">As </span><span style="color: #2b91af">Customer</span>)
        <span style="color: blue">If </span>((customer.EntityState = <span style="color: #2b91af">EntityState</span>.Detached) = <span style="color: blue">False</span>) <span style="color: blue">Then
            Me</span>.ObjectContext.ObjectStateManager.
                ChangeObjectState(customer, <span style="color: #2b91af">EntityState</span>.Deleted)
        <span style="color: blue">Else
            Me</span>.ObjectContext.Customers.Attach(customer)
            <span style="color: blue">Me</span>.ObjectContext.Customers.DeleteObject(customer)
        <span style="color: blue">End If
    End Sub
End Class

</span></pre>


<p>You now are ready to import this WCF RIA Service into a LightSwitch application.</p>

<h1>LightSwitch Application</h1>

<p>Open Visual Studio LightSwitch and create a new LightSwitch application.&#160; Name it “Northwind”.&#160; Make sure the solution is being shown by opening Tools –&gt; Options. Under “Projects and Solutions” ensure that “Always show solution” is checked. Then, in the Solution Explorer, right-click on the solution and say “Add –&gt; Existing Project”. Navigate to the Class Library you created above. (The Open File Dialog may filter only *.lsproj files. Either typing the full path into the dialog or navigating to the folder, typing * and pressing “Enter” into the File name text box will allow you to select the NorthwindService.csproj/vbproj project.)</p>

<p>Now click the “Attach to external Data Source” link in LightSwitch and select “WCF RIA Service”.&#160; </p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/5047.image_043F6ADE.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/5047.image_5F00_043F6ADE.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/1727.image_thumb_2EAB9BFB.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/1727.image_5F00_thumb_5F00_2EAB9BFB.png" width="473" height="371" /></a></p>

<p>Click Next.&#160; Since the new LightSwitch application doesn’t have any references, no classes are shown.&#160; Click the “Add Reference” button and select the “Projects” tab and double-click the NorthwindService project.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/0741.image_74BC590E.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/0741.image_5F00_74BC590E.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/7178.image_thumb_62075F57.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/7178.image_5F00_thumb_5F00_62075F57.png" width="483" height="397" /></a></p>

<p>Select the “NorthwindService.NorthwindService” class and click Next.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/6102.image_7A2AC9B2.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/6102.image_5F00_7A2AC9B2.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/3858.image_thumb_39887D43.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/3858.image_5F00_thumb_5F00_39887D43.png" width="487" height="382" /></a></p>

<p>Select all the Entities check box and click “Finish”.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/8168.image_71C6F45B.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/8168.image_5F00_71C6F45B.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/7266.image_thumb_3EF6EDE7.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/7266.image_5F00_thumb_5F00_3EF6EDE7.png" width="544" height="427" /></a></p>

<p>One last thing needs to happen in order for you to use this data source.&#160; You need to copy the “NorthwindEntities” connection string from the NorthwindService class library’s App.Config into your application’s web.config.&#160; Open the App.config file and copy the line starting with “&lt;add name=”NorthwindEntities”…”.&#160; Paste this line under the &lt;connectionStrings&gt; node in the LightSwitch web.config.&#160; To open the LightSwitch web.config:</p>

<p>Switch your Solution Explorer to “File View”. </p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/39/73/metablogapi/4762.image_1B983DD1.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-39-73-metablogapi/4762.image_5F00_1B983DD1.png"><img title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/39/73/metablogapi/5857.image_thumb_02303A97.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-39-73-metablogapi/5857.image_5F00_thumb_5F00_02303A97.png" width="322" height="205" /></a> </p>

<p>Then click on the “Show All Files” tool bar button. </p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/39/73/metablogapi/1541.image_0F964D9D.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-39-73-metablogapi/1541.image_5F00_0F964D9D.png"><img title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/39/73/metablogapi/5342.image_thumb_4840F7AA.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-39-73-metablogapi/5342.image_5F00_thumb_5F00_4840F7AA.png" width="324" height="242" /></a> </p>

<p>Under the “ServerGenerated” project (or just “Server” project if you are using Visual Studio 11) you will find the “Web.config” file. </p>

<p>That’s it.&#160; Now you have a fully functioning data source that can insert, update and delete records using stored procedures.&#160; You can create your LightSwitch screens and business logic as usual, and quickly and easily make a functioning application using stored procedures. </p>

<p>I have uploaded a sample application in both C# and VB to the MSDN Code Gallery at <a title="https://code.msdn.microsoft.com/Updating-Records-in-c88c7997" href="https://code.msdn.microsoft.com/Updating-Records-in-c88c7997">https://code.msdn.microsoft.com/Updating-Records-in-c88c7997</a>.</p>

<p>&#160;</p>

<p>Eric</p>

<p>&#160;</p>

<p>p.s. For more information on what the Entity Framework can do with views and stored procedures, see Julie Lerman’s excellent article: <a href="https://msdn.microsoft.com/en-us/data/gg699321">Stored Procedures in the Entity Framework</a></p>

<h1>Stored Procedures Used in This Article</h1>

<pre class="code"><span style="color: blue">CREATE Procedure </span>[dbo]<span style="color: gray">.</span>[InsertCustomer]
    @CustomerID <span style="color: blue">nchar</span><span style="color: gray">(</span>5<span style="color: gray">),
    </span>@CompanyName <span style="color: blue">nvarchar</span><span style="color: gray">(</span>40<span style="color: gray">),
    </span>@ContactName <span style="color: blue">nvarchar</span><span style="color: gray">(</span>30<span style="color: gray">),
    </span>@ContactTitle <span style="color: blue">nvarchar</span><span style="color: gray">(</span>30<span style="color: gray">),
    </span>@Address <span style="color: blue">nvarchar</span><span style="color: gray">(</span>60<span style="color: gray">),
    </span>@City <span style="color: blue">nvarchar</span><span style="color: gray">(</span>15<span style="color: gray">),
    </span>@Region <span style="color: blue">nvarchar</span><span style="color: gray">(</span>15<span style="color: gray">),
    </span>@PostalCode <span style="color: blue">nvarchar</span><span style="color: gray">(</span>10<span style="color: gray">),
    </span>@Country <span style="color: blue">nvarchar</span><span style="color: gray">(</span>15<span style="color: gray">),
    </span>@Phone <span style="color: blue">nvarchar</span><span style="color: gray">(</span>24<span style="color: gray">),
    </span>@Fax <span style="color: blue">nvarchar</span><span style="color: gray">(</span>24<span style="color: gray">)
</span><span style="color: blue">AS
INSERT INTO </span>[Northwind]<span style="color: gray">.</span>[dbo]<span style="color: gray">.</span>[Customers]
           <span style="color: gray">(</span>[CustomerID]
           <span style="color: gray">,</span>[CompanyName]
           <span style="color: gray">,</span>[ContactName]
           <span style="color: gray">,</span>[ContactTitle]
           <span style="color: gray">,</span>[Address]
           <span style="color: gray">,</span>[City]
           <span style="color: gray">,</span>[Region]
           <span style="color: gray">,</span>[PostalCode]
           <span style="color: gray">,</span>[Country]
           <span style="color: gray">,</span>[Phone]
           <span style="color: gray">,</span>[Fax]<span style="color: gray">)
     </span><span style="color: blue">VALUES
           </span><span style="color: gray">(</span>@CustomerID
           <span style="color: gray">,</span>@CompanyName
           <span style="color: gray">,</span>@ContactName
           <span style="color: gray">,</span>@ContactTitle
           <span style="color: gray">,</span>@Address
           <span style="color: gray">,</span>@City
           <span style="color: gray">,</span>@Region
           <span style="color: gray">,</span>@PostalCode
           <span style="color: gray">,</span>@Country
           <span style="color: gray">,</span>@Phone
           <span style="color: gray">,</span>@Fax<span style="color: gray">)</span></pre>

<pre class="code"><span style="color: gray"></span>&#160;</pre>

<pre class="code"><span style="color: blue">CREATE PROCEDURE </span>[dbo]<span style="color: gray">.</span>[UpdateCustomer]
    @CustomerID <span style="color: blue">nchar</span><span style="color: gray">(</span>5<span style="color: gray">),
    </span>@CompanyName <span style="color: blue">nvarchar</span><span style="color: gray">(</span>40<span style="color: gray">),
    </span>@ContactName <span style="color: blue">nvarchar</span><span style="color: gray">(</span>30<span style="color: gray">),
    </span>@ContactTitle <span style="color: blue">nvarchar</span><span style="color: gray">(</span>30<span style="color: gray">),
    </span>@Address <span style="color: blue">nvarchar</span><span style="color: gray">(</span>60<span style="color: gray">),
    </span>@City <span style="color: blue">nvarchar</span><span style="color: gray">(</span>15<span style="color: gray">),
    </span>@Region <span style="color: blue">nvarchar</span><span style="color: gray">(</span>15<span style="color: gray">),
    </span>@PostalCode <span style="color: blue">nvarchar</span><span style="color: gray">(</span>10<span style="color: gray">),
    </span>@Country <span style="color: blue">nvarchar</span><span style="color: gray">(</span>15<span style="color: gray">),
    </span>@Phone <span style="color: blue">nvarchar</span><span style="color: gray">(</span>24<span style="color: gray">),
    </span>@Fax <span style="color: blue">nvarchar</span><span style="color: gray">(</span>24<span style="color: gray">)
</span><span style="color: blue">AS
UPDATE </span>[Northwind]<span style="color: gray">.</span>[dbo]<span style="color: gray">.</span>[Customers]
   <span style="color: blue">SET </span>[CompanyName] <span style="color: gray">= </span>@CompanyName
      <span style="color: gray">,</span>[ContactName] <span style="color: gray">= </span>@ContactName
      <span style="color: gray">,</span>[ContactTitle] <span style="color: gray">= </span>@ContactTitle
      <span style="color: gray">,</span>[Address] <span style="color: gray">= </span>@Address
      <span style="color: gray">,</span>[City] <span style="color: gray">= </span>@City
      <span style="color: gray">,</span>[Region] <span style="color: gray">= </span>@Region
      <span style="color: gray">,</span>[PostalCode] <span style="color: gray">= </span>@PostalCode
      <span style="color: gray">,</span>[Country] <span style="color: gray">= </span>@Country
      <span style="color: gray">,</span>[Phone] <span style="color: gray">= </span>@Phone
      <span style="color: gray">,</span>[Fax] <span style="color: gray">= </span>@Fax
 <span style="color: blue">WHERE </span>CustomerID<span style="color: gray">=</span>@CustomerID </pre>

<pre class="code">&#160;</pre>

<pre class="code"><span style="color: blue">CREATE PROCEDURE </span>[dbo]<span style="color: gray">.</span>[DeleteCustomer]
    @CustomerID <span style="color: blue">nchar</span><span style="color: gray">(</span>5<span style="color: gray">)
</span><span style="color: blue">AS

DELETE FROM </span>[Northwind]<span style="color: gray">.</span>[dbo]<span style="color: gray">.</span>[Customers]
 <span style="color: blue">WHERE </span><a href="mailto:CustomerID=@CustomerID">CustomerID<span style="color: gray">=</span>@CustomerID</a></pre>]]></content:encoded>
    </item>
    <item>
      <title>Executing a Simple Stored Procedure in LightSwitch</title>
      <link>https://docs.microsoft.com/archive/blogs/eric_erhardt/executing-a-simple-stored-procedure-in-lightswitch</link>
      <pubDate>Tue, 17 Apr 2012 09:10:28 GMT</pubDate>
      <dc:creator><![CDATA[Eric Erhardt]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/eric_erhardt/2012/04/17/executing-a-simple-stored-procedure-in-lightswitch/</guid>
      <description><![CDATA[Note: This article applies to LightSwitch in both Visual Studio 2010 and Visual Studio 11. Many...]]></description>
      <content:encoded><![CDATA[<p><em>Note: This article applies to LightSwitch in both Visual Studio 2010 and Visual Studio 11.</em></p> <p>Many existing databases make use of <a href="https://msdn.microsoft.com/en-us/library/aa214299(SQL.80).aspx">stored procedures</a> (or stored procs). There are advantages that stored procedures have over other types of database interaction as listed in MSDN at <a title="https://msdn.microsoft.com/en-us/library/aa214299(SQL.80).aspx" href="https://msdn.microsoft.com/en-us/library/aa214299(SQL.80).aspx">https://msdn.microsoft.com/en-us/library/aa214299(SQL.80).aspx</a>.&nbsp; This makes them very popular with database administrators. So it is very common that existing databases already have stored procedures in them that you will want to take advantage of in your LightSwitch application.</p> <p>This article is the first in a two part series that will show you how to execute a stored procedure in your LightSwitch application. The second part will describe displaying and editing data from a stored procedure in your LightSwitch screens.</p> <h1>Business Scenario</h1> <p>Our customer wants an application that can track employee information. One of the pieces of information is to track if the employee is married or not, which is used for tax purposes. The application should also allow the user to update the marital status (going from single to married, and married to single).</p> <h1>The Database</h1> <p>For this example, we are going to use the <a href="https://msftdbprodsamples.codeplex.com/">AdventureWorks sample database</a>. The AdventureWorks database has a “HumanResources” schema that stores information about your company’s organization, employees, and job candidates. The AdventureWorks database has a stored procedure that allows an application to update an Employee’s personal information. One of these pieces of information is the employee’s marital status. Here is what the stored procedure looks like:</p><pre class="code"><span style="color: blue">CREATE PROCEDURE </span>[HumanResources]<span style="color: gray">.</span>[uspUpdateEmployeePersonalInfo]
@EmployeeID [int]<span style="color: gray">, 
</span>@NationalIDNumber [nvarchar]<span style="color: gray">(</span>15<span style="color: gray">), 
</span>@BirthDate [datetime]<span style="color: gray">, 
</span>@MaritalStatus [nchar]<span style="color: gray">(</span>1<span style="color: gray">), 
</span>@Gender [nchar]<span style="color: gray">(</span>1<span style="color: gray">)
</span><span style="color: blue">WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON</span><span style="color: gray">;
</span><span style="color: blue">UPDATE </span>[HumanResources]<span style="color: gray">.</span>[Employee] 
<span style="color: blue">SET </span>[NationalIDNumber] <span style="color: gray">= </span>@NationalIDNumber 
<span style="color: gray">,</span>[BirthDate] <span style="color: gray">= </span>@BirthDate 
<span style="color: gray">,</span>[MaritalStatus] <span style="color: gray">= </span>@MaritalStatus 
<span style="color: gray">,</span>[Gender] <span style="color: gray">= </span>@Gender 
<span style="color: blue">WHERE </span>[EmployeeID] <span style="color: gray">= </span>@EmployeeID<span style="color: gray">;
</span><span style="color: blue">END</span><span style="color: gray">;
</span></pre>
<p>&nbsp;</p>
<p>This is a very simple stored procedure that takes in five parameters and updates the Employee record with the matching EmployeeID with the other 4 parameters’ values.&nbsp; The specific parameter we are interested in is @MaritalStatus.</p>
<h1></h1>
<h1>The Application</h1>
<p>I’m going to use Visual Studio LightSwitch 2011 for this post, but these same steps will work with Visual Studio 11 Beta or later.</p>
<p>Start by creating a new LightSwitch application named AdventureWorks and click “Attach to external Data Source”.&nbsp; Select Database and enter the connection information to your AdventureWorks database.&nbsp; Select all tables and hit Finish.</p>
<p>Next create a new Search Data Screen and select “AdventureWorksData.Employees” as the data source:</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/3771.image_10EF6F25.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/3771.image_5F00_10EF6F25.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/1526.image_thumb_15F1ACD4.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/1526.image_5F00_thumb_5F00_15F1ACD4.png" width="562" height="402"></a></p>
<p>&nbsp;</p>
<p>We should now have a functioning Employee Search screen.&nbsp; Hit F5 just to make sure everything is hooked up correctly.&nbsp; Your app should look like this:</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/8055.image_09EFBCA0.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/8055.image_5F00_09EFBCA0.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/4010.image_thumb_539E9490.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/4010.image_5F00_thumb_5F00_539E9490.png" width="570" height="331"></a></p>
<p>Notice the far right column “Marital Status” has values ‘M’ and ‘S’.&nbsp; This isn’t the best UI, because my user would like to see “Married” and “Single”.&nbsp; There is a super simple way to do this in LightSwitch.&nbsp; Open the Employees table, and select the MaritalStatus property.&nbsp; Notice in the Properties sheet, there is a link to Choice List…&nbsp; Click that link.</p>
<p>&nbsp;</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/1780.image_2781979F.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/1780.image_5F00_2781979F.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/3240.image_thumb_3FA501FA.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/3240.image_5F00_thumb_5F00_3FA501FA.png" width="580" height="465"></a></p>
<p>This presents you with a Choice List dialog that allows you to map values in the database with values to display on the screen.&nbsp; Fill out the dialog as shown below.&nbsp; (Note that Choice List can be used for other data types, like boolean, integers, etc.)</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/0216.image_50A92FDD.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/0216.image_5F00_50A92FDD.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/5315.image_thumb_491DC070.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/5315.image_5F00_thumb_5F00_491DC070.png" width="336" height="315"></a></p>
<p>Now you can run your application again and see that it correctly displays marital status as a user would expect.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/1185.image_164DB9FC.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/1185.image_5F00_164DB9FC.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/7140.image_thumb_5C5E770F.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/7140.image_5F00_thumb_5F00_5C5E770F.png" width="587" height="317"></a></p>
<h1></h1>
<h1>Invoking the stored procedure</h1>
<p>Now we are ready to write the code to update the employee’s marital status.&nbsp; However, if we are writing code in a button on the screen, the issue we hit is the button code will execute on the client tier.&nbsp; But there is no way to access the database from the client.&nbsp; Instead we need to make a call from the client to get onto the middle tier.&nbsp; A simple way to do this is to take advantage of the save pipeline built into LightSwitch.&nbsp; Whenever a record is inserted, updated or deleted, LightSwitch will invoke methods (Inserting, Updating, Deleting, etc.) on the middle tier.&nbsp; This allows you to write business logic that is ensured to run, no matter what client is making the request.&nbsp; We will use this functionality to invoke our stored procedure.&nbsp; To start, create a new Table and name it “UpdatePersonalInfoOperation”.&nbsp; Add a property for each input parameter of the stored procedure.&nbsp; (Keep in mind that adding a new table will create an intrinsic ApplicationData database that will need to be deployed along with your application.)</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/3583.image_4FDAD5C9.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/3583.image_5F00_4FDAD5C9.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/0385.image_thumb_0021AA80.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/0385.image_5F00_thumb_5F00_0021AA80.png" width="596" height="337"></a></p>
<p>To invoke this ‘operation’, we will create a new UpdatePersonalInfoOperation record, set all the properties and save the record.&nbsp; This will execute the UpdatePersonalInfoOperations_Inserting method on the middle tier.&nbsp; So let’s write our inserting logic by dropping down the Write Code button at the top right of the designer and selecting “UpdatePersonalInfoOperations_Inserting”.&nbsp; Here is the code:</p>
<p><strong>C#:</strong></p><pre class="code"><span style="color: blue">using </span>System.Configuration;
<span style="color: blue">using </span>System.Data;
<span style="color: blue">using </span>System.Data.SqlClient;
    
<span style="color: blue">public partial class </span><span style="color: #2b91af">ApplicationDataService
</span>{
    <span style="color: blue">partial void </span>UpdatePersonalInfoOperations_Inserting(<span style="color: #2b91af">UpdatePersonalInfoOperation </span>entity)
    {
        <span style="color: blue">using </span>(<span style="color: #2b91af">SqlConnection </span>connection = <span style="color: blue">new </span><span style="color: #2b91af">SqlConnection</span>())
        {
            <span style="color: blue">string </span>connectionStringName = <span style="color: blue">this</span>.DataWorkspace.AdventureWorksData.Details.Name;
            connection.ConnectionString =
                <span style="color: #2b91af">ConfigurationManager</span>.ConnectionStrings[connectionStringName].ConnectionString;

            <span style="color: blue">string </span>procedure = <span style="color: #a31515">"HumanResources.uspUpdateEmployeePersonalInfo"</span>;
            <span style="color: blue">using </span>(<span style="color: #2b91af">SqlCommand </span>command = <span style="color: blue">new </span><span style="color: #2b91af">SqlCommand</span>(procedure, connection))
            {
                command.CommandType = <span style="color: #2b91af">CommandType</span>.StoredProcedure;

                command.Parameters.Add(
                    <span style="color: blue">new </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@EmployeeID"</span>, entity.EmployeeID));
                command.Parameters.Add(
                    <span style="color: blue">new </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@NationalIDNumber"</span>, entity.NationalIDNumber));
                command.Parameters.Add(
                    <span style="color: blue">new </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@BirthDate"</span>, entity.BirthDate));
                command.Parameters.Add(
                    <span style="color: blue">new </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@MaritalStatus"</span>, entity.MaritalStatus));
                command.Parameters.Add(
                    <span style="color: blue">new </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@Gender"</span>, entity.Gender));

                connection.Open();
                command.ExecuteNonQuery();
            }
        }

        <span style="color: blue">this</span>.Details.DiscardChanges();
    }
}
</pre><pre class="code"></pre>
<p><strong>VB:</strong></p><pre class="code"><span style="color: blue">Imports </span>System.Configuration
<span style="color: blue">Imports </span>System.Data
<span style="color: blue">Imports </span>System.Data.SqlClient

<span style="color: blue">Namespace </span>LightSwitchApplication
    <span style="color: blue">Public Class </span><span style="color: #2b91af">ApplicationDataService
        </span><span style="color: blue">Private Sub </span>UpdatePersonalInfoOperations_Inserting(entity <span style="color: blue">As </span>UpdatePersonalInfoOperation)
            <span style="color: blue">Using </span>connection = <span style="color: blue">New </span><span style="color: #2b91af">SqlConnection
                </span><span style="color: blue">Dim </span>connectionStringName = <span style="color: blue">Me</span>.DataWorkspace.AdventureWorksData.Details.Name
                connection.ConnectionString =
                    <span style="color: #2b91af">ConfigurationManager</span>.ConnectionStrings(connectionStringName).ConnectionString

                <span style="color: blue">Dim </span>procedure = <span style="color: #a31515">"HumanResources.uspUpdateEmployeePersonalInfo"
                </span><span style="color: blue">Using </span>command = <span style="color: blue">New </span><span style="color: #2b91af">SqlCommand</span>(procedure, connection)
                    command.CommandType = <span style="color: #2b91af">CommandType</span>.StoredProcedure

                    command.Parameters.Add(
                        <span style="color: blue">New </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@EmployeeID"</span>, entity.EmployeeID))
                    command.Parameters.Add(
                        <span style="color: blue">New </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@NationalIDNumber"</span>, entity.NationalIDNumber))
                    command.Parameters.Add(
                        <span style="color: blue">New </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@BirthDate"</span>, entity.BirthDate))
                    command.Parameters.Add(
                        <span style="color: blue">New </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@MaritalStatus"</span>, entity.MaritalStatus))
                    command.Parameters.Add(
                        <span style="color: blue">New </span><span style="color: #2b91af">SqlParameter</span>(<span style="color: #a31515">"@Gender"</span>, entity.Gender))

                    connection.Open()
                    command.ExecuteNonQuery()
                <span style="color: blue">End Using
            End Using

            Me</span>.Details.DiscardChanges()
        <span style="color: blue">End Sub
</span><span style="color: blue">    End Class
End Namespace

</span></pre>
<p>You will have to add a reference from your Server project to the System.Configuration assembly in order to use the ConfigurationManager class.&nbsp; (In the Solution Explorer toolbar, drop down the View toggle and select “File View”.&nbsp; Then right-click the Server project and say “Add Reference”.&nbsp; In the .NET tab, select System.Configuration.)</p>
<p>This code creates a SqlConnection and gets the connection string from the web.config.&nbsp; Note that since we are attached to an external database, the name of the connection string setting is the name of the data source.&nbsp; If we needed to get the connection string of the intrinsic “ApplicationData” database, the name of the setting would be hard-coded to “_IntrinsicData”.</p>
<p>Then, the code creates a SqlCommand object with the required command text, adds the parameter values, and executes the command.&nbsp; Notice the “Using” statements.&nbsp; These statements are important because if an exception occurs while processing this code, we are guaranteed that the connection to the database will get cleaned up in a timely manner.</p>
<p>Finally, the code calls DiscardChanges().&nbsp; This call is needed because we don’t really want to insert an UpdatePersonalInfoOperation record in the intrinsic database.&nbsp; We created and saved the record only as a mechanism to execute code on the middle tier.&nbsp; Saving a record for every call to this operation isn’t necessary.&nbsp; On the other hand, if you want an easy way to log whenever the operation is invoked, then remove the call to DiscardChanges() and the record will be inserted, recording the parameter values to the operation.</p>
<p>Note that you can use any of your favorite frameworks for invoking stored procedures (Entity Framework, Linq To SQL, etc.).&nbsp; I just showed SqlClient since it has been around since .Net 1.0 and pretty simple with nothing else to setup.</p>
<h1>Creating a Button to Call Our Operation</h1>
<p>Now let’s invoke this middle tier operation.&nbsp; We wish to add a button to our application that will mark a Single employee as Married. First, open the SearchEmployees screen and add a new button to the ribbon. At the top of the screen designer, right-click the “Screen Command Bar” content item and select “Add Button…”.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/5383.image_5466D4AD.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/5383.image_5F00_5466D4AD.png"><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/4401.image_thumb_2CC05883.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/4401.image_5F00_thumb_5F00_2CC05883.png" width="598" height="162"></a></p>
<p>Name the button “MarkAsMarried”. We only want this button to be enabled for single employees, so right-click the button and select “Edit CanExecute Code”. Enter in the following code:</p>
<p><strong>C#:</strong></p><pre class="code"><span style="color: blue">partial void </span>MarkAsMarried_CanExecute(<span style="color: blue">ref bool </span>result)
{
    result = <span style="color: blue">this</span>.Employees.SelectedItem != <span style="color: blue">null </span>&amp;&amp; 
        <span style="color: blue">this</span>.Employees.SelectedItem.MaritalStatus == <span style="color: #a31515">"S"</span>;
}
</pre>
<p><strong>VB:</strong></p><pre class="code"><span style="color: blue">Private Sub </span>MarkAsMarried_CanExecute(<span style="color: blue">ByRef </span>result <span style="color: blue">As Boolean</span>)
    result = <span style="color: blue">Me</span>.Employees.SelectedItem <span style="color: blue">IsNot Nothing And
        Me</span>.Employees.SelectedItem.MaritalStatus = <span style="color: #a31515">"S"
</span><span style="color: blue">End Sub
</span></pre>
<p>Back in the screen designer, right-click on the button again and select “Edit Execute Code”.&nbsp; Enter the following code:</p>
<p><strong>C#:</strong></p><pre class="code"><span style="color: blue">partial void </span>MarkAsMarried_Execute()
{
    <span style="color: #2b91af">DataWorkspace </span>dataWorkspace = <span style="color: blue">new </span><span style="color: #2b91af">DataWorkspace</span>();
    <span style="color: #2b91af">Employee </span>employee = <span style="color: blue">this</span>.Employees.SelectedItem;

    <span style="color: #2b91af">UpdatePersonalInfoOperation </span>operation = 
        dataWorkspace.ApplicationData.UpdatePersonalInfoOperations.AddNew();
    operation.EmployeeID = employee.EmployeeID;
    operation.NationalIDNumber = employee.NationalIDNumber;
    operation.BirthDate = employee.BirthDate;
    operation.MaritalStatus = <span style="color: #a31515">"M"</span>;
    operation.Gender = employee.Gender;

    dataWorkspace.ApplicationData.SaveChanges();
}
</pre>
<p><strong>VB:</strong></p><pre class="code"><span style="color: blue">Private Sub </span>MarkAsMarried_Execute()
    <span style="color: blue">Dim </span>dataWorkspace = <span style="color: blue">New </span>DataWorkspace
    <span style="color: blue">Dim </span>employee = <span style="color: blue">Me</span>.Employees.SelectedItem

    <span style="color: blue">Dim </span>operation =
        dataWorkspace.ApplicationData.UpdatePersonalInfoOperations.AddNew()
    operation.EmployeeID = employee.EmployeeID
    operation.NationalIDNumber = employee.NationalIDNumber
    operation.BirthDate = employee.BirthDate
    operation.MaritalStatus = <span style="color: #a31515">"M"
    </span>operation.Gender = employee.Gender

    dataWorkspace.ApplicationData.SaveChanges()
<span style="color: blue">End Sub
</span></pre>
<p>This code first creates a new DataWorkspace.&nbsp; This is needed because we don’t want to modify the current change set on the screen.&nbsp; Instead, we will make an independent change set that only contains the operation entity we wish to invoke.&nbsp; When it is complete, we discard the DataWorkspace and operation entity.</p>
<p>Next, we create a new UpdatePersonalInfoOperation making sure to use our newly created DataWorkspace’s ApplicationData.&nbsp; We grab the currently selected employee’s information and set it on the operation, but we tell the operation to change the MaritalStatus to “M”.&nbsp; Finally, we invoke the operation by calling SaveChanges.</p>
<p>That’s it.&nbsp; Now you can run your application, select a single employee, and click on the Mark As Married button.&nbsp; The stored procedure will be invoked.</p>
<h1>Advanced topics</h1>
<h2>Refreshing your screen</h2>
<p>After invoking the UpdatePersonalInfoOperation, you will notice that your screen is not updated with the latest data – the selected employee still says “Single”.&nbsp; You can fix this by issuing a query in your button code to read the updated results.&nbsp; However, note that this only works if the records being refreshed don’t already have changes made to them.&nbsp; If a record is currently modified, it is not possible to refresh its values by executing a query.</p>
<p>To refresh the screen, you can either call “Employees.Refresh()” or “DataWorkspace.AdventureWorksData.Employees_Single(operation.EmployeeID)” at the end of the button’s Execute method.&nbsp; Note that Employees.Refresh() will refresh all the records where Employees_Single will just refresh the selected item.</p>
<h2>Allowing certain users to update personal information</h2>
<p>A lot of times, you only want specific people to be able to invoke the stored procedure.&nbsp; Using the pattern above, it is very simple to enable this in your application.&nbsp; First, start by creating a Permission by navigating to the Application’s Properties (right-click on the application in the Solution Explorer and select “Properties” or double click the “Properties” item under the application).&nbsp; On the “Access Control” tab, enable authentication and enter a new Permission in the grid.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/0218.image_79080A78.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/0218.image_5F00_79080A78.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/44/62/metablogapi/5483.image_thumb_37F98B14.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-44-62-metablogapi/5483.image_5F00_thumb_5F00_37F98B14.png" width="668" height="269"></a></p>
<p>Now, to only allow users with the UpdatePersonalInfo permission to invoke the stored procedure, we just need to say that only these users are allowed to “insert” the UpdatePersonalInfoOperation records.&nbsp; So go back to the UpdatePersonalInfoOperation entity and drop down “Write Code” –&gt; UpdatePersonalInfoOperations_CanInsert and enter the following code:</p>
<p><strong>C#:</strong></p><pre class="code"><span style="color: blue">partial void </span>UpdatePersonalInfoOperations_CanInsert(<span style="color: blue">ref bool </span>result)
{
    result = <span style="color: blue">this</span>.Application.User.HasPermission(<span style="color: #2b91af">Permissions</span>.UpdatePersonalInfo);
}</pre>
<p><strong>VB:</strong></p><pre class="code"><span style="color: blue">Private Sub </span>UpdatePersonalInfoOperations_CanInsert(<span style="color: blue">ByRef </span>result <span style="color: blue">As Boolean</span>)
    result = <span style="color: blue">Me</span>.Application.User.HasPermission(Permissions.UpdatePersonalInfo)
<span style="color: blue">End Sub

</span></pre>
<p>Now if a user isn’t granted the UpdatePersonalInfo permission, and they try invoking this operation, it will throw a PermissionException and not allow the user to perform the operation.&nbsp; This isn’t a great user experience, so the last thing to change in the application is the button’s CanExecute code to check if the current user has permission to insert UpdatePeronalInfoOperation records.&nbsp; Change your button’s CanExecute method as follows:</p>
<p><strong>C#:</strong></p><pre class="code"><span style="color: blue">partial void </span>MarkAsMarried_CanExecute(<span style="color: blue">ref bool </span>result)
{
    result = <span style="color: blue">this</span>.Employees.SelectedItem != <span style="color: blue">null </span>&amp;&amp;
        <span style="color: blue">this</span>.Employees.SelectedItem.MaritalStatus == <span style="color: #a31515">"S" </span><font style="background-color: #ffff00">&amp;&amp;
        <span style="color: blue">this</span>.DataWorkspace.ApplicationData.UpdatePersonalInfoOperations.CanInsert</font>;
}
</pre>
<p><strong>VB:</strong></p><pre class="code"><span style="color: blue">Private Sub </span>MarkAsMarried_CanExecute(<span style="color: blue">ByRef </span>result <span style="color: blue">As Boolean</span>)
    result = <span style="color: blue">Me</span>.Employees.SelectedItem <span style="color: blue">IsNot Nothing And
        Me</span>.Employees.SelectedItem.MaritalStatus = <span style="color: #a31515">"S" </span><font style="background-color: #ffff00"><span style="color: blue">And
        Me</span>.DataWorkspace.ApplicationData.UpdatePersonalInfoOperations.CanInsert</font>
<span style="color: blue">End Sub

</span></pre>
<p>For more information on securing your LightSwitch applications, be sure to check out this excellent MSDN Magazine article: <a href="https://msdn.microsoft.com/en-us/magazine/hh456409.aspx">Securing Access to LightSwitch Applications</a>.</p>
<h2></h2>
<h2>Passing Result Parameters from a Stored Procedure</h2>
<p>There are plenty of cases where the stored procedure will return values (rows modified, success/failure info, the result of the procedure, etc.).&nbsp; There is a very simple way to pass these values back to the client button code so it can be relayed to the user.&nbsp; Start by adding an extra property to the UpdatePersonalInfoOperation entity.&nbsp; Be sure to uncheck “Required” as this will cause validation to fail because the value won’t be set before calling SaveChanges() to invoke the operation.&nbsp; This extra property will be used as the “result” of the operation.</p>
<p>Inside the UpdatePersonalInfoOperations_Inserting middle tier method, set the record’s “result” property to the value you wish to pass back to the button code.</p>
<p>In the button code, after the call to SaveChanges(), you can get the “result” property off of the UpdatePersonalInfoOperation record, which will now be set to result of the operation.</p>
<p>Note that you can add multiple “result” properties to the UpdatePersonalInfoOperation entity to suit your needs.</p>
<p>Passing result parameters works even if you are calling DiscardChanges() in your UpdatePersonalInfoOperations_Inserting method.&nbsp; The result properties are still serialized to the client on the record.</p>
<h2></h2>
<h1></h1>
<h1>Conclusion</h1>
<p>So you can see, even though LightSwitch doesn’t support executing stored procedures out of the box, there are plenty of hooks that allow you to invoke the stored procedures you need to create your application.</p>
<p>I have uploaded this example application in both VB and C# to the MSDN Code Gallery: <a title="https://code.msdn.microsoft.com/Executing-a-Simple-Stored-b43fe7e5" href="https://code.msdn.microsoft.com/Executing-a-Simple-Stored-b43fe7e5">https://code.msdn.microsoft.com/Executing-a-Simple-Stored-b43fe7e5</a>.</p>
<p>&nbsp;</p>
<p>Eric</p>]]></content:encoded>
    </item>
  </channel>
</rss>