Пример #1
0
        /// <summary>
        /// Gets details of a single <see cref="Contact"/> Graph.
        /// </summary>
        /// <returns>A view with the details of a single <see cref="Contact"/>.</returns>
        public ActionResult Details(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            // Setup Graph API connection and get single Contact
            Guid          ClientRequestId = Guid.NewGuid();
            GraphSettings graphSettings   = new GraphSettings();

            graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
            GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings);

            Contact contact = graphConnection.Get <Contact>(objectId);

            return(View(contact));
        }
 public GraphModel(DocumentClient client, DocumentCollection collection)
 {
     this.client          = client;
     this.collection      = collection;
     this.graphConnection = new GraphConnection(client, collection);
     this.graphCommand    = new GraphCommand(this.graphConnection);
 }
Пример #3
0
        public ActionResult Delete(User user)
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and delete User
                var clientRequestId = Guid.NewGuid();
                var graphSettings   = new GraphSettings {
                    ApiVersion = GraphConfiguration.GraphApiVersion
                };
                var graphConnection = new GraphConnection(accessToken, clientRequestId, graphSettings);
                graphConnection.Delete(user);
                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View(user));
            }
        }
Пример #4
0
        static int Main(string[] args)
        {
            var connection = new GraphConnection();

            if (args.Length < 1)
            {
                PrintUsage();

                return(1);
            }

            string responseContent;

            try
            {
                responseContent = connection.InvokeRequestAndDeserialize(args[0]);
            }
            catch (GraphHttpException exception)
            {
                Console.Error.WriteLine("Request failed with status code {0}", exception.StatusCode);
                Console.Error.WriteLine(exception.Message);
                return(1);
            }

            Console.WriteLine(responseContent);

            return(0);
        }
        public ActionResult Create([Bind(Include = "DisplayName,Description,MailNickName,SecurityEnabled")] Group group)
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and add Group
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings);
                group.MailEnabled = false;

                graphConnection.Add(group);
                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
Пример #6
0
        /// <summary>
        /// Gets a list of <see cref="User"/> objects that a given <see cref="User"/> has as a direct report.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param>
        /// <returns>A view with the list of <see cref="User"/> objects.</returns>
        public ActionResult GetDirectReports(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            // Setup Graph API connection and get Group membership
            Guid          ClientRequestId = Guid.NewGuid();
            GraphSettings graphSettings   = new GraphSettings();

            graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
            GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings);

            GraphObject         graphUser = graphConnection.Get <User>(objectId);
            IList <GraphObject> results   = graphConnection.GetAllDirectLinks(graphUser, LinkProperty.DirectReports);
            IList <User>        reports   = new List <User>();

            foreach (GraphObject obj in results)
            {
                if (obj is User)
                {
                    User user = (User)obj;
                    reports.Add(user);
                }
            }
            return(View(reports));
        }
Пример #7
0
        public ActionResult Create([Bind(Include = "UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user)
        {
            //Get the access token as we need it to make a call to the Graph API
            var accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and add User
                var clientRequestId = Guid.NewGuid();
                var graphSettings   = new GraphSettings {
                    ApiVersion = GraphConfiguration.GraphApiVersion
                };
                var graphConnection = new GraphConnection(accessToken, clientRequestId, graphSettings);

                graphConnection.Add(user);
                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
Пример #8
0
        // GET: UserProfile
        public ActionResult Index()
        {
            string clientId        = ConfigurationManager.AppSettings["ida:ClientID"];
            string appKey          = ConfigurationManager.AppSettings["ida:Password"];
            string graphResourceID = "https://graph.windows.net";
            string signedInUserID  = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string tenantID        = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string userObjectID    = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            try
            {
                // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
                ClientCredential clientcred = new ClientCredential(clientId, appKey);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID), new EFADALTokenCache(signedInUserID));
                AuthenticationResult  result      = authContext.AcquireTokenSilent(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // use the token for querying the graph
                GraphSettings graphSettings = new GraphSettings();
                graphSettings.ApiVersion      = "2013-11-08";
                graphSettings.GraphDomainName = "graph.windows.net";
                Guid            ClientRequestId = Guid.NewGuid();
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);
                User            user            = graphConnection.Get <User>(userObjectID);

                return(View(user));
            }
            // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
            catch (Exception ee)
            {
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }
        }
Пример #9
0
        public void Test()
        {
            var connection = new GraphConnection <int>();

            connection.AddPredecessor(1);
            Assert.True(connection.IsPredecessors(1));
            Assert.True(connection.RemovePredecessor(1));
            Assert.False(connection.IsPredecessors(1));
            connection.AddSuccessor(1);
            Assert.True(connection.IsSuccessors(1));
            Assert.True(connection.RemoveSuccessor(1));
            Assert.False(connection.IsSuccessors(1));
            connection.AddPredecessor(1);
            connection.AddSuccessor(1);
            Assert.True(connection.IsPredecessors(1));
            Assert.True(connection.IsSuccessors(1));
            Assert.True(connection.RemovePredecessor(1));
            Assert.False(connection.IsPredecessors(1));
            connection.AddPredecessor(1);
            Assert.True(connection.RemoveSuccessor(1));
            Assert.False(connection.IsSuccessors(1));
            Assert.True(connection.RemovePredecessor(1));
            Assert.False(connection.RemovePredecessor(1));
            Assert.False(connection.RemoveSuccessor(1));
        }
Пример #10
0
        public override void OnTapUp(float x, float y)
        {
            if (IsInConnector(x, y, parentNode.Width) && Graph.currentlyInteractingNode != null && Graph.currentlyInteractingRow != -1)
            {
                var newConnection = new GraphConnection();
                if (this is OutputRow)
                {
                    newConnection.source    = parentNode;
                    newConnection.sourceRow = parentNode.Rows.FindIndex(r => r == this);
                    newConnection.sink      = Graph.currentlyInteractingNode;
                    newConnection.sinkRow   = Graph.currentlyInteractingRow;
                }
                else if (this is InputRow)
                {
                    newConnection.source    = Graph.currentlyInteractingNode;
                    newConnection.sourceRow = Graph.currentlyInteractingRow;
                    newConnection.sink      = parentNode;
                    newConnection.sinkRow   = parentNode.Rows.FindIndex(r => r == this);
                }

                if (!parentNode.parentGraph.connections.Exists(c => c.Equals(newConnection)) && ConnectionFilter(newConnection))
                {
                    parentNode.parentGraph.connections.Add(newConnection);
                }
            }
        }
Пример #11
0
        public void TestClone()
        {
            BuildCyclicGraph();

            Graph <String> dup = (Graph <String>)Graph.Clone();

            Assert.IsTrue(ListsAreEqual(Graph.Nodes, dup.Nodes));

            Assert.AreEqual(dup.Weights.Count, Graph.Weights.Count);
            foreach (GraphNode <String> sourceKeyNode in dup.Weights.Keys)
            {
                Assert.IsTrue(Graph.Weights.ContainsKey(sourceKeyNode));
                Assert.AreEqual(dup.Weights[sourceKeyNode].Count, Graph.Weights[sourceKeyNode].Count);
                foreach (GraphNode <String> destinationKeyNode in dup.Weights[sourceKeyNode].Keys)
                {
                    Assert.IsTrue(Graph.Weights[sourceKeyNode].ContainsKey(destinationKeyNode));
                    Assert.AreEqual(dup.Weights[sourceKeyNode][destinationKeyNode].Count, Graph.Weights[sourceKeyNode][destinationKeyNode].Count);
                    for (Int32 i = 0; i < dup.Weights[sourceKeyNode][destinationKeyNode].Count; ++i)
                    {
                        GraphConnection <String> dupConnection   = dup.Weights[sourceKeyNode][destinationKeyNode][i];
                        GraphConnection <String> graphConnection = Graph.Weights[sourceKeyNode][destinationKeyNode][i];
                        Assert.AreEqual(dupConnection.Weight, graphConnection.Weight, WEIGHT_TOLERANCE);
                    }
                }
            }
        }
Пример #12
0
    /// <summary>
    /// Splits a list of borders into clusters, where in each cluster the borders are connected
    /// </summary>
    public static List <List <GraphConnection> > FindBorderClusters(List <GraphConnection> borders)
    {
        List <List <GraphConnection> > clusters = new List <List <GraphConnection> >();

        List <GraphConnection> bordersWithoutCluster = new List <GraphConnection>();

        bordersWithoutCluster.AddRange(borders);

        while (bordersWithoutCluster.Count > 0)
        {
            List <GraphConnection>  cluster      = new List <GraphConnection>();
            Queue <GraphConnection> bordersToAdd = new Queue <GraphConnection>();
            bordersToAdd.Enqueue(bordersWithoutCluster[0]);
            while (bordersToAdd.Count > 0)
            {
                GraphConnection borderToAdd = bordersToAdd.Dequeue();
                cluster.Add(borderToAdd);
                List <GraphConnection> connectedBorders = borderToAdd.Connections.Where(x => borders.Contains(x)).ToList();
                foreach (GraphConnection connectedBorder in connectedBorders)
                {
                    if (!cluster.Contains(connectedBorder) && !bordersToAdd.Contains(connectedBorder))
                    {
                        bordersToAdd.Enqueue(connectedBorder);
                    }
                }
            }
            clusters.Add(cluster);
            foreach (GraphConnection border in cluster)
            {
                bordersWithoutCluster.Remove(border);
            }
        }

        return(clusters);
    }
Пример #13
0
        /// <summary>
        /// Gets a list of <see cref="Contact"/> objects from Graph.
        /// </summary>
        /// <returns>A view with the list of <see cref="Contact"/> objects.</returns>
        public ActionResult Index()
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            //Setup Graph API connection and get a list of users
            Guid          ClientRequestId = Guid.NewGuid();
            GraphSettings graphSettings   = new GraphSettings();

            graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
            GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings);

            PagedResults <Contact> pagedResults = graphConnection.List <Contact>(null, new FilterGenerator());

            return(View(pagedResults.Results));
        }
Пример #14
0
        /// <summary>
        /// Creates a view to for editing an existing <see cref="User"/> in Graph.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param>
        /// <returns>A view with details to edit <see cref="User"/>.</returns>
        public ActionResult Edit(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            // Setup Graph API connection and get single User
            var clientRequestId = Guid.NewGuid();
            var graphSettings   = new GraphSettings {
                ApiVersion = GraphConfiguration.GraphApiVersion
            };
            var graphConnection = new GraphConnection(accessToken, clientRequestId, graphSettings);

            var user = graphConnection.Get <User>(objectId);

            return(View(user));
        }
        /// <summary>
        /// Creates a view to delete an existing <see cref="User"/>.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param>
        /// <returns>A view of the <see cref="User"/> to be deleted.</returns>
        public ActionResult Delete(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and get single User
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings);
                User            user            = graphConnection.Get <User>(objectId);
                return(View(user));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
Пример #16
0
        public AzureADGraphConnection(string tenantName, string clientId, string clientSecret)
        {
            var authenticationContext = new AuthenticationContext("https://login.windows.net/" + tenantName, false);
            var clientCred            = new ClientCredential(clientId, clientSecret);
            var token = authenticationContext.AcquireToken(Resource, clientCred).AccessToken;

            _graphConnection = new GraphConnection(token, ClientRequestId);
        }
Пример #17
0
        public ActionResult Create([Bind(Include = "DisplayName,Description,MailNickName,SecurityEnabled")] Group group)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and add Group
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                if (result != null)
                {
                    GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId,
                                                                          graphSettings);
                    group.MailEnabled = false;
                    graphConnection.Add(group);
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
            ViewBag.ErrorMessage = "AuthorizationRequired";
            return(View());
        }
Пример #18
0
        public IEnumerable <User> GetUsersInGroup(string accessToken, string groupId)
        {
            CallContext     currentCallContext = new CallContext(accessToken, Guid.NewGuid());
            GraphConnection graphConnection    = new GraphConnection(currentCallContext);
            var             fieldAgentsGroup   = graphConnection.Get <Group>(groupId);
            var             fieldAgentMembers  = graphConnection.GetLinks(fieldAgentsGroup, "members", null);

            return(fieldAgentMembers.Results.OfType <User>());
        }
        public ActionResult Users()
        {
            // get the tenantName
            var tenantId = ClaimsPrincipal.Current.FindFirst(ClaimType).Value;

            var authenticationContext = new AuthenticationContext(
                string.Format(AuthString, tenantId),
                false);

            authenticationContext.TokenCacheStore.Clear();

            // retrieve the clientId and password from the Web.config file
            var clientId     = ConfigurationManager.AppSettings["ClientId"];
            var clientSecret = ConfigurationManager.AppSettings["Password"];

            // create the credentials and get a token
            var clientCred = new ClientCredential(clientId, clientSecret);

            try
            {
                var token = authenticationContext.AcquireToken(Resource, clientCred).AccessToken;

                if (!string.IsNullOrEmpty(token))
                {
                    var graphSettings = new GraphSettings
                    {
                        ApiVersion      = "2013-11-08",
                        GraphDomainName = "graph.windows.net"
                    };

                    // get tenant information
                    var graphConnection = new GraphConnection(token, graphSettings);
                    var tenant          = graphConnection.Get(typeof(TenantDetail), tenantId);
                    if (tenant != null)
                    {
                        var tenantDetail = (TenantDetail)tenant;
                        ViewBag.OtherMessage = "User List from tenant: " + tenantDetail.DisplayName;
                    }

                    // get the list of users
                    var pagedReslts = graphConnection.List <User>(null, new FilterGenerator());
                    return(this.View(pagedReslts.Results));
                }
            }
            catch (ActiveDirectoryAuthenticationException ex)
            {
                ViewBag.OtherMessage = string.Format("Acquiring a token failed with the following error: {0}", ex.Message);
            }
            catch (AuthorizationException e)
            {
                ViewBag.OtherMessage = string.Format("Failed to return the list of Users with Exception: {0}", e.ErrorMessage);
            }

            return(this.View());
        }
        /// <summary>
        /// Gets a list of <see cref="User"/> objects that are members of a give <see cref="Role"/>.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="Role"/>.</param>
        /// <returns>A view with the list of <see cref="User"/> objects.</returns>
        public ActionResult GetMembers(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;
            IList <User>         users  = new List <User>();

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // Setup Graph API connection and get a list of roles
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                Role role = graphConnection.Get <Role>(objectId);
                IList <GraphObject> members = graphConnection.GetAllDirectLinks(role, LinkProperty.Members);

                // Filter for users
                foreach (GraphObject obj in members)
                {
                    if (obj is User)
                    {
                        users.Add((User)obj);
                    }
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            return(View(users));
        }
        /// <summary>
        /// Creates a view to for adding a key credential to an existing <see cref="Application"/> in Graph.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="Application"/>.</param>
        /// <returns>A view with details to add a key to the <see cref="Application"/>.</returns>
        public ActionResult AddKey(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;
            Application          app    = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                //Setup Graph API connection and get a list of groups
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                app = graphConnection.Get <Application>(objectId);
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }
            KeyCredential key = new KeyCredential();

            key.KeyId = System.Guid.NewGuid();
            key.Type  = "Symmetric";
            key.Usage = "Verify";
            String keyValue = "VSoJ0xLgSyQv60M+mJCtJOMM6yflDz5pLnAVNzGT6do=";

            byte[] keyBytes = System.Text.Encoding.ASCII.GetBytes(keyValue);
            key.Value = keyBytes;
            app.KeyCredentials.Add(key);

            return(View(app));
        }
Пример #22
0
        public ActionResult Edit([Bind(Include = "ObjectId,UserPrincipalName,DisplayName,AccountEnabled,GivenName,Surname,JobTitle,Department,Mobile,StreetAddress,City,State,Country,")] User user, FormCollection values)
        {
            //Get the access token as we need it to make a call to the Graph API
            string accessToken = AuthUtils.GetAuthToken(Request, HttpContext);

            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // TODO: Add update logic here

                // Setup Graph API connection and update single User
                var clientRequestId = Guid.NewGuid();
                var graphSettings   = new GraphSettings {
                    ApiVersion = GraphConfiguration.GraphApiVersion
                };
                var graphConnection = new GraphConnection(accessToken, clientRequestId, graphSettings);
                graphConnection.Update(user);

                // update thumbnail photo



                if (!String.IsNullOrEmpty(values["photofile"]))
                {
                    //string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
                    //string filename = Path.GetFileName(values["photofile"]);
                    //Image image = Image.FromFile(filename);

                    var imageFile = Path.Combine(Server.MapPath("~/app_data"), values["photofile"]);
                    var image     = Image.FromFile(imageFile);

                    var stream = new MemoryStream();
                    image.Save(stream, ImageFormat.Jpeg);

                    // Write the photo file to the Graph service.
                    graphConnection.SetStreamProperty(user, GraphProperty.ThumbnailPhoto, stream, "image/jpeg");
                }


                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
        /// <summary>
        /// Gets a list of <see cref="Contact"/> objects from Graph.
        /// </summary>
        /// <returns>A view with the list of <see cref="Contact"/> objects.</returns>
        public ActionResult Index()
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result      = null;
            List <Contact>       contactList = new List <Contact>();

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // Setup Graph API connection and get a list of users
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                // Get all results into a list
                PagedResults <Contact> pagedResults = graphConnection.List <Contact>(null, new FilterGenerator());
                contactList.AddRange(pagedResults.Results);
                while (!pagedResults.IsLastPage)
                {
                    pagedResults = graphConnection.List <Contact>(pagedResults.PageToken, new FilterGenerator());
                    contactList.AddRange(pagedResults.Results);
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            return(View(contactList));
        }
Пример #24
0
        private static bool UserIsMemberOfGroup(GraphConnection graphConnection, string userUPN, string groupDisplayName)
        {
            // Get the group for which we want to check membership
            FilterGenerator filter           = new FilterGenerator();
            Expression      filterExpression = ExpressionHelper.CreateEqualsExpression(typeof(Group), GraphProperty.DisplayName, groupDisplayName);

            filter.QueryFilter = filterExpression;
            PagedResults <Group> groupToCheckResults = graphConnection.List <Group>(null, filter);

            if (groupToCheckResults.Results.Count == 1)
            {
                // Add group to our groups to check list
                Group          groupToCheck = groupToCheckResults.Results[0] as Group;
                IList <String> groupsList   = new List <string>();
                groupsList.Add(groupToCheck.ObjectId);

                // Get the user for which we want to check the group membership
                FilterGenerator userFilter           = new FilterGenerator();
                Expression      userFilterExpression = ExpressionHelper.CreateEqualsExpression(typeof(User), GraphProperty.UserPrincipalName, userUPN);
                userFilter.QueryFilter = userFilterExpression;
                User retrievedUser = new User();
                PagedResults <User> pagedUserResults = graphConnection.List <User>(null, userFilter);
                if (pagedUserResults.Results.Count == 1)
                {
                    retrievedUser = pagedUserResults.Results[0] as User;

                    // Check if the user belongs to any of the passed groups
                    IList <String> memberships = graphConnection.CheckMemberGroups(retrievedUser, groupsList);

                    // If the passed group is returned back then the user is a member
                    if (memberships.Contains(groupToCheck.ObjectId))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    throw new ArgumentException(String.Format("Group {0} does not exist", groupDisplayName));
                }
            }
            else
            {
                throw new ArgumentException(String.Format("User {0} does not exist", userUPN));
            }
        }
Пример #25
0
        public List <String> GetUsersInGroup(string accessToken, string groupId)
        {
            CallContext     currentCallContext = new CallContext(accessToken, Guid.NewGuid());
            GraphConnection graphConnection    = new GraphConnection(currentCallContext);
            var             fieldAgentsGroup   = graphConnection.Get <Group>(groupId);
            var             fieldAgentMembers  = graphConnection.GetLinks(fieldAgentsGroup, "members", null);
            var             fieldAgents        = fieldAgentMembers.Results.OfType <User>();
            List <String>   agentIds           = new List <string>();

            foreach (User user in fieldAgents)
            {
                agentIds.Add(user.ObjectId);
            }
            return(agentIds);
        }
Пример #26
0
        public void Initialize(ClaimsPrincipal p)
        {
            var authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture,
                                                                      LoginUrl,
                                                                      GetTenantIdFromClaimsPrincipal(p)));

            var credential = new ClientCredential(ClientId, ClientSecret);

            AuthenticationResult authenticationResult = authContext.AcquireToken(GraphUrl, credential);
            string token = authenticationResult.AccessToken;

            var callContext = new CallContext(token, Guid.NewGuid(), "1.21-preview");

            _graphConnection = new GraphConnection(callContext);
        }
Пример #27
0
    public void Init(GraphConnection connection)
    {
        Connection = connection;

        StartPoint = Connection.StartNode.BorderPoint;
        EndPoint   = Connection.EndNode.BorderPoint;
        Regions    = Connection.Polygons.Select(x => x.Region).ToList();

        Center = new Vector2((StartPoint.Position.x + EndPoint.Position.x) / 2, (StartPoint.Position.y + EndPoint.Position.y) / 2);
        Length = Vector2.Distance(StartPoint.Position, EndPoint.Position);
        Angle  = Vector2.SignedAngle((EndPoint.Position - StartPoint.Position), new Vector2(1, 0));

        this.transform.position   = new Vector3(Center.x, BorderHeight * 0.5f, Center.y);
        this.transform.rotation   = Quaternion.Euler(0, Angle, 0);
        this.transform.localScale = new Vector3(Length, BorderHeight, BorderWidth);
    }
        /// <summary>
        /// GraphConnection is done based on application parameters. The connection is not based on any
        /// particular user.
        /// </summary>
        /// <returns></returns>
        private static GraphConnection BuildGraphConnectionForApplication()
        {
            var clientId     = ConfigurationManager.AppSettings.Get("ida:ClientID");
            var clientSecret = ConfigurationManager.AppSettings.Get("ida:Password");
            var clientCred   = new ClientCredential(clientId, clientSecret);

            var authorityDomain = ConfigurationManager.AppSettings.Get("ida:AuthorityDomain"); // custom appSetting in web.config - <add key="ida:AuthorityDomain" value="pragmaticazure.com" />

            Debug.Assert(!String.IsNullOrWhiteSpace(authorityDomain));
            var authorityUrl          = String.Format(AadAuthorityUrlTemplate, authorityDomain);
            var authenticationContext = new AuthenticationContext(authorityUrl);
            var authenticationResult  = authenticationContext.AcquireToken(GraphUrl, clientCred);

            var callContext     = new CallContext(authenticationResult.AccessToken, Guid.NewGuid(), GraphApiVersion);
            var graphConnection = new GraphConnection(callContext);

            return(graphConnection);
        }
Пример #29
0
        static void Main(string[] args)
        {
            try
            {
                // get OAuth token using Client Credentials
                string authString = "https://login.windows.net/" + ConfigurationManager.AppSettings["TenantName"];
                AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);

                // Config for OAuth client credentials
                ClientCredential clientCred = new ClientCredential(ConfigurationManager.AppSettings["AzureADClientId"], ConfigurationManager.AppSettings["AzureADClientSecret"]);
                string           resource   = "https://graph.windows.net";
                string           token      = String.Empty;

                // Authenticate
                AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred);
                token = authenticationResult.AccessToken;

                // setup Graph connection
                GraphConnection graphConnection = SetupGraphConnection(token);

                // Check group memberships. Pass along UPN of user and displayname of
                // the group to be checked. API support checking multiple groups at once
                Test(graphConnection, "*****@*****.**", "executives");
                Test(graphConnection, "*****@*****.**", "executives");
                Test(graphConnection, "*****@*****.**", "employees");

                Console.WriteLine("Press enter to continue...");
                Console.ReadLine();
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                Console.ResetColor();
                Console.ReadKey();
                return;
            }
        }
Пример #30
0
        public ActionResult Edit([Bind(Include = "ObjectId,UserPrincipalName,DisplayName,City,Department")] User user)
        {
            string accessToken = null;
            string tenantId    = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;

            if (tenantId != null)
            {
                accessToken = TokenCacheUtils.GetAccessTokenFromCacheOrRefreshToken(tenantId, graphResourceId);
            }
            if (accessToken == null)
            {
                //
                // If refresh is set to true, the user has clicked the link to be authorized again.
                //
                if (Request.QueryString["reauth"] == "True")
                {
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // TODO: Add update logic here
                CallContext currentCallContext = new CallContext(
                    accessToken, Guid.NewGuid(), graphApiVersion);
                GraphConnection graphConnection = new GraphConnection(currentCallContext);
                graphConnection.Update(user);
                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
Пример #31
0
 protected override void AddInitialCell(CPos location)
 {
     var cost = heuristic(location);
     Graph[location] = new CellInfo(0, cost, location, CellStatus.Open);
     var connection = new GraphConnection(location, cost);
     OpenQueue.Add(connection);
     StartPoints.Add(connection);
     considered.AddLast(new Pair<CPos, int>(location, 0));
 }