/// <summary>
        /// Report List (PartialView)
        /// </summary>
        public ActionResult _ReportList(SampleQueryModel query)
        {
            var model = new PageViewModel();

            model.PerPageCount = query.RecordCount;
            model.CurrentPage  = query.PageNumber;
            model.DataUrl      = Url.Action(RouteData.Values["action"].ToString(), RouteData.Values["controller"]);
            model.QueryObjJson = JsonConvert.SerializeObject(query);
            model.AjaxDivID    = "div_SampleList";

            ViewBag.Header    = TableHeaderHelper.GetModelTableHeaderByTitleItemResource(new SampleViewModel());
            ViewBag.TableData = GetSampleData(query);

            model.TotalCount = ViewBag.TotalCount;  //取資料function回傳

            //excel用
            var excelQueryModel = new ExcelQueryModel <SampleQueryModel>
            {
                ExportActionPath = Url.Action("ExportLogListExcel", RouteData.Values["controller"].ToString()),
                Query            = query,
                LogType          = "Sample",
                TitleList        = ViewBag.Header
            };

            ViewBag.ExcelQueryModel = excelQueryModel;
            ViewBag.ExcelQueryModel = excelQueryModel;

            model.TotalCount = ViewBag.TotalCount;  //取資料function回傳
            return(PartialView("_List", model));
        }
        public void AddSampleQueryIntoEmptyListOfSampleQueries()
        {
            /* Arrange */

            SampleQueriesList sampleQueriesList = new SampleQueriesList();

            SampleQueryModel sampleQueryModel = new SampleQueryModel()
            {
                Id         = Guid.Parse("3482cc10-f2be-40fc-bcdb-d3ac35f3e4c3"),
                Category   = "Getting Started",
                Method     = SampleQueryModel.HttpMethods.GET,
                HumanName  = "my manager",
                RequestUrl = "/v1.0/me/manager",
                DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_manager",
                SkipTest   = false
            };

            /* Act */

            // Add the new sample query to the empty list of sample queries
            sampleQueriesList = GraphExplorerSamplesService.Services.SamplesService.AddToSampleQueriesList
                                    (sampleQueriesList, sampleQueryModel);

            // Assert
            Assert.NotEmpty(sampleQueriesList.SampleQueries);
        }
        public async Task <IActionResult> GetSampleQueryByIdAsync(string id)
        {
            try
            {
                // Get the list of sample queries
                SampleQueriesList sampleQueriesList = await GetSampleQueriesListAsync();

                if (sampleQueriesList.SampleQueries.Count == 0)
                {
                    return(NoContent()); // list is empty, just return status code 204 - No Content
                }

                // Search for sample query with the provided id
                SampleQueryModel sampleQueryById = sampleQueriesList.SampleQueries.Find(x => x.Id == Guid.Parse(id));

                if (sampleQueryById == null)
                {
                    return(NotFound()); // sample query with the given id doesn't exist in the list of sample queries
                }

                // Success; return the found sample query
                return(Ok(sampleQueryById));
            }
            catch (Exception exception)
            {
                return(new JsonResult(exception.Message)
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        public void AddSampleQueryToTopOfListOfSampleQueriesIfHighestRankedSampleQueryCategory()
        {
            /* Arrange */

            // Create a list of sample queries
            List <SampleQueryModel> sampleQueries = new List <SampleQueryModel>()
            {
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("7d5bac53-2e16-4162-b78f-7da13e77da1b"),
                    Category   = "Groups",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "all groups in my organization",
                    RequestUrl = "/v1.0/groups",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/group",
                    SkipTest   = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("48b62369-3974-4783-a5c6-ae4ea2d8ae1b"),
                    Category   = "Outlook Mail",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "my high important mail",
                    RequestUrl = "/v1.0/me/messages?$filter=importance eq 'high'",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_messages",
                    SkipTest   = false
                }
            };

            SampleQueriesList sampleQueriesList = new SampleQueriesList()
            {
                SampleQueries = sampleQueries
            };

            /* Create a new 'Users' sample query model object that will be inserted into
             * the list of sample queries as the highest ranked sample category
             */
            SampleQueryModel sampleQueryModel = new SampleQueryModel()
            {
                Id         = Guid.Parse("3482cc10-f2be-40fc-bcdb-d3ac35f3e4c3"),
                Category   = "Users",
                Method     = SampleQueryModel.HttpMethods.GET,
                HumanName  = "my manager",
                RequestUrl = "/v1.0/me/manager",
                DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_manager",
                SkipTest   = false
            };

            /* Act */

            // Assign a new Id to the new sample query
            sampleQueryModel.Id = Guid.NewGuid();

            // Add the new sample query to the list of sample queries
            SampleQueriesList newSampleQueriesList = GraphExplorerSamplesService.Services.SamplesService.AddToSampleQueriesList
                                                         (sampleQueriesList, sampleQueryModel);

            // Assert - the new sample query should be inserted at index[0] of the list of sample queries
            Assert.Equal(sampleQueryModel.Id, newSampleQueriesList.SampleQueries[0].Id);
        }
        public void ThrowArgumentNullExceptionIfAddToSampleQueriesListSampleQueriesListParameterIsNull()
        {
            /* Arrange */

            SampleQueriesList nullSampleQueriesList = null;

            SampleQueryModel sampleQueryModel = new SampleQueryModel()
            {
                Id         = Guid.Parse("3482cc10-f2be-40fc-bcdb-d3ac35f3e4c3"),
                Category   = "Getting Started",
                Method     = SampleQueryModel.HttpMethods.GET,
                HumanName  = "my manager",
                RequestUrl = "/v1.0/me/manager",
                DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_manager",
                SkipTest   = false
            };

            /* Act and Assert */

            // Assign a new Id to the new sample query
            sampleQueryModel.Id = Guid.NewGuid();

            // Null sample queries list
            Assert.Throws <ArgumentNullException>(() =>
                                                  GraphExplorerSamplesService.Services.SamplesService.AddToSampleQueriesList(nullSampleQueriesList, sampleQueryModel));
        }
        public void ThrowArgumentOutOfRangeExceptionIfInvalidCategoryIsSet()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act and Assert
            Assert.Throws <ArgumentOutOfRangeException>(() => sampleQueryModel.Category = "foobar");
        }
        public void ThrowArgumentOutOfRangeExceptionIfHumanNamePropertyIsSetToMoreThan64Characters()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act and Assert
            Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                        sampleQueryModel.HumanName = @"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");
        }
        public void ThrowArgumentExceptionIfDocLinkPropertyIsNotSetToAbsoluteUriValue()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act and Assert
            Assert.Throws <ArgumentException>(() =>
                                              sampleQueryModel.DocLink = "developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/users");
        }
Esempio n. 9
0
        public async Task <IActionResult> CreateSampleQueryAsync([FromBody] SampleQueryModel sampleQueryModel)
        {
            try
            {
                // Get the list of policies
                SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync();

                string categoryName = sampleQueryModel.Category;

                ClaimsIdentity      identity = (ClaimsIdentity)User.Identity;
                IEnumerable <Claim> claims   = identity.Claims;
                string userPrincipalName     =
                    (claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnJwt, StringComparison.OrdinalIgnoreCase)) ??
                     claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnUriSchema, StringComparison.OrdinalIgnoreCase)))?.Value;

                // Check if authenticated user is authorized for this action
                bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Post);

                if (!isAuthorized)
                {
                    return(new JsonResult(
                               $"{userPrincipalName} is not authorized to create the sample query. Category: '{categoryName}'")
                    {
                        StatusCode = StatusCodes.Status403Forbidden
                    });
                }

                // Get the list of sample queries
                SampleQueriesList sampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("en-US");

                // Assign a new Id to the new sample query
                sampleQueryModel.Id = Guid.NewGuid();

                // Add the new sample query to the list of sample queries
                SampleQueriesList newSampleQueriesList = SamplesService.AddToSampleQueriesList(sampleQueriesList, sampleQueryModel);

                // Get the serialized JSON string of the sample query
                string newSampleQueriesJson = SamplesService.SerializeSampleQueriesList(newSampleQueriesList);

                // Disabled functionality
                // await _fileUtility.WriteToFile(updatedSampleQueriesJson, _queriesFilePathSource);

                // Create the query Uri for the newly created sample query
                string newSampleQueryUri = string.Format("{0}://{1}{2}/{3}", Request.Scheme, Request.Host, Request.Path.Value, sampleQueryModel.Id.ToString());

                // Success; return the new sample query that was added along with its Uri
                return(Created(newSampleQueryUri, sampleQueryModel));
            }
            catch (Exception exception)
            {
                return(new JsonResult(exception.Message)
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        public void ThrowArgumentExceptionIfRequestUrlPropertyIsSetToInvalidValue()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act and Assert
            Assert.Throws <ArgumentException>(() =>
                                              sampleQueryModel.RequestUrl = "v1.0/me/photo/$value"); // Missing starting slash
            Assert.Throws <ArgumentException>(() =>
                                              sampleQueryModel.RequestUrl = "/v1.0mephoto$value");   // Missing subsequent slash
        }
        public void BuildStringOfCategories()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act
            string stringOfCategories = sampleQueryModel.BuildStringOfCategories();

            // Assert
            Assert.NotNull(stringOfCategories);
        }
        public void TrimAllLeadingAndTrailingWhiteSpacesFromDocLinkValueIfPresent()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act
            sampleQueryModel.DocLink = "   https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/users    ";

            // Assert
            Assert.False(sampleQueryModel.DocLink.StartsWith(" "));
            Assert.False(sampleQueryModel.DocLink.EndsWith(" "));
        }
        public void ThrowArgumentNullExceptionIfUpdateSampleQueriesListSampleQueryModelParameterIsNull()
        {
            /* Arrange */

            // Create list of sample queries
            List <SampleQueryModel> sampleQueries = new List <SampleQueryModel>()
            {
                new SampleQueryModel()
                {
                    Id        = Guid.Parse("3482cc10-f2be-40fc-bcdb-d3ac35f3e4c3"),
                    Category  = "Getting Started",
                    Method    = SampleQueryModel.HttpMethods.GET,
                    HumanName = "my manager", RequestUrl = "/v1.0/me/manager",
                    DocLink   = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_manager",
                    SkipTest  = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("48b62369-3974-4783-a5c6-ae4ea2d8ae1b"),
                    Category   = "Users",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "my direct reports",
                    RequestUrl = "/v1.0/me/directReports",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_directreports",
                    SkipTest   = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("7d5bac53-2e16-4162-b78f-7da13e77da1b"),
                    Category   = "Groups",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "all groups in my organization",
                    RequestUrl = "/v1.0/groups",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/group",
                    SkipTest   = false
                }
            };

            SampleQueriesList sampleQueriesList = new SampleQueriesList()
            {
                SampleQueries = sampleQueries
            };

            SampleQueryModel sampleQueryModel = null;

            Guid id = Guid.NewGuid();

            /* Act and Assert */

            // Null sample query model
            Assert.Throws <ArgumentNullException>(() =>
                                                  GraphExplorerSamplesService.Services.SamplesService.UpdateSampleQueriesList(sampleQueriesList, sampleQueryModel, id));
        }
        public void TrimAllLeadingAndTrailingWhiteSpacesFromRequestUrlValueIfPresent()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act
            sampleQueryModel.RequestUrl = "  /v1.0/me/photo/$value  "; // leading and trailing whitespaces

            // Assert
            Assert.False(sampleQueryModel.RequestUrl.StartsWith(" "));
            Assert.False(sampleQueryModel.RequestUrl.EndsWith(" "));
            Assert.Equal("/v1.0/me/photo/$value", sampleQueryModel.RequestUrl);
        }
        public void TrimAllLeadingAndTrailingWhiteSpacesFromHumanNameValueIfPresent()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act
            sampleQueryModel.HumanName = "   my profile    "; // leading and trailing whitespaces

            // Assert
            Assert.False(sampleQueryModel.HumanName.StartsWith(" "));
            Assert.False(sampleQueryModel.HumanName.EndsWith(" "));
            Assert.Equal("my profile", sampleQueryModel.HumanName);
        }
        public void TrimAllLeadingAndTrailingWhiteSpacesFromCategoryValueIfPresent()
        {
            // Arrange
            SampleQueryModel sampleQueryModel = new SampleQueryModel();

            // Act
            sampleQueryModel.Category = "   Users    "; // leading and trailing whitespaces

            // Assert
            Assert.False(sampleQueryModel.Category.StartsWith(" "));
            Assert.False(sampleQueryModel.Category.EndsWith(" "));
            Assert.Equal("Users", sampleQueryModel.Category);
        }
        public async Task <IActionResult> CreateSampleQueryAsync([FromBody] SampleQueryModel sampleQueryModel)
        {
            try
            {
                // Get the list of policies
                SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync();

                string categoryName      = sampleQueryModel.Category;
                string userPrincipalName = User.Identity.Name;

                // Check if authenticated user is authorized for this action
                bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Post);

                if (!isAuthorized)
                {
                    return(new JsonResult(
                               $"{userPrincipalName} is not authorized to create the sample query. Category: '{categoryName}'")
                    {
                        StatusCode = StatusCodes.Status401Unauthorized
                    });
                }

                // Get the list of sample queries
                SampleQueriesList sampleQueriesList = await GetSampleQueriesListAsync();

                // Assign a new Id to the new sample query
                sampleQueryModel.Id = Guid.NewGuid();

                // Add the new sample query to the list of sample queries
                SampleQueriesList newSampleQueriesList = SamplesService.AddToSampleQueriesList(sampleQueriesList, sampleQueryModel);

                // Get the serialized JSON string of the sample query
                string newSampleQueriesJson = SamplesService.SerializeSampleQueriesList(newSampleQueriesList);

                // Save the document-readable JSON-styled string to the source file
                await _fileUtility.WriteToFile(newSampleQueriesJson, _queriesFilePathSource);

                // Create the query Uri for the newly created sample query
                string newSampleQueryUri = string.Format("{0}://{1}{2}/{3}", Request.Scheme, Request.Host, Request.Path.Value, sampleQueryModel.Id.ToString());

                // Success; return the new sample query that was added along with its Uri
                return(Created(newSampleQueryUri, sampleQueryModel));
            }
            catch (Exception exception)
            {
                return(new JsonResult(exception.Message)
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        /// <summary>
        /// Get Data
        /// </summary>
        public List <SampleDataModel> GetSampleData(SampleQueryModel query, bool getExcel = false)
        {
            string slitStr   = getExcel ? "\n" : "<br>";
            var    data      = new List <SampleDataModel>();
            var    apiResult =                                  /* get data */
                               if (/* get some data success */) //有資料則轉成報表格式
            {
                data = apiResult.Select(x => new SampleViewModel()
                {
                    ViewCollumn1 = x.DataCollumn1,
                    ViewCollumn2 = x.DataCollumn2,
                }).ToList();
            }

            ViewBag.TotalCount = /* apiResult total count */
                                 return(data);
        }
Esempio n. 19
0
        /// <summary>
        /// Replaces the default password with a random Guid value in the postBody template of the Users sample query.
        /// </summary>
        /// <param name="sampleQueriesList">An instance of <see cref="SampleQueriesList"/> with the Users sample query whose password in the postBody template
        /// needs to be replaced with a random Guid value.</param>
        private static void GenerateUniqueUserPassword(SampleQueriesList sampleQueriesList)
        {
            SampleQueryModel sampleQuery = sampleQueriesList.SampleQueries.Find(s => s.Category == "Users" && s.Method == SampleQueryModel.HttpMethods.POST);

            if (sampleQuery != null && !string.IsNullOrEmpty(sampleQuery.PostBody))
            {
                try
                {
                    JObject postBodyObject = JObject.Parse(sampleQuery.PostBody);

                    postBodyObject["passwordProfile"]["password"] = Guid.NewGuid();

                    sampleQuery.PostBody = postBodyObject.ToString();
                }
                catch
                {
                    // no action required
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Adds a <see cref="SampleQueryModel"/> object into an instance of a <see cref="SampleQueriesList"/>.
        /// </summary>
        /// <param name="sampleQueriesList">The instance of a <see cref="SampleQueriesList"/> which the <see cref="SampleQueryModel"/>
        /// object will be added into.</param>
        /// <param name="sampleQueryModel">The <see cref="SampleQueryModel"/> object to be added.</param>
        /// <returns>The instance of a <see cref="SampleQueriesList"/> with the newly added <see cref="SampleQueryModel"/> object.</returns>
        public static SampleQueriesList AddToSampleQueriesList(SampleQueriesList sampleQueriesList, SampleQueryModel sampleQueryModel)
        {
            if (sampleQueriesList == null)
            {
                throw new ArgumentNullException(nameof(sampleQueriesList), "The list of sample queries cannot be null.");
            }
            if (sampleQueryModel == null)
            {
                throw new ArgumentNullException(nameof(sampleQueryModel), "The sample query model object cannot be null.");
            }

            // Determine the location in the list of query samples to add the new sample query in
            int sampleQueryIndex = GetNewSampleQueryIndex(sampleQueriesList, sampleQueryModel);

            // Insert the new sample query into the list of sample queries
            sampleQueriesList.SampleQueries.Insert(sampleQueryIndex, sampleQueryModel);

            // Return the new list of sample queries
            return(sampleQueriesList);
        }
        public void ThrowInvalidOperationExceptionIfUpdateSampleQueriesListSampleQueryIdNotFoundInCollection()
        {
            /* Arrange */

            // Create a list of sample queries
            List <SampleQueryModel> sampleQueries = new List <SampleQueryModel>()
            {
                new SampleQueryModel()
                {
                    Id        = Guid.Parse("3482cc10-f2be-40fc-bcdb-d3ac35f3e4c3"),
                    Category  = "Getting Started",
                    Method    = SampleQueryModel.HttpMethods.GET,
                    HumanName = "my manager", RequestUrl = "/v1.0/me/manager",
                    DocLink   = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_manager",
                    SkipTest  = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("48b62369-3974-4783-a5c6-ae4ea2d8ae1b"),
                    Category   = "Users",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "my direct reports",
                    RequestUrl = "/v1.0/me/directReports",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_directreports",
                    SkipTest   = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("7d5bac53-2e16-4162-b78f-7da13e77da1b"),
                    Category   = "Groups",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "all groups in my organization",
                    RequestUrl = "/v1.0/groups",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/group",
                    SkipTest   = false
                }
            };

            SampleQueriesList sampleQueriesList = new SampleQueriesList()
            {
                SampleQueries = sampleQueries
            };

            /* Create a 'Users' sample query model object that should update an existing 'Users'
             * sample query object in the list of sample queries.
             */
            SampleQueryModel sampleQueryModel = new SampleQueryModel()
            {
                Category   = "Users",
                Method     = SampleQueryModel.HttpMethods.GET,
                HumanName  = "my direct reports",
                RequestUrl = "/v1.0/me/directReports",
                DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_directreports",
                SkipTest   = false,
                Tip        = "This item has been updated." // updated field
            };

            Guid id = Guid.Parse("5484add6-d4be-4560-82ef-31ef738775e8"); // non-existent id

            /* Act and Assert */

            // Attempt to update the provided sample query model into the list of sample queries with a non existent id
            Assert.Throws <InvalidOperationException>(() =>
                                                      GraphExplorerSamplesService.Services.SamplesService.UpdateSampleQueriesList
                                                          (sampleQueriesList, sampleQueryModel, id));
        }
        public void UpdateSampleQueryInListOfSampleQueries()
        {
            /* Arrange */

            // Create a list of sample queries
            List <SampleQueryModel> sampleQueries = new List <SampleQueryModel>()
            {
                new SampleQueryModel()
                {
                    Id        = Guid.Parse("3482cc10-f2be-40fc-bcdb-d3ac35f3e4c3"),
                    Category  = "Getting Started",
                    Method    = SampleQueryModel.HttpMethods.GET,
                    HumanName = "my manager", RequestUrl = "/v1.0/me/manager",
                    DocLink   = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_manager",
                    SkipTest  = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("48b62369-3974-4783-a5c6-ae4ea2d8ae1b"),
                    Category   = "Users",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "my direct reports",
                    RequestUrl = "/v1.0/me/directReports",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_directreports",
                    SkipTest   = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("7d5bac53-2e16-4162-b78f-7da13e77da1b"),
                    Category   = "Groups",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "all groups in my organization",
                    RequestUrl = "/v1.0/groups",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/group",
                    SkipTest   = false
                }
            };

            SampleQueriesList sampleQueriesList = new SampleQueriesList()
            {
                SampleQueries = sampleQueries
            };

            /* Create a 'Users' sample query model object that will update an existing 'Users'
             * sample query object in the list of sample queries.
             */
            SampleQueryModel sampleQueryModel = new SampleQueryModel()
            {
                Category   = "Users",
                Method     = SampleQueryModel.HttpMethods.GET,
                HumanName  = "my direct reports",
                RequestUrl = "/v1.0/me/directReports",
                DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_directreports",
                SkipTest   = false,
                Tip        = "This item has been updated." // update field
            };

            Guid id = Guid.Parse("48b62369-3974-4783-a5c6-ae4ea2d8ae1b");

            /* Act */

            // Update the provided sample query model into the list of sample queries
            SampleQueriesList updatedSampleQueriesList = GraphExplorerSamplesService.Services.SamplesService.UpdateSampleQueriesList
                                                             (sampleQueriesList, sampleQueryModel, id);

            // Assert - item on index[1] has an updated property value
            Assert.Equal(sampleQueryModel.Tip, updatedSampleQueriesList.SampleQueries[1].Tip);
        }
        public void ReplaceDefaultPasswordWithUniqueValueInPostBodyTemplateOfUsersSampleQuery()
        {
            /* Act */

            string jsonString = @"{
                   ""SampleQueries"" :
                    [                        
                        {
                        ""id"": ""F1E6738D-7C9C-4DB7-B5EC-1C92DADD03CB"",
                        ""category"": ""Users"",
                        ""method"": ""POST"",
                        ""humanName"": ""create user"",
                        ""requestUrl"": ""/v1.0/users"",
                        ""docLink"": ""https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_post_users"",
                        ""headers"": [
                            {
                                ""name"": ""Content-type"",
                                ""value"": ""application/json""
                            }
                        ],
                        ""postBody"": ""{\r\n \""accountEnabled\"": true,\r\n \""city\"": \""Seattle\"",\r\n \""country\"": \""United States\"",\r\n
                        \""department\"": \""Sales & Marketing\"",\r\n\""displayName\"": \""Melissa Darrow\"",\r\n\""givenName\"": \""Melissa\"",\r\n 
                        \""jobTitle\"": \""Marketing Director\"",\r\n\""mailNickname\"": \""MelissaD\"",\r\n \""passwordPolicies\"": 
                        \""DisablePasswordExpiration\"",\r\n \""passwordProfile\"": {\r\n \""password\"": \""Test1234\"",\r\n
                        \""forceChangePasswordNextSignIn\"": false\r\n},\r\n \""officeLocation\"": \""131/1105\"",\r\n\""postalCode\"": \""98052\"",\r\n
                        \""preferredLanguage\"": \""en -US\"",\r\n \""state\"": \""WA\"",\r\n \""streetAddress\"": \""9256 Towne Center Dr., Suite 400\"",\r\n 
                        \""surname\"": \""Darrow\"",\r\n \""mobilePhone\"": \"" + 1 206 555 0110\"",\r\n \""usageLocation\"": \""US\"",\r\n \""userPrincipalName\"": 
                        \""MelissaD@{domain}\""\r\n }"",
                        ""skipTest"": false
                        }
                    ]
            }";

            /* Extract the original password from the passwordProfile key in the postBody template of the Users sample query. */

            JObject sampleQueryObject = JObject.Parse(jsonString);

            JObject originalPostBodyObject = JObject.Parse(sampleQueryObject.SelectToken("SampleQueries[0].postBody").ToString());

            string originalPassword = (string)originalPostBodyObject["passwordProfile"]["password"];

            /* Act */

            SampleQueriesList sampleQueriesList = GraphExplorerSamplesService.Services.SamplesService.DeserializeSampleQueriesList(jsonString);

            /* Extract the newly generated password. */

            SampleQueryModel sampleQuery = sampleQueriesList.SampleQueries
                                           .Find(s => s.Category == "Users" && s.Method == SampleQueryModel.HttpMethods.POST);

            JObject newPostBodyObject = JObject.Parse(sampleQuery.PostBody);
            string  newPassword       = (string)newPostBodyObject["passwordProfile"]["password"];

            // Assert that the newly generated password is of type Guid and is unique
            Assert.Collection(sampleQueriesList.SampleQueries,
                              item =>
            {
                Assert.IsType <Guid>(Guid.Parse(newPassword));
                Assert.NotEqual(originalPassword, newPassword);
            });
        }
Esempio n. 24
0
        public async Task <IActionResult> UpdateSampleQueryAsync(string id, [FromBody] SampleQueryModel sampleQueryModel)
        {
            try
            {
                // Get the list of policies
                SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync();

                string categoryName = sampleQueryModel.Category;

                ClaimsIdentity      identity = (ClaimsIdentity)User.Identity;
                IEnumerable <Claim> claims   = identity.Claims;
                string userPrincipalName     =
                    (claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnJwt, StringComparison.OrdinalIgnoreCase)) ??
                     claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnUriSchema, StringComparison.OrdinalIgnoreCase)))?.Value;

                // Check if authenticated user is authorized for this action
                bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Put);

                if (!isAuthorized)
                {
                    return(new JsonResult(
                               $"{userPrincipalName} is not authorized to update the sample query. Category: '{categoryName}'")
                    {
                        StatusCode = StatusCodes.Status403Forbidden
                    });
                }

                // Get the list of sample queries
                SampleQueriesList sampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("en-US");

                if (sampleQueriesList.SampleQueries.Count == 0)
                {
                    return(NotFound()); // List is empty; the sample query being searched is definitely not in an empty list
                }

                // Check if the sample query model exists in the list of sample queries
                bool sampleQueryExists = sampleQueriesList.SampleQueries.Exists(x => x.Id == Guid.Parse(id));

                if (!sampleQueryExists)
                {
                    throw new InvalidOperationException($"No sample query found with id: {id}");
                }

                // Update the provided sample query model into the list of sample queries
                SampleQueriesList updatedSampleQueriesList = SamplesService.UpdateSampleQueriesList(sampleQueriesList, sampleQueryModel, Guid.Parse(id));

                // Get the serialized JSON string of this sample query
                string updatedSampleQueriesJson = SamplesService.SerializeSampleQueriesList(updatedSampleQueriesList);

                // Success; return the sample query model object that was just updated
                return(Ok(sampleQueryModel));
            }
            catch (InvalidOperationException invalidOpsException)
            {
                // sample query with provided id not found
                return(new JsonResult(invalidOpsException.Message)
                {
                    StatusCode = StatusCodes.Status404NotFound
                });
            }
            catch (Exception exception)
            {
                return(new JsonResult(exception.Message)
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
 public ActionResult Index(SampleQueryModel query)
 {
     return(View());
 }
        public async Task <IActionResult> UpdateSampleQueryAsync(string id, [FromBody] SampleQueryModel sampleQueryModel)
        {
            try
            {
                // Get the list of policies
                SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync();

                string categoryName      = sampleQueryModel.Category;
                string userPrincipalName = User.Identity.Name;

                // Check if authenticated user is authorized for this action
                bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Put);

                if (!isAuthorized)
                {
                    return(new JsonResult(
                               $"{userPrincipalName} is not authorized to update the sample query. Category: '{categoryName}'")
                    {
                        StatusCode = StatusCodes.Status401Unauthorized
                    });
                }

                // Get the list of sample queries
                SampleQueriesList sampleQueriesList = await GetSampleQueriesListAsync();

                if (sampleQueriesList.SampleQueries.Count == 0)
                {
                    return(NotFound()); // List is empty; the sample query being searched is definitely not in an empty list
                }

                // Check if the sample query model exists in the list of sample queries
                bool sampleQueryExists = sampleQueriesList.SampleQueries.Exists(x => x.Id == Guid.Parse(id));

                if (!sampleQueryExists)
                {
                    throw new InvalidOperationException($"No sample query found with id: {id}");
                }

                // Update the provided sample query model into the list of sample queries
                SampleQueriesList updatedSampleQueriesList = SamplesService.UpdateSampleQueriesList(sampleQueriesList, sampleQueryModel, Guid.Parse(id));

                // Get the serialized JSON string of this sample query
                string updatedSampleQueriesJson = SamplesService.SerializeSampleQueriesList(updatedSampleQueriesList);

                // Save the document-readable JSON-styled string to the source file
                await _fileUtility.WriteToFile(updatedSampleQueriesJson, _queriesFilePathSource);

                // Success; return the sample query model object that was just updated
                return(Ok(sampleQueryModel));
            }
            catch (InvalidOperationException invalidOpsException)
            {
                // sample query with provided id not found
                return(new JsonResult(invalidOpsException.Message)
                {
                    StatusCode = StatusCodes.Status404NotFound
                });
            }
            catch (Exception exception)
            {
                return(new JsonResult(exception.Message)
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        public void AddSampleQueryIntoListOfSampleQueriesInHierarchicalOrderOfCategories()
        {
            /* Arrange */

            // Create a list of sample queries
            List <SampleQueryModel> sampleQueries = new List <SampleQueryModel>()
            {
                new SampleQueryModel()
                {
                    Id        = Guid.Parse("3482cc10-f2be-40fc-bcdb-d3ac35f3e4c3"),
                    Category  = "Getting Started",
                    Method    = SampleQueryModel.HttpMethods.GET,
                    HumanName = "my manager", RequestUrl = "/v1.0/me/manager",
                    DocLink   = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_manager",
                    SkipTest  = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("48b62369-3974-4783-a5c6-ae4ea2d8ae1b"),
                    Category   = "Users",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "my direct reports",
                    RequestUrl = "/v1.0/me/directReports",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_directreports",
                    SkipTest   = false
                },
                new SampleQueryModel()
                {
                    Id         = Guid.Parse("7d5bac53-2e16-4162-b78f-7da13e77da1b"),
                    Category   = "Groups",
                    Method     = SampleQueryModel.HttpMethods.GET,
                    HumanName  = "all groups in my organization",
                    RequestUrl = "/v1.0/groups",
                    DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/group",
                    SkipTest   = false
                },
            };

            SampleQueriesList sampleQueriesList = new SampleQueriesList()
            {
                SampleQueries = sampleQueries
            };

            /* Create a new 'Users' sample query model object that will be inserted into
             * the list of sample queries in a hierarchical order of categories.
             */
            SampleQueryModel sampleQueryModel = new SampleQueryModel()
            {
                Category   = "Users",
                Method     = SampleQueryModel.HttpMethods.GET,
                HumanName  = "all users in the organization",
                RequestUrl = "/v1.0/users",
                DocLink    = "https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/users",
                SkipTest   = false,
            };

            /* Act */

            // Assign a new Id to the new sample query
            sampleQueryModel.Id = Guid.NewGuid();

            // Add the new sample query to the list of sample queries
            SampleQueriesList newSampleQueriesList = GraphExplorerSamplesService.Services.SamplesService.AddToSampleQueriesList
                                                         (sampleQueriesList, sampleQueryModel);

            // Assert - the new sample query should be inserted at index[2] of the list of sample queries
            Assert.Equal(sampleQueryModel.Id, newSampleQueriesList.SampleQueries[2].Id);
        }
Esempio n. 28
0
        /// <summary>
        /// Determines the zero-based index value in the instance of a <see cref="SampleQueriesList"/> where a given <see cref="SampleQueryModel"/>
        /// object should be inserted.
        /// </summary>
        /// <param name="sampleQueriesList">The instance of a <see cref="SampleQueriesList"/> where the given <see cref="SampleQueryModel"/>
        /// object should be inserted into.
        /// <param name="sampleQuery">The <see cref="SampleQueryModel"/> object which needs to be inserted.</param>
        /// <returns>The zero-based index where the <see cref="SampleQueryModel"/> object needs to be inserted into in an instance of a
        /// <see cref="SampleQueriesList"/>.</returns>
        private static int GetNewSampleQueryIndex(SampleQueriesList sampleQueriesList, SampleQueryModel sampleQuery)
        {
            // The current sample category will be the starting point of the list of categories
            string currentCategory = SampleQueriesCategories.CategoriesList.Find(x => x == sampleQuery.Category);

            if (sampleQueriesList.SampleQueries.Count == 0)
            {
                return(0); // the list is empty; this will be the first sample query
            }

            // Search for this category from the list of sample queries
            foreach (SampleQueryModel sampleQueryItem in sampleQueriesList.SampleQueries)
            {
                if (sampleQueryItem.Category.Contains(currentCategory))
                {
                    // Find the index of the last sample query in the batch of matched category
                    int index = sampleQueriesList.SampleQueries.FindLastIndex(x => x.Category == currentCategory);

                    return(++index); // new sample should be added in the next index position
                }
            }

            /* All sample queries categories in the list have been traversed with no match found;
             * Add it to the top of the list */
            return(0);
        }
        /// <summary>
        /// Determines the zero-based index value in the instance of a <see cref="SampleQueriesList"/> where a given <see cref="SampleQueryModel"/>
        /// object should be inserted.
        /// </summary>
        /// <param name="sampleQuery">The <see cref="SampleQueryModel"/> object which needs to be inserted.</param>
        /// <returns>The zero-based index where the <see cref="SampleQueryModel"/> object needs to be inserted into in an instance of a
        /// <see cref="SampleQueriesList"/>.</returns>
        private static int GetNewSampleQueryIndex(SampleQueriesList sampleQueriesList, SampleQueryModel sampleQuery)
        {
            // The current sample category will be the starting point of the linked list of categories
            var currentCategory = SampleQueriesCategories.CategoriesLinkedList.Find(sampleQuery.Category);

            if (sampleQueriesList.SampleQueries.Count == 0 || currentCategory == null || currentCategory.Previous == null)
            {
                // The list is either empty or the sample query category is the first in the hierarchy of the linked list of categories
                return(0);
            }

            /*
             * Given the starting position of the sample query's category in the linked list of categories,
             * search for a matching category value from the list of sample queries.
             * Repeat this for all the categories higher up the hierarchy of categories in the linked list.
             * If a match is found, then the sample query should be inserted below the index value
             * of the matched category; else, the current category is the top-most ranked category
             * in the list of sample queries and the sample query should be added to the top of the list.
             */
            while (currentCategory != null)
            {
                foreach (var sampleQueryItem in sampleQueriesList.SampleQueries)
                {
                    if (sampleQueryItem.Category.Contains(currentCategory.Value))
                    {
                        // Find the index of the last sample query in the batch of matched category
                        int index = sampleQueriesList.SampleQueries.FindLastIndex(x => x.Category == currentCategory.Value);

                        return(++index); // new sample should be added in the next index position
                    }
                }

                // Go up the hierarchy and search again
                currentCategory = currentCategory.Previous;
            }

            /* All categories up the hierarchy have been traversed with no match found;
             * this is currently the top-most ranked category in the list of sample queries */
            return(0);
        }
Esempio n. 30
0
        /// <summary>
        /// Updates a <see cref="SampleQueryModel"/> object within an instance of a <see cref="SampleQueriesList"/>.
        /// The new <see cref="SampleQueryModel"/> object overwrites the existing one entirely except for its Id property.
        /// </summary>
        /// <param name="sampleQueriesList">The list of sample queries which contains the <see cref="SampleQueryModel"/> model object be updated.</param>
        /// <param name="sampleQueryModel">The <see cref="SampleQueryModel"/> object to update.</param>
        /// <param name="sampleQueryId">The Id value of the <see cref="SampleQueryModel"/> object to be updated.</param>
        /// <returns>The updated list of <see cref="SampleQueriesList"/>.</returns>
        public static SampleQueriesList UpdateSampleQueriesList(SampleQueriesList sampleQueriesList, SampleQueryModel sampleQueryModel, Guid sampleQueryId)
        {
            if (sampleQueriesList == null || sampleQueriesList.SampleQueries.Count == 0)
            {
                throw new ArgumentNullException(nameof(sampleQueriesList), "The list of sample queries cannot be null or empty.");
            }
            if (sampleQueryModel == null)
            {
                throw new ArgumentNullException(nameof(sampleQueryModel), "The sample query model object cannot be null.");
            }
            if (sampleQueryId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(sampleQueryId), "The sample query id cannot be empty.");
            }

            // Get the index of the sample query model in the list of sample queries
            int sampleQueryIndex = sampleQueriesList.SampleQueries.FindIndex(x => x.Id == sampleQueryId);

            // Check to ascertain the sample query is existent
            if (sampleQueryIndex < 0)
            {
                throw new InvalidOperationException($"No sample query found with id: {sampleQueryId}");
            }

            // Check if Id property for the sample query model object is empty
            if (sampleQueryModel.Id == Guid.Empty)
            {
                // Assign the Id before inserting this sample query object in the list
                sampleQueryModel.Id = sampleQueryId;
            }

            // Insert the new sample query object into the list of sample queries at the index of the original sample query object
            sampleQueriesList.SampleQueries.Insert(sampleQueryIndex, sampleQueryModel);

            // Original sample query object pushed to the next index; increment index then remove it
            sampleQueriesList.SampleQueries.RemoveAt(++sampleQueryIndex);

            // Return the new list of sample queries
            return(sampleQueriesList);
        }