<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Lightswitch for the Enterprise</title>
	<atom:link href="http://blog.pragmaswitch.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://blog.pragmaswitch.com</link>
	<description>Make things as simple as possible but no simpler.</description>
	<lastBuildDate>Mon, 20 May 2013 14:24:14 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Setting up an integrated build and deploy pipeline for LightSwitch applications (part 2)</title>
		<link>http://blog.pragmaswitch.com/?p=1181</link>
		<comments>http://blog.pragmaswitch.com/?p=1181#comments</comments>
		<pubDate>Wed, 15 May 2013 16:51:45 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[TFS]]></category>
		<category><![CDATA[WebDeploy]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1181</guid>
		<description><![CDATA[Introduction We continue in this article the deployment of a LightSwitch application from a build server. Basically, the approach can be used for any other web application type, so not only for LightSwitch applications. I have written already a whole...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We continue in this article the deployment of a LightSwitch application from a build server. Basically, the approach can be used for any other web application type, so not only for LightSwitch applications.</p>
<p>I have written already a whole series of articles in preparation of this one:</p>
<p><a title="Setting up an integrated build and deploy pipeline for LightSwitch applications (part 1)" href="http://blog.pragmaswitch.com/?p=849">SETTING UP AN INTEGRATED BUILD AND DEPLOY PIPELINE FOR LIGHTSWITCH APPLICATIONS (PART 1)</a></p>
<p><a title="Automatically deploy a LightSwitch-ready hosting website with ability to set the https certificate." href="http://blog.pragmaswitch.com/?p=654">AUTOMATICALLY DEPLOY A LIGHTSWITCH-READY HOSTING WEBSITE WITH ABILITY TO SET THE HTTPS CERTIFICATE.</a></p>
<p><a title="Automatically deploy a LightSwitch-ready application pool with ability to set the app pool Identity." href="http://blog.pragmaswitch.com/?p=640">AUTOMATICALLY DEPLOY A LIGHTSWITCH-READY APPLICATION POOL WITH ABILITY TO SET THE APP POOL IDENTITY.</a></p>
<h2>What will we cover in this article?</h2>
<p>The first part of this series explained how we can correctly setup a build server and the build script to get everything built and to get a generated webdeploy package.</p>
<p>In this article we will elaborate a command file that will be eventually called from the build server in order to deploy the site, app pool and application on the target server.</p>
<p>So basically we are skipping, for the time being, the step in between: a dedicated TFS build server process template which will call this command file.</p>
<p>The advantage of this approach is that you can already start with manually executing this script. Anyhow, if things go wrong on the build server, the best approach is to call the script manually so that you can find out if things are going wrong with the process template or with the deployment script.</p>
<h2>The big picture</h2>
<p>Let&#8217;s first depict which servers are involved:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/overall.png"><img class="aligncenter size-full wp-image-1187" alt="overall" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/overall.png" width="1725" height="715" /></a></p>
<h2>What&#8217;s the process?</h2>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/process1.png"><img class="aligncenter size-full wp-image-1192" alt="process" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/process1.png" width="1830" height="1073" /></a></p>
<h2></h2>
<h2>Which files do we need?</h2>
<p>This ones:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/files.png"><img class="aligncenter size-full wp-image-1182" alt="files" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/files.png" width="254" height="185" /></a></p>
<p>&nbsp;</p>
<p>Let&#8217;s explore them one by one:</p>
<ul>
<li><strong>The LightSwitch package</strong> (LSFullDeployment.zip): obviously, we will not need to provide this file, because it will be generated by the build server. It&#8217;s the same file that would be generated by visual studio on your development machine, when you publish your application. Of course we make sure that on the build machine the &#8220;release&#8221; build is built.</li>
<li><strong>TemplateAppPoolPackage: </strong>this is a fixed zip file, you need to create it once. This is explained in detail here: <a title="Automatically deploy a LightSwitch-ready application pool with ability to set the app pool Identity." href="http://blog.pragmaswitch.com/?p=640">AUTOMATICALLY DEPLOY A LIGHTSWITCH-READY APPLICATION POOL WITH ABILITY TO SET THE APP POOL IDENTITY.</a> Since the file is the same for all deployments, it could make sense to store it on the build server in a dedicated place, in such a way the build process template processing could pick it up.</li>
<li><strong>TemplateWebSitePackage</strong>: basically the same logic as for the TemplateAppPoolPackage. If you want to know how to create it: <a title="Automatically deploy a LightSwitch-ready hosting website with ability to set the https certificate." href="http://blog.pragmaswitch.com/?p=654">AUTOMATICALLY DEPLOY A LIGHTSWITCH-READY HOSTING WEBSITE WITH ABILITY TO SET THE HTTPS CERTIFICATE.</a> Since the file is the same for all deployments, it could make sense to store it on the build server in a dedicated place, in such a way the build process template processing could pick it up.</li>
<li><strong>RemoteDeployFromBuildserver.cmd: </strong>this is the main process. This will be the command file that will be called from the build server process template on the build server and it will trigger the remote deployment. We&#8217;ll see later in this article the further details. This command file is also generic for all applications, but you could also decide to keep it specific per project.</li>
<li><strong>RunOnIISServer.cmd: </strong>this is an &#8220;auxiliary&#8221; command file which is called from RemoteDEployFromBuildServer. This file will be triggered from the build server but directly executed on the target IIS server. So, in practice this file is transferred from the build server to the target server and executed there locally. The reason why we need this functionality is because it contains some AppCmd commands which can not be executed remotely. . This command file is also generic for all applications but have as well the option to make it specific per application.</li>
<li><strong>SetWebAppAndAppPoolParameters.xml: </strong>this xml files contains the application and application pool parameters used during deployment. This file should be provided inside your visual studio solution and should be checked-in in TFS. Obviously, this xml file is specific per application.</li>
<li><strong>WebAppDeclareParameters:</strong> there are occasions where you want to have more application specific parameters and corresponding parameter values in your web.config. This mechanism is explained here: <a title="Tweaking the LightSwitch webdeploy package with a simple script." href="http://blog.pragmaswitch.com/?p=120">TWEAKING THE LIGHTSWITCH WEBDEPLOY PACKAGE WITH A SIMPLE SCRIPT</a>. The parameters that you want additionally are stored in WebAppDeclareParameters.xml. The WebAppDeclareParameters file is optional and should be provided inside your visual studio solution and should be checked-in in TFS. Obviously, this xml file is specific per application.</li>
</ul>
<h2> Let&#8217;s explore RemoteDeployFromBuildServer.cmd</h2>
<p>Schematically I goes as follows:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/deployCmd.png"><img class="aligncenter size-full wp-image-1194" alt="deployCmd" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/deployCmd.png" width="1842" height="1073" /></a></p>
<p>And here is the script:</p>
<pre class="brush: shell; gutter: true; first-line: 1">rem ******************************
rem deployment specific parameters
rem ******************************

SET "SiteName=TESTSITE"
SET "AppName=LSFullDeployment"
SET "AppPoolName=TESTAppPool"
SET "SiteHttpsPort=*:123:"
SET "WebAppSourcePackageName=LSFullDeployment.zip"

rem *************************************
rem  server specific params
rem *************************************
SET _httpsSiteCertificate="de0e36943ab3fab29322ee58edebb2e304a48370"
SET _dummyPassword="secret"  
SET "_physicalRootPath=D:\Inetpub\"
SET "_computerName=https://myserver.cloudapp.net:8172/msdeploy.axd,UserName='administrator',Password='mysecretpassword',AuthType='Basic' -allowUntrusted"

rem ********************
rem invariant parameters
rem ********************

SET "_appPoolParametersFile=SetWebAppAndAppPoolParameters.xml"
SET "_webAppParametersFile=SetWebAppAndAppPoolParameters.xml"
SET "_webAppTargetpackageName=DEPLOY.%WebAppSourcePackageName%
SET "_destinationWebSitePhysicalPath=%_physicalRootPath%%SiteName%"

net start msdepsvc

rem ***********************
rem prereqs RUNCOMMAND deletion of web app and website
msdeploy -verb:sync -source:runcommand=RunOnIISServer.cmd -dest:auto,ComputerName=%_computerName%
rem ***********************

rem **********************************************
rem ***************create app pool****************
rem **********************************************

msdeploy.exe -verb:sync -source:package="TemplateAppPoolPackage.zip",encryptpassword=%_dummyPassword% -dest:appPoolConfig=%AppPoolName%,computerName=%_computerName% -setParamFile=%_appPoolParametersFile%

rem **********************create web site*************
rem **************************************************
rem **************************************************

rem todo add  

msdeploy  -verb:sync -source:package="TemplateWebSitePackage.zip",encryptpassword=%_dummyPassword% -dest:appHostConfig=%SiteName%,ComputerName=%_computerName% -replace:objectName=virtualDirectory,targetAttributeName=physicalPath,match="^D:\\inetpub\\PreTemplateWebSite",replace=%_destinationWebSitePhysicalPath%  -setParam:"Application Pool"=%AppPoolName% -replace:objectName=httpCert,targetAttributeName=hash,replace=%_httpsSiteCertificate% -setParam:"Site-https"=%SiteHttpsPort%

rem *********************************************************
rem **********************create web application*************
rem *********************************************************

msdeploy.exe -verb:sync -source:package=%WebAppSourcePackageName% -dest:package=%_webAppTargetPackageName% -declareParamFile="WebAppDeclareParameters.xml"

msdeploy.exe -verb:sync -source:package=%_webAppTargetPackageName%  -dest:auto,ComputerName=%_computerName% -setParamFile=%_webAppParametersFile% -skip:ObjectName=dbFullSql</pre>
<p>&nbsp;</p>
<h2> What&#8217;s in RunOnIISServer.cmd?</h2>
<p>This command will completely destroy the site and the application. That&#8217;s just one approach is it&#8217;s the brute force approach.</p>
<pre class="brush: shell; gutter: false; first-line: 1">rem ******************************
rem deployment specific parameters
rem ******************************

SET "SiteName=TESTSITE"
SET "AppName=LSFullDeployment"

rem *********************************************
rem ***********remove site and app **************
rem *********************************************
SET appPath=

FOR /F %%s in ('c:\windows\System32\inetsrv\appcmd list app /path:/%AppName% /Site.Name:%SiteName%') do SET  appPath=%%s

IF /I "%appPath%" EQU "" (
 echo "Great,nothing to delete... app %SiteName%/%AppName% does't exist"
 ) ELSE (
 c:\windows\System32\inetsrv\appcmd delete app /app.name:%SiteName%/%AppName%
 )

SET siteID=

FOR /F %%s in ('c:\windows\System32\inetsrv\appcmd.exe list sites %SiteName% /text:id') do SET  siteID=%%s

IF /I "%siteid%" EQU "" (
 echo "Great,nothing to delete... Site %SiteName% does't exist"
) ELSE (
 echo SiteName=%SiteName% &amp;&amp; echo SiteID=%SiteID%
c:\windows\System32\inetsrv\appcmd delete site /site.name:%SiteName%
 )</pre>
<p>&nbsp;</p>
<p>As you can see, we use AppCmd, and that can not be execute remotely. That&#8217;s why in the RemoteDeployFromBuildServer.cmd command, we execute this file as a webdeploy &#8216;RunCommand&#8217;. The command file is simply transfered to the IIS server and executed over there locally (where it has access to AppCmd).</p>
<h2>What about the parameter file?</h2>
<p>In fact I put both the web application parameters and the application parameters in the same file:</p>
<pre class="brush: xml; gutter: false; first-line: 1">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;parameters&gt;
  &lt;setParameter name="IisWebApplication" value="TESTSITE/LSFullDeployment" /&gt;
  &lt;setParameter name="ApplicationDataConnectionString" value="Data Source=mydbserver;Initial Catalog=MyDB; Integrated Security=true" /&gt;
  &lt;setParameter name="SecurityDataConnectionString" value="Data Source=mydbserver;Initial Catalog=MyDB; Integrated Security=true" /&gt;
  &lt;setParameter name="MembershipConnectionStringReference" value="_securityData" /&gt;
  &lt;setParameter name="RoleConnectionStringReference" value="_securityData" /&gt;
  &lt;setParameter name="ProfileConnectionStringReference" value="_securityData" /&gt;
  &lt;setParameter name="LoginUrl" value="~/Security.aspx" /&gt;

 &lt;setParameter name="managedPipelineMode" value="Integrated" /&gt; 
 &lt;setParameter name="identityType" value="SpecificUser" /&gt;
 &lt;setParameter name="username" value="MyDomain\MyUser" /&gt; 
 &lt;setParameter name="password" value="MyUserPassword" /&gt; 
 &lt;setParameter name="managedRuntimeVersion" value="v4.0" /&gt;
&lt;/parameters&gt;</pre>
<h2> What should be installed on my build server?</h2>
<p>Visual studio ! Theoretically it is not necessary, but I strongly advice to simply install visual studio and check if everything works fine, e.g. building a LightSwitch project.</p>
<h2>What should be installed on the IIS web server?</h2>
<p>Webdeploy obviously. Also worth mentioning that IIS should be installed as well <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In order to be able to run the msdeploy RunCommand execute the following from the command line:</p>
<p lang="nl-BE">sc privs wmsvc SeChangeNotifyPrivilege/SeImpersonatePrivilege/SeAssignPrimaryTokenPrivilege/SeIncreaseQuotaPrivilege</p>
<p lang="nl-BE">Don&#8217;t forget to restart the WmSvc service afterwards. I can assure you, If you don&#8217;t know the above, it can take weeks&#8230; <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p lang="nl-BE">You will need also an administrator account on the IIS server which you can use in the deployment script.  Remember this line in the deploy command:</p>
<pre>SET "_computerName=https://myserver.cloudapp.net:8172/msdeploy.axd,UserName='administrator',Password='mysecretpassword',AuthType='Basic' -allowUntrusted"</pre>
<p>The userName here is the administrator account on the IIS Server.  The allowUntrusted parameter tells webdeploy to trust also an https connection without a valid certificate.</p>
<p>Finally, port 8172 should be accessible on your IIS server. That&#8217;s the port that webdeploy uses.</p>
<h2>Conclusion</h2>
<p>We have now everything in place to call from the build server in order to trigger a full blown deployment based on parameters.</p>
<p>The above can also be interesting if you don&#8217;t use a build server, but simply want to deploy from the command line. In a next article we&#8217;ll integrate everything in the build process template.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1181</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A new RIA approach in LightSwitch: the ServerApplicationContext RIA Service.</title>
		<link>http://blog.pragmaswitch.com/?p=1159</link>
		<comments>http://blog.pragmaswitch.com/?p=1159#comments</comments>
		<pubDate>Mon, 13 May 2013 14:59:24 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[RiaServices]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1159</guid>
		<description><![CDATA[Introduction Ria Services are in the LightSwitch community very popular.  They are interesting because they allow me to reshape my data in a very elegant way. In this article I&#8217;ll introduce another way to use RIA Services based on the...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Ria Services are in the LightSwitch community very popular.  They are interesting because they allow me to reshape my data in a very elegant way.</p>
<p>In this article I&#8217;ll introduce another way to use RIA Services based on the LightSwitch V3 ServerApplicationContext.</p>
<h2>How are RIA services traditionally used in LightSwitch?</h2>
<p>As you know, when it comes to databases, we distinct in LightSwitch 2 basic approaches</p>
<ul>
<li>the intrinsic database approach or</li>
<li>the external database approach.</li>
</ul>
<p>In contrast to the external approach, when working intrinsically, LightSwitch takes all responsibility for the (intrinsic) database scheme.</p>
<p>Now, what&#8217;s the role of RIA Services in this picture. Basically, a RIA service is a service layer on top of a data layer (in most cases, but not necessarily,  based on entity framework).</p>
<h2>Why are they interesting?</h2>
<p>Also RIA services allows 2 approaches</p>
<ul>
<li>they allow me to <strong>connect to and reshape an  external data source</strong>: this can be really anything, I can even provide an Iqueryable &#8220;connection&#8221; to an xml file.</li>
<li>they allow me to <strong>reshape my existing LightSwitch data model</strong>. Classic example (remember this, I&#8217;ll refer to soon): I have a customer and an order table and I want to have a DTO (data transfer object) composed of CustomerName and OrderCount. This is called an aggregation and this is not out-of-the-box available in LightSwitch. So, thank you RIA services ! I tend to call this type of RIA Service: an <strong>intrinsic database RIA Service.</strong></li>
</ul>
<p>In most cases the second approach, the intrinsic database RIA Service is used. There is a handy Nuget package available for injecting the necessary functionality directly in a .Net 4.0 Class Library:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/ria.png"><img class="aligncenter size-full wp-image-1163" alt="ria" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/ria.png" width="769" height="118" /></a></p>
<h2>What are the drawbacks?</h2>
<h3>The LightSwitch application domain logic is completely ignored.</h3>
<p>Although this might be desired behavior in some very particular cases, the intrisic database RIA service completely ignores your application domain logic.  An example can illustrate: if  in my above &#8220;classic&#8221; example, my customer table has a Filter method (e.g. only show customers from Belgium), this rule will be completely ignored in my intrinsic database RIA Service. In other words when I retrieve the Customer/OrderCount DTO I get all customers, also the ones not living in Belgium.</p>
<h3>Project compilation will trigger hundreds of compilation warning.</h3>
<p>This is a rather annoying side-effect of including the ApplicationDataObjectContext.cs (which is one the LightSwitch auto generated files) into the RIA Service project. This is because the imported types conflict with the existing LightSwitch types.</p>
<p>&nbsp;</p>
<h2>Tata, a new approach: the ServiceApplicationContext RIA Service</h2>
<p>In order to grasp the idea quickly, simply start with generating a classic Ria Service (e.g. based on my nuget package) and update the LightSwitch domain service base class (I prefer to isolate this logic in a base class)</p>
<pre class="brush: csharp; gutter: false; first-line: 1">using System.Linq;
using System.ServiceModel.DomainServices.Server;
using Microsoft.LightSwitch.Server;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Details;

namespace RiaService
{
    public class LightSwitchDomainServiceBase : DomainService
    {
        IServerApplicationContext _context = ServerApplicationContextFactory.Current;

        public IServerApplicationContext Context
        {
            get
            {
                return _context;
            }
        }

        protected override int Count&lt;T&gt;(IQueryable&lt;T&gt; query)
        {
            return query.Count();
        }
        internal IDataServiceQueryable GetEntitySetDataService(string dataSourceName, string entitySetName)
        {
            IDataService dataService 
                = Context.DataWorkspace.Details.Properties[dataSourceName].Value as IDataService;

            var entitySet = dataService.Details.Properties.All()
                .OfType&lt;IDataServiceEntitySetProperty&gt;()
                .Where(n =&gt; n.Name == entitySetName).SingleOrDefault().Value;

            return dataService.Details.Properties[entitySet.Details.Name].Value as IDataServiceQueryable;
        }
    }
}</pre>
<p>Note that you need a binary reference to Microsoft.LightSwitch.dll (from C:\Program Files (x86)\Microsoft SDKs\LightSwitch\v3.0\Client\Microsoft.LightSwitch.dll) and Microsoft.LightSwitch.Server.dll (from C:\Program Files (x86)\Microsoft SDKs\LightSwitch\v3.0\Server\Microsoft.LightSwitch.Server.dll).</p>
<p>So, what&#8217;s different here? Well, in a traditional RIA service we would make a connection to the intrinsic database by reusing the ObjectContext:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public ApplicationData Context 
        {
            get
            {
                if (this.m_context == null)
                {
                    string connString =
                        System.Web.Configuration.WebConfigurationManager
                        .ConnectionStrings["_IntrinsicData"].ConnectionString;
                    EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
                    builder.Metadata =
                        "res://*/ApplicationData.csdl|res://*/ApplicationData.ssdl|res://*/ApplicationData.msl";
                    builder.Provider =
                        "System.Data.SqlClient";
                    builder.ProviderConnectionString = connString;
                      //for a lightSwitch V2 project change in the next line ApplicationData to ApplicationDataObjectContext
                    this.m_context = new ApplicationData(builder.ConnectionString);
                }
                return this.m_context;
            }
        }</pre>
<p>In our new approach we won&#8217;t longer use this! Instead of setting up the ObjectContext we simply setup an IServerApplicationContext ! There is one helper method included in the base class, which allows us to retrieve easily a DataService based on name of an entitySet (e.g. Customers). It&#8217;s not at all mandatory to use this, the base class provides easy access to the ServerApplicationContext via the &#8220;Context&#8221; property. As a result: full access to everything, and much more than in a regular Ria Service !</p>
<p>So far so good. Let&#8217;s create now a domain service based on the above base class for following data transfer object:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">  public class ExampleCustomerDTO
    {
        [Key]
        public int Id { get; set; }
        public string CustomerName { get; set; }
    }</pre>
<p>The domain services goes as follows:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">namespace RiaService.Services
{
    using System.Linq;
    using RiaService.DTO;
    using System.ServiceModel.DomainServices.Server;
    using Microsoft.LightSwitch;

    public class ExampleCustomerDomainService : LightSwitchDomainServiceBase
    {
        [Query(IsDefault = true)]
        public IQueryable&lt;ExampleCustomerDTO&gt; GetCustomersDTO()
        {
            string dataSourceName = "ApplicationData";
            string entitySetName = "Customers";
            var query = this.GetEntitySetDataService(dataSourceName, entitySetName);//as IDataServiceQueryable&lt;Customer&gt;;

            return GetCustomQuery(query);
        }

        private IQueryable&lt;ExampleCustomerDTO&gt; GetCustomQuery(IDataServiceQueryable query)
        {
            var dtoQuery = from IEntityObject c in query
                           select new ExampleCustomerDTO
                           {
                               Id = (int)c.Details.Properties["Id"].Value,
                               CustomerName = c.Details.Properties["LastName"].Value.ToString()
                           };

            return dtoQuery.AsQueryable();
        }
    }
}</pre>
<p>Basically, rather similar to a classic domain service. We split the call in two steps:</p>
<p>first, we retrieve an IDataServiceQueryable based on &#8220;Customers&#8221; and secondly, we massage the data into the ExampleCustomerDTO structure.</p>
<h2>What are the advantages of the ServerApplicationContext RIA approach?</h2>
<ul>
<li> The application domain logic is fully respected: if I have a filter (row level security) on Customers, the ServerApplicationContext RIA Service is fully respect these rules !</li>
<li>Since we don&#8217;t share any generated files with the LightSwitch server project, we got rid of all compilation warnings.</li>
<li>We have full access to the Server application object: this means that we can access also other datasources inside the Application model and do aggregations between data sources !</li>
</ul>
<h2>What&#8217;s the disadvantage?</h2>
<p>We lose strongly typed access when doing the DTO projection:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">var dtoQuery = from IEntityObject c in query
                           select new ExampleCustomerDTO
                           {
                               Id = (int)c.Details.Properties["Id"].Value,
                               CustomerName = c.Details.Properties["LastName"].Value.ToString()
                           };</pre>
<p>As you can see, we access the EntityObject by means of the weakly typed API. This can unfortunately not be solved by adding a file reference to ApplicationDataObjectContext class because the &#8220;EntityObjects&#8221; inside this class are based on material inside LightSwitchApplication.Implementation, which differ from the types present in &#8220;LightSwitchApplication&#8221;.</p>
<p>Nonetheless, I&#8217;m convinced there is a workaround for this.</p>
<h2>Try it out.</h2>
<p>Here is a sample : <a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/RiaServerApplicationContext.zip">RiaServerApplicationContext</a></p>
<p>The sample has both the classic RIA service and the ServerApplicationContext RIA service. It has a customer table with a simple row level security rule (only customers with last name starting with &#8216;x&#8217; are returned). You can easily verify the different behavior and play with it, in case you like it <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Note that my project has still compilation warnings, but that&#8217;s because of the classic RIA service.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1159</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flexible CSV exports over web-api with server side MEF – discover the export formats. (part 4)</title>
		<link>http://blog.pragmaswitch.com/?p=1153</link>
		<comments>http://blog.pragmaswitch.com/?p=1153#comments</comments>
		<pubDate>Wed, 08 May 2013 13:17:59 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Reporting]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1153</guid>
		<description><![CDATA[Introduction Our previous post showed how we can consume an export by clicking a button. But let&#8217;s presume now that we want to present the user with a list of available export formats. Since we use MEF server side that&#8217;s...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Our previous post showed how we can consume an export by clicking a button. But let&#8217;s presume now that we want to present the user with a list of available export formats. Since we use MEF server side that&#8217;s a piece of cake. At the end of the post you&#8217;ll find a zip with the full code.</p>
<p>I&#8217;ll focus here only on the server side. I simply provide the list of potential export formats in a textbox. I leave it to the reader to invent a decent client side implementation <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>My client side implementation goes as follows:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/list.png"><img class="aligncenter size-full wp-image-1154" alt="list" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/list.png" width="313" height="286" /></a></p>
<p>&nbsp;</p>
<p>I provide a list of available exports for the customer type.</p>
<h2>The controller</h2>
<p>In order to keep things a bit clean, I designed a separate controller for this:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Details;
using Microsoft.LightSwitch.Server;
using Microsoft.VisualStudio.ExtensibilityHosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Net.Http;
using System.Net;

namespace LightSwitchApplication.LightSwitchToolbox.ExportModule
{
    public class ExportMetaDataController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage GetProjectors(GetMetaDataCommandParameters requestParams)
        {

            string dataServiceName = requestParams.DataServiceName;
            string entitySetName = requestParams.EntitySetName;
            using (IServerApplicationContext ctx = ServerApplicationContextFactory.CreateContext())
            {
                IDataService dataService =
                    ctx.DataWorkspace.Details.Properties[dataServiceName].Value as IDataService;

                var entitySet = dataService.Details.Properties.All()
                    .OfType&lt;IDataServiceEntitySetProperty&gt;()
                    .Where(n =&gt; n.Name == entitySetName).SingleOrDefault().Value;
                Type entityType = entitySet.Details.EntityType;

                var projections = VsExportProviderService
                    .GetExports&lt;IProjection, IProjectionMetaData&gt;()
                    .Where(p =&gt; p.Metadata.SourceEntityType.Equals(entityType));

                List&lt;string&gt; result = new List&lt;string&gt;();
                foreach (var item in projections)
                {
                    result.Add(item.Metadata.ProjectionName);
                }

                var response = Request.CreateResponse&lt;IEnumerable&lt;string&gt;&gt;(HttpStatusCode.Accepted, result);

                return response;
            }
        }
    }
}</pre>
<p>The VsExportProviderService gives us a list of potential export types (projection strategies) for our source type (in my case here: customers).</p>
<p>This time I get in the request parameters via a dedicated class:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> public class GetMetaDataCommandParameters
    {
        public string DataServiceName { get; set; }
        public string EntitySetName { get; set; }
    }</pre>
<h2>How can we consume this in the SilverLight client?</h2>
<p>I&#8217;m basically using my nuget package for <a title="Start web-api commanding in 30 seconds in LightSwitch via Nuget TheLightSwitchToolbox." href="http://blog.pragmaswitch.com/?p=876">web-api based commanding.</a> By doing so the client side call is very simple is robust:</p>
<p>&nbsp;</p>
<pre class="brush: csharp; gutter: true; first-line: 1">partial void GetProjectors_Execute()
        {
            this.StartWebApiCommand&lt;IEnumerable&lt;string&gt;&gt;("api/ExportMetaData/GetProjectors",
                new GetMetaDataCommandParameters { DataServiceName = "ApplicationData", EntitySetName = "Customers" },
                 (error, response) =&gt;
                 {
                     if (error != null)
                     {
                         this.ShowMessageBox("error = " + error.Message);
                     }
                     else
                     {
                         string text = "Available export formats : " + Environment.NewLine;
                         foreach (var item in response)
                         {
                             text = text + item.ToString() + Environment.NewLine;
                         }
                         this.ShowMessageBox(text);
                     }
                 }
                 );
        }</pre>
<h2>Conclusion</h2>
<p>Here is the full code: <a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/CSVExport.zip">CSVExport</a></p>
<p>The above is a prototype. Of course, what you want is that the user can select a certain export projection strategy by means of a fancy selection screen.  But it should be clear the MEF has also for LightSwitch a very prominent place.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1153</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flexible CSV exports over web-api with server side MEF &#8211; the silverlight and html client. (part 3)</title>
		<link>http://blog.pragmaswitch.com/?p=1148</link>
		<comments>http://blog.pragmaswitch.com/?p=1148#comments</comments>
		<pubDate>Wed, 08 May 2013 13:02:24 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Reporting]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1148</guid>
		<description><![CDATA[Introduction We want to consume now the MEF based export functionality from the silverlight client. Let&#8217;s first take a look at a potential screen where we use it: So, we have a bunch of customer (with orders) data and there...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We want to consume now the MEF based export functionality from the silverlight client.</p>
<p>Let&#8217;s first take a look at a potential screen where we use it:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/screen.png"><img class="aligncenter size-full wp-image-1149" alt="screen" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/screen.png" width="945" height="477" /></a></p>
<p>So, we have a bunch of customer (with orders) data and there are some buttons where we can select a specific export strategy:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/buttons.png"><img class="aligncenter size-full wp-image-1150" alt="buttons" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/buttons.png" width="399" height="88" /></a></p>
<p>&nbsp;</p>
<p>As you can see, we can ask for customers with orders count and customers with full name only.</p>
<h2>How do we initiate the web-api call in the silverlight client?</h2>
<pre class="brush: csharp; gutter: false; first-line: 1"> partial void CustomersWithOrderCountExport_Execute()
        {
            string projectionName = "Customers with order count";
            GetExport(projectionName);
        }

        private static void GetExport(string projectionName)
        {
            Dispatchers.Main.Invoke(() =&gt;
            {
                Uri baseAddress = new Uri(new Uri(System.Windows.Application.Current.Host.Source.AbsoluteUri), "../../");
                string url = baseAddress.AbsoluteUri
                    + @"api/CSVExport/GetExport/?dataServiceName=ApplicationData&amp;entitySetName=Customers&amp;projectionName=" + projectionName;
                HtmlPage.Window.Navigate(new Uri(url), "_blank");
            });
        }</pre>
<p>We only need to provide the dataService (ApplicationData), the entity set type (e.g. Customers) and the name of the specific projection strategy (in my example: Customers with order count).</p>
<h2>How do we initiate the web-api call in the html client?</h2>
<p>Place a button on the browse customer screen, and provide following code:</p>
<pre class="brush: javascript; gutter: false; first-line: 1">myapp.BrowseCustomers.GetCustomersWithOrderCountExport_execute = function (screen) {

    var baseAddress = window.location + "../..";
    window.open(baseAddress +
        "/api/CSVExport/GetExport/?dataServiceName=ApplicationData&amp;entitySetName=Customers&amp;projectionName=Customers with order count");
};</pre>
<h2>Why do I believe this is cool?</h2>
<p>That&#8217;s of course a difficult question to answer for me since I designed the above <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I think it&#8217;s cool because the heavy lifting of export generation is completely moved to the infrastructure level (assumed you can inject it via nuget). Adding a new export type is only a matter of writing the lamdba expression for the projection and providing it a meaningful name.</p>
<p>Furthermore, since we use web-api, the whole infrastructure works both in the html client and the silverlight client !</p>
<p>Enjoy !</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1148</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flexible CSV exports over web-api with server side MEF. (part 2)</title>
		<link>http://blog.pragmaswitch.com/?p=1143</link>
		<comments>http://blog.pragmaswitch.com/?p=1143#comments</comments>
		<pubDate>Wed, 08 May 2013 12:36:35 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Reporting]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1143</guid>
		<description><![CDATA[Introduction In  a previous post I introduced the usage of MEF (the managed extensibility framework) for making the management of the CSV exports more simple. The basic idea is to have an approach with which we can easily create a...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>In  a <a title="Flexible CSV exports over web-api with server side MEF. (part 1)" href="http://blog.pragmaswitch.com/?p=1116">previous pos</a>t I introduced the usage of MEF (the managed extensibility framework) for making the management of the CSV exports more simple.</p>
<p>The basic idea is to have an approach with which we can easily create a new CSV export, by means of the strictest minimum of code :</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public class CustomerCSV3
    {
        public string FullName { get; set; }
        public int OrderCount { get; set; }
    }

    [Export(typeof(IProjection))]
    [ProjectionMetadata(typeof(Customer), "Customers with order count")]

    public class CustomerWithOrderCountProjection : IProjection&lt;Customer, CustomerCSV3&gt;
    {
        public Expression&lt;Func&lt;Customer, CustomerCSV3&gt;&gt; GetProjection()
        {
            return (Customer c) =&gt; new CustomerCSV3 { FullName = c.FirstName + " " + c.LastName, OrderCount = c.Orders.Count() };
        }
    }</pre>
<p>&nbsp;</p>
<p>But, &#8230; making this possible, requires quite a lot of infrastructure code. I&#8217;ll try to make this available via a Nuget package so that it&#8217;s a matter of seconds to have it available.</p>
<p>As you can see in the following view on my solution folder (of the server project), we really need quite some classes and interfaces:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/solutionView.png"><img class="aligncenter size-full wp-image-1144" alt="solutionView" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/05/solutionView.png" width="344" height="401" /></a></p>
<p>&nbsp;</p>
<p>This post is about MEF, where the notation of Exports is key. Now, from a functional perspective this post is also about exporting data. This can be a source of confusion for the reader who is not familiar with MEF. The concept of Export in MEF has really nothing to do with exporting data <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>The CSV Export Controller</h2>
<p>All request for a report will pass through one specific method in a specific controller:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Server;
using Microsoft.VisualStudio.ExtensibilityHosting;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
using Microsoft.LightSwitch.Details;

namespace LightSwitchApplication
{
    public class CSVExportController : ApiController
    {
        private static readonly MediaTypeHeaderValue _mediaType = MediaTypeHeaderValue.Parse("text/csv");

        [HttpGet]
        public HttpResponseMessage GetExport(string dataServiceName, string entitySetName, string projectionName)
        {
            IProjector projector = new Projector();

            IEnumerable data = projector.ApplySourceDataProjection(dataServiceName, entitySetName, projectionName);

            CSVExportEngine exportEngine = new CSVExportEngine();

            StringBuilder stringBuilder = exportEngine.GenerateExport(data);

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            MemoryStream memStream
                = new MemoryStream(encoding.GetBytes(stringBuilder.ToString()));
            HttpResponseMessage fullResponse = Request.CreateResponse(HttpStatusCode.OK);
            fullResponse.Content = new StreamContent(memStream);
            fullResponse.Content.Headers.ContentType = _mediaType;
            string fileName = String.Format("data-{0}.csv", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
            fullResponse.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("fileName") { FileName = fileName };
            return fullResponse;
        }

}</pre>
<p>So, the GetExport method  handles a request for a specific report based on a specific projection name. We apply as good as we can <em>seperation of concerns. </em>The retrieval of the data which we want to export is handled by the <strong>Projector</strong> (based on IProjector) class, whereas the generation of the export itself is done by the <strong>CSVExportEngine</strong>. The rest of the controller method is boilerplate code for pushing the export to the client, simple basic web-api.</p>
<h2>The Projector</h2>
<pre class="brush: csharp; gutter: false; first-line: 1">using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Details;
using Microsoft.LightSwitch.Server;
using Microsoft.VisualStudio.ExtensibilityHosting;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Linq.Expressions;

namespace LightSwitchApplication
{
    public class Projector: IProjector
    {
        public IEnumerable ApplySourceDataProjection(
           string dataServiceName,
           string entitySetName,
           string projectionName)
        {
            using (IServerApplicationContext ctx = ServerApplicationContextFactory.CreateContext())
            {
                IDataService dataService =
                   ctx.DataWorkspace.Details.Properties[dataServiceName].Value as IDataService;
                var entitySet = dataService.Details.Properties.All()
                  .OfType&lt;IDataServiceEntitySetProperty&gt;()
                  .Where(n =&gt; n.Name == entitySetName).SingleOrDefault().Value;
                Type entityType = entitySet.Details.EntityType;

                var projections = VsExportProviderService.GetExports&lt;IProjection, IProjectionMetaData&gt;().Where(m =&gt; m.Metadata.SourceEntityType.Equals(entityType));
                if (projections == null || projections.Count() == 0)
                {
                    throw new ArgumentException("No suitable projection found");
                }

                dynamic projection
                    = projections.Where(c =&gt; c.Metadata.ProjectionName == projectionName)
                    .FirstOrDefault().Value;
                dynamic sourceQuery
                    = dataService.Details.Properties[entitySetName].Value;
                var destinationQuery
                    = DataServiceQueryable.Select(sourceQuery, projection.GetProjection()); //dyn invok
                return destinationQuery.Execute();
            }
        }
    }
}</pre>
<p>The most important part here it the retrieval of the projection strategy based on the projection name:</p>
<pre>VsExportProviderService.GetExports&lt;IProjection, IProjectionMetaData&gt;()</pre>
<p>Since our projections are decorated with the Export attribute, they can be easily resolved. We use also specific meta data attributes:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">
using System;
using System.ComponentModel.Composition;
namespace LightSwitchApplication
{
    
    public interface IProjectionMetaData
    {
        string ProjectionName { get; }
        Type SourceEntityType { get; }
    }


    [MetadataAttribute]
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class ProjectionMetadataAttribute : ExportAttribute
    {
        public ProjectionMetadataAttribute(Type sourceEntityType,string projectionName)
            : base(typeof(IProjectionMetaData))
        {
            ProjectionName = projectionName;
            SourceEntityType = sourceEntityType;
        }

        public string ProjectionName { get; set; }
        public Type SourceEntityType { get; set; }
    }
}</pre>
<p>&nbsp;</p>
<h2>The CSV Export class</h2>
<p>We call in our CSV export controller a specific CSV exporter:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">using System;
using System.Linq;
using System.Text;
using System.Collections;

namespace LightSwitchApplication
{
    public class CSVExportEngine
    {
        public StringBuilder GenerateExport(IEnumerable data)
        {
            StringBuilder stringBuilder = new StringBuilder();
            Type itemType = data.GetType().GetGenericArguments()[0];
            string header = string.Join&lt;string&gt;(",", itemType.GetProperties().Select(x =&gt; x.Name));
            stringBuilder.AppendLine(header);
            foreach (var entity in data)
            {
                var vals = entity.GetType().GetProperties().Select(
                        pi =&gt; new
                        {
                            Value = pi.GetValue(entity, null)
                        });

                string _valueLine = string.Empty;

                foreach (var val in vals)
                {

                    if (val.Value != null)
                    {
                        var _val = val.Value.ToString();

                        //Check if the value contans a comma and place it in quotes if so
                        if (_val.Contains(","))
                            _val = string.Concat("\"", _val, "\"");

                        //Replace any \r or \n special characters from a new line with a space
                        if (_val.Contains("\r"))
                            _val = _val.Replace("\r", " ");
                        if (_val.Contains("\n"))
                            _val = _val.Replace("\n", " ");

                        _valueLine = string.Concat(_valueLine, _val, ",");
                    }
                    else
                    {
                        _valueLine = string.Concat(string.Empty, ",");
                    }
                }

                stringBuilder.AppendLine(_valueLine.TrimEnd(','));
            }
            return stringBuilder;
        }
    }
}</pre>
<p>This class is really nothing special, just a simple CSV generator <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Remember the the projections must derive from:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">using Microsoft.LightSwitch;
using System;
using System.Linq.Expressions;

namespace LightSwitchApplication
{
    public interface IProjection&lt;T, S&gt; : IProjection
        where T : IEntityObject
        where S : class,new()
    {
        Expression&lt;Func&lt;T, S&gt;&gt; GetProjection();
    }
    public interface IProjection
    {
    }

}</pre>
<h2>Conclusion</h2>
<p>This was the difficult part. Now, we only need to consume this functionality from the client: both the silverlight and html client.</p>
<p>I&#8217;ll cover that in a next post !</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1143</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>State driven security in LightSwitch (part 6): client side CanUpdate handling</title>
		<link>http://blog.pragmaswitch.com/?p=1131</link>
		<comments>http://blog.pragmaswitch.com/?p=1131#comments</comments>
		<pubDate>Mon, 29 Apr 2013 07:43:45 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1131</guid>
		<description><![CDATA[Introduction In the previous post, we covered the most technical part in this series on state driven security: the server side logic for state driven can-update handling. To top it all, we still need a client side experience for this. That&#8217;s...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>In the previous post, we covered the most technical part in this series on state driven security: <a title="State driven security in LightSwitch (part 5): let the state dictate what you can update" href="http://blog.pragmaswitch.com/?p=1068">the server side logic for state driven can-update handling.</a> To top it all, we still need a client side experience for this. That&#8217;s the current post. If you grasped the logic behind the previous articles, the current one is very trivial and simple.</p>
<p>This post is the start of a series:</p>
<ul>
<li><a title="State driven security (part1) in LightSwitch" href="http://blog.pragmaswitch.com/?p=961">part 1</a> : introduction</li>
<li><a title="State driven security in LightSwitch (part2): the big picture" href="http://blog.pragmaswitch.com/?p=1045">part 2</a> : the big picture</li>
<li><a title="State driven security in LightSwitch (part 3): server side state transition security" href="http://blog.pragmaswitch.com/?p=1046">part 3</a> : state transition security (server side)</li>
<li><a title="State driven security in LightSwitch (part 4): client side state transition convenience." href="http://blog.pragmaswitch.com/?p=1050">part 4</a> : state transition security (client)</li>
<li><a title="State driven security in LightSwitch (part 5): let the state dictate what you can update" href="http://blog.pragmaswitch.com/?p=1068">part 5</a> : state driven can do update behavior (server side)</li>
<li><a title="State driven security in LightSwitch (part 6): client side CanUpdate handling" href="http://blog.pragmaswitch.com/?p=1131">part 6</a> : this post</li>
</ul>
<h2>The Silverlight client</h2>
<p>Let&#8217;s first indicate clearly what we want to achive: when an entity (or an attached entity in the object graph) is in a functional state where it can not be edited, the controls should adapt accordingly. Following example illustrates the situation where an holiday request body can no longer be updated (except the state) and the attached &#8220;Holiday request management feedback sub entity can be edited.</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/silverlight11.png"><img class="aligncenter size-full wp-image-1134" alt="silverlight1" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/silverlight11.png" width="1033" height="454" /></a></p>
<p>&nbsp;</p>
<p>The code for doing is, is pretty simple, just call the private method SetHolidayRequestVisibility in the HolidayRequestDetail_InitializeDataWorkspace method:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">private void SetHolidayRequestVisibility(string stateValue)
        {
            bool isReadOnly = !StateManagement.CanUpdateEntityInState(CurrentHolidayRequest, OriginalValueOfRequestState);
            this.FindControl("Description").IsReadOnly = isReadOnly;
            this.FindControl("Requestor").IsReadOnly = isReadOnly;
            if (CurrentHolidayRequest.HolidayRequestManagementFeedback != null)
            {
                isReadOnly = !StateManagement.CanUpdateEntityInState(
                    CurrentHolidayRequest.HolidayRequestManagementFeedback,
                    OriginalValueOfRequestState);
                this.FindControl("CurrentHolidayRequest_HolidayRequestManagementFeedback").IsReadOnly = isReadOnly;
            }
        }</pre>
<p>The reason why it&#8217;s so simple, is because the StateManagement class can be linked as a file reference into the Silverlight assembly. That&#8217;s a technique that -unfortunately- we can&#8217;t apply in the html5 client.</p>
<h2>The html5 client</h2>
<p>We are lucky, the html5 implementation of the above is quite similar to a recent post of Beth Massi <a href="http://blogs.msdn.com/b/bethmassi/archive/2013/04/17/using-lightswitch-serverapplicationcontext-and-webapi-to-get-user-permissions.aspx">Using LightSwitch ServerApplicationContext and WebAPI to Get User Permissions</a></p>
<p>We simply need to expose the StateManagement.CanUpdateEntityInState method via a web-api interface.  I presume you can do this yourself <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>&nbsp;</p>
<h2>How can I get the infrastructure code?</h2>
<p>Via nuget. Open the nuget management console:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/nuget.png"><img class="aligncenter size-full wp-image-1135" alt="nuget" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/nuget.png" width="962" height="124" /></a></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1131</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Flexible CSV exports over web-api with server side MEF. (part 1)</title>
		<link>http://blog.pragmaswitch.com/?p=1116</link>
		<comments>http://blog.pragmaswitch.com/?p=1116#comments</comments>
		<pubDate>Wed, 24 Apr 2013 13:06:21 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Reporting]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1116</guid>
		<description><![CDATA[Introduction Since the introduction of LightSwitch V3, the amount of plumbing options we have in LightSwitch increased drastically. Especially when using it in combination with proven technologies like web-api and the new ServerApplicationContext in LightSwitch V3. Today, we&#8217;ll add another...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Since the introduction of LightSwitch V3, the amount of plumbing options we have in LightSwitch increased drastically. Especially when using it in combination with proven technologies like web-api and the new ServerApplicationContext in LightSwitch V3.</p>
<p>Today, we&#8217;ll add another technology: <a title="Managed Extensibility Framework (MEF)" href="http://msdn.microsoft.com/en-us/library/dd460648.aspx">the managed extensibility  framework</a>. Not just for the sake of the technology, but for solving a real live problem: flexible exports.</p>
<h2>What do I mean with flexible exports</h2>
<p>Let&#8217;s first clearly define that an export is not the same as a report. An export simply retrieves data from the server and presents it to the user in the form of a kind of tabular structure which can be opened by the user in Excel (the most portable format for this is CSV, comma separated value).</p>
<p>The most simple export is the one that available out of the box in LightSwitch. This export is ok for simple usage, but in most cases the user would like to have a richer set of potential export definitions she can select from.</p>
<p>So, wouldn&#8217;t it be nice that instead of a simple Customer export, the user could have some more options when she clicks the export button:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/selectionscreen.png"><img class="aligncenter size-full wp-image-1117" alt="selectionscreen" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/selectionscreen.png" width="278" height="175" /></a></p>
<p>Obviously, we want to reuse the approach via web-api  I documented over here: <a title="Reporting with Web-Api in LightSwitch" href="http://blog.pragmaswitch.com/?p=773">reporting via web-api</a>.</p>
<p>In this post I want to focus on an elegant way to define the different export definitions.</p>
<h2>It&#8217;s all about projection strategies</h2>
<p>In order to come up with a good approach, let&#8217;s first focus on what different between the above (potentially over simplified) export definitions.</p>
<blockquote><p><strong>Basically, the three definitions are just variations on the applied &#8220;projection strategy&#8221;.  A projection is a prominent &#8220;Linq&#8221; concept. When you do a select new (with is the core element in our web-api based exporting solution I referred to above) you are applying a projection.</strong></p></blockquote>
<p>&nbsp;</p>
<p>An example can clarify:</p>
<pre class="brush: csharp; gutter: true; first-line: 1">    {
        public Expression&lt;Func&lt;Customer, CustomerCSV1&gt;&gt; GetProjection()
        {
            return (Customer c) =&gt; new CustomerCSV1 { FullName = c.FirstName + " " + c.LastName };
        }
    }</pre>
<p>The above projection goes together with following POCO class.</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> public class CustomerCSV1
    {
        public string FullName { get; set; }
    }</pre>
<p>So, our customer entity is projected into a new POCO type (CustomerCSV1) which massages the data into a structure with only a FullName field (which is a concatenation of FirstName and LastName). In mathematical terms the Customer class is the &#8220;Source&#8221; and the CustomerCSV1 class is the &#8220;domain&#8221; (the destination if you want). The data are projected from source to domain.</p>
<p>That&#8217;s easy. Another projection can incorporate the underlying orders of the customer:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public Expression&lt;Func&lt;Customer, CustomerCSV3&gt;&gt; GetProjection()
        {
            return (Customer c) =&gt; new CustomerCSV3 { FullName= c.FirstName + " " + c.LastName, OrderCount = c.Orders.Count()};
        }</pre>
<p>Based on following domain poco:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public class CustomerCSV3
    {
        public string FullName { get; set; }
        public int OrderCount { get; set; }
    }</pre>
<blockquote><p><strong>It is clear that even the most flexible export solution can not avoid that the above projection strategy and the corresponding POCO have to be created in code. But our goal is that this is the only thing we need to do: new projection strategies should be resolved by the system automatically !</strong></p></blockquote>
<h2> That&#8217;s why we need the Managed Extensibility framework.</h2>
<p>Sometimes people compare MEF with an IOC (inversion of control) container, but that&#8217;s not completely accurate. MEF brings in a way imports and exports (euh&#8230; not data exports as above, but code functionality of course)  together by means of attribute decoration. But, I said already too much, no MEF tutorial here. Use your browser.</p>
<p>Adding a new strategy to our CSV export machinery would look as follows:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">  [Export(typeof(IProjection))]
  [ExportProjection( "First Name only")]

    public class CustomerFirstNameProjection : IProjection&lt;Customer, CustomerCSV2&gt;
    {
        public Expression&lt;Func&lt;Customer, CustomerCSV2&gt;&gt; GetProjection()
        {
            return (Customer c) =&gt; new CustomerCSV2 { FirstName = c.FirstName };
        }
    }</pre>
<p>As you can see we decorated the CustomerFirstNameProjection with two attributes:</p>
<ul>
<li><strong>[Export(typeof(IProjection))]</strong> : tells that we want to include this strategy in our export repository. By doing so, our export selection window is automatically updated with another export template !</li>
<li><strong>[ExportProjection("First Name only")]: </strong>we want to provide the export strategy a meaningful name.</li>
</ul>
<p>&nbsp;</p>
<h2>What&#8217;s next?</h2>
<p>The implementation of the above. Be prepared for pretty technical code, but remember it&#8217;s infrastructure code, the goals is writing less code when using it !</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1116</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>State driven security in LightSwitch (part 5): let the state dictate what you can update</title>
		<link>http://blog.pragmaswitch.com/?p=1068</link>
		<comments>http://blog.pragmaswitch.com/?p=1068#comments</comments>
		<pubDate>Thu, 18 Apr 2013 18:47:07 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1068</guid>
		<description><![CDATA[Introduction We have so far a decent way to protect state transitions and a comfortable client side implementation. Now, we will cover another important facet of state driven security: the ability to update entities based on the current state. Why...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We have so far a decent way to protect state transitions and a comfortable client side implementation. Now, we will cover another important facet of state driven security: the ability to update entities based on the current state.</p>
<h2>Why do we need some new base infrastructure for this?</h2>
<p>It is tempting to think that we can use for this the standard LightSwitch Can_&lt;CRUD&gt; methods like the one here for update:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> partial void HolidayRequests_CanUpdate(ref bool result)
        {

        }</pre>
<p>What&#8217;s the problem? Well, &#8230; these set of methods is only suitable for course grained security. It can provide a go/no go for updating an entity as a whole, without referring to a particular row. Indeed, there is no current entity parameter in the above method.</p>
<p>Of course, we can still use these set of security methods, but not when it is about security related to the current state of an entity.</p>
<h2>What do we need exactly?</h2>
<p>We need a way to enforce that given a certain state (e.g. Approved) an entity (or any entity inside the object graph related to the entity monitored by the state property) can not be updated. Let&#8217;s extend our Validate method, with another one from our StateManagement class: the ValidateCanUpdateEntityGivenCurrentState method:</p>
<p>&nbsp;</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> partial void HolidayRequests_Validate(HolidayRequest entity, 
            EntitySetValidationResultsBuilder results)
        {
            StateManagement.ValidateCanUpdateEntityGivenCurrentState(
                entity,
                entity,
                s =&gt; s.HolidayStateCode,
                results);

            StateManagement.ValidateStateTransition(
                entity,
                s =&gt; s.HolidayStateCode, 
                this.DataWorkspace.ApplicationData.StateCodes, 
                results);
        }</pre>
<p>The ValidateCanUpdateEntityGivenCurrentState is flexible enough to cope both with the situation where the state is included in the entity to validate or not.</p>
<p>&nbsp;</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public static void ValidateCanUpdateEntityGivenCurrentState&lt;TEntityContainingState, TStateProperty, TEntityToValidate&gt;(
            TEntityToValidate entityToValidate,
            TEntityContainingState entityContainingStateProperty,
            Expression&lt;Func&lt;TEntityContainingState, TStateProperty&gt;&gt; statePropertyLambda,
            EntitySetValidationResultsBuilder results, params IEntityProperty[] excludeProperties)
            where TEntityContainingState : IEntityObject
            where TEntityToValidate : IEntityObject
        {
            var stateProperty = entityContainingStateProperty.GetEntityTrackedProperty(statePropertyLambda);

            if (stateProperty.Value == null || entityToValidate.Details.EntityState == EntityState.Added) 
            {
                return;
            }
            var originalStateCode = stateProperty.OriginalValue as IStateCode;

            if (!entityToValidate.CanUpdateEntityInState(originalStateCode.StateValue))
            {
                if (entityToValidate.Equals(entityContainingStateProperty))
                {
                    // when the state field is part of the entity to validate, 
                    // the statefield and rowversion must be excluded from validation

                    var statePropToExclude
                        = entityContainingStateProperty.GetEntityTrackedProperty(statePropertyLambda);
                    var rowVersionPropToExclude
                        = entityContainingStateProperty.Details.Properties["RowVersion"];

                    IEntityProperty[] updatedExcludeProperties = new IEntityProperty[excludeProperties.Count() + 2];
                    for (int i = 0; i &lt; excludeProperties.Count(); i++)
                    {
                        updatedExcludeProperties[i] = excludeProperties[i];
                    }
                    updatedExcludeProperties[excludeProperties.Count()] = statePropToExclude;
                    updatedExcludeProperties[excludeProperties.Count() + 1] = rowVersionPropToExclude;
                    entityToValidate.ValidateFieldsAreUnmodified(results, updatedExcludeProperties);
                }
                else
                {
                    entityToValidate.ValidateFieldsAreUnmodified(results, excludeProperties);

                }
            }
        }</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>We&#8217;ll again use the permission table to check if we have CanUpdate permission given the current state:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public static bool CanUpdateEntityInState(this IEntityObject entity, string currentState)
        {
            if (entity == null)
            {
                throw new ArgumentException("entity cannot be null");
            }
            string entityName = entity.Details.Name;
            string requiredPermission
                = string.Format(CanUpdateEntityPermissionFormat, entityName, currentState);

            return Application.Current.User.HasPermission("LightSwitchApplication:" + requiredPermission);
        }</pre>
<p>Note, that the above method makes use of the CanUpdateEntityPermissionFormat:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">        private static readonly string CanUpdateEntityPermissionFormat = "CanUpdate{0}InState{1}";</pre>
<p>The Format allows to specify update conditions for any entity type involved in the state logic.</p>
<p>Eventually, we&#8217;ll call this:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public static void ValidateFieldsAreUnmodified(this IEntityObject entity,
           EntitySetValidationResultsBuilder results, params IEntityProperty[] excludeProperties)
        {
            foreach (var item in entity.Details.Properties.All().OfType&lt;IEntityTrackedProperty&gt;())
            {
                if (item.IsChanged &amp;&amp; !excludeProperties.Contains(item))
                {
                    results.AddPropertyError(string.Format("Field {0} may not be updated", item.Name), item);
                }
            }
        }</pre>
<p>Basically, all props are entity are checked if there are changes. We have also the ability to excluded certain properties. Why do we need this? Well, in case you state field is present inside the entity you are checking for modifications, it should be possible to exclude this field from the modification check. Obviously, the &#8220;RowVersion&#8221; field should be excluded also.</p>
<p>For this reason it could make sense (and the ValidateCanUpdateEntityGivenCurrentState is ready for this) to store the state field in a dedicated entity which is bound as a 1 to 0..1 relationship to the entity on which the state is applied. By doing so, you can avoid the avoid the usage of the above ExcludeProperties.</p>
<p>The nice thing about the exclude properties is that they can be specified in a strongly typed manner (by means of a lambda expression).</p>
<p>We can also apply the same validation method the the entity attached to the HolidayRequest entity:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">partial void HolidayRequestManagementFeedbacks_Validate(HolidayRequestManagementFeedback entity, EntitySetValidationResultsBuilder results)
        {
            StateManagement.ValidateCanUpdateEntityGivenCurrentState(
                entity, entity.HolidayRequest,
                s =&gt; s.HolidayStateCode,
                results);
        }</pre>
<pre class="brush: csharp; gutter: false; first-line: 1"></pre>
<p>We simply tell the method that the state can be found in entity.HolidayRequest and that the field is s=&gt;s.HolidayStateCode.</p>
<h2>the whole infrastructure class so far</h2>
<pre class="brush: csharp; gutter: false; first-line: 1">using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Details;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace LightSwitchApplication
{
    public interface IStateCode : IEntityObject
    {
        string StateValue { get; }
        bool IsInitialState { get; }
    }
    public static class PropertyExtensions
    {
        public static IEntityTrackedProperty GetEntityTrackedProperty&lt;TSource, TProperty&gt;(
           this TSource entity,
           Expression&lt;Func&lt;TSource, TProperty&gt;&gt; propertyLambda) where TSource : IEntityObject
        {
            string fieldName = entity.GetEntityObjectPropertyName(propertyLambda);
            return entity.Details.Properties[fieldName] as IEntityTrackedProperty;
        }

        public static string GetEntityObjectPropertyName&lt;TSource, TProperty&gt;
          (this TSource source,
          Expression&lt;Func&lt;TSource, TProperty&gt;&gt; propertyLambda) where TSource : IEntityObject
        {
            MemberExpression member = propertyLambda.Body as MemberExpression;
            if (member == null)
                throw new ArgumentException(string.Format(
                    "Expression '{0}' refers to a method, not a property.",
                    propertyLambda.ToString()));

            PropertyInfo propInfo = member.Member as PropertyInfo;
            if (propInfo == null)
                throw new ArgumentException(string.Format(
                    "Expression '{0}' refers to a field, not a property.",
                    propertyLambda.ToString()));

            return propInfo.Name;
        }
    }
    public static class StateManagement
    {
        private static readonly string StateTransitionPermissionFormat = "CanDoTransitionFrom{0}To{1}";
        private static readonly string CanUpdateEntityPermissionFormat = "CanUpdate{0}InState{1}";

        public static void ValidateCanUpdateEntityGivenCurrentState&lt;TEntityContainingState, TStateProperty, TEntityToValidate&gt;(
            TEntityToValidate entityToValidate,
            TEntityContainingState entityContainingStateProperty,
            Expression&lt;Func&lt;TEntityContainingState, TStateProperty&gt;&gt; statePropertyLambda,
            EntitySetValidationResultsBuilder results, params IEntityProperty[] excludeProperties)
            where TEntityContainingState : IEntityObject
            where TEntityToValidate : IEntityObject
        {
            var stateProperty = entityContainingStateProperty.GetEntityTrackedProperty(statePropertyLambda);

            if (stateProperty.Value == null || entityToValidate.Details.EntityState == EntityState.Added) 
            {
                return;
            }
            var originalStateCode = stateProperty.OriginalValue as IStateCode;

            if (!entityToValidate.CanUpdateEntityInState(originalStateCode.StateValue))
            {
                if (entityToValidate.Equals(entityContainingStateProperty))
                {
                    // when the state field is part of the entity to validate, 
                    // the statefield and rowversion must be excluded from validation

                    var statePropToExclude
                        = entityContainingStateProperty.GetEntityTrackedProperty(statePropertyLambda);
                    var rowVersionPropToExclude
                        = entityContainingStateProperty.Details.Properties["RowVersion"];

                    IEntityProperty[] updatedExcludeProperties = new IEntityProperty[excludeProperties.Count() + 2];
                    for (int i = 0; i &lt; excludeProperties.Count(); i++)
                    {
                        updatedExcludeProperties[i] = excludeProperties[i];
                    }
                    updatedExcludeProperties[excludeProperties.Count()] = statePropToExclude;
                    updatedExcludeProperties[excludeProperties.Count() + 1] = rowVersionPropToExclude;
                    entityToValidate.ValidateFieldsAreUnmodified(results, updatedExcludeProperties);
                }
                else
                {
                    entityToValidate.ValidateFieldsAreUnmodified(results, excludeProperties);

                }
            }
        }

        public static void ValidateStateTransition&lt;T, TSource, TProperty&gt;(
            TSource entityContainingTheState,
            Expression&lt;Func&lt;TSource, TProperty&gt;&gt; statePropertyLambda,
            T stateCodes,
            EntitySetValidationResultsBuilder results, bool ignoreReflexiveTransitions = true)
            where T : IEntitySet
            where TSource : IEntityObject
        {
            var stateProperty = entityContainingTheState.GetEntityTrackedProperty(statePropertyLambda);
            var requestedStateCode = stateProperty.Value as IStateCode;

            if (requestedStateCode == null || entityContainingTheState.Details.EntityState == EntityState.Added)
            {
                string initialStateValue = StateManagement.GetInitialStateValue(stateCodes);
                if (requestedStateCode == null || requestedStateCode.StateValue != initialStateValue)
                {
                    results.AddEntityError(string.Format("The initial state must be {0}", initialStateValue));
                }
            }
            else
            {
                var originalStateCode = stateProperty.OriginalValue as IStateCode;

                bool stateChanged = !(originalStateCode.StateValue == requestedStateCode.StateValue);
                if (stateChanged || ignoreReflexiveTransitions == false)
                {
                    bool transitionIsAllowed
                        = StateManagement.IsStateTransitionAllowed(originalStateCode.StateValue, requestedStateCode.StateValue);
                    if (!transitionIsAllowed)
                    {
                        results.AddEntityError(string.Format("transition not allowed from {0} to {1}",
                            originalStateCode.StateValue, requestedStateCode.StateValue));
                    }
                }
            }
        }

        public static bool CanUpdateEntityInState(this IEntityObject entity, string currentState)
        {
            if (entity == null)
            {
                throw new ArgumentException("entity cannot be null");
            }
            string entityName = entity.Details.Name;
            string requiredPermission
                = string.Format(CanUpdateEntityPermissionFormat, entityName, currentState);

            return Application.Current.User.HasPermission("LightSwitchApplication:" + requiredPermission);
        }

        public static void ValidateFieldsAreUnmodified(this IEntityObject entity,
           EntitySetValidationResultsBuilder results, params IEntityProperty[] excludeProperties)
        {
            foreach (var item in entity.Details.Properties.All().OfType&lt;IEntityTrackedProperty&gt;())
            {
                if (item.IsChanged &amp;&amp; !excludeProperties.Contains(item))
                {
                    results.AddPropertyError(string.Format("Field {0} may not be updated", item.Name), item);
                }
            }
        }

        public static List&lt;string&gt; GetAllowedStatesFor&lt;T&gt;(string currentState, T stateCodes)
            where T : IEntitySet
        {
            List&lt;string&gt; allowedStates = new List&lt;string&gt;();
            if (string.IsNullOrEmpty(currentState))
            {
                string initialStateValue = GetInitialStateValue&lt;T&gt;(stateCodes);
                allowedStates.Add(initialStateValue);
            }
            else
            {
                allowedStates.Add(currentState);

                foreach (IStateCode item in stateCodes)
                {
                    string requestedState = item.StateValue;
                    if (IsStateTransitionAllowed(currentState, requestedState))
                    {
                        allowedStates.Add(requestedState);
                    }
                }
            }
            return allowedStates;
        }

        public static string GetInitialStateValue&lt;T&gt;(T stateCodes) where T : IEntitySet
        {
            var stateList = new List&lt;IStateCode&gt;();
            //no better way currently than using a temp collection

            foreach (IStateCode item in stateCodes)
            {
                stateList.Add(item);
            }

            var initialStateRecord =
               stateList.Where(s =&gt; s.IsInitialState == true).Single(); // there must be one IsInitialState=true

            return initialStateRecord.StateValue;
        }

        public static bool IsStateTransitionAllowed(string currentState, string requestedState)
        {
            string requiredPermission
                = string.Format(StateTransitionPermissionFormat, currentState, requestedState);

            bool transitionIsAllowed
                = Application.Current.User.HasPermission("LightSwitchApplication:" + requiredPermission);
            return transitionIsAllowed;
        }
    }
}</pre>
<h2>How do we define the permissions for the can do behavior?</h2>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/candopermissions.png"><img class="aligncenter size-full wp-image-1111" alt="candopermissions" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/candopermissions.png" width="885" height="162" /></a></p>
<h2>What&#8217;s next?</h2>
<p>A client side implementation for both the html client and the silverlight client for State driven CanUpdate behavior.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1068</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>State driven security in LightSwitch (part 4): client side state transition convenience.</title>
		<link>http://blog.pragmaswitch.com/?p=1050</link>
		<comments>http://blog.pragmaswitch.com/?p=1050#comments</comments>
		<pubDate>Thu, 18 Apr 2013 18:29:45 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1050</guid>
		<description><![CDATA[Introduction We have so far a security server side state transition implementation. Let&#8217;s take a look now how we can use this both in an Html client and a Silverlight Client. We&#8217;ll work step-by-step because that allows us to test...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We have so far a security server side state transition implementation. Let&#8217;s take a look now how we can use this both in an Html client and a Silverlight Client. We&#8217;ll work step-by-step because that allows us to test also our server side security implementation.</p>
<h2>The Html Client</h2>
<p>Simple generate a browse screen and an Add/Edit screen and out-of-the-box you&#8217;ll get this when creating a new HolidayRequest.</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/html1.png"><img class="aligncenter size-full wp-image-1054" alt="html1" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/html1.png" width="466" height="510" /></a></p>
<p>&nbsp;</p>
<p>When we would select as initial state &#8220;OpenForApproval&#8221;, we would get following error:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/html2.png"><img class="aligncenter size-full wp-image-1056" alt="html2" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/html2.png" width="496" height="406" /></a></p>
<p>Simple but effective. Also when we change state from Draft to a state which should not be allowed, we&#8217;ll get an error:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/html3.png"><img class="aligncenter size-full wp-image-1057" alt="html3" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/html3.png" width="461" height="395" /></a></p>
<p>&nbsp;</p>
<p>Ok great to learn that our state transitions are nicely protected. Let&#8217;s do the same for the Siverlight Client.</p>
<h2>The silverlight client</h2>
<p>I presume you are familiar how to construct in the silverlight client some screen for our simple scenario. But let&#8217;s try to add some extra comfort. We are convinced now that our server side state transition logic is secure, we just checked it with the html client. So, would it not be more convenient for the user if the states would be pre-filtered depending on which transitions are allowed.</p>
<p>So, instead of :</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/silverlight1.png"><img class="aligncenter size-full wp-image-1060" alt="silverlight1" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/silverlight1.png" width="455" height="309" /></a></p>
<p>&nbsp;</p>
<p>we want:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/Silverlight2.png"><img class="aligncenter size-full wp-image-1061" alt="Silverlight2" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/Silverlight2.png" width="462" height="304" /></a> Given the fact our original state is &#8220;Draft&#8221;, we can only do the transition to OpenForComment or stay in Draft.</p>
<p>This can be simply done by changing the datasource of the StateCode field to another dedicated query with following code:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> partial void GetAllowedStates_PreprocessQuery(string currentState, ref IQueryable&lt;StateCode&gt; query)
        {
            List&lt;string&gt; allowedState = StateManagement.GetAllowedStatesFor(currentState, this.DataWorkspace.ApplicationData.StateCodes);
            query = query.Where(s =&gt; allowedState.Contains(s.StateValue));
        }</pre>
<p>We make use here again of our StateManagement class:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> public static List&lt;string&gt; GetAllowedStatesFor(string currentState, IEntitySet stateCodes)
        {
            List&lt;string&gt; allowedState = new List&lt;string&gt;();
            allowedState.Add(currentState);

            foreach (IStateCode item in stateCodes)
            {
                string requestedState = item.StateValue;
                if (IsStateTransitionAllowed(currentState, requestedState))
                {
                    allowedState.Add(requestedState);
                }
            }
            return allowedState;
        }</pre>
<p>Under the hood, this we&#8217;ll simply analyse the state transition related permissions in our permission table. So, we nicely reuse the functionality of the state transition validation in our previous post ! Note, we rely in the GetAllowedStateFor method on the IStateCode interface. Since we enforce that the table containing the states implements this interface we can access strongly typed the StateValue property.</p>
<p>But, client side, there is an important caveat here ! It&#8217;s about the query parameter of the GetAllowedStates query. Let&#8217;s first take a look at our screen&#8217;s ViewModel:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/viemodel.png"><img class="aligncenter size-full wp-image-1062" alt="viemodel" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/viemodel.png" width="627" height="511" /></a></p>
<p>The GetAllowedStates query has a parameter called currentState. It would be very tempting to directly bind this parameter to the StateValue of the CurrentHolidayRequest. Don&#8217;t do this, because that will give unwanted side-effects. The point is that we want that our  state transitions happen in discrete steps, meaning that the state is only effectively changed when the entity is saved. If we bind the currentState parameter directly to the StateValue field of the HolidayRequest Screen object, we&#8217;ll see that the list of available states changes each time we take another value in the state dropdown!</p>
<p>We can avoid this by creating another string based property on our ViewModel: OriginalValueOfRequestState.</p>
<p>We&#8217;ll provide following code:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> partial void HolidayRequestDetail_InitializeDataWorkspace(List&lt;IDataService&gt; saveChangesTo)
        {
            CurrentHolidayRequest = this.DataWorkspace.ApplicationData.HolidayRequests_SingleOrDefault(HolidayRequestId);
            OriginalValueOfRequestState = CurrentHolidayRequest.StateCode.StateValue;
        }</pre>
<p>So, we&#8217;ll capture first the original state value and we only update this value when the HolidayRequest is saved:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> partial void HolidayRequestDetail_Saved()
        {
            OriginalValueOfRequestState = CurrentHolidayRequest.StateCode.StateValue;
        }</pre>
<h2>A better html client user experience for state transitions</h2>
<p>We want the same level of convenience (the pre-selected states) now in the html client. That&#8217;s pretty simple:</p>
<p>Connect the same query (GetAllowedStates) as in the silverlight client to the Holiday State Code:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/addedithtml.png"><img class="aligncenter size-full wp-image-1105" alt="addedithtml" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/addedithtml.png" width="678" height="348" /></a></p>
<p>&nbsp;</p>
<p>And provide following code (many thanks to <a href="http://social.msdn.microsoft.com/profile/huy%20nguyen%20msft/?ws=usercard-mini">Huy Nguyen</a> for the help on the forum):</p>
<pre class="brush: javascript; gutter: false; first-line: 1">myapp.AddEditHolidayRequest.created = function (screen) {
    screen.HolidayRequest.getHolidayStateCode().then(
        function completed(result) {
            screen.OriginalValueOfRequestState = result.StateValue;
        }
    );
};

myapp.AddEditHolidayRequest.AddManagementFeedback_execute = function (screen) {
    var mgtFeedback = new myapp.HolidayRequestManagementFeedback();
    screen.HolidayRequest.setHolidayRequestManagementFeedback(mgtFeedback);
    screen.showTab("ManagementFeedback");
};
myapp.AddEditHolidayRequest.AddManagementFeedback_canExecute = function (screen) {
    return !screen.HolidayRequest.HolidayRequestManagementFeedback;
};</pre>
<h2>What next?</h2>
<p>In a next post, we&#8217;ll provide the necessary server side material to protect (make them read-only) entities based on the state of the entity of another entity in the object graph.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1050</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>State driven security in LightSwitch (part 3): server side state transition security</title>
		<link>http://blog.pragmaswitch.com/?p=1046</link>
		<comments>http://blog.pragmaswitch.com/?p=1046#comments</comments>
		<pubDate>Wed, 17 Apr 2013 19:48:06 +0000</pubDate>
		<dc:creator>paul van bladel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://blog.pragmaswitch.com/?p=1046</guid>
		<description><![CDATA[Introduction This post of mainly about the server side. We want to come up with a nice piece of base infrastructure with which we can protect server side the state transition of a certain entity. The base infrastructure should be...]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>This post of mainly about the server side. We want to come up with a nice piece of base infrastructure with which we can protect server side the state transition of a certain entity. The base infrastructure should be treatable as a black box and should be easily consumable and easy to setup inside a LightSwitch project where state matters.</p>
<p>Although what follows is all about the server side, I might improve the understanding to first see things on the client: we want that when a user makes a state transition which is not allowed, she get a nice error message:</p>
<p>&nbsp;</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/InvalidTransition.png"><img class="aligncenter size-full wp-image-1084" alt="InvalidTransition" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/InvalidTransition.png" width="575" height="270" /></a></p>
<p>&nbsp;</p>
<p>The message is clear: the user tried to change state from draft directly to approved, which is not allowed. Obviously, we add later on the necessary functionality so that client side the user could not even try to do this transition.</p>
<p>&nbsp;</p>
<h2>Where do we want to validate the state transition?</h2>
<p>Obviously server side, because that&#8217;s the place where we protect our assets. The best place to trigger this validation is in the Validate method of the entity which carries the state. In our example the state property is part of the entity which is monitored by the state the HolidayRequest entity.</p>
<pre class="brush: actionscript3; gutter: true; first-line: 1"> partial void HolidayRequests_Validate(HolidayRequest entity, 
            EntitySetValidationResultsBuilder results)
        {
            StateManagement.ValidateStateTransition(
                entity,
                s =&gt; s.HolidayStateCode, 
                this.DataWorkspace.ApplicationData.StateCodes, 
                results);
        }</pre>
<p>That&#8217;s a very simple call into the black box. Let&#8217;s first inspect the method signature:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> public static void ValidateStateTransition&lt;T, TSource, TProperty&gt;(
            TSource entityContainingTheState,
            Expression&lt;Func&lt;TSource, TProperty&gt;&gt; statePropertyLambda,
            T stateCodes,
            EntitySetValidationResultsBuilder results, bool ignoreReflexiveTransitions = true)
            where T : IEntitySet
            where TSource : IEntityObject
        {
}</pre>
<p>The signature has some generic parameters, but luckily we don&#8217;t need to specify the generic types when calling the method (they are auto discovered) <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In case you want to go away now, think again,  this was the most difficult part. I&#8217;ll explain the internals of the ValidateStateTransition method now, but you don&#8217;t need to understand all details, you can use the method as a black box !</p>
<p>This simple method call is doing all the heavy lifting for us. Obviously it needs to know  where the state property is stored and it needs to know the name of the field containing the state (we do this via a lamdba expression in such a way things are strongly typed !). It needs also to know where the list of potential states are. The method has a optional parameter &#8220;ignoreReflexiveTransitions&#8221;. A reflexive transition is a transition from state A to state A. Kind of null transition if you want. Being able to capture such a transition can be important in very specific cases, but for most cases you just want to ignore this transition (that&#8217;s why the default value is true).</p>
<p>Let&#8217;s take a close look now to the ValidateStateTransition method:</p>
<pre class="brush: csharp; gutter: false; first-line: 1"> public static void ValidateStateTransition&lt;T, TSource, TProperty&gt;(
            TSource entityContainingTheState,
            Expression&lt;Func&lt;TSource, TProperty&gt;&gt; statePropertyLambda,
            T stateCodes,
            EntitySetValidationResultsBuilder results, bool ignoreReflexiveTransitions = true)
            where T : IEntitySet
            where TSource : IEntityObject
        {
            var stateProperty = entityContainingTheState.GetEntityTrackedProperty(statePropertyLambda);
            var requestedStateCode = stateProperty.Value as IStateCode;

            if (requestedStateCode == null || entityContainingTheState.Details.EntityState == EntityState.Added)
            {
                string initialStateValue = StateManagement.GetInitialStateValue(stateCodes);
                if (requestedStateCode == null || requestedStateCode.StateValue != initialStateValue)
                {
                    results.AddEntityError(string.Format("The initial state must be {0}", initialStateValue));
                }
            }
            else
            {
                var originalStateCode = stateProperty.OriginalValue as IStateCode;

                bool stateChanged = !(originalStateCode.StateValue == requestedStateCode.StateValue);
                if (stateChanged || ignoreReflexiveTransitions == false)
                {
                    bool transitionIsAllowed
                        = StateManagement.IsStateTransitionAllowed(originalStateCode.StateValue, requestedStateCode.StateValue);
                    if (!transitionIsAllowed)
                    {
                        results.AddEntityError(string.Format("transition not allowed from {0} to {1}",
                            originalStateCode.StateValue, requestedStateCode.StateValue));
                    }
                }
            }

        }</pre>
<p>It&#8217;s clear that the ValidateStateTransition method needs as input the current state and the requested state, but what is the current state? This is of course the state currently in the database. The state mentioned in the entity is the requested state. We don&#8217;t need to do an additional database call to get the current state value. LightSwitch is doing this already for us. We can get the &#8220;original&#8221; value of each  EntityTracked property by means of following extension method:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public static IEntityTrackedProperty GetEntityTrackedProperty&lt;TSource, TProperty&gt;(
           this TSource entity,
           Expression&lt;Func&lt;TSource, TProperty&gt;&gt; propertyLambda) where TSource : IEntityObject
        {
            string fieldName = entity.GetEntityObjectPropertyName(propertyLambda);
            return entity.Details.Properties[fieldName] as IEntityTrackedProperty;
        }</pre>
<p>I make use here of an other extension method, <a title="Avoiding magic strings in LightSwitch (part 1)" href="http://blog.pragmaswitch.com/?p=949">GetEntityObjectPropertyName</a>, I documented in a previous post. So, the extension method returns us based on a lambda expression an IEntityTrackedProperty. We&#8217;ll need this to get access to the original value of the state field.</p>
<p>In a first block we&#8217;ll check if there is effectively a state in the entity and if we check in the case the entity itself in &#8220;create&#8221; mode, that the state is given the mandatory initial state which we can find in our StateCode table. (remember the field &#8220;IsInitialState&#8221; is part of our IStateCode interface).</p>
<p>For the rest, the logic of this method is very straightforward: we&#8217;ll check if the transition is allowed and if not, we&#8217;ll fill the ValidationResult object with a nice error message. Note also the logic for the reflexive transitions.</p>
<p>As explained earlier, we&#8217;ll use the build-in permission mechanism of LightSwitch to keep track of the allowed transitions:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/statepermissions.png"><img class="aligncenter size-full wp-image-1047" alt="statepermissions" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/statepermissions.png" width="1021" height="230" /></a></p>
<p>The permissions follow a strict naming scheme. By doing so we can use it directly in code:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">    private static readonly string StateTransitionPermissionFormat = "CanDoTransitionFrom{0}To{1}";</pre>
<p>The current schema presumes that we only have one state aware entity in our app. Of course the format can be easily extended to support more state aware entities: &#8220;CanDo{0}TransitionFrom{1}To{2}&#8221;. where {0} can be replaced by the state aware entity (e.g. HolidayRequest).</p>
<p>Now we are close to the actual verification of the state transition, which is really as simple as possible but no simpler:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public static bool IsStateTransitionAllowed(string currentState, string requestedState)
        {
            string requiredPermission
                = string.Format(StateTransitionPermissionFormat, currentState, requestedState);

            bool transitionIsAllowed
                = Application.Current.User.HasPermission("LightSwitchApplication:" + requiredPermission);
            return transitionIsAllowed;
        }</pre>
<p>The method for retrieving the InitialState goes as follows:</p>
<pre class="brush: csharp; gutter: false; first-line: 1">public static string GetInitialStateValue&lt;T&gt;(T stateCodes) where T : IEntitySet
        {
            var stateList = new List&lt;IStateCode&gt;();
            //no better way currently than using a temp collection

            foreach (IStateCode item in stateCodes)
            {
                stateList.Add(item);
            }

            var initialStateRecord =
               stateList.Where(s =&gt; s.IsInitialState == true).Single(); // there must be one IsInitialState=true

            return initialStateRecord.StateValue;
        }</pre>
<h2></h2>
<h2>Consume the permissions in a specific role</h2>
<p>Let&#8217;s configure now, as an example the permissions for the Manager role.  It&#8217;s always a good practice to limit the permissions of managers to the strictest mininum <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  In our example they only get the permission to approve or reject a holiday request:</p>
<p><a href="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/managerpermissions.png"><img class="aligncenter size-full wp-image-1091" alt="managerpermissions" src="http://blog.pragmaswitch.com/wp-content/uploads/2013/04/managerpermissions.png" width="675" height="180" /></a></p>
<h2>What&#8217;s the advantage of this approach?</h2>
<p>It&#8217;s cool because there is no magic involved, it simply uses all goodness of LightSwitch, nothing more and nothing less.</p>
<p>Adding a new transition only boils down to adding a new entry in the permission table. Do you know that you even do not need to recompile the application when you would be need to add a new transition? This is since we don&#8217;t have any hard coded reference to our transitions inside the application. Simply add the the new permission directly in the database table.  Of course when you don&#8217;t use the permission designer, the permission will not be available in the LightSwitch security screens, where you can compose a role by selecting the various permissions.</p>
<p>An alternative approach could be to add upfront all theoretically possible permissions, so the mathematical product set. In case you have 3 permissions (A,B,C) that would be</p>
<ul>
<li>CanDoTransitionFromAToB</li>
<li>CanDoTransitionFromAToC</li>
<li>CanDoTransitionFromBToA</li>
<li>CanDoTransitionFromBToC</li>
<li>CanDoTransitionFromCToA</li>
<li>CanDoTransitionFromCToB</li>
</ul>
<p>Of course for large state diagrams, this can become cumbersome, so I would simply stick to the first approach.</p>
<blockquote><p>The most important advantage is that the call to the ValidateStateTransition method is a nice black box, but it is not really relying on a whole series of assumptions nor conventions.</p>
<ul>
<li>The only code prerequisite is that that the field which carries the state must be an entity which implement IStateCode, that&#8217;s all.</li>
<li>Secondly we need of course the permission table setup and here we need to follow the naming convention of the state transition permissions we defined in code ( CanDoTransitionFrom{0}To{1}</li>
</ul>
</blockquote>
<h2>What could still be improved?</h2>
<p>The only magic strings we have now are in the permission table and they are functionally dependent on the values in our StateCode table. The permissions are inside the project model file (the .lsml file). I have done already some research on how to generate strongly typed material from the model file. See my post on <a title="Avoiding magic strings in LightSwitch (part 2): Getting strongly typed access to the LightSwitch choice lists" href="http://blog.pragmaswitch.com/?p=915">strongly typed code values</a>. In this approach I&#8217;m reading from the model file. In case we would like to improve this state transition permission approach, it could be interesting to write the permissions directly into the model file based on the information coming from a permission designer. Would be cool, but I&#8217;m quite reluctant to do so. I think that the model file is the domain of the LightSwitch product team, we should not touch it <img src='http://blog.pragmaswitch.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>What&#8217;s next?</h2>
<p>We have now a secure server side framework method for the state transitions. How will we consume this client side and add some comfort so that the user can not select state transitions which are not allowed.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pragmaswitch.com/?feed=rss2&#038;p=1046</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
