Пример #1
0
        /// <summary>
        /// Entry point to generate snippets from the payload
        /// </summary>
        /// <param name="language"></param>
        /// <param name="httpRequestMessage"></param>
        /// <returns>String of snippet generated</returns>
        public string ProcessPayloadRequest(HttpRequestMessage httpRequestMessage, string language)
        {
            var(edmModel, serviceRootUri) = GetModelAndServiceUriTuple(httpRequestMessage.RequestUri);
            var snippetModel = new SnippetModel(httpRequestMessage, serviceRootUri.AbsoluteUri, edmModel);

            switch (language.ToLower())
            {
            case "c#":
                var csharpGenerator = new CSharpGenerator(edmModel, IsCommandLine);
                return(csharpGenerator.GenerateCodeSnippet(snippetModel, CSharpExpressions));

            case "javascript":
                return(JavaScriptGenerator.GenerateCodeSnippet(snippetModel, JavascriptExpressions));

            case "objective-c":
                var objectiveCGenerator = new ObjectiveCGenerator(edmModel);
                return(objectiveCGenerator.GenerateCodeSnippet(snippetModel, ObjectiveCExpressions));

            case "java":
                var javaGenerator = new JavaGenerator(edmModel);
                return(javaGenerator.GenerateCodeSnippet(snippetModel, JavaExpressions));

            default:
                throw new Exception("Invalid Language selected");
            }
        }
Пример #2
0
        //This tests that snippets that fetch collections are deserialized to MSCollection Instances
        public void GeneratesSnippetsFetchingCollectionToMsCollectionInstances()
        {
            //Arrange
            LanguageExpressions expressions = new ObjectiveCExpressions();

            var requestPayload = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/drive/root/children");
            var snippetModel   = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

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

            //Assert code snippet string matches expectation
            const string expectedSnippet = "NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@\"/me/drive/root/children\"]]];\r\n" +
                                           "[urlRequest setHTTPMethod:@\"GET\"];\r\n\r\nMSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest \r\n" +
                                           "\tcompletionHandler: ^(NSData *data, NSURLResponse *response, NSError *nserror) {\r\n" +
                                           "\r\n" +
                                           "\t\tNSError *jsonError = nil;\r\n" +
                                           "\t\tMSCollection *collection = [[MSCollection alloc] initWithData:data error:&jsonError];\r\n" +                                             //deserialize the data to a MSCollection
                                           "\t\tMSGraphDriveItem *driveItem = [[MSGraphDriveItem alloc] initWithDictionary:[[collection value] objectAtIndex: 0] error:&nserror];\r\n" + //get an single element in the collection
                                           "\r\n" +
                                           "}];" +
                                           "\r\n" +
                                           "\r\n" +
                                           "[meDataTask execute];";

            //Assert the snippet generated is as expected
            Assert.Equal(AuthProviderPrefix + expectedSnippet, result);
        }
Пример #3
0
        private void populateLists() {
            IProxyGenerator gen1 = new CSharpGenerator();
            cmbGenerator.Items.Add(new GeneratorItem(gen1.GetName(), gen1));

            IProxyGenerator gen2 = new JavaScriptGenerator();
            cmbGenerator.Items.Add(new GeneratorItem(gen2.GetName(), gen2));

            IProxyGenerator gen3 = new JavaScriptDojoAMDGenerator();
            cmbGenerator.Items.Add(new GeneratorItem(gen3.GetName(), gen3));

            IProxyGenerator gen4 = new JavaGenerator();
            cmbGenerator.Items.Add(new GeneratorItem(gen4.GetName(), gen4));

            IProxyGenerator gen5 = new ObjectiveCGenerator();
            cmbGenerator.Items.Add(new GeneratorItem(gen5.GetName(), gen5));

            IProxyGenerator gen6 = new FlexGenerator();
            cmbGenerator.Items.Add(new GeneratorItem(gen6.GetName(), gen6));

            IProxyGenerator gen7 = new AngularGenerator();
            cmbGenerator.Items.Add(new GeneratorItem(gen7.GetName(), gen7));
            
            cmbTypeMap.Items.Add(new TypeMapItem("No Type Map", null));
            ResourceManager resMan = new ResourceManager();
            foreach (TypeMap tm in resMan.GetTypeMaps())
            {
                TypeMapItem item = new TypeMapItem(tm.Name, tm);
                cmbTypeMap.Items.Add(item);
            }
            cmbTypeMap.Items.Add(new TypeMapItem("Custom", null));
        }
        //This tests asserts that we can generate snippets from json objects with nested objects inside them.
        public void RecursivelyGeneratesNestedPasswordProfileObjectFromJson()
        {
            //Arrange
            LanguageExpressions expressions = new ObjectiveCExpressions();
            //json string with nested object properties
            const string userJsonObject = "{\r\n  \"accountEnabled\": true,\r\n  " +
                                          "\"displayName\": \"displayName-value\",\r\n  " +
                                          "\"mailNickname\": \"mailNickname-value\",\r\n  " +
                                          "\"userPrincipalName\": \"[email protected]\",\r\n " +
                                          " \"passwordProfile\" : {\r\n    \"forceChangePasswordNextSignIn\": true,\r\n    \"password\": \"password-value\"\r\n  }\r\n}";//nested passwordProfile Object

            var requestPayload = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/users")
            {
                Content = new StringContent(userJsonObject, Encoding.UTF8, "application/json")
            };
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

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

            //Assert code snippet string matches expectation
            const string expectedSnippet = "NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@\"/users\"]]];\r\n" +
                                           "[urlRequest setHTTPMethod:@\"POST\"];\r\n" +
                                           "[urlRequest setValue:@\"application/json\" forHTTPHeaderField:@\"Content-Type\"];\r\n" +
                                           "\r\n" +
                                           "MSGraphUser *user = [[MSGraphUser alloc] init];\r\n" +
                                           "[user setAccountEnabled: true];\r\n" +
                                           "[user setDisplayName:@\"displayName-value\"];\r\n" +
                                           "[user setMailNickname:@\"mailNickname-value\"];\r\n" +
                                           "[user setUserPrincipalName:@\"[email protected]\"];\r\n" +
                                           "MSGraphPasswordProfile *passwordProfile = [[MSGraphPasswordProfile alloc] init];\r\n" +
                                           "[passwordProfile setForceChangePasswordNextSignIn: true];\r\n" +
                                           "[passwordProfile setPassword:@\"password-value\"];\r\n" +
                                           "[user setPasswordProfile:passwordProfile];\r\n" +
                                           "\r\n" +
                                           "NSError *error;\r\n" +
                                           "NSData *userData = [user getSerializedDataWithError:&error];\r\n" +
                                           "[urlRequest setHTTPBody:userData];\r\n" +
                                           "\r\n" +
                                           "MSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest \r\n" +
                                           "\tcompletionHandler: ^(NSData *data, NSURLResponse *response, NSError *nserror) {\r\n\r\n" +
                                           "\t\t//Request Completed\r\n\r\n" +
                                           "}];" +
                                           "\r\n\r\n" +
                                           "[meDataTask execute];";

            //Assert the snippet generated is as expected
            Assert.Equal(AuthProviderPrefix + expectedSnippet, result);
        }
        //This tests asserts that we can generate snippets with enums separate with Or binary action
        public void GeneratesSnippetsForOdataActionsBySerializingIntoDictionary()
        {
            //Arrange
            LanguageExpressions expressions = new ObjectiveCExpressions();
            //json string with nested object array
            const string messageJsonObject = "{\r\n    " +
                                             "\"EmailAddresses\": [\r\n" +
                                             "        \"[email protected]\", \r\n" +
                                             "        \"[email protected]\"\r\n" +
                                             "    ],\r\n" +
                                             "    \"MailTipsOptions\": \"automaticReplies\"\r\n" +
                                             "}";

            var requestPayload = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/me/getMailTips")
            {
                Content = new StringContent(messageJsonObject, Encoding.UTF8, "application/json")
            };
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

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

            //Assert code snippet string matches expectation
            const string expectedSnippet = "NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@\"/me/getMailTips\"]]];\r\n" +
                                           "[urlRequest setHTTPMethod:@\"POST\"];\r\n[urlRequest setValue:@\"application/json\" forHTTPHeaderField:@\"Content-Type\"];\r\n" +
                                           "\r\n" +
                                           "NSMutableDictionary *payloadDictionary = [[NSMutableDictionary alloc] init];\r\n" +
                                           "\r\n" +
                                           "NSMutableArray *emailAddressesList = [[NSMutableArray alloc] init];\r\n" +
                                           "[emailAddressesList addObject: @\"[email protected]\"];\r\n" +
                                           "[emailAddressesList addObject: @\"[email protected]\"];\r\n" +
                                           "payloadDictionary[@\"EmailAddresses\"] = emailAddressesList;\r\n" +
                                           "\r\n" +
                                           "MSGraphMailTipsType *mailTipsOptions = [MSGraphMailTipsType automaticReplies];\r\n" +
                                           "payloadDictionary[@\"MailTipsOptions\"] = mailTipsOptions;\r\n" +
                                           "\r\n" +
                                           "NSData *data = [NSJSONSerialization dataWithJSONObject:payloadDictionary options:kNilOptions error:&error];\r\n" +
                                           "[urlRequest setHTTPBody:data];\r\n" +
                                           "\r\n" +
                                           "MSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest \r\n" +
                                           "\tcompletionHandler: ^(NSData *data, NSURLResponse *response, NSError *nserror) {\r\n\r\n" +
                                           "\t\t//Request Completed\r\n\r\n" +
                                           "}];\r\n" +
                                           "\r\n" +
                                           "[meDataTask execute];";

            //Assert the snippet generated is as expected
            Assert.Equal(AuthProviderPrefix + expectedSnippet, result);
        }
        //This tests asserts that we can generate snippets from json objects with nested arrays inside them.
        public void RecursivelyGeneratesNestedPhonesListFromJsonObject()
        {
            //Arrange
            LanguageExpressions expressions = new ObjectiveCExpressions();
            //json string with nested objects string array
            const string userJsonObject = "{\r\n  \"accountEnabled\": true,\r\n  " +
                                          "\"businessPhones\": [\r\n    \"businessPhones-value\",\"businessPhones-value2\",\"businessPhones-value3\"\r\n  ],\r\n  " +//nested ArrayObject with 3 items
                                          "\"city\": \"city-value\"\r\n}";

            var requestPayload = new HttpRequestMessage(HttpMethod.Patch, "https://graph.microsoft.com/v1.0/me")
            {
                Content = new StringContent(userJsonObject, Encoding.UTF8, "application/json")
            };
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

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

            //Assert code snippet string matches expectation
            const string expectedSnippet = "NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@\"/me\"]]];\r\n" +
                                           "[urlRequest setHTTPMethod:@\"PATCH\"];\r\n[urlRequest setValue:@\"application/json\" forHTTPHeaderField:@\"Content-Type\"];\r\n" +
                                           "\r\n" +
                                           "MSGraphUser *user = [[MSGraphUser alloc] init];\r\n" +
                                           "[user setAccountEnabled: true];\r\n" +
                                           "NSMutableArray *businessPhonesList = [[NSMutableArray alloc] init];\r\n" +
                                           "[businessPhonesList addObject: @\"businessPhones-value\"];\r\n" +
                                           "[businessPhonesList addObject: @\"businessPhones-value2\"];\r\n" +
                                           "[businessPhonesList addObject: @\"businessPhones-value3\"];\r\n" +
                                           "[user setBusinessPhones:businessPhonesList];\r\n" +
                                           "[user setCity:@\"city-value\"];\r\n" +
                                           "\r\n" +
                                           "NSError *error;\r\n" +
                                           "NSData *userData = [user getSerializedDataWithError:&error];\r\n" +
                                           "[urlRequest setHTTPBody:userData];\r\n" +
                                           "\r\n" +
                                           "MSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest \r\n" +
                                           "\tcompletionHandler: ^(NSData *data, NSURLResponse *response, NSError *nserror) {\r\n\r\n" +
                                           "\t\t//Request Completed\r\n\r\n" +
                                           "}];\r\n" +
                                           "\r\n" +
                                           "[meDataTask execute];";

            //Assert the snippet generated is as expected
            Assert.Equal(AuthProviderPrefix + expectedSnippet, result);
        }
Пример #7
0
        //This tests that snippets that Namespaces and sub namespaces are taken into account.
        public void GeneratesSnippetsWithMultipleNamespaces()
        {
            //Arrange
            string authProviderPrefixBeta = "MSHTTPClient *httpClient = [MSClientFactory createHTTPClientWithAuthenticationProvider:authenticationProvider];\r\n\r\n" +
                                            "NSString *MSGraphBaseURL = @\"https://graph.microsoft.com/beta/\";\r\n";
            LanguageExpressions expressions = new ObjectiveCExpressions();

            var          requestPayload = new HttpRequestMessage(HttpMethod.Patch, "https://graph.microsoft.com/beta/termStore/sets/{setId}");
            const string jsonObject     = "{\r\n" +
                                          "  \"description\": \"mySet\",\r\n" +
                                          "}";

            requestPayload.Content = new StringContent(jsonObject);
            string    betaServiceUrl = "https://graph.microsoft.com/beta";
            IEdmModel betaIeEdmModel = CsdlReader.Parse(XmlReader.Create(CommonGeneratorShould.CleanBetaMetadata));
            var       snippetModel   = new SnippetModel(requestPayload, betaServiceUrl, betaIeEdmModel);

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

            //Assert code snippet string matches expectation
            const string expectedSnippet = "NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@\"/termStore/sets/{setId}\"]]];\r\n" +
                                           "[urlRequest setHTTPMethod:@\"PATCH\"];\r\n" +
                                           "[urlRequest setValue:@\"text/plain\" forHTTPHeaderField:@\"Content-Type\"];\r\n" +
                                           "\r\n" +
                                           "MSGraphTermStoreSet *set = [[MSGraphTermStoreSet alloc] init];\r\n" +
                                           "[set setDescription:@\"mySet\"];\r\n" +
                                           "\r\n" +
                                           "NSError *error;\r\n" +
                                           "NSData *setData = [set getSerializedDataWithError:&error];\r\n" +
                                           "[urlRequest setHTTPBody:setData];\r\n" +
                                           "\r\n" +
                                           "MSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest \r\n" +
                                           "\tcompletionHandler: ^(NSData *data, NSURLResponse *response, NSError *nserror) {\r\n" +
                                           "\r\n" +
                                           "\t\t//Request Completed\r\n" +
                                           "\r\n" +
                                           "}];\r\n" +
                                           "\r\n" +
                                           "[meDataTask execute];";

            //Assert the snippet generated is as expected
            Assert.Equal(authProviderPrefixBeta + expectedSnippet, result);
        }
        //This tests asserts that we can generate snippets from json objects with nested object lists(JArray) inside them.
        public void RecursivelyGeneratesNestedRecipientListObjectsFromJson()
        {
            //Arrange
            LanguageExpressions expressions = new ObjectiveCExpressions();
            //json string with nested object array
            const string messageJsonObject = "{\r\n    " +
                                             "\"subject\":\"Did you see last night's game?\",\r\n" +
                                             "\"importance\":\"Low\",\r\n" +
                                             "\"body\":{\r\n" +
                                             "\"contentType\":\"HTML\",\r\n" +
                                             "\"content\":\"They were <b>awesome</b>!\"\r\n" +
                                             "},\r\n" +
                                             "\"toRecipients\":[\r\n" +
                                             "{\r\n" +
                                             "\"emailAddress\":{\r\n" +
                                             "\"address\":\"[email protected]\"\r\n" +
                                             "}\r\n" +
                                             "},\r\n" +
                                             "{\r\n" +
                                             "\"emailAddress\":{\r\n" +
                                             "\"address\":\"[email protected]\"\r\n" +
                                             "}\r\n" +
                                             "}\r\n" +
                                             "]\r\n" +
                                             "}";

            var requestPayload = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/me/messages")
            {
                Content = new StringContent(messageJsonObject, Encoding.UTF8, "application/json")
            };
            var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, _edmModel);

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

            //Assert code snippet string matches expectation
            const string expectedSnippet = "NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@\"/me/messages\"]]];\r\n" +
                                           "[urlRequest setHTTPMethod:@\"POST\"];\r\n" +
                                           "[urlRequest setValue:@\"application/json\" forHTTPHeaderField:@\"Content-Type\"];\r\n" +
                                           "\r\n" +
                                           "MSGraphMessage *message = [[MSGraphMessage alloc] init];\r\n" +
                                           "[message setSubject:@\"Did you see last night's game?\"];\r\n" +
                                           "[message setImportance: [MSGraphImportance low]];\r\n" +
                                           "MSGraphItemBody *body = [[MSGraphItemBody alloc] init];\r\n" +
                                           "[body setContentType: [MSGraphBodyType html]];\r\n" +
                                           "[body setContent:@\"They were <b>awesome</b>!\"];\r\n" +
                                           "[message setBody:body];\r\nNSMutableArray *toRecipientsList = [[NSMutableArray alloc] init];\r\n" +
                                           "MSGraphRecipient *toRecipients = [[MSGraphRecipient alloc] init];\r\n" +
                                           "MSGraphEmailAddress *emailAddress = [[MSGraphEmailAddress alloc] init];\r\n" +
                                           "[emailAddress setAddress:@\"[email protected]\"];\r\n" +
                                           "[toRecipients setEmailAddress:emailAddress];\r\n" +
                                           "[toRecipientsList addObject: toRecipients];\r\n" +
                                           "MSGraphRecipient *toRecipients = [[MSGraphRecipient alloc] init];\r\n" +
                                           "MSGraphEmailAddress *emailAddress = [[MSGraphEmailAddress alloc] init];\r\n" +
                                           "[emailAddress setAddress:@\"[email protected]\"];\r\n" +
                                           "[toRecipients setEmailAddress:emailAddress];\r\n" +
                                           "[toRecipientsList addObject: toRecipients];\r\n" +
                                           "[message setToRecipients:toRecipientsList];\r\n" +
                                           "\r\n" +
                                           "NSError *error;\r\n" +
                                           "NSData *messageData = [message getSerializedDataWithError:&error];\r\n" +
                                           "[urlRequest setHTTPBody:messageData];\r\n" +
                                           "\r\n" +
                                           "MSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest \r\n" +
                                           "\tcompletionHandler: ^(NSData *data, NSURLResponse *response, NSError *nserror) {\r\n\r\n" +
                                           "\t\t//Request Completed\r\n\r\n" +
                                           "}];\r\n" +
                                           "\r\n" +
                                           "[meDataTask execute];";

            //Assert the snippet generated is as expected
            Assert.Equal(AuthProviderPrefix + expectedSnippet, result);
        }
Пример #9
0
        private void processClientCode(NameValueCollection queryString, HttpContext context)
        {
            IProxyGenerator generator = null;
            ResourceManager resMan = new ResourceManager();
            string platform = queryString["platform"];
            if (string.IsNullOrEmpty(platform))
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("No Platform is Specified");
                return;
            }
            platform = platform.ToLower();
            if (platform == "csharp")
            {
                TypeMap tm = resMan.GetTypeMap("dotnet-csharp.typemap");
                generator = new CSharpGenerator(tm);
            }
            else if (platform == "java")
            {
                TypeMap tm = resMan.GetTypeMap("dotnet-java.typemap");
                generator = new JavaGenerator(tm);
            }
            else if (platform == "js-angularjs")
            {
                generator = new AngularGenerator();
            }
            else if (platform == "js-dojo")
            {
                generator = new JavaScriptGenerator();
            }
            else if (platform == "js-dojo-amd")
            {
                generator = new JavaScriptDojoAMDGenerator();
            }
            else if (platform == "flex")
            {
                generator = new FlexGenerator();
            }
            else if (platform == "objc")
            {
                TypeMap tm = resMan.GetTypeMap("dotnet-objc.typemap");
                generator = new ObjectiveCGenerator(tm);
            }

            if (generator == null)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Unknown Platform");
                return;
            }

            string format = queryString["format"];
            format = format == null ? "zip" : format.ToLower();


            Service svc = createService();
            IDictionary<string, string> files = generator.Generate(svc);

            if (format == "zip")
            {
                byte[] buffer = ZipExporter.Export(files);
                MemoryStream ms = new MemoryStream(buffer);
                //context.Response.ContentType = "application/zip";
                context.Response.ContentType = "application/octet-stream";
                string fileName = string.Format("{0}_{1}.zip", svc.Name, platform);
                context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                ms.CopyTo(context.Response.OutputStream);
                context.Response.OutputStream.Close();
            }
            else if (format == "json")
            {
                string s = JsonConvert.SerializeObject(files);
                context.Response.ContentType = "text/json";
                context.Response.Write(s);
            }
            else if (format == "xml")
            {

            }
            
        }