コード例 #1
0
        /// <summary>
        /// Helper function to make check and ensure that a variable name is not a reserved keyword for the language in use.
        /// If it is reserved, return an appropiate transformation of the variale name
        /// </summary>
        /// <param name="variableName">variable name to check for uniqueness</param>
        /// <param name="languageExpressions">Language expressions that holds list of reserved words for filtering</param>
        /// <returns>Modified variable name that is not a keyword</returns>
        public static string EnsureVariableNameIsNotReserved(string variableName, LanguageExpressions languageExpressions)
        {
            if (languageExpressions.ReservedNames.Contains(variableName))
            {
                return(languageExpressions.ReservedNameEscapeSequence + variableName);//append the language specific escape sequence
            }

            return(variableName);
        }
コード例 #2
0
        /// <summary>
        /// Generate a list of Request options and populate them as needed in a java specific function.
        /// Java does not have helper functions for all the odata parameter types and therefore the missing ones are inserted as query options here.
        /// </summary>
        /// <param name="snippetModel">Snippet model built from the request</param>
        /// <param name="languageExpressions">Language Expressions needed for the language</param>
        private static string GenerateRequestOptionsSection(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            if (!JavaModelHasRequestOptionsParameters(snippetModel))
            {
                return(string.Empty); //nothing to do here
            }
            var stringBuilder         = new StringBuilder();
            var requestOptionsPattern = "requestOptions.add(new QueryOption(\"{0}\", \"{1}\"));\r\n";

            stringBuilder.Append("LinkedList<Option> requestOptions = new LinkedList<Option>();\r\n");

            //insert any header options options
            foreach (var(key, value) in snippetModel.RequestHeaders)
            {
                if (key.ToLower().Equals("host", StringComparison.Ordinal))//no need to generate source for the host header
                {
                    continue;
                }
                //append the header to the snippet
                var valueString = value.First().Replace("\"", languageExpressions.DoubleQuotesEscapeSequence);
                stringBuilder.Append($"requestOptions.add(new HeaderOption(\"{key}\", \"{valueString}\"));\r\n");
            }

            //insert any custom query options
            foreach (var(key, value) in snippetModel.CustomQueryOptions)
            {
                stringBuilder.Append(string.Format(requestOptionsPattern, key, value));
            }

            //Append any search queries
            if (!string.IsNullOrEmpty(snippetModel.SearchExpression))
            {
                stringBuilder.Append(string.Format(requestOptionsPattern, "$search", snippetModel.SearchExpression));
            }

            //return request options section with a new line appended
            return($"{stringBuilder}\r\n");
        }
コード例 #3
0
        /// <summary>
        /// Formulates the requested Graph snippets and returns it as string for Java
        /// </summary>
        /// <param name="snippetModel">Model of the Snippets info <see cref="SnippetModel"/></param>
        /// <param name="languageExpressions">The language expressions to be used for code Gen</param>
        /// <returns>String of the snippet in Java code</returns>
        public string GenerateCodeSnippet(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            var snippetBuilder = new StringBuilder();

            try
            {
                var segment = snippetModel.Segments.Last();
                snippetModel.ResponseVariableName = CommonGenerator.EnsureVariableNameIsNotReserved(snippetModel.ResponseVariableName, languageExpressions);

                /*Auth provider section*/
                snippetBuilder.Append("IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();\r\n\r\n");
                //append any request options present
                snippetBuilder.Append(GenerateRequestOptionsSection(snippetModel, languageExpressions));
                /*Generate the query section of the request*/
                var requestActions = CommonGenerator.GenerateQuerySection(snippetModel, languageExpressions);

                if (snippetModel.Method == HttpMethod.Get)
                {
                    var typeName = GetJavaReturnTypeName(segment);
                    snippetBuilder.Append($"{typeName} {snippetModel.ResponseVariableName} = ");

                    if (segment is PropertySegment)
                    {
                        return(GenerateCustomRequestForPropertySegment(snippetBuilder, snippetModel));
                    }

                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{requestActions}\n\t.get();"));
                }
                else if (snippetModel.Method == HttpMethod.Post)
                {
                    switch (segment)
                    {
                    case NavigationPropertySegment _:
                    case EntitySetSegment _:
                    case NavigationPropertyLinkSegment _:
                        if (string.IsNullOrEmpty(snippetModel.RequestBody))
                        {
                            throw new Exception("No request Body present for Java POST request");
                        }

                        snippetBuilder.Append(JavaGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                            snippetModel.ResponseVariableName
                        }));
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{requestActions}\n\t.post({snippetModel.ResponseVariableName});"));
                        break;

                    case OperationSegment _:
                        //deserialize the object since the json top level contains the list of parameter objects
                        if (JsonConvert.DeserializeObject(snippetModel.RequestBody) is JObject testObj)
                        {
                            foreach (var(key, jToken) in testObj)
                            {
                                var jsonString = JsonConvert.SerializeObject(jToken);
                                snippetBuilder.Append(JavaGenerateObjectFromJson(segment, jsonString, new List <string> {
                                    CommonGenerator.LowerCaseFirstLetter(key)
                                }));
                            }
                        }
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{requestActions}\n\t.post();"));
                        break;

                    default:
                        throw new Exception("Unknown Segment Type in URI for method POST");
                    }
                }
                else if (snippetModel.Method == HttpMethod.Patch)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception("No request Body present for Java Patch request");
                    }

                    snippetBuilder.Append(JavaGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                        snippetModel.ResponseVariableName
                    }));

                    if (segment is PropertySegment)
                    {
                        return(GenerateCustomRequestForPropertySegment(snippetBuilder, snippetModel));
                    }

                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{requestActions}\n\t.patch({snippetModel.ResponseVariableName});"));
                }
                else if (snippetModel.Method == HttpMethod.Put)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception("No request Body present for Java Put request");
                    }

                    if (snippetModel.ContentType.Contains("json"))
                    {
                        snippetBuilder.Append(JavaGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                            snippetModel.ResponseVariableName
                        }));
                    }
                    else
                    {
                        snippetBuilder.Append($"byte[] {snippetModel.ResponseVariableName} = Base64.getDecoder().decode({AddQuotesIfMising(snippetModel.RequestBody?.Replace("\n", string.Empty)?.Replace("\r", string.Empty))});\n\t");
                    }
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{requestActions}\n\t.put({snippetModel.ResponseVariableName});"));
                }
                else if (snippetModel.Method == HttpMethod.Delete)
                {
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{requestActions}\n\t.delete();"));
                }
                else
                {
                    throw new NotImplementedException("HTTP method not implemented for Java");
                }

                return(snippetBuilder.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #4
0
        /// <summary>
        /// Formulates the requested Graph snippets and returns it as string for JavaScript
        /// </summary>
        /// <param name="snippetModel">Model of the Snippets info <see cref="SnippetModel"/></param>
        /// <param name="languageExpressions">The language expressions to be used for code Gen</param>
        /// <returns>String of the snippet in Javascript code</returns>
        public static string GenerateCodeSnippet(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            try
            {
                var snippetBuilder = new StringBuilder();
                snippetModel.ResponseVariableName = CommonGenerator.EnsureVariableNameIsNotReserved(snippetModel.ResponseVariableName, languageExpressions);
                //setup the auth snippet section
                snippetBuilder.Append("const options = {\n");
                snippetBuilder.Append("\tauthProvider,\n};\n\n");
                //init the client
                snippetBuilder.Append("const client = Client.init(options);\n\n");

                if (snippetModel.Method == HttpMethod.Get)
                {
                    //append any queries with the actions
                    var getActions = CommonGenerator.GenerateQuerySection(snippetModel, languageExpressions) + "\n\t.get();";
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, getActions));
                }
                else if (snippetModel.Method == HttpMethod.Post)
                {
                    if (!string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        snippetBuilder.Append(JavascriptGenerateObjectFromJson(snippetModel.RequestBody, snippetModel.ResponseVariableName));
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, $"\n\t.post({snippetModel.ResponseVariableName});"));
                    }
                    else
                    {
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, "\n\t.post();"));
                    }
                }
                else if (snippetModel.Method == HttpMethod.Patch)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception("No body present for PATCH method in Javascript");
                    }

                    snippetBuilder.Append(JavascriptGenerateObjectFromJson(snippetModel.RequestBody, snippetModel.ResponseVariableName));
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"\n\t.update({snippetModel.ResponseVariableName});"));
                }
                else if (snippetModel.Method == HttpMethod.Delete)
                {
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, "\n\t.delete();"));
                }
                else if (snippetModel.Method == HttpMethod.Put)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception("No body present for PUT method in Javascript");
                    }

                    snippetBuilder.Append(JavascriptGenerateObjectFromJson(snippetModel.RequestBody, snippetModel.ResponseVariableName));
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"\n\t.put({snippetModel.ResponseVariableName});"));
                }
                else
                {
                    throw new NotImplementedException("HTTP method not implemented for Javascript");
                }

                return(snippetBuilder.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #5
0
        /// <summary>
        /// Formulates the requested Graph snippets and returns it as string for Csharp
        /// </summary>
        /// <param name="snippetModel">Model of the Snippets info <see cref="SnippetModel"/></param>
        /// <param name="languageExpressions">The language expressions to be used for code Gen</param>
        /// <returns>String of the snippet in Csharp code</returns>
        public static string GenerateCodeSnippet(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            var snippetBuilder = new StringBuilder();

            try
            {
                snippetBuilder.Append("GraphServiceClient graphClient = new GraphServiceClient( authProvider );\r\n\r\n");
                var segment = snippetModel.Segments.Last();
                snippetModel.ResponseVariableName = CommonGenerator.EnsureVariableNameIsNotReserved(snippetModel.ResponseVariableName, languageExpressions);
                //Csharp properties are uppercase so replace with list with uppercase version
                snippetModel.SelectFieldList = snippetModel.SelectFieldList.Select(CommonGenerator.UppercaseFirstLetter).ToList();
                var actions = CommonGenerator.GenerateQuerySection(snippetModel, languageExpressions);

                //append any custom queries present
                snippetBuilder.Append(GenerateCustomQuerySection(snippetModel));

                if (snippetModel.Method == HttpMethod.Get)
                {
                    var extraSnippet = "";
                    if (segment is PropertySegment && !segment.EdmType.IsStream())//streams can be sorted out normally
                    {
                        extraSnippet = GeneratePropertySectionSnippet(snippetModel);
                        snippetModel.SelectFieldList = snippetModel.SelectFieldList.Select(CommonGenerator.UppercaseFirstLetter).ToList();
                        actions = CommonGenerator.GenerateQuerySection(snippetModel, languageExpressions);
                    }
                    snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.GetAsync();"));
                    snippetBuilder.Append(extraSnippet);
                }
                else if (snippetModel.Method == HttpMethod.Post)
                {
                    switch (segment)
                    {
                    case NavigationPropertySegment _:
                    case EntitySetSegment _:
                    case NavigationPropertyLinkSegment _:
                        if (string.IsNullOrEmpty(snippetModel.RequestBody))
                        {
                            throw new Exception($"No request Body present for POST of entity {snippetModel.ResponseVariableName}");
                        }

                        snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                        snippetBuilder.Append(CSharpGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                            snippetModel.ResponseVariableName
                        }));
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.AddAsync({snippetModel.ResponseVariableName});"));

                        break;

                    case OperationSegment _:
                        //deserialize the object since the json top level contains the list of parameter objects
                        if (JsonConvert.DeserializeObject(snippetModel.RequestBody) is JObject testObj)
                        {
                            foreach (var(key, jToken) in testObj)
                            {
                                var jsonString = JsonConvert.SerializeObject(jToken);
                                snippetBuilder.Append($"var {CommonGenerator.LowerCaseFirstLetter(key)} = ");
                                snippetBuilder.Append(CSharpGenerateObjectFromJson(segment, jsonString, new List <string> {
                                    CommonGenerator.LowerCaseFirstLetter(key)
                                }));
                            }
                        }
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.PostAsync();"));
                        break;

                    default:
                        throw new Exception("Unknown Segment Type in URI for method POST");
                    }
                }
                else if (snippetModel.Method == HttpMethod.Patch)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception($"No request Body present for Patch of entity {snippetModel.ResponseVariableName}");
                    }

                    snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                    snippetBuilder.Append(CSharpGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                        snippetModel.ResponseVariableName
                    }));

                    if (segment is PropertySegment)
                    {
                        snippetBuilder.Append(GeneratePropertySectionSnippet(snippetModel));
                    }

                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.UpdateAsync({snippetModel.ResponseVariableName});"));
                }
                else if (snippetModel.Method == HttpMethod.Delete)
                {
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.DeleteAsync();"));
                }
                else if (snippetModel.Method == HttpMethod.Put)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception($"No request Body present for PUT of entity {snippetModel.ResponseVariableName}");
                    }

                    if (snippetModel.ContentType.Equals("application/json", StringComparison.OrdinalIgnoreCase))
                    {
                        snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                        snippetBuilder.Append(CSharpGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                            snippetModel.ResponseVariableName
                        }));
                    }
                    else
                    {
                        snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = \"{snippetModel.RequestBody.Trim()}\"\n\n");
                    }

                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.PutAsync({snippetModel.ResponseVariableName});"));
                }
                else
                {
                    throw new NotImplementedException("HTTP method not implemented for C#");
                }

                return(snippetBuilder.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// Formulates the requested Graph snippets and returns it as string for Objective C
        /// </summary>
        /// <param name="snippetModel">Model of the Snippets info <see cref="SnippetModel"/></param>
        /// <param name="languageExpressions">The language expressions to be used for code Gen</param>
        /// <returns>String of the snippet in Objective C code</returns>
        public static string GenerateCodeSnippet(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            StringBuilder snippetBuilder = new StringBuilder();
            var           segment        = snippetModel.Segments.Last();

            /*Auth provider section*/
            snippetBuilder.Append("MSHTTPClient *httpClient = [MSClientFactory createHTTPClientWithAuthenticationProvider:authenticationProvider];\r\n\r\n");

            /*Request generation section*/
            snippetBuilder.Append($"NSString *MSGraphBaseURL = @\"{snippetModel.ODataUriParser.ServiceRoot}\";\r\n");
            snippetBuilder.Append($"NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@\"{snippetModel.Path}{snippetModel.QueryString}\"]]];\r\n");
            snippetBuilder.Append($"[urlRequest setHTTPMethod:@\"{snippetModel.Method}\"];\r\n");

            //add header to the Request headers list so it used in the request builder
            if (snippetModel.ContentType != null)
            {
                snippetModel.RequestHeaders = snippetModel.RequestHeaders.Append(new KeyValuePair <string, IEnumerable <string> >("Content-Type", new[] { snippetModel.ContentType }));
            }

            snippetBuilder.Append(CommonGenerator.GenerateQuerySection(snippetModel, languageExpressions));
            snippetBuilder.Append("\r\n");

            //create object to send out now that we have a payload it is not null
            if (!string.IsNullOrEmpty(snippetModel.RequestBody))
            {
                if (segment is OperationSegment)
                {
                    snippetBuilder.Append("NSMutableDictionary *payloadDictionary = [[NSMutableDictionary alloc] init];\r\n\r\n");
                    //deserialize the object since the json top level contains the list of parameter objects
                    if (JsonConvert.DeserializeObject(snippetModel.RequestBody) is JObject testObj)
                    {
                        foreach (var(key, jToken) in testObj)
                        {
                            var jsonString = JsonConvert.SerializeObject(jToken);
                            snippetBuilder.Append(ObjectiveCGenerateObjectFromJson(segment, jsonString, new List <string> {
                                CommonGenerator.LowerCaseFirstLetter(key)
                            }));
                            snippetBuilder.Append(jToken.Type == JTokenType.Array
                                ? $"payloadDictionary[@\"{key}\"] = {CommonGenerator.LowerCaseFirstLetter(key)}List;\r\n\r\n"
                                : $"payloadDictionary[@\"{key}\"] = {CommonGenerator.LowerCaseFirstLetter(key)};\r\n\r\n");
                        }
                    }
                    snippetBuilder.Append("NSData *data = [NSJSONSerialization dataWithJSONObject:payloadDictionary options:kNilOptions error:&error];\r\n");
                    snippetBuilder.Append("[urlRequest setHTTPBody:data];\r\n\r\n");
                }
                else
                {
                    snippetBuilder.Append($"{ObjectiveCGenerateObjectFromJson(snippetModel.Segments.Last(), snippetModel.RequestBody, new List<string> {snippetModel.ResponseVariableName})}\r\n");
                    snippetBuilder.Append("NSError *error;\r\n");
                    snippetBuilder.Append($"NSData *{snippetModel.ResponseVariableName}Data = [{snippetModel.ResponseVariableName} getSerializedDataWithError:&error];\r\n");
                    snippetBuilder.Append($"[urlRequest setHTTPBody:{snippetModel.ResponseVariableName}Data];\r\n\r\n");
                }
            }

            /*Task/Response generation section*/
            snippetBuilder.Append("MSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest \r\n");
            snippetBuilder.Append("\tcompletionHandler: ^(NSData *data, NSURLResponse *response, NSError *nserror) {\r\n\r\n");

            //typically a GET request a json payload of the entity coming back
            if (snippetModel.Method == HttpMethod.Get)
            {
                if (segment.EdmType is IEdmCollectionType collectionType)
                {
                    //Get underlying model if it is an entity
                    if (collectionType.ElementType.Definition is IEdmNamedElement edmNamedElement)
                    {
                        snippetModel.ResponseVariableName = edmNamedElement.Name;
                    }
                    snippetBuilder.Append("\t\tNSError *jsonError = nil;\r\n");
                    snippetBuilder.Append("\t\tMSCollection *collection = [[MSCollection alloc] initWithData:data error:&jsonError];\r\n");
                    snippetBuilder.Append($"\t\tMSGraph{CommonGenerator.UppercaseFirstLetter(snippetModel.ResponseVariableName)} *{snippetModel.ResponseVariableName} " +
                                          $"= [[MSGraph{CommonGenerator.UppercaseFirstLetter(snippetModel.ResponseVariableName)} alloc] " +
                                          "initWithDictionary:[[collection value] objectAtIndex: 0] error:&nserror];\r\n\r\n");
                }
                else
                {
                    snippetBuilder.Append($"\t\tMSGraph{CommonGenerator.UppercaseFirstLetter(snippetModel.ResponseVariableName)} *{snippetModel.ResponseVariableName} " +
                                          $"= [[MSGraph{CommonGenerator.UppercaseFirstLetter(snippetModel.ResponseVariableName)} alloc] initWithData:data error:&nserror];\r\n\r\n");
                }
            }
            else
            {
                snippetBuilder.Append("\t\t//Request Completed\r\n\r\n");
            }
            snippetBuilder.Append("}];\r\n\r\n");
            snippetBuilder.Append("[meDataTask execute];");

            return(snippetBuilder.ToString());
        }
コード例 #7
0
        /// <summary>
        /// Formulates the requested Graph snippets and returns it as string for Csharp
        /// </summary>
        /// <param name="snippetModel">Model of the Snippets info <see cref="SnippetModel"/></param>
        /// <param name="languageExpressions">The language expressions to be used for code Gen</param>
        /// <returns>String of the snippet in Csharp code</returns>
        public string GenerateCodeSnippet(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            var snippetBuilder = new StringBuilder();

            try
            {
                snippetBuilder.Append("GraphServiceClient graphClient = new GraphServiceClient( authProvider );\r\n\r\n");
                var segment = snippetModel.Segments.Last();
                snippetModel.ResponseVariableName = CommonGenerator.EnsureVariableNameIsNotReserved(snippetModel.ResponseVariableName, languageExpressions);
                var actions = CommonGenerator.GenerateQuerySection(snippetModel, languageExpressions);

                //append any custom queries present
                snippetBuilder.Append(GenerateCustomQuerySection(snippetModel));

                if (snippetModel.Method == HttpMethod.Get)
                {
                    var extraSnippet = "";
                    if (segment is PropertySegment && !segment.EdmType.IsStream())//streams can be sorted out normally
                    {
                        extraSnippet = GeneratePropertySectionSnippet(snippetModel);
                        snippetModel.SelectFieldList = snippetModel.SelectFieldList.Select(CommonGenerator.UppercaseFirstLetter).ToList();
                        actions = CommonGenerator.GenerateQuerySection(snippetModel, languageExpressions);
                    }
                    snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.GetAsync();"));
                    snippetBuilder.Append(extraSnippet);
                }
                else if (snippetModel.Method == HttpMethod.Post)
                {
                    switch (segment)
                    {
                    case NavigationPropertySegment _:
                    case EntitySetSegment _:
                    case NavigationPropertyLinkSegment _:
                        if (string.IsNullOrEmpty(snippetModel.RequestBody))
                        {
                            throw new Exception($"No request Body present for POST of entity {snippetModel.ResponseVariableName}");
                        }

                        snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                        snippetBuilder.Append(CSharpGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                            snippetModel.ResponseVariableName
                        }));
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.AddAsync({snippetModel.ResponseVariableName});"));

                        break;

                    case OperationSegment os:
                        //deserialize the object since the json top level contains the list of parameter objects
                        if (JsonConvert.DeserializeObject(snippetModel.RequestBody) is JObject testObj)
                        {
                            foreach (var(key, jToken) in testObj)
                            {
                                var jsonString = JsonConvert.SerializeObject(jToken);

                                // see examples in TypeIsInferredFromActionParametersForNonNullableType
                                // and TypeIsInferredFromActionParametersForNullableType tests.

                                var parameter = CommonGenerator.LowerCaseFirstLetter(key);

                                var path = new List <string> {
                                    CommonGenerator.LowerCaseFirstLetter(key)
                                };
                                var value = CSharpGenerateObjectFromJson(segment, jsonString, path);
                                var typeHintOnTheLeftHandSide = "var";

                                // If the value is null we can't resolve the type by using var on the left hand side.
                                // For example, we can't say "var index = null;". That won't be a compilable snippet.
                                // In these cases, we look for the type of "index" in action parameters.
                                if (value.Trim() == "null;")
                                {
                                    var parameterType = os.Operations?
                                                        .SingleOrDefault(o => o.Name == os.Identifier)?
                                                        .Parameters?
                                                        .SingleOrDefault(p => p.Name == parameter)?
                                                        .Type;

                                    if (parameterType == null)
                                    {
                                        throw new NotSupportedException("Parameter type from URL is not found in metadata!");
                                    }

                                    if (parameterType.IsNullable)
                                    {
                                        typeHintOnTheLeftHandSide = new CSharpTypeProperties(parameterType.Definition, false).ClassName;
                                        if (EdmTypesNonNullableByDefault.Contains(typeHintOnTheLeftHandSide))
                                        {
                                            typeHintOnTheLeftHandSide += "?";
                                        }
                                    }
                                    else
                                    {
                                        throw new NotSupportedException("Not nullable type is set to null in the sample!");
                                    }
                                }

                                snippetBuilder.Append($"{typeHintOnTheLeftHandSide} {parameter} = {value}");
                            }
                        }
                        snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.PostAsync();"));
                        break;

                    default:
                        throw new Exception("Unknown Segment Type in URI for method POST");
                    }
                }
                else if (snippetModel.Method == HttpMethod.Patch)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception($"No request Body present for Patch of entity {snippetModel.ResponseVariableName}");
                    }

                    snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                    snippetBuilder.Append(CSharpGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                        snippetModel.ResponseVariableName
                    }));

                    if (segment is PropertySegment)
                    {
                        snippetBuilder.Append(GeneratePropertySectionSnippet(snippetModel));
                    }

                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.UpdateAsync({snippetModel.ResponseVariableName});"));
                }
                else if (snippetModel.Method == HttpMethod.Delete)
                {
                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.DeleteAsync();"));
                }
                else if (snippetModel.Method == HttpMethod.Put)
                {
                    if (string.IsNullOrEmpty(snippetModel.RequestBody))
                    {
                        throw new Exception($"No request Body present for PUT of entity {snippetModel.ResponseVariableName}");
                    }

                    var genericType   = string.Empty;
                    var objectToBePut = snippetModel.ResponseVariableName;
                    if (snippetModel.ContentType.Equals("application/json", StringComparison.OrdinalIgnoreCase))
                    {
                        if (snippetModel.Segments.Last() is NavigationPropertyLinkSegment)
                        {
                            // if we are putting reference, we should send id to that object in PutAsync()
                            // and the request body should contain a JSON with @odata.id key
                            var body = JsonConvert.DeserializeObject(snippetModel.RequestBody) as JObject;

                            // HTTP sample is in this format: https://graph.microsoft.com/v1.0/users/{id}
                            // but C# SDK reconstructs the URL from {id}
                            var id = body["@odata.id"].ToString().Split("/").Last();
                            objectToBePut = $"\"{id}\"";
                        }
                        else
                        {
                            snippetBuilder.Append($"var {snippetModel.ResponseVariableName} = ");
                            snippetBuilder.Append(CSharpGenerateObjectFromJson(segment, snippetModel.RequestBody, new List <string> {
                                snippetModel.ResponseVariableName
                            }));
                        }
                    }
                    else
                    {
                        snippetBuilder.Append($"using var {snippetModel.ResponseVariableName} = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(\"{snippetModel.RequestBody.Trim()}\"));\n\n");

                        // resolve type for PutAsync<T>
                        var genericEdmType = snippetModel.Segments[snippetModel.Segments.Count - 2].EdmType;
                        if ((genericEdmType as IEdmEntityType)?.HasStream == false)
                        {
                            genericType = "<" + CommonGenerator.UppercaseFirstLetter(genericEdmType.ToString().Split(".").Last()) + ">";
                        }
                    }

                    snippetBuilder.Append(GenerateRequestSection(snippetModel, $"{actions}\n\t.PutAsync{genericType}({objectToBePut});"));
                }
                else
                {
                    throw new NotImplementedException("HTTP method not implemented for C#");
                }

                return(snippetBuilder.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #8
0
        /// <summary>
        /// Generate a list of Request options and populate them as needed in a java specific function.
        /// Java does not have helper functions for all the odata parameter types and therefore the missing ones are inserted as query options here.
        /// </summary>
        /// <param name="snippetModel">Snippet model built from the request</param>
        /// <param name="languageExpressions">Language Expressions needed for the language</param>
        private static string GenerateRequestOptionsSection(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            if (!JavaModelHasRequestOptionsParameters(snippetModel))
            {
                return(string.Empty); //nothing to do here
            }
            var stringBuilder         = new StringBuilder();
            var requestOptionsPattern = "requestOptions.add(new QueryOption(\"{0}\", \"{1}\"));\r\n";

            stringBuilder.Append("LinkedList<Option> requestOptions = new LinkedList<Option>();\r\n");

            //insert any header options options
            foreach (var(key, value) in snippetModel.RequestHeaders)
            {
                if (key.ToLower().Equals("host", StringComparison.Ordinal))//no need to generate source for the host header
                {
                    continue;
                }
                //append the header to the snippet
                var valueString = value.First().Replace("\"", languageExpressions.DoubleQuotesEscapeSequence);
                stringBuilder.Append($"requestOptions.add(new HeaderOption(\"{key}\", \"{valueString}\"));\r\n");
            }

            //insert any custom query options
            foreach (var(key, value) in snippetModel.CustomQueryOptions)
            {
                stringBuilder.Append(string.Format(requestOptionsPattern, key, value));
            }

            //Append any filter queries
            if (snippetModel.FilterFieldList.Any())
            {
                var filterResult = CommonGenerator.GetListAsStringForSnippet(snippetModel.FilterFieldList, languageExpressions.FilterExpressionDelimiter);
                stringBuilder.Append(string.Format(requestOptionsPattern, "$filter", filterResult));//append the filter to the snippet
            }

            //Append any order by queries
            if (snippetModel.OrderByFieldList.Any())
            {
                var orderByResult = CommonGenerator.GetListAsStringForSnippet(snippetModel.OrderByFieldList, languageExpressions.OrderByExpressionDelimiter);
                stringBuilder.Append(string.Format(requestOptionsPattern, "$orderby", orderByResult));//append the order by result to the snippet
            }

            //Append any skip queries
            if (snippetModel.ODataUri.Skip.HasValue)
            {
                stringBuilder.Append(string.Format(requestOptionsPattern, "$skip", snippetModel.ODataUri.Skip));
            }

            //Append any search queries
            if (!string.IsNullOrEmpty(snippetModel.SearchExpression))
            {
                stringBuilder.Append(string.Format(requestOptionsPattern, "$search", snippetModel.SearchExpression));
            }

            //Append any skip token queries
            if (!string.IsNullOrEmpty(snippetModel.ODataUri.SkipToken))
            {
                stringBuilder.Append(string.Format(requestOptionsPattern, "$skiptoken", snippetModel.ODataUri.SkipToken));
            }

            //return request options section with a new line appended
            return($"{stringBuilder}\r\n");
        }
コード例 #9
0
        /// <summary>
        /// Language agnostic function to generate Query section of code snippet
        /// </summary>
        /// <param name="snippetModel">Model of the snippet</param>
        /// <param name="languageExpressions">Instance of <see cref="LanguageExpressions"/> that holds the expressions for the specific language</param>
        public static string GenerateQuerySection(SnippetModel snippetModel, LanguageExpressions languageExpressions)
        {
            var snippetBuilder = new StringBuilder();

            //Append any headers section
            foreach (var(key, value) in snippetModel.RequestHeaders)
            {
                //no need to generate source for the host header
                if (key.ToLower().Equals("host", StringComparison.Ordinal))
                {
                    continue;
                }
                //append the header to the snippet
                var valueString = value.First()
                                  .EscapeQuotesInLiteral(languageExpressions.DoubleQuotesEscapeSequence, languageExpressions.SingleQuotesEscapeSequence);
                snippetBuilder.Append(string.Format(languageExpressions.HeaderExpression, key, valueString));
            }
            //Append any filter queries
            if (snippetModel.FilterFieldList.Any())
            {
                var filterResult = string.Join(languageExpressions.FilterExpressionDelimiter, snippetModel.FilterFieldList)
                                   .EscapeQuotesInLiteral(languageExpressions.DoubleQuotesEscapeSequence, languageExpressions.SingleQuotesEscapeSequence);
                //append the filter to the snippet
                snippetBuilder.Append(string.Format(languageExpressions.FilterExpression, filterResult));
            }

            //Append any search queries
            if (!string.IsNullOrEmpty(snippetModel.SearchExpression))
            {
                snippetBuilder.Append(string.Format(languageExpressions.SearchExpression,
                                                    snippetModel.SearchExpression
                                                    .EscapeQuotesInLiteral(languageExpressions.DoubleQuotesEscapeSequence, languageExpressions.SingleQuotesEscapeSequence)));
            }

            //Append the expand section
            if (!string.IsNullOrEmpty(snippetModel.ExpandFieldExpression))
            {
                //append the expand result to the snippet
                snippetBuilder.Append(string.Format(languageExpressions.ExpandExpression,
                                                    snippetModel.ExpandFieldExpression
                                                    .EscapeQuotesInLiteral(languageExpressions.DoubleQuotesEscapeSequence, languageExpressions.SingleQuotesEscapeSequence)));
            }

            //Append any select queries
            if (snippetModel.SelectFieldList.Any())
            {
                var selectResult = string.Join(languageExpressions.SelectExpressionDelimiter, snippetModel.SelectFieldList)
                                   .EscapeQuotesInLiteral(languageExpressions.DoubleQuotesEscapeSequence, languageExpressions.SingleQuotesEscapeSequence);
                //append the select result to the snippet
                snippetBuilder.Append(string.Format(languageExpressions.SelectExpression, selectResult));
            }

            //Append any orderby queries
            if (snippetModel.OrderByFieldList.Any())
            {
                var orderByResult = string.Join(languageExpressions.OrderByExpressionDelimiter, snippetModel.OrderByFieldList)
                                    .EscapeQuotesInLiteral(languageExpressions.DoubleQuotesEscapeSequence, languageExpressions.SingleQuotesEscapeSequence);
                //append the orderby result to the snippet
                snippetBuilder.Append(string.Format(languageExpressions.OrderByExpression, orderByResult));
            }

            //Append any skip queries
            if (snippetModel.ODataUri.Skip.HasValue)
            {
                snippetBuilder.Append(string.Format(languageExpressions.SkipExpression, snippetModel.ODataUri.Skip));
            }

            //Append any skip token queries
            if (!string.IsNullOrEmpty(snippetModel.ODataUri.SkipToken))
            {
                snippetBuilder.Append(string.Format(languageExpressions.SkipTokenExpression,
                                                    snippetModel.ODataUri.SkipToken
                                                    .EscapeQuotesInLiteral(languageExpressions.DoubleQuotesEscapeSequence, languageExpressions.SingleQuotesEscapeSequence)));
            }

            //Append any top queries
            if (snippetModel.ODataUri.Top.HasValue)
            {
                snippetBuilder.Append(string.Format(languageExpressions.TopExpression, snippetModel.ODataUri.Top));
            }

            return(snippetBuilder.ToString());
        }