1

I'm try to get a unique session id whenever a user launches an app. This ID should be created every time a user enters the application. Is something like this available in Windows 8 WinJS API?

bhavinp
  • 823
  • 1
  • 9
  • 18
  • What is the purpose of this session id? Why not just generate a GUID when the user activates the app? – JP Alioto Feb 20 '13 at 19:38
  • This information is required for tracking purposes, it will be sent to a server logging the user activity and I need the session ID to distinguish an application session. I cannot generate one myself because the way its architected, there can be multiple GUIDs generated per session. So I was wondering if there is already something available in Windows 8 for a unique application session for every launch. – bhavinp Feb 20 '13 at 19:45
  • What do you mean "there can be multiple GUIDs generated per session"? If you don't want there to be multiple GUIDs, generate it once and store it. – JP Alioto Feb 20 '13 at 20:05
  • The thing is, I'm making a library and the object within can be instantiated and disposed of multiple times per session; so I need a way to either store a value for the session or pull one from the WinJS API – bhavinp Feb 20 '13 at 20:11
  • I ended up doing the following using the code to generate a guid below. var sessionState = WinJS.Application.sessionState; if (sessionState["application_session_unique_identifier"] == null) { sessionState["application_session_unique_identifier"] = this.guid(); } – bhavinp Feb 20 '13 at 20:44

2 Answers2

2

Session Ids are and likely will always be GUID based because of the random nature and very very very rare chance of a collision (duplicate id)

If using csharp (I know you aren't here, I'll address that), it's simply a matter of creating one on your application startup in cs


var id = Guid.NewGuid();

since you are using WinJS there is no built in Guid support, so you can either create a Windows Store component to distribute with your app and thus use csharp to create it, or generate one in JavaScript as taken from (please upvote the source SO post linked here if it applies):

Create GUID / UUID in JavaScript?


function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
             .toString(16)
             .substring(1);
};

function guid() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
         s4() + '-' + s4() + s4() + s4();
}

var uuid = guid();
Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
1

Here's my GUID creation function of choice...

createGuid: function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });

If you look at it too long your head will explode so just plug it in and use it :)

Jeremy Foster
  • 4,673
  • 3
  • 30
  • 49