/// <summary> /// Removes a <see cref="SampleQueryModel"/> object from 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 removed from.</param> /// <param name="sampleQueryId">The Id value of the <see cref="SampleQueryModel"/> object to be deleted.</param> /// <returns>The new instance of a <see cref="SampleQueriesList"/> without the removed <see cref="SampleQueryModel"/> object.</returns> public static SampleQueriesList RemoveSampleQuery(SampleQueriesList sampleQueriesList, 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 (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}"); } // Delete the sample query model from the list of sample queries at its given index sampleQueriesList.SampleQueries.RemoveAt(sampleQueryIndex); // Return the new list of sample queries return(sampleQueriesList); }
public async Task FetchSamplesFromGithub() { //Arrange var configuration = new ConfigurationBuilder() .AddJsonFile(".\\GithubTestFiles\\appsettings-test.json") .Build(); string org = configuration["BlobStorage:Org"]; string branchName = configuration["BlobStorage:Branch"]; _samplesStore = new SamplesStore(configuration, _httpClientUtility, _fileUtility, _samplesCache); /* Act */ // Fetch en-US sample queries SampleQueriesList englishSampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("en-US", org, branchName); // Fetch es-ES sample queries SampleQueriesList espanolSampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("es-ES", org, branchName); /* Assert */ // en-US Assert.NotNull(englishSampleQueriesList); Assert.Equal(151, englishSampleQueriesList.SampleQueries.Count); // es-ES Assert.NotNull(espanolSampleQueriesList); Assert.Equal(149, espanolSampleQueriesList.SampleQueries.Count); }
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 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 async Task CorrectlySeedLocaleCachesOfSampleQueriesWhenMultipleRequestsReceived() { // Arrange _samplesStore = new SamplesStore(_fileUtility, _configuration, _samplesCache); /* Act */ // Fetch en-US sample queries SampleQueriesList englishSampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("en-US"); // Fetch es-ES sample queries SampleQueriesList espanolSampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("es-ES"); // Fetch fr-FR sample queries SampleQueriesList frenchSampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("fr-FR"); /* Assert */ // en-US Assert.Equal(151, englishSampleQueriesList.SampleQueries.Count); Assert.Equal("Getting Started", englishSampleQueriesList.SampleQueries[0].Category); Assert.Equal("my profile", englishSampleQueriesList.SampleQueries[0].HumanName); // es-ES Assert.Equal(149, espanolSampleQueriesList.SampleQueries.Count); Assert.Equal("Introducción", espanolSampleQueriesList.SampleQueries[0].Category); Assert.Equal("mi perfil", espanolSampleQueriesList.SampleQueries[0].HumanName); // fr-FR Assert.Equal(149, frenchSampleQueriesList.SampleQueries.Count); Assert.Equal("Requêtes de base", frenchSampleQueriesList.SampleQueries[0].Category); Assert.Equal("mon profil", frenchSampleQueriesList.SampleQueries[0].HumanName); }
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); }
/// <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> /// Preprocesses sample queries with the established business rules. /// </summary> /// <param name="sampleQueriesList">An instance of <see cref="SampleQueriesList"/> that requires preprocessing.</param> /// <returns>An instance of <see cref="SampleQueriesList"/> that has been preprocessed with the established business rules.</returns> private static SampleQueriesList SanitizeSampleQueries(SampleQueriesList sampleQueriesList) { SampleQueriesList orderedSampleQueries = OrderSamplesQueries(sampleQueriesList); GenerateUniqueUserPassword(orderedSampleQueries); return(orderedSampleQueries); }
public void ThrowArgumentNullExceptionIfSerializeSampleQueriesListSampleQueriesListParameterIsNull() { // Arrange SampleQueriesList nullSampleQueriesList = null; // Act and Assert Assert.Throws <ArgumentNullException>(() => GraphExplorerSamplesService.Services.SamplesService.SerializeSampleQueriesList(nullSampleQueriesList)); }
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 }); } }
/// <summary> /// Deserializes a JSON string into a list of <see cref="SampleQueryModel"/> objects. /// </summary> /// <param name="jsonString">The JSON string to be deserialized into a list of <see cref="SampleQueryModel"/> objects.</param> /// <returns>The deserialized list of <see cref="SampleQueryModel"/> objects.</returns> public static SampleQueriesList DeserializeSampleQueriesList(string jsonString) { if (string.IsNullOrEmpty(jsonString)) { throw new ArgumentNullException(nameof(jsonString), "The JSON string to be deserialized cannot be null or empty."); } SampleQueriesList sampleQueriesList = JsonConvert.DeserializeObject <SampleQueriesList>(jsonString); return(sampleQueriesList); }
/// <summary> /// Orders the English version of sample queries and deserializes the file contents /// </summary> /// <param name="fileContents">The json files to be deserialized.</param> /// <param name="locale">The language code for the preferred localized file.</param> /// <returns>The deserialized instance of a <see cref="SampleQueriesList"/>.</returns> private SampleQueriesList DeserializeSamplesList(string fileContents, string locale) { /* Current business process only supports ordering of the English * translation of the sample queries. */ bool orderSamples = locale.Equals("en-us", StringComparison.OrdinalIgnoreCase); SampleQueriesList sampleQueriesList = SamplesService.DeserializeSampleQueriesList(fileContents, orderSamples); return(sampleQueriesList); }
public void RemoveSampleQueryFromListOfSampleQueries() { /* 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 }; Guid idToDelete = Guid.Parse("48b62369-3974-4783-a5c6-ae4ea2d8ae1b"); // id of sample query to delete from list of sample queries /* Act */ // Remove the User's query from the list of sample queries SampleQueriesList updatedSampleQueriesList = GraphExplorerSamplesService.Services.SamplesService.RemoveSampleQuery (sampleQueriesList, idToDelete); // Assert - reference to the deleted User's sample query with the given id should be null Assert.Null(updatedSampleQueriesList.SampleQueries.Find(x => x.Id == idToDelete)); }
public void SerializeSampleQueriesListIfSampleQueriesListParameterIsEmptyCollection() { // Arrange SampleQueriesList emptySampleQueriesList = new SampleQueriesList(); // Act string sampleQueriesJson = GraphExplorerSamplesService.Services.SamplesService.SerializeSampleQueriesList(emptySampleQueriesList); // Assert Assert.NotNull(sampleQueriesJson); }
public void ReturnEmptyCollectionWhenJsonFileIsEmptyInDeserializeSampleQueriesListJsonStringParameter() { // Arrange string emptyJsonFileContents = "{ }"; // Act SampleQueriesList sampleQueriesList = GraphExplorerSamplesService.Services.SamplesService.DeserializeSampleQueriesList(emptyJsonFileContents); // Assert Assert.Empty(sampleQueriesList.SampleQueries); }
/// <summary> /// Serializes an instance of a <see cref="SampleQueriesList"/> into JSON string. /// </summary> /// <param name="sampleQueriesList">The instance of <see cref="SampleQueriesList"/> to be deserialized.</param> /// <returns>The serialized JSON string from an instance of a <see cref="SampleQueriesList"/>.</returns> public static string SerializeSampleQueriesList(SampleQueriesList sampleQueriesList) { if (sampleQueriesList == null) { throw new ArgumentNullException(nameof(sampleQueriesList), "The list of sample queries cannot be null."); } string sampleQueriesJson = JsonConvert.SerializeObject(sampleQueriesList, Formatting.Indented); return(sampleQueriesJson); }
public async Task ReturnNullIfSampleQueryFileIsEmpty() { // Arrange _samplesStore = new SamplesStore(_fileUtility, _configuration, _samplesCache); // Act - Fetch ja-JP sample queries which is empty SampleQueriesList japaneseSampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("ja-JP"); // Assert Assert.Null(japaneseSampleQueriesList); }
public async Task <IActionResult> GetSampleQueriesListAsync(string search, string org, string branchName) { try { string locale = RequestHelper.GetPreferredLocaleLanguage(Request); SampleQueriesList sampleQueriesList = null; if (!string.IsNullOrEmpty(org) && !string.IsNullOrEmpty(branchName)) { // Fetch samples file from Github sampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync(locale, org, branchName); } else { // Fetch sample queries from Azure Blob sampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync(locale); } if (sampleQueriesList == null || sampleQueriesList.SampleQueries.Count == 0) { // List is empty, just return status code 204 - No Content return(NoContent()); } if (string.IsNullOrEmpty(search)) { // No query string value provided; return entire list of sample queries return(Ok(sampleQueriesList)); } // Search sample queries List <SampleQueryModel> filteredSampleQueries = sampleQueriesList.SampleQueries. FindAll(x => (x.Category != null && x.Category.ToLower().Contains(search.ToLower())) || (x.HumanName != null && x.HumanName.ToLower().Contains(search.ToLower())) || (x.Tip != null && x.Tip.ToLower().Contains(search.ToLower()))); if (filteredSampleQueries.Count == 0) { // Search parameter not found in list of sample queries return(NotFound()); } // Success; return the found list of sample queries from filtered search return(Ok(filteredSampleQueries)); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
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 ThrowInvalidOperationExceptionIfRemoveSampleQuerySampleQueryIdNotFoundInCollection() { /* 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 }; Guid id = Guid.Parse("e6819ecc-f5aa-4792-ac86-c25234383513"); // Non-existent id /* Act and Assert */ // Attempt to remove a sample query from the list of sample queries with a non-existent id Assert.Throws <InvalidOperationException>(() => GraphExplorerSamplesService.Services.SamplesService.RemoveSampleQuery (sampleQueriesList, id)); }
public void SerializeListOfSampleQueriesIntoJsonString() { /* Arrange */ // Create a list of three 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 }; /* Act */ // Get the serialized JSON string of the list of sample queries string newSampleQueriesJson = GraphExplorerSamplesService.Services.SamplesService.SerializeSampleQueriesList(sampleQueriesList); // Assert Assert.NotNull(newSampleQueriesJson); }
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> /// Orders the list of sample queries alphabetically based on their category names with 'Getting Started' as the top-most sample query. /// </summary> /// <param name="sampleQueriesList">An instance of <see cref="SampleQueriesList"/> whose list of sample queries need to be ordered.</param> /// <returns>An instance of <see cref="SampleQueriesList"/> whose list of sample queries have been ordered alphabetically with 'Getting Started' /// as the top-most sample query.</returns> private static SampleQueriesList OrderSamplesQueries(SampleQueriesList sampleQueriesList) { List <SampleQueryModel> sortedSampleQueries = sampleQueriesList.SampleQueries .OrderBy(s => s.Category) .Where(s => s.Category != "Getting Started") // skipped, as it should always be the top-most sample query in the list .ToList(); SampleQueriesList sortedSampleQueriesList = new SampleQueriesList(); // Add back 'Getting Started' to the top of the list sortedSampleQueriesList.SampleQueries.AddRange(sampleQueriesList.SampleQueries.FindAll(s => s.Category == "Getting Started")); // Add the rest of the sample queries sortedSampleQueriesList.SampleQueries.AddRange(sortedSampleQueries); return(sortedSampleQueriesList); }
public async Task ReturnNotNullIfSampleQueriesFileHasEmptyJsonObject() { //Arrange var configuration = new ConfigurationBuilder() .AddJsonFile(".\\GithubTestFiles\\appsettings-test.json") .Build(); string org = configuration["BlobStorage:Org"]; string branchName = configuration["BlobStorage:Branch"]; _samplesStore = new SamplesStore(configuration, _httpClientUtility, _fileUtility, _samplesCache); // Act - Fetch ja-JP sample queries which is empty SampleQueriesList japaneseSampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("ja-JP", org, branchName); // Assert Assert.NotNull(japaneseSampleQueriesList); }
public async Task <IActionResult> GetSampleQueriesListAsync(string search) { try { // Get the list of sample queries SampleQueriesList sampleQueriesList = await GetSampleQueriesListAsync(); if (sampleQueriesList.SampleQueries.Count == 0) { // List is empty, just return status code 204 - No Content return(NoContent()); } if (string.IsNullOrEmpty(search)) { // No query string value provided; return entire list of sample queries return(Ok(sampleQueriesList)); } // Search sample queries List <SampleQueryModel> filteredSampleQueries = sampleQueriesList.SampleQueries. FindAll(x => (x.Category != null && x.Category.ToLower().Contains(search.ToLower())) || (x.HumanName != null && x.HumanName.ToLower().Contains(search.ToLower())) || (x.Tip != null && x.Tip.ToLower().Contains(search.ToLower()))); if (filteredSampleQueries.Count == 0) { // Search parameter not found in list of sample queries return(NotFound()); } // Success; return the found list of sample queries from filtered search return(Ok(filteredSampleQueries)); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public void ThrowArgumentNullExceptionIfRemoveSampleQuerySampleQueriesListParameterIsNullOrEmptyCollection() { /* Arrange */ SampleQueriesList nullSampleQueriesList = null; SampleQueriesList emptySampleQueriesList = new SampleQueriesList(); Guid id = Guid.Parse("9fd2bcca-6597-4fd8-a6de-0119a0b94e20"); /* Act and Assert */ // Null sample queries list Assert.Throws <ArgumentNullException>(() => GraphExplorerSamplesService.Services.SamplesService.RemoveSampleQuery(nullSampleQueriesList, id)); // Empty sample queries list Assert.Throws <ArgumentNullException>(() => GraphExplorerSamplesService.Services.SamplesService.RemoveSampleQuery(emptySampleQueriesList, id)); }
/// <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); }
/// <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 } } }
/// <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); }