public ActionResult Index()
        {
            if ((int)Session["UserID"] == -1)
            {
                return(RedirectToAction("Login", "User"));
            }

            SnippetModel sm = new SnippetModel();

            return(View(sm));
        }
        /// <summary>
        /// Generate the snippet section that makes the call to the api
        /// </summary>
        /// <param name="snippetModel">Snippet model built from the request</param>
        /// <param name="requestActions">String of requestActions to be done inside the code block</param>
        private static string GenerateRequestSection(SnippetModel snippetModel, string requestActions)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.Append("graphClient");
            stringBuilder.Append(JavaGenerateResourcesPath(snippetModel));//Generate the Resources path for Csharp
            //check if there are any custom query options appended
            stringBuilder.Append(JavaModelHasRequestOptionsParameters(snippetModel) ? "\n\t.buildRequest( requestOptions )" : "\n\t.buildRequest()");
            stringBuilder.Append(requestActions);//Append footers
            return(stringBuilder.ToString());
        }
Example #3
0
        public void SetAppropriateVariableNameForUsersList()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the variable name is "users" for the users collection
            Assert.Equal("users", snippetModel.ResponseVariableName);
        }
Example #4
0
        public void PopulateExpandFieldExpression()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/drive/root?$expand=children");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert
            Assert.Equal("children", snippetModel.ExpandFieldExpression);
        }
Example #5
0
        public void SetAppropriateVariableNameForChildrenItemsInDrive()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0//drives/{drive-id}/items/{item-id}/children");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the variable name is "children" for the collection returned
            Assert.Equal("children", snippetModel.ResponseVariableName);
        }
Example #6
0
        public void SetAppropriateVariableNameForSingleUser()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users/{id|userPrincipalName}");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the variable name is "user" for the single user.
            Assert.Equal("user", snippetModel.ResponseVariableName);
        }
Example #7
0
        public void SetAppropriateVariableNameForCalendarGroups()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/calendarGroups");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the variable name is "calendarGroups" for the collection returned
            Assert.Equal("calendarGroups", snippetModel.ResponseVariableName);
        }
Example #8
0
        public void SetAppropriateVariableNameForEventCreate()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/me/events");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the variable name is "event" (singular) as we are making a post call to create an entity
            Assert.Equal("event", snippetModel.ResponseVariableName);
        }
Example #9
0
        public void PopulateEmptyStringOnEmptyRequestBody()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/people/");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the request body is empty
            Assert.Equal("", snippetModel.RequestBody);
        }
        /// <summary>
        /// Helper Function to quickly tell if one needs request options added for snippet generation to take place.
        /// </summary>
        /// <param name="snippetModel">Model to used for snippet generation</param>
        /// <returns>boolean value showing whether or not the snippet generation needs to have request options</returns>
        private static bool JavaModelHasRequestOptionsParameters(SnippetModel snippetModel)
        {
            if (snippetModel.CustomQueryOptions.Any() ||
                snippetModel.RequestHeaders.Any(x => !x.Key.ToLower().Equals("host")) ||
                !string.IsNullOrEmpty(snippetModel.SearchExpression))
            {
                return(true);
            }

            return(false);
        }
Example #11
0
        public void PopulateSearchExpression()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/people/?$search=\"Irene McGowen\"");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert
            Assert.Equal("Irene McGowen", snippetModel.SearchExpression);
        }
        public void PopulateOrderByListField()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users?$orderby=displayName");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert
            Assert.Equal("displayName", snippetModel.OrderByFieldList.First());
        }
        public void PopulateFilterListField()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users?$filter=startswith(displayName,'J')");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert
            Assert.Equal("startswith(displayName,'J')", snippetModel.FilterFieldList.First());
        }
        public void PopulateExpandFieldExpressionFromMultipleQueryString()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users?$select=id,displayName,mail&$expand=extensions");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert
            Assert.Equal("extensions", snippetModel.ExpandFieldExpression);
        }
        public void SetsAppropriateVariableNameForEventUpdate()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Patch, "https://graph.microsoft.com/v1.0/groups/{id}/events/{id}");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the variable name is "event" for an event update
            Assert.Equal("event", snippetModel.ResponseVariableName);
        }
Example #16
0
        public void PopulateSelectListField()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/messages?$select=from,subject");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert
            Assert.Equal("from", snippetModel.SelectFieldList[0]);
            Assert.Equal("subject", snippetModel.SelectFieldList[1]);
        }
        public ActionResult Detail(int id)
        {
            if ((int)Session["UserID"] == -1)
            {
                return(RedirectToAction("Login", "User"));
            }

            SnippetModel sm = new SnippetModel();

            sm.GetSnippet(id);
            return(View(sm));
        }
Example #18
0
        public async Task ParsesBodyPropertyTypeMap()
        {
            using var request = new HttpRequestMessage(HttpMethod.Post, $"{ServiceRootUrl}/me/findMeetingTimes")
                  {
                      Content = new StringContent(TypesSample, Encoding.UTF8)
                  };
            var snippetModel     = new SnippetModel(request, ServiceRootUrl, await GetV1TreeNode());
            var snippetCodeGraph = new SnippetCodeGraph(snippetModel);

            var property = FindPropertyInSnippet(snippetCodeGraph.Body, "additionalData").Value;

            Assert.Equal(PropertyType.Map, property.PropertyType);
        }
Example #19
0
        public void GetParameterListFromOperationSegment_ShouldReturnStringWithDoubleQuotesForOdataActionParameter()
        {
            //Arrange
            var requestPayload   = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/drive/items/{id}/workbook/worksheets/{id|name}/range(address='A1:B2')");
            var snippetModel     = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);
            var operationSegment = snippetModel.Segments.Last() as OperationSegment;

            //Act
            var result = CommonGenerator.GetParameterListFromOperationSegment(operationSegment, snippetModel);

            //Assert the string parameter is now double quoted
            Assert.Equal("\"A1:B2\"", result.First());
        }
        //This tests asserts that we return an error if we try to get beta snippets for Java
        public void ThrowsNotImplementedExceptionForBeta()
        {
            //Arrange
            LanguageExpressions expressions = new JavaExpressions();

            //Act
            var requestPayload = new HttpRequestMessage(HttpMethod.Get,
                                                        "https://graph.microsoft.com/beta/me");
            var snippetModel = new SnippetModel(requestPayload, "https://graph.microsoft.com/beta", _edmModel);

            //Assert that we do not generate snippets for java beta for now
            Assert.Throws <NotImplementedException>(() => new JavaGenerator(_edmModel).GenerateCodeSnippet(snippetModel, expressions));
        }
Example #21
0
        public async Task ParsesBodyTypeBinary()
        {
            using var request = new HttpRequestMessage(HttpMethod.Put, $"{ServiceRootUrl}/applications/{{application-id}}/logo")
                  {
                      Content = new ByteArrayContent(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 })
                  };
            request.Content.Headers.ContentType = new("application/octet-stream");

            var snippetModel = new SnippetModel(request, ServiceRootUrl, await GetV1TreeNode());
            var result       = new SnippetCodeGraph(snippetModel);

            Assert.Equal(PropertyType.Binary, result.Body.PropertyType);
        }
Example #22
0
        //This tests asserts that we can properly generate snippets with some property originally set to null.
        public void GeneratesSnippetsWithRecurrencePropertySetToNull()
        {
            //Arrange
            LanguageExpressions expressions = new CSharpExpressions();
            //This request example is present at the link
            //https://docs.microsoft.com/en-us/graph/api/event-update?view=graph-rest-1.0&tabs=http#request
            const string messageJsonObject = "{\r\n" +
                                             "  \"originalStartTimeZone\": \"originalStartTimeZone-value\",\r\n" +
                                             "  \"originalEndTimeZone\": \"originalEndTimeZone-value\",\r\n" +
                                             "  \"responseStatus\": {\r\n" +
                                             "    \"response\": \"\",\r\n" +
                                             "    \"time\": \"datetime-value\"\r\n" +
                                             "  },\r\n" +
                                             "  \"recurrence\": null,\r\n" +    //property set to null in request object
                                             "  \"iCalUId\": \"iCalUId-value\",\r\n" +
                                             "  \"reminderMinutesBeforeStart\": 99,\r\n" +
                                             "  \"isReminderOn\": true\r\n" +
                                             "}";
            var requestPayload = new HttpRequestMessage(HttpMethod.Patch, "https://graph.microsoft.com/v1.0/me/events/{id}")
            {
                Content = new StringContent(messageJsonObject)
            };

            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Act by generating the code snippet
            var result = CSharpGenerator.GenerateCodeSnippet(snippetModel, expressions);

            //Assert code snippet string matches expectation
            const string expectedSnippet = "var @event = new Event\r\n" +
                                           "{\r\n" +
                                           "\tOriginalStartTimeZone = \"originalStartTimeZone-value\",\r\n" +
                                           "\tOriginalEndTimeZone = \"originalEndTimeZone-value\",\r\n" +
                                           "\tResponseStatus = new ResponseStatus\r\n" +
                                           "\t{\r\n" +
                                           "\t\tResponse = ResponseType.None,\r\n" +
                                           "\t\tTime = DateTimeOffset.Parse(\"datetime-value\")\r\n" + //the dateTimeOffset appropriately parsed
                                           "\t},\r\n" +
                                           "\tRecurrence = null,\r\n" +                                //the property has been appropriately set to null
                                           "\tICalUId = \"iCalUId-value\",\r\n" +
                                           "\tReminderMinutesBeforeStart = 99,\r\n" +
                                           "\tIsReminderOn = true\r\n" +
                                           "};\r\n" +
                                           "\r\n" +
                                           "await graphClient.Me.Events[\"{id}\"]\n" +
                                           "\t.Request()\n" +
                                           "\t.UpdateAsync(@event);";

            //Assert the snippet generated is as expected
            Assert.Equal(AuthProviderPrefix + expectedSnippet, result);
        }
Example #23
0
        public void GenerateQuerySection_ShouldReturnAppropriateJavascriptSkipExpression()
        {
            //Arrange
            LanguageExpressions expressions = new JavascriptExpressions();
            //no query present
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/events?$skip=20");
            var snippetModel   = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Act
            var result = CommonGenerator.GenerateQuerySection(snippetModel, expressions);

            //Assert string is empty
            Assert.Equal("\n\t.skip(20)", result);
        }
Example #24
0
        public void GenerateQuerySection_ShouldReturnAppropriateJavascriptSelectExpression()
        {
            //Arrange
            LanguageExpressions expressions = new JavascriptExpressions();
            //no query present
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users/{id}?$select=displayName,givenName,postalCode");
            var snippetModel   = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Act
            var result = CommonGenerator.GenerateQuerySection(snippetModel, expressions);

            //Assert string is empty
            Assert.Equal("\n\t.select('displayName,givenName,postalCode')", result);
        }
Example #25
0
        public void GenerateQuerySection_ShouldReturnEmptyStringIfQueryListIsEmpty()
        {
            //Arrange
            LanguageExpressions expressions = new JavascriptExpressions();
            //no query present
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/drive/root");
            var snippetModel   = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Act
            var result = CommonGenerator.GenerateQuerySection(snippetModel, expressions);

            //Assert string is empty
            Assert.Equal("", result);
        }
Example #26
0
        public void GenerateQuerySection_ShouldReturnAppropriateJavascriptFilterExpression()
        {
            //Arrange
            LanguageExpressions expressions = new JavascriptExpressions();
            //no query present
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users?$filter=startswith(givenName, 'J')");
            var snippetModel   = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Act
            var result = CommonGenerator.GenerateQuerySection(snippetModel, expressions);

            //Assert string is empty
            Assert.Equal("\n\t.filter('startswith(givenName, 'J')')", result);
        }
        /// <summary>
        /// This is a language agnostic function that looks at a operationSegment and returns a list of parameters needed by the operation.
        /// If the method is a post, the parameters are sought for in the request body. Otherwise they are sort for in the request url
        /// </summary>
        /// <param name="operationSegment">OData OperationSegment representing a Function or action</param>
        /// <param name="snippetModel">Snippet Model to obtain useful data from</param>
        /// <param name="collectionSuffix">Suffix to be added to elements that are proved to be members collections</param>
        /// <param name="isOrderedByOptionalParameters">Flag to show whether the parameters are ordered by the the metadata or optionality of params</param>
        /// <returns></returns>
        public static IEnumerable <string> GetParameterListFromOperationSegment(
            OperationSegment operationSegment, SnippetModel snippetModel, string collectionSuffix = "",
            bool isOrderedByOptionalParameters = true, bool returnEnumTypeIfEnum = false)
        {
            var paramList = new List <string>();

            if (snippetModel.Method == HttpMethod.Post)
            {
                //read parameters from request body since this is an odata action
                var parametersProvided = new List <string>();
                if (!string.IsNullOrEmpty(snippetModel.RequestBody) &&
                    JsonConvert.DeserializeObject(snippetModel.RequestBody) is JObject testObj)
                {
                    foreach (var(key, _) in testObj)
                    {
                        parametersProvided.Add(key);
                    }
                }

                if (isOrderedByOptionalParameters)
                {
                    //first populate the required parameters
                    var requiredParameters = operationSegment.Operations.First().Parameters.Where(param => !param.Type.IsNullable);
                    paramList = AddValidParameterItemsFromIEdmOperationParameterList(paramList, requiredParameters, parametersProvided, collectionSuffix);
                    //populate the parameters the optional parameters we have from the request
                    var optionalParameters = operationSegment.Operations.First().Parameters.Where(param => param.Type.IsNullable);
                    paramList = AddValidParameterItemsFromIEdmOperationParameterList(paramList, optionalParameters, parametersProvided, collectionSuffix);
                }
                else
                {
                    //use the order from the metadata
                    var parameters = operationSegment.Operations.First().Parameters;
                    paramList = AddValidParameterItemsFromIEdmOperationParameterList(paramList, parameters, parametersProvided, collectionSuffix);
                }
            }
            else
            {
                //read parameters from url since this is an odata function
                foreach (var parameter in operationSegment.Parameters)
                {
                    var value = GetParameterValueFromOperationUrlSegement(parameter, returnEnumTypeIfEnum);
                    if (!string.IsNullOrEmpty(value))
                    {
                        paramList.Add(value);
                    }
                }
            }

            return(paramList);
        }
        /// <summary>
        /// Generate the snippet section that makes the call to the api
        /// </summary>
        /// <param name="snippetModel">Snippet model built from the request</param>
        /// <param name="actions">String of actions to be done inside the code block</param>
        private static string GenerateRequestSection(SnippetModel snippetModel, string actions)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.Append("await graphClient");
            //Generate the Resources path for Csharp
            stringBuilder.Append(CSharpGenerateResourcesPath(snippetModel));
            //check if there are any custom query options appended
            stringBuilder.Append(snippetModel.CustomQueryOptions.Any() ? "\n\t.Request( queryOptions )" : "\n\t.Request()");
            //Append footers
            stringBuilder.Append(actions);

            return(stringBuilder.ToString());
        }
        /// <summary>
        /// Generate the snippet section for the Property segment for CSharp code as this section cannot be directly accessed in \
        /// a URL fashion
        /// </summary>
        /// <param name="snippetModel">Snippet model built from the request</param>
        private static string GeneratePropertySectionSnippet(SnippetModel snippetModel)
        {
            if (snippetModel.Segments.Count < 2)
            {
                return("");
            }

            var stringBuilder  = new StringBuilder();
            var desiredSegment = snippetModel.Segments.Last();
            var segmentIndex   = snippetModel.Segments.Count - 1;

            //move back to find first segment that is not a PropertySegment
            while ((desiredSegment is PropertySegment) && (segmentIndex > 0))
            {
                desiredSegment = snippetModel.Segments[--segmentIndex];
            }

            var selectField = snippetModel.Segments[segmentIndex + 1].Identifier;

            //generate path to the property
            var properties = "";

            while (segmentIndex < snippetModel.Segments.Count - 1)
            {
                properties = properties + "." + CommonGenerator.UppercaseFirstLetter(snippetModel.Segments[++segmentIndex].Identifier);
            }

            //modify the responseVarible name
            snippetModel.ResponseVariableName = desiredSegment.Identifier;
            var variableName    = snippetModel.Segments.Last().Identifier;
            var parentClassName = GetCsharpClassName(desiredSegment, new List <string> {
                snippetModel.ResponseVariableName
            });


            if (snippetModel.Method == HttpMethod.Get)
            {
                //we are retrieving the value
                snippetModel.SelectFieldList.Add(selectField);
                stringBuilder.Append($"\n\nvar {variableName} = {snippetModel.ResponseVariableName}{properties};");
            }
            else
            {
                //we are modifying the value
                stringBuilder.Append($"var {snippetModel.ResponseVariableName} = new {parentClassName}();");//initialise the classname
                stringBuilder.Append($"\n{snippetModel.ResponseVariableName}{properties} = {variableName};\n\n");
            }

            return(stringBuilder.ToString());
        }
Example #30
0
        public void PopulatesCustomQueryOptions()
        {
            //Arrange
            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/calendar/calendarView?startDateTime=2017-01-01T19:00:00.0000000&endDateTime=2017-01-07T19:00:00.0000000");

            //Act
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

            //Assert that the keys and values are as expected
            Assert.Equal("startDateTime", snippetModel.CustomQueryOptions.First().Key);
            Assert.Equal("2017-01-01T19:00:00.0000000", snippetModel.CustomQueryOptions.First().Value);
            Assert.Equal("endDateTime", snippetModel.CustomQueryOptions.Last().Key);
            Assert.Equal("2017-01-07T19:00:00.0000000", snippetModel.CustomQueryOptions.Last().Value);
        }