Showing posts with label windows azure cache service. Show all posts
Showing posts with label windows azure cache service. Show all posts

Tuesday, October 22, 2013

Geotopia: additional features and sending emails

In the last blog I explained how to use Windows Azure Active Directory and Windows Azure Caching Service. This blog post will dive a bit deeper in these concepts but also adds SendGrid to the solution in order to send emails to users with their temporary password.

The WebAPI Controller will perform the following steps:

1. Create a user in WAAD by using Microsoft.WindowsAzure.ActiveDirectory.GraphHelper. The following snippets achieves this goal. It also creates some temporary password based on a Guid.

Note: your tenant ID can be found on the Windows Azure portal. Go to your application in the directory screen on the portal. Click View Endpoints and you will see a list of endpoints. When you have a look at your OAuth 2.0 token endpoint you will see the URL in following shape:

https://login.windows.net//oauth2/token?api-version=1.0

//add to to Windows Azure Active Directory
            string clientId = CloudConfigurationManager.GetSetting("ClientId").ToString();
            string password = CloudConfigurationManager.GetSetting("ClientPassword").ToString();
            // get a token using the helper
            AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken("", clientId, password);
            // initialize a graphService instance using the token acquired from previous step
            DirectoryDataService graphService = new DirectoryDataService("", token);

            User newWAADUser = new Microsoft.WindowsAzure.ActiveDirectory.User();
            newWAADUser.accountEnabled = true;
            newWAADUser.displayName = user.UserName;
            newWAADUser.mailNickname = user.UserName;
            PasswordProfile pwdProfile = new PasswordProfile();
            pwdProfile.forceChangePasswordNextLogin = true;
            pwdProfile.password = Guid.NewGuid().ToString("N").Substring(1, 10) + "!";
            newWAADUser.userPrincipalName = user.UserName + "@geotopia.onmicrosoft.com";
            newWAADUser.passwordProfile = pwdProfile;
            graphService.AddTousers(newWAADUser);
            var response = graphService.SaveChanges();

I registered "FirstUser" as being the user with an emailaddress I own. As you can see in the next figure, the user is added to the Windows Azure Active Directory.


2. An email is sent to the user with his/her temporary password which is generated in step 1. For sending emails, I use the Windows Azure add-on SendGrid which can be easily configured.

//send email to user by using SendGrid
            SendGrid myMessage = SendGrid.GetInstance();
            myMessage.AddTo(user.EmailAddress);
            myMessage.From = new MailAddress("info@geotopia.com", "Geotopia Administrator");
            myMessage.Subject = "Attention: Your temporary password for Geotopia";
            myMessage.Text = "Your username on Geotopia is:" + user.UserName + "\n\r";
            myMessage.Text += "Temporary password:" + pwdProfile.password + "\n\r";
            myMessage.Text += "\n\r";
            myMessage.Text += "The first time you sign in with your temporary password, you need to change it.";

            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential("", "");

            // Create an SMTP transport for sending email.
            var transportSMTP = SMTP.GetInstance(credentials);

            // Send the email.
            transportSMTP.Deliver(myMessage);

After this, I get an email!


3. The user is added to the neo4j graph db. This snippet is already shown in the previous blog post.
4. Add the user to the Windows Azure Cache. This snippets is also shown in the previous blog post.

So, with everything in place now I finalize the search window on geotopia to look for users and start following them. I will blog about this feature in the next few days....

Happy coding!


Monday, October 21, 2013

Geotopia: searching and adding users (Windows Azure Cache Service)

Now that we are able to sign in and add geotopic, the next step would be to actually find users and follow them. The first version of Geotopia will allow everybody to follow everybody, a ring of authorization will be added in the future (users need to allow you to follow them after all).

For fast access and fast search, I decided to use the Windows Azure Cache Service preview to store a table of available users. An entry in the cache is created for everyone that signed up.

First of all, I created a a new cache on the Windows Azure portal.


Azure now has a fully dedicated cache for me up and running. Every created cache has a default cache that is used when no additional information is provided.

Next step is to get the necessary libraries and add them to my webrole. Use the Nuget package manager to get them and search for Windows Azure Caching. This will add the right assemblies and modifies the web.config. It adds a configsection to the configuration file (dataCacheClients).

Now with the cache in place and up and running, I can start adding entries to the cache when somebody signs up and make him/her available in the search screen.

Later on, we can also cache Page Output (performance!) and Session State (scalability).

I also created a controller/view combination that allows users to signup with simply their username and an emailaddress. The temporarily password will be sent to this email account.

Download the Windows Azure AD  Graph Helper at http://code.msdn.microsoft.com/Windows-Azure-AD-Graph-API-a8c72e18 and add it to your solution. Reference it from the project that needs to query the graph and create users.

Summary
The UserController performs the following tasks:
1. Add the registered user to Windows Azure Active Directory by using the Graph Helper
2. Adds the user to the neo4j graph db to enable it to post geotopics
3. Add the user to the Windows Azure Cache to make the user findable.

This snippet does it all.

            string clientId = CloudConfigurationManager.GetSetting("ClientId").ToString();
            string password = CloudConfigurationManager.GetSetting("ClientPassword").ToString();
            // get a token using the helper
            AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken("", clientId, password);
            // initialize a graphService instance using the token acquired from previous step
            DirectoryDataService graphService = new DirectoryDataService("", token);
            //add to Neo4j graph
            GeotopiaUser user1 = new GeotopiaUser(user.UserName, user.UserName, user.UserName + "@geotopia.onmicrosoft.com");

            var geoUser1 = client.Create(user1,
                new IRelationshipAllowingParticipantNode[0],
                new[]
                            {
                                new IndexEntry("GeotopiaUser")
                                {
                                    { "Id", user1.id.ToString() }
                                }
                            });
            //add to cache
            object result = cache.Get(user.UserName);
            if (result == null)
            {
                // "Item" not in cache. Obtain it from specified data source
                // and add it.
                cache.Add(user.UserName, user);
            }
            else
            {
                Trace.WriteLine(String.Format("User already exists : {0}", user.UserName));
                // "Item" is in cache, cast result to correct type.
            }

The modal dialog on the Geotopia canvas searches the cache every time a keydown is notices and displays the users that meet the query input of the dialog.