You are here:   Blog
Register   |  Login

 

Dec 16

Written by: Michael Washington
12/16/2012 9:51 AM  RssIcon

image

In the Visual Studio LightSwitch HTML Client, extra steps are required to determine who the currently logged in user is.

image

The first step is to turn on authentication in the LightSwitch project.

image

We create a UserName field. Notice that it is Required. This is the thing that will cause a problem (demonstrated later).

image

We select the Entity (table), then we select Write Code, then the Inserting method.

We use the following code for the method:

 

        partial void PromiseOrdersSet_Inserting(PromiseOrders entity)
        {
            // Set the Username 
            entity.UserName = this.Application.User.Name;
        }

 

We also set the updating method:

 

        partial void PromiseOrdersSet_Updating(PromiseOrders entity)
        {
            // Set the Username 
            entity.UserName = this.Application.User.Name;
        }

 

We need to do this to protect the OData service points. Only setting this on the client side code (shown later) is not enough.

A user could access the OData service point directly and alter the value. Using the code above prevents this.

image

However, the UserName is not populated when we run the application.

image

To fix this, we first switch to File View.

image

We add a page to the Server project using the following code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LightSwitchApplication.Web
{
    public class GetUserName : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            using (var serverContext = ServerApplicationContext.CreateContext())
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(serverContext.Application.User.Name);
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

(this code uses the new serverContext API)

 

image

We switch back to Logical View, select the Entity, Client (tab), Write Code, and then the created method.

We add the following code:

 

myapp.PromiseOrders.created = function (entity) {
    // Set the default date for the Order
    entity.OrderDate = new Date();
    // Using a Promise object we can call the CallGetUserName function
    msls.promiseOperation(CallGetUserName).then(function PromiseSuccess(PromiseResult) {
        // Set the result of the CallGetUserName function to the 
        // UserName of the entity
        entity.UserName = PromiseResult;
    });
};
// This function will be wrapped in a Promise object
function CallGetUserName(operation) {
    $.ajax({
        type: 'post',
        data: {},
        url: '../web/GetUserName.ashx',
        success: operation.code(function AjaxSuccess(AjaxResult) {
            operation.complete(AjaxResult);
        })
    });
}

 

We run the project:

image

The UserName is now retrieved.

 

LightSwitch Help Website Articles

Writing JavaScript That Implements The Binding Pattern In Visual Studio LightSwitch

Implementing The Wijmo Radial Gauge In The LightSwitch HTML Client

Writing JavaScript In LightSwitch HTML Client Preview

Creating JavaScript Using TypeScript in Visual Studio LightSwitch

Theming Your LightSwitch Website Using JQuery ThemeRoller

Using Toastr with Visual Studio LightSwitch HTML Client (Preview)

 

LightSwitch Team HTML and JavaScript Articles

Custom Controls and Data Binding in the LightSwitch HTML Client (Joe Binder)

Creating Screens with the LightSwitch HTML Client (Joe Binder)

The LightSwitch HTML Client: An Architectural Overview (Stephen Provine)

Writing JavaScript Code in LightSwitch (Joe Binder)

New LightSwitch HTML Client APIs (Stephen Provine)

A New API for LightSwitch Server Interaction: The ServerApplicationContext

Building a LightSwitch HTML Client: eBay Daily Deals (Andy Kung)

 

Download Code

The LightSwitch project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

(you must have HTML Client Preview 2 or higher installed to run the code)

44 comment(s) so far...


Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Hi,

I'm try write down the stps above but I'm have problem with the part "We switch back to Logical View, select the Entity, Client (tab), Write Code, and then the created method.". I can't find the Client (tab). Beside that I can't find the "created method" (I understand because of the missing tab, right ?

Thanks for the help. Congratulations for the blog (Good job).

By Ventocilla on   1/9/2013 4:50 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Ventocilla - If you do not see that Client Tab then you do not have the HTML Client Preview 2 installed. There is a link at the bottom of my Blog post.

By Michael Washington on   1/9/2013 4:58 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Ok. Thanks a lot. I'm going to check that.

By Ventocilla on   1/12/2013 3:41 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Hi Michael,
thanks for the article, but i'm having some problems with this when I try to deploy it to an azure website. When running in debug mode all is well but when I try to run deployed on azure website it doesn't work.

To test this I added a simple Desktop client to your sample code just so that I could get the Administration screens to add new users. I added two users; test1 and test2, using the desktop client.

When I run the HTMLClient it prompts me for username and password as expected, but when I make the ajax call I receive an empty string for the user. I've tested that the IHttpHandler code is being called by hardcoding a dummy username to be returned.

Any idea what i'm doing wrong here!!! Any help would be greatly appreciated.

By dparker on   1/22/2013 4:17 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@dparker - I suspect that the path that the JavaScript is using needs to be adjusted when you deploy to Azure. Using Fiddler should help you figure out what is wrong.

By Michael Washington on   1/22/2013 5:49 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@dparker - The previous Beta of LightSwitch did not properly work with Forms Authentication. The new version does so this should no longer be a problem.

By Michael Washington on   3/14/2013 6:11 AM
Gravatar

Retrieving The Current User In The LightSwitch HTML Client

Hi michael washington , i deployed the PictureUploader application . can you give login user name and password , i try the server authentication its throw the this error "Your login attempt was not successful. Please try again"

By venkadesan on   4/18/2013 7:41 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@venkadesan - When you deploy an application the Publish wizard has a screen that allows you to set the username and password.

By Michael Washington on   4/18/2013 8:56 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Michael,
Does this work for windows authentication as well or only for forms authentication?
Scott

By Scott on   4/25/2013 9:44 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Scott - It has only been tested with Forms Authentication so I do not know.

By Michael Washington on   4/25/2013 9:45 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Michael,
I had the code in the Entity "Created" js instead of the html client browseappointments "created" screen. It works with AD/Windows and returns the correct username. :)
Scott

By Scott on   4/25/2013 2:09 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Thank you! This was very helpful in being able to customize the visible and enabled objects by user in my lightswitch html application.

By Louis Garcia on   6/21/2013 9:27 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I just finished doing this tutorial using the new Lightswitch in Visual Studio 2013 Preview.

It was interesting to see how the UI has been refined between VS 2012 and 2013. My hat is off to the UX designers...they did a great job streamlining these tasks. The part where it switched between "Logical View" and "Files view" was a little tricky, but everything went very smoothly.

Michael, thanks for a great blog post!

By infomaven on   7/21/2013 4:57 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I have tried this example a couple of times now and continue to get an error message (captured via Fiddler)

Any ideas on what the cause and resolution could be? Thanks in advance.

b> Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.


Parser Error Message: Could not create type '.GetUserName'.


By Darren on   7/25/2013 12:08 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Darren - When you download the code sample from the download page, does it work for you?

By Michael Washington on   7/25/2013 12:09 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Michael - thanks for the follow up. Yes it does work on the download and I have just figured out what the issue was when I tried to translate the solution to my own project.

Gets me every time, but it was a case sensitivity issue in the namespace. The actual namespace was LightSwitchApplication.Web and in the GetUserName markup file it was labeled as LightswitchApplication.Web -- lower case s got me.

Thanks again for your attention in following up. Have a great day.

BTW - I bought your most recent book and have been using it with my first HTML client project. Very helpful. I have a half dozen LS Silverlight projects under my belt but this is my first attempt with the HTML client.

By Darren on   7/26/2013 7:06 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Is this still the recommended method in VS LightSwitch 2013? If not, would you please point me in the right direction?

Thanks for all your articles - they've been very helpful.

By Mike Hellem on   11/17/2013 3:34 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@mike hellem - Yes this is still the way for Vs2013

By Michael Washington on   11/17/2013 3:35 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Thanks for the article Michael.

I can't run it on vb, your example runs ok on C#.

Public Class GetUserName
Implements IHttpHandler

Sub ProcessRequest(ByVal context As HttpContext)Implements IHttpHandler.ProcessRequest
Using serverContext = ServerApplicationContext.CreateContext()

context.Response.ContentType = "text/plain"
context.Response.Write(serverContext.Application.User.Name)

End Using

End Sub

ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property

End Class

Anything wrong?

By Fernando on   12/9/2013 7:57 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Fernando - Sorry I am no help on the VB. There can be small differences in the language that I do not keep up with. Post to the Microsoft forums and someone will know.

By Michael Washington on   12/9/2013 7:58 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I was tired yerterday... this morning with new energy I fixed:

Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

Dim servercontext = ServerApplicationContext.CreateContext()

context.Response.ContentType = "text/plain"
context.Response.Write(servercontext.Application.User.Name)

End Sub

Thanks!

By Fernando on   12/10/2013 4:46 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Michael you rock, you save my life, thank you very much

By Zuhtu İLİK on   1/7/2014 5:59 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Hi Michel,
Do you have any idea why there are times that I retrieve the user correctly, and others not?
I don't know where I could start looking to resolve it.

Thanks!

By Fernando on   1/29/2014 8:21 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Fernando - I think it is case sensitive. Change the code to convert the username and the name in the database to lowercase before doing the comparison.

By Michael Washington on   1/29/2014 8:22 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I haven't been clear, on "entity.UserName = PromiseResult;" there are times that I get the user name, and there are times that I get "" on PromiseResult.
I use a breakpoint on GetUserName, and using debug, the times that it didn't get the user, didn't go into "GetUserName". Is there a way to debug the function: "function CallGetUserName"?

Thanks!

By Fernando on   1/31/2014 4:50 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Fernando - I do not get that problem. I am unsure why that happens for you. You can place a breakpoint anywhere in the code to debug, however I am unsure if it will reveal anything.

By Michael Washington on   1/31/2014 4:51 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I think the problem comes in because the code sample above does not have a line saying

servercontext.Dispose

after the Response.Write call. This one caused me lots of problems yesterday, but adding a Dispose seems to have fixed it.

Regards,
Reece

By Reece Watkins on   2/20/2014 8:18 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Reece Watkins - THanks!

By Michael Washington on   2/20/2014 8:18 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Quick addendum: Fernando's original VB code fragment should have worked, as wrapping the Response.Write in a Using block removes the need to explicitly call Dispose on the variable servercontext. I've tried both ways now in my app, and they work either way. My original error stemmed from using the Dim statement to instantiate servercontext without calling Dispose explicitly, as Fernando did in his second code fragment. This caused all sorts of hangs, Runtime Errors returned, and general chaos. However, as soon as the Dispose was handled properly, either explicitly or implicitly with a Using block, the app then worked as it should.

By Reece Watkins on   2/20/2014 10:37 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I was trying to solve this for months and today I've found my error, then I wanted to share it and I found that Reece has posted the answer one month ago :(
I don't forget "Using" lesson in my life ;)

Thanks Reece!

By Fernando on   3/27/2014 4:37 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

First off I just purchased your html client book (Michael) and it is very good.
I have a question about this solution. I have a UserModified field in a table that I update on the server side using the entity_Updating method and this works by itself. I do not need to show this on the html client side. However, the issue is that when I click on a grid in the browse screen to edit record and then save and if I click on same record to edit again and click save, I get the Save Operation failed error and it wants me to refresh the browse screen which I do not want to do. This seems to be an issue (look at http://markgstacey.net/2013/05/09/using-sql-server-defaults-with-lightswitch/ and http://social.msdn.microsoft.com/Forums/en-US/786d9d6f-ba7c-476c-b9ff-efb4f4b653c7/value-on-screen-doesnt-match-value-in-the-entity?forum=lightswitchhtml ) in VS 2012.

I am using VS 2013 and it still is an issue that Huy Nguyen said that would be fixed in an update to refresh the screen.
So should I use the code in the first link to fix my issue or maybe update UserModified in the client side using your code? I do not understand why this is still an issue. That means you cannot save any data in the Updating method in the server since the html client will cache and not sync with the server changes. This means you cannot use the updating method at all in my opinion. I am using AD authentication.

By G Wade on   3/28/2014 7:08 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@G Wade - It does not appear to me that the issue you are having is related to the link you posted. My advise is to make a post in the LightSwitch forums posting as much of the code and screen shots as you can. The comments in my blog is horrible for resolving any issues.

By Michael Washington on   3/28/2014 7:11 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

OK, I added it to the msdn forum, http://social.msdn.microsoft.com/Forums/vstudio/en-US/e694fc49-d349-45ca-b812-f21fafebcaec/save-operation-failed-in-html-client-screen?forum=lightswitch .
I noticed that when I remove the code in the server side updating method everything is OK but when the usermodified field is updated then I get the error: Save Operation failed. The data your are editing has been updated by another transaction. Please refresh the page and try again. It is just a simple browse grid screen and an edit screen.
Thanks

By G Wade on   3/28/2014 1:24 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Hi Michael,
I had problems again with promise operation after March 2014 Update, but just with an upgraded project.
Now the url needs myapp.rootUri.

Do you know why this has changed?

Thank you!

By Fernando on   5/6/2014 12:51 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Fernando - I am sorry I do not know.

By Michael Washington on   5/6/2014 12:51 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

Hi,

one thing I don't understand.
Why would we create the UserName field when there is CreatedBy field already there.
Isn't it the same user (string)? How can we call that CreatedBy field in the screen?

By Semper on   6/29/2014 10:22 PM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Semper - This tutorial was created before the CreatedBy field was a part of LightSwitch. This tutorial will show the user name before the record is saved. The CreatedBy field will only be updated after the record is saved.

By Michael Washington on   6/30/2014 3:52 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I am using Visual Studio 2013 and your solution works if I use Windows Authenfication. In my own solution which is using a database as datasource, I allways recieving "No items". It doesn't seems to entering the methods (inserting, updating or create) ? Any idea whats happening? Is this the only way of getting the logged in user?

By Freddie on   9/3/2014 7:44 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Freddie - This is the only example I have. This may help: http://blogs.msdn.com/b/mthalman/archive/2013/06/25/customizing-lightswitch-user-management.aspx

By Michael Washington on   9/3/2014 7:50 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I wonder if you could use the screen object instead like:

myapp.PromiseOrders.created = function (screen) {

By Freddie on   9/4/2014 3:40 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

I am getting this error:
arguments = Accessing the 'arguments' property of a function is not allowed in strict mode
when the application executes:
ls.promiseOperation(CallGetUserName).then(function PromiseSuccess(PromiseResult) {

Any cluess?

By Freddie on   9/4/2014 3:41 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Freddie - The comments section is not a good place to handle technical questions. You can get help in the Officuial LightSwitch forums at: http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=lightswitch

By Michael Washington on   9/4/2014 4:08 AM
Gravatar

is it possible to disable case-sensitive of datagrid serach box in lightswitch

HI ,

Could you please help me.

I have created one lightswtich application using c#. my problem is when i'm not able to search the record with name of some 'X' in data grid until and unless providing very first letter as capital.

thanks in advance.

Thanks,
Siva.

By Siva on   9/15/2014 3:47 AM
Gravatar

Re: Retrieving The Current User In The LightSwitch HTML Client

@Siva - For help please post to the LightSwitch forums at: http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=lightswitch

By Michael Washington on   9/15/2014 3:49 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 

Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation