public PSADServicePrincipal CreateServicePrincipal(CreatePSServicePrincipalParameters createParameters)
        {
            ServicePrincipalCreateParameters graphParameters = new ServicePrincipalCreateParameters
            {
                AppId          = createParameters.ApplicationId.ToString(),
                AccountEnabled = createParameters.AccountEnabled
            };

            try
            {
                return(GraphClient.ServicePrincipal.Create(graphParameters).ServicePrincipal.ToPSADServicePrincipal());
            }
            catch (CloudException ce)
            {
                if (ce.Response.StatusCode == HttpStatusCode.Forbidden)
                {
                    GetCurrentUserResult currentUser = GraphClient.Objects.GetCurrentUser();
                    if (currentUser.AADObject != null && string.Equals(currentUser.AADObject.UserType, "Guest", StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new InvalidOperationException(ProjectResources.CreateServicePrincipalNotAllowedGuestUser);
                    }
                }

                throw;
            }
        }
        public PSADApplication CreateApplication(CreatePSApplicationParameters createParameters)
        {
            IList <PasswordCredential> passwordCredentials = createParameters.PasswordCredentials != null
                ? createParameters.PasswordCredentials.Select(psCredential => psCredential.ToGraphPasswordCredential()).ToList()
                : null;

            IList <KeyCredential> keyCredentials = createParameters.KeyCredentials != null
                ? createParameters.KeyCredentials.Select(psCredential => psCredential.ToGraphKeyCredential()).ToList()
                : null;

            ApplicationCreateParameters graphParameters = new ApplicationCreateParameters
            {
                DisplayName         = createParameters.DisplayName,
                Homepage            = createParameters.HomePage,
                IdentifierUris      = createParameters.IdentifierUris,
                PasswordCredentials = passwordCredentials,
                KeyCredentials      = keyCredentials
            };

            try
            {
                return(GraphClient.Application.Create(graphParameters).Application.ToPSADApplication());
            }
            catch (CloudException ce)
            {
                if (ce.Response.StatusCode == HttpStatusCode.Forbidden)
                {
                    GetCurrentUserResult currentUser = GraphClient.Objects.GetCurrentUser();
                    if (currentUser.AADObject != null && string.Equals(currentUser.AADObject.UserType, "Guest", StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new InvalidOperationException(ProjectResources.CreateApplicationNotAllowedGuestUser);
                    }
                }

                throw;
            }
        }
        /// <summary>
        /// Gets the details for current logged in user
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Server response for Active Directory objects inquiry API calls
        /// </returns>
        public async Task <GetCurrentUserResult> GetCurrentUserAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                TracingAdapter.Enter(invocationId, this, "GetCurrentUserAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.TenantID);
            url = url + "/me";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=1.6-internal");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    GetCurrentUserResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new GetCurrentUserResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            AADObject aADObjectInstance = new AADObject();
                            result.AADObject = aADObjectInstance;

                            JToken objectIdValue = responseDoc["objectId"];
                            if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
                            {
                                string objectIdInstance = ((string)objectIdValue);
                                aADObjectInstance.ObjectId = objectIdInstance;
                            }

                            JToken objectTypeValue = responseDoc["objectType"];
                            if (objectTypeValue != null && objectTypeValue.Type != JTokenType.Null)
                            {
                                string objectTypeInstance = ((string)objectTypeValue);
                                aADObjectInstance.ObjectType = objectTypeInstance;
                            }

                            JToken displayNameValue = responseDoc["displayName"];
                            if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
                            {
                                string displayNameInstance = ((string)displayNameValue);
                                aADObjectInstance.DisplayName = displayNameInstance;
                            }

                            JToken userPrincipalNameValue = responseDoc["userPrincipalName"];
                            if (userPrincipalNameValue != null && userPrincipalNameValue.Type != JTokenType.Null)
                            {
                                string userPrincipalNameInstance = ((string)userPrincipalNameValue);
                                aADObjectInstance.UserPrincipalName = userPrincipalNameInstance;
                            }

                            JToken mailValue = responseDoc["mail"];
                            if (mailValue != null && mailValue.Type != JTokenType.Null)
                            {
                                string mailInstance = ((string)mailValue);
                                aADObjectInstance.Mail = mailInstance;
                            }

                            JToken mailEnabledValue = responseDoc["mailEnabled"];
                            if (mailEnabledValue != null && mailEnabledValue.Type != JTokenType.Null)
                            {
                                bool mailEnabledInstance = ((bool)mailEnabledValue);
                                aADObjectInstance.MailEnabled = mailEnabledInstance;
                            }

                            JToken securityEnabledValue = responseDoc["securityEnabled"];
                            if (securityEnabledValue != null && securityEnabledValue.Type != JTokenType.Null)
                            {
                                bool securityEnabledInstance = ((bool)securityEnabledValue);
                                aADObjectInstance.SecurityEnabled = securityEnabledInstance;
                            }

                            JToken signInNameValue = responseDoc["signInName"];
                            if (signInNameValue != null && signInNameValue.Type != JTokenType.Null)
                            {
                                string signInNameInstance = ((string)signInNameValue);
                                aADObjectInstance.SignInName = signInNameInstance;
                            }

                            JToken servicePrincipalNamesArray = responseDoc["servicePrincipalNames"];
                            if (servicePrincipalNamesArray != null && servicePrincipalNamesArray.Type != JTokenType.Null)
                            {
                                foreach (JToken servicePrincipalNamesValue in ((JArray)servicePrincipalNamesArray))
                                {
                                    aADObjectInstance.ServicePrincipalNames.Add(((string)servicePrincipalNamesValue));
                                }
                            }

                            JToken userTypeValue = responseDoc["userType"];
                            if (userTypeValue != null && userTypeValue.Type != JTokenType.Null)
                            {
                                string userTypeInstance = ((string)userTypeValue);
                                aADObjectInstance.UserType = userTypeInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }