YAB (yet another blog) Site

Posts tagged ‘Technical Write-ups’

Developing Web Application (including Authorization/Authentication) – ZERO CODE using LightSwitch

In the previous write-up on LightSwitch, we discussed about how to build screens and navigations and build an application. Taking a step forward, using LightSwitch I want to build a web application which supports features like Authentication and Authorization out of box. What is the catch?! Yes, the catch is, still, ZERO CODE written! J.

A quick recap on creating a Web application using LightSwitch, your mandatory pre-requisite is Visual Studio LightSwitch 2011. First step, obviously, to create a new LightSwitch Application (C#) project.

From Now on to the basic entity model, I’m going to skip, (refer to my previous write-up for details). For the sake of simplicity, we’ll use the good old PUBS sample database for the demo purpose. We’ll play around entities like Authors & Titles.

Using Add screen wizards, let us add a new List Detail screen for entities, Authors & Titles. During the addition, let us also enable the dependency relationship details for AuthorsTitles & TitleAuthors to be included in the screen.

After necessary Screen designs, Get down to the properties page of LightSwitch Project to define key properties for Access Control, Application type Publish the application into a host environment.

The Publishing Wizard of LightSwitch can help in hosting the web application in a Windows Azure (Cloud) or host the application services on a separate IIS Server. For the sake of this demo, let us focus on hosting the app in IIS. Select the option for client & Application Server as in the setting below:

Before we hit on Publish button, we’ve one more step to complete, to set the access control. In the properties page, click on Access Control to set the type of Authentication

By default, the Authentication type is not enabled. The web application can either select Windows Authentication or use Forms based authentication. Let us select Forms authentication for this example and Windows Authentication works the same way, as usual.

LightSwitch has a built-in permission called Security Administration, and any user who receives this permission becomes a security administrator. The Security Administration permission allows the logged-on user to access the Security Administration screens in the running LightSwitch client application, which will show automatically for users who have been granted this privilege. If you are curious to know if LightSwitch do provide us with any default screen to manage User & Roles, please click on Screen Navigation to find a separate Menu group, ‘Administration’ with tasks Roles & User under them. This group of screens is visible only for those roles with ‘SecurityAdministration’ permission. When a user logs in with Security Administration privilege, the client application screen will have additional task menu on the left side.

We are almost done with other settings in the property page, we could go back to Application type property page and select the publish Wizard for finishing details on security settings. Publish step will build the LightSwitch application, bundle them with all required resources and then take us through a set of wizard screens to define properties to host the output files into the target environment.

Publish Wizard begins with Client configuration. We had earlier marked this as a Web Application and this choice is reflected in the Wizard.

Next step is to define the Application Server. Again, we opted to host this on an IIS Server; this option is reflected in the wizard. However, before we move on to next step, need to ensure that IIS server has LightSwitch pre-requisites installed on the application server. The LightSwitch server prerequisites are installed by using Web Platform Installer. You can download Web Platform Installer from the Microsoft Download Site. Once the pre-requisites on the IIS server are confirmed, the next step is to ‘Specify Publishing Reference’. The wizard can create an MSDeploy package or remotely deploy on IIS server directly

The next step is to define Database connection to the DB where Authentication information to be persisted. For this demo, I set it to a SQL DB where ASPNET user tables are created and stored.

During the Publishing wizard, in order for the LS app to work with access control, the wizard themselves provides an entry to create Application Administrator User at this time. And other users can be created through application User management screens.

Next step is to specify application Data Source connection strings in the ‘Other Connections’ page. The Wizard auto-populates the connection string based on the initial definition we provided during the Entity data source definition. Post this step, we have an optional step to specify Certificate for SSL (which are self-explanatory), final page in the wizard is the Publish Summary Page as below.

Once we click on the publish button, the MsDeploy package is remotely deployed into the IIS Server (Localhost in this case) under Default Web site\WebAppAuth Application. You’ll see the status update of ‘Published Successfully’ in the visual studio status bar, once it is published.

One point to note about authentication is, this works only on deployed environment and does not work during the Debug mode. So to test Authentication, you need to deploy them in the hosting environment.

Unlike the debug mode, when the application is launched from the hosted environment, the initial page is a Login Page. In the login page, use the ‘Admin’ user credential that was specified during the Publish Wizard. We could additionally see two more tasks on the left menu, viz., Roles, Users.

Till this point of time, we’ve not written a line of code, however, we’ve accomplished a Web application with a login page, Authentication and Authorization capability.

Securing Data on the Logic Tier

As we get to next stage, we might have functionality to enable or disable screens for certain role permissions alone.

The logic tier includes two major groups of components where you apply permissions checking: entities and queries.

Entities are the general mechanism for accessing and working with application data. There are four main actions you can carry out with entities: read, insert, update and delete. LightSwitch gives developers a hook-point to verify a user’s permissions as each action is carried out, and it also provides a simple API for checking if the current user has a specific permission defined in the application. The following code shows an example of the permissions check and the various gate methods the API provides to allow a developer to check permissions:

partial void Employee_CanUpdate

(ref bool result)

{

result = Application.Current.User.HasPermission

(Permissions.EmployeeUpdate);

}

partial void Employee_CanInsert…

partial void Employee_CanRead…

partial void Employee_CanDelete…

partial void SaveChanges_CanExecute…

A couple of things should be noted. First, these methods, with the exception of SaveChanges_CanExecute, are implemented on the entity set as a whole and not on the specific entity instances. Therefore, any checks performed can’t be related to data values on a specific entity instance. The SaveChanges_CanExecute method controls access to changes in the entire data source and therefore can’t contain entity- or entity-set-specific logic. Second, if the Employee_CanRead method returns false, the Employee_CanUpdate and Employee_CanDelete methods will not be called, as they would be implicitly false as well. A user is not allowed to update or delete an entity if she isn’t allowed to read it.

The “Can” methods are the basic way to do coarse-grained security. They support basic data access-control policies. However, they have some limitations. When more fine-grained control for reading data is needed, you can implement access-control logic on queries. To control the writing of data at a more granular level, you must do so in the Save Pipeline.

Queries are also secured on the logic tier. Each query has a method that allows you to control access. LightSwitch automatically generates three queries for each entity that exists: an All query to return all of the entity instances, and Single and SingleOrDefault queries to return one entity instance by key. Each of these built-in queries has a CanExecute method that can be used to implement access control:

partial void Employees_All_CanExecute(ref bool result)

{

result = Application.Current.User.HasPermission

(Permissions.QueryEmployees);

}

partial void Employees_Single_CanExecute…

partial void Employees_SingleOrDefault_CanExecute…

It’s important to note that LightSwitch queries are composable, meaning new queries can be based on an existing query. When applying access-control logic to queries, the permission requirements on the initial query serve as input to queries composed on that query. The Single and the SingleOrDefault queries are composed on the ‘All’ query, so securing the All query also secures these queries if no specific permissions are specified for the derived query. However, if you like, you can specify permissions on the derived query that are less restrictive than those on the composing query. Also, the CanRead method on the entity set will be applied before CanExecute for any queries of that type.

SignOut

You may also see the logged in user name on the bottom right corner of the screen. You’ll be curious to note that, there’s no Sign out option by default.

Indeed, it is little tricky to implement the Sign Out option. Since these buttons are on the Silverlight application pages, they need to rely on the server side of the application to perform ‘FormsAuthentication.SignOut()’ operation. This part is not straightforward. To accomplish a Sign-out functionality, create a Separate ASP.NET web project and name it as same project name as LightSwitch application, WebAppAuth. Add a Web Page, LogOut.aspx like the following:

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title></title>

</head>

<body>

<form id=”form1″ runat=”server”>

<div></div>

</form>

</body>

</html

And for the code-behind file:

namespace WebAppAuth

{

public partial class LogOutForm : System.Web.UI.Page

{

protected void Page_Load

(object sender, EventArgs e)

{

FormsAuthentication.SignOut();

Response.Redirect(“default.htm”);

}

}

}

Build this Web project and copy the LogOff.aspx from your ASPX project to the root location of your published LightSwitch app, right next to web.config and default.htm. And Copy the WebAppAuth.dll from the ASPX bin folder into the to the bin directory of your published LightSwitch app.

The next step is to wire up the ASPX page with the LightSwitch App. The easiest way, is to introduce a button on the LS App Screen and place the Button_Execute code

using Microsoft.LightSwitch.Threading;

using System.Windows.Browser;

partial void LogOut_Execute()

{

Dispatchers.Main.Invoke(() =>

{

HtmlPage.Window.Navigate(new Uri(“LogOff.aspx”, UriKind.Relative));

});

}

The above code needs reference to System.Windows.Browser assembly in the client. And after this wire-up, don’t forget to build your LS app and publish it to the remote host server.

This work around can be attached directly through the publishing process automatically by manually editing the WebAppAuth.lsproj file to manually include the Logoff pages automatically while you publish changes to your LS application. For steps to manually doing this, refer to this link.

Reference:

http://msdn.microsoft.com/en-us/magazine/hh456409.aspx

http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/35/Saving-Files-To-File-System-With-LightSwitch-Uploading-Files.aspx

http://lightswitchhelpwebsite.com/

Windows 8 on the go

For weeks now, I’m running my Windows 8 using the open source Oracle Virtual Box. Initial Wow factor, enthusiasm to play with Metro style apps kept the ball rolling very fast. The Host and the Guest spared 2GB RAM each. All is well, until I started working with VS 11 Developer preview in the guest OS. The wait time between clicks kept on increasing. Obvious that 2GB of RAM is no more sufficient enough for dev box. I could not afford a new separate PC for Windows 8. Forget about that in the corporate environment, it’s way not possible through red tapes and governance model they have. Then, one day on a coffee talk, someone was explaining about the Linux on the go option. Wherein, User can carry their entire OS in a USB Thumb drive. After few initial failed google’ing, I came across the Build presentation by Steve Silverberg, which mentioned about Windows 8 on the GO…. To be frank, my initial thought was, it is going to be as easy as To-go order at McD. Later, I realized, it is going to cost me some round trips.

That’s interesting. I decided to try the Windows 8 on the go. Before we get carried away, let us understand, what’s this Windows 8 on the go?, By Windows-on-the-go means, installing Windows operating system on a removable/distributable disk like a USB pen drive or USB Hard Disk. When Windows 8 is installed on the USB drive, plug the USB drive into a particular computer (it can be multiple computers) and alter the boot sequence to boot from USB, for the first time, it installs required drivers for the devices around in that computer and reboots, from next time on, it boots straight into Windows 8 on the USB distributable. This is not something unique to Windows 8. Linux OS flavors have been doing this for years now. And infact, Enterprise edition of Windows 7 too have tools to make windows distributed on the go. Microsoft has been optimizing Windows 8 to run from flash, and to use flash storage, over a USB bus. Also, I read that this is not perfect, yet but better. 

Some pre-requisite for this to work on host computer,

The computer is to have either USB 2.0 or USB 3.0 and BIOS to support boot from USB and UEFI. And on the deployment side, I’m supposed to have a USB pen drive which is 32GB minimum. Portable Workspace Creator (pwcreator.exe) rejects anything below 32GB! Why is this restriction? When my Windows 8 on VDI can run on anything as low as 15GB of space! I could not find any answers. The smallest foot print virtual drive I tried for a Windows 8 32 Bit OS was 15 GB, in size. So, I wanted to still try this On-the-go stuff with a 16GB USB drive (Crazy, am I !?).

As a preparative step, with all the enthusiasm, I ordered a 16 GB HP Pen drive from FlipKart for Rs840. Flipkart took three days to deliver (a nice safe 7″ packing for a  1″ long pen drive). Now that I’ve a USB drive, I wanted to use PWCreater.Exe to load the image of Windows 8 into the portable drive.

The first bad news: I searched the entire Windows 8 systems folder for the Portable workspace creator. There’s no file called PWcreator.exe in the entire machine. Where did it go, what happened to all those Web sites which talked abt ‘The Portable Workspace creator’. Alas, this is available only for Enterprise Edition and not available part of the preview version! Bugged! MS restricted it for Volume licensing Enterprise customers only.

Back to Google, I came by one write-up by Günter Born. The time I started looking for this option only a handful of initial writers wrote about this approach. By the time, I get this completed; I could see a lot of blog posting on the same topic. Thanks to Born for this write-up. Otherwise, I would have stopped and waited for inclusion of PWCreator. Born also tried the same steps and options, I had thought but finally cracked a way out! The idea is, make use of DiskPart (Disk Partition tool) to create a clean primary partition and use an Imaging tool to copy the windows image into the USB drive and as a final step move necessary files into BOOT sector so that when UEFI/USB boot enabled computer can boot from the OS in the removable drive. Ta da!

Windows 7 rather Vista onwards provided an Automated Installation Kit. Part of this free downloadable, we get a command line tool called IMAGEX.exe, to create and deploy Windows Disk Images in the Windows Imaging Format (WIM). You can locate the WIM file under <Drive:>\Source\install.wim. WIM is a file based image format. Of late, windows setup themselves uses WAIK APIs to install the fresh instance or cloned instance of the OS. One deterrent was the download for AIK for windows 7 itself. It is hosted in one of the slowest download servers! It took very long time to download, that too, multiple times, for a single a 1.66 GB file! FlashGet is of good use, here.

Once WAIK got downloaded, I installed the AIK toolkit in the host machine. Then build an ISO of entire Tools\X86 of the toolkit and hosted it in the Guest OS, so that I could make use of these tools inside Windows 8. By the way, the Guest Virtual box setup was of the spec: A 32-bit Windows 8 8150 build. It used 2 GB of Ram from host with a 15GB VDI. Before using imaging tool, we need to prepare the USB drive for required partition. I used DIskPart tool with the sequence of commands:

DISKPART

DISKPART> LIST DISK
DISKPART> SELECT DISK 1
REM: In my case, the HP w165 was in #1.

DISKPART> CLEAN
REM: To clean drive

DISKPART> CREATE PARTITION PRIMARY
REM: Creates a partition and makes it a primary

DISKPART> FORMAT fs=ntfs quick
REM: Format the partition in NTFS format

DISKPART> ACTIVE
REM: Mark the selected partition as active

DISKPART> exit

This prepares the partition part of the requirement for USB drive. Next comes the part to restore image using IMAGEX.exe. Open the command prompt with Adminstrator privilege and run:

> imagex.exe /apply d:\sources\install.wim 1 f:\
Here, my Windows 8 ISO was available in D drive and HP-w165 USB is in F drive.

For some of them, Imagex took 3 hours to copy. It took me close to 127 mins to complete. Next step, is to copy windows boot files into boot sector. For this, used the command,

bcdboot.exe f:\windows /s f:

For some reason, ALL option (as mentioned in born’s site was not working for me). F: represents the target media USB drive.

BCDBoot worked and successfully loaded the boot files to target USB drive. Quickly, I restarted my machine and altered the boot sequence to accommodate USB boot. I was too eager to see the windows running on the stick.

More eager you are, result sounds more critical (esp., when it is bad): The initial run on my laptop took nearly 2 hours. That too just for initial setup (Good part in that, I had the patience to wait through the 2 hours setup! ). After all slow boot up and ‘Getting Device information’ and setup cycles, Windows 8 was finally getting loaded from my USB pen drive. Any operations other than Disk read/write works like charm. But poor 16 GB kid of hard disk could not keep up to the speed. Probably, a USB 3.0 on my machine could have made is a better experience.

After some playing with Win8, I shut down the machine and took the USB out. Could feel the heat on the USB connector pin! Thank god, it didn’t melt! 😀

Anyways, Windows 8 on the Go, worked. Did it solve my problem of programming faster? No, I need to go back to a richer virtual box or set up a new separate box.

“Good judgment comes from bad experience. Experience comes from bad judgment.”

Using Microsoft Visual Studio LightSwitch 2011

Writing Application is never the same again with LightSwitch 2011. LightSwitch is simplified and self-service model for application development. It lets the user decide whether the applications developed be deployed for Desktop or Web or Cloud.

Most of the business applications are data-centric application. Meaning, they revolve around business entities and in simpler perspective, they are either Add/Update/Delete/View of the business entities spiced with business rules, on top. That evolves the style of developing application, as well. LightSwitch is all about the smartest and easiest way of building highly robust applications, in the way we think of these business applications.

What is LightSwitch?

One line answer: LightSwitch is a new edition of Visual Studio.

LightSwitch helps developer to build application using .NET stack and wrap them into an abstraction layer which can be further optimized for maintenance and management of business entities. LightSwitch business applications are multi-tiered, featuring a client application and a combination of LINQ, WCF RIA Services and the Entity Framework to implement the application services tier. LightSwitch application is built using development best practices, on top, eliminates exhaustive and repetitive plumbing code required to construct a properly architected database, data access tier, and user interface (UI) framework.

LightSwitch comes with a unique designer and development templates. The designer include facility to design business entities, database or some form to persist these business entities (List a SharePoint), design screens to perform business action on those entities and finally, the logic and rules that bind them all together. In short, the designer with LightSwitch helps the developer with the entire ingredient required to build an application from scratch.

Where to begin the app development, did you say screen design? Let us take a step back. Typically, the screen design requirements are driven by the Data model. The Data Model is driven by the business requirement. First thing first, let us come up with Data Model and persist the data. The Data Model is presented using the entity framework 4.1.

The screen design can now be inferred from the data model or the table schema or can be built using a hybrid approach where the screens are generated and customized as per requirements. In addition to the screen design, the other part is the data rules. LightSwitch provides both declarative and imperative option. Either the rules can be defined in the property window (declarative) or written in the code (imperative), as well. They can be simple language expressions or a complete method embedded into the application using C# or VB.NET.

Let us try to create a LightSwitch Application. Before starting with a LightSwitch app development, Visual Studio LightSwitch has to be installed. For this demonstration, we had installed LightSwitch on top of Visual Studio 2010 ultimate on the machine. Hence application is built using the VS2010, as well.

Ok. Begin with a new Project. After LightSwitch is installed, on the ‘New project template’, you’ll get a new category for ‘LightSwitch Applications (Visual C#)’.

Visual Studio, as usual, does a lot of ‘behind the scene’ plumbing for the application. As mentioned earlier, the next step is to ‘Start with Data’.

Let us start with a new table. For illustration, let us build an application around an imaginative Customer who has attributes like ID, Name, DateOfBirth, etc.

With the above step, we created a business entity, named it as Customer and defined its attributes. In addition to this, the other things to do are to create Queries, add computed properties, add more entities and build relationship between them, write business rules in C# and bind them, etc. For the brevity of this demonstration, let us jump to screen design by clicking on Add Screens button on the top.

Voilà! There are so many screen templates already, by default. Do developers need to think of any other standard screens?? Well, let’s begin with ‘New Data Screen’ and then create a ‘List and Details Screen’. Note, the important aspect here is to attach the Customer entity as Business Model under Screen Data section.

Once the screen is created, the VS takes you back to the Designer page where developer can do further customization,as required. Would like to add one more screen for List and details? Let us use the Solution Explorer, right click on Screens folder and add ‘List and details’ screen. Again, remember to bind the Customer entity with the newly built CustomerListDetail screen.

To recap, so far, we’ve not written a line of code. We created an entity and two screens on top of this entity. Let us say, one for ‘New data form’ and another to ‘List and details’ screen. Can we now build the application? Do we need to do any more plumbing? May be not required! I trust LightSwitch.

Go ‘F5’ (Start debugging). The application is built and starts running.

Enter a customer detail and Save the data with save icon on the top. Then get into List view to see the other screen.

That’s it folks!! The application is ready! As required, the developer can now fit in the remaining business logics and customizations as per needs. LightSwitch makes developer’s life a lot easier.

There are many more aspects to talk about LightSwitch applications. What is covered in this write up is just an iota of the ocean. ! A lot more can happen over extensibility provisioned on LightSwitch. In addition to this simple approach of building a new application from the scratch in no-time, it also provides a customizable template that enables the developer to write custom business logic and build application that logic in no time. Also, we get tons of plug-ins and starter kit to build different kinds of applications like BI Solutions, etc. LightSwitch fundamentally enabled extension models so that the eco-system with strong developer community and independent software vendors can provide their own extensible templates and starter kits to build new applications integrated with advanced functionalities, out of box.

Reference

Repository

Sometimes, at work, I used to write some technical write-up that are free from IPR & confindentiality, for educative purpose. Using this opportunity at wordpress to host them somewhere on the web !

%d bloggers like this: