diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index c29203bdd26..fc4be18c3b5 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -19,12 +19,14 @@ fi cd $APP_DIR ./bin/android-java-petstore.sh +./bin/csharp-petstore.sh ./bin/dynamic-html.sh ./bin/html-petstore.sh ./bin/jaxrs-petstore-server.sh ./bin/java-petstore.sh ./bin/php-petstore.sh ./bin/python-petstore.sh +./bin/ruby-petstore.sh ./bin/objc-petstore.sh ./bin/scala-petstore.sh ./bin/tizen-petstore.sh diff --git a/bin/csharp-petstore.sh b/bin/csharp-petstore.sh new file mode 100755 index 00000000000..a72a6cf84f0 --- /dev/null +++ b/bin/csharp-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l csharp -o samples/client/petstore/csharp" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java new file mode 100644 index 00000000000..ffd2438de97 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java @@ -0,0 +1,166 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/csharp"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "csharp"; + } + + public String getHelp() { + return "Generates a CSharp client library."; + } + + public CSharpClientCodegen() { + super(); + outputFolder = "generated-code/csharp"; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("api.mustache", ".cs"); + templateDir = "csharp"; + apiPackage = "io.swagger.Api"; + modelPackage = "io.swagger.Model"; + + reservedWords = new HashSet ( + Arrays.asList( + "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.cs")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs")); + supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); + supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "List"); + instantiationTypes.put("map", "Dictionary"); + + typeMapping = new HashMap(); + typeMapping.put("boolean", "bool?"); + typeMapping.put("integer", "int?"); + typeMapping.put("float", "float?"); + typeMapping.put("long", "long?"); + typeMapping.put("double", "double?"); + typeMapping.put("number", "double?"); + typeMapping.put("Date", "DateTime"); + typeMapping.put("file", "byte[]"); + typeMapping.put("array", "List"); + typeMapping.put("map", "Dictionary"); + + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // camelize the variable name + // pet_id => PetId + name = camelize(name); + + // for reserved word or word starting with number, append _ + if(reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if(reservedWords.contains(name)) + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return type; + } + else + type = swaggerType; + return type; + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig index 8303425734d..2d6e751d314 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig @@ -15,3 +15,4 @@ com.wordnik.swagger.codegen.languages.TizenClientCodegen com.wordnik.swagger.codegen.languages.PhpClientCodegen com.wordnik.swagger.codegen.languages.RubyClientCodegen com.wordnik.swagger.codegen.languages.PythonClientCodegen +com.wordnik.swagger.codegen.languages.CSharpClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 3d556fa72f8..4a58ae943e0 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -40,7 +40,7 @@ /// public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // create path and map variables - var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{paramName}}" + "}", apiInvoker.escapeString({{{paramName}}}.ToString())){{/pathParams}}; + var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{baseName}}" + "}", apiInvoker.escapeString({{{paramName}}}.ToString())){{/pathParams}}; // query params var queryParams = new Dictionary(); @@ -56,19 +56,19 @@ {{#queryParams}}if ({{paramName}} != null){ string paramStr = ({{paramName}} is DateTime) ? ((DateTime)(object){{paramName}}).ToString("u") : Convert.ToString({{paramName}}); - queryParams.Add("{{paramName}}", paramStr); + queryParams.Add("{{baseName}}", paramStr); } {{/queryParams}} - {{#headerParams}}headerParams.Add("{{paramName}}", {{paramName}}); + {{#headerParams}}headerParams.Add("{{baseName}}", {{paramName}}); {{/headerParams}} {{#formParams}}if ({{paramName}} != null){ if({{paramName}} is byte[]) { - formParams.Add("{{paramName}}", {{paramName}}); + formParams.Add("{{baseName}}", {{paramName}}); } else { string paramStr = ({{paramName}} is DateTime) ? ((DateTime)(object){{paramName}}).ToString("u") : Convert.ToString({{paramName}}); - formParams.Add("{{paramName}}", paramStr); + formParams.Add("{{baseName}}", paramStr); } } {{/formParams}} @@ -78,7 +78,7 @@ var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); return {{#returnType}}((object)response) as {{{returnType}}}{{/returnType}}; } else { - var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); + var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); if(response != null){ return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}})){{/returnType}}; } @@ -98,4 +98,4 @@ {{/operation}} } {{/operations}} - } \ No newline at end of file + } diff --git a/samples/client/petstore/csharp/CSharpPetstoreCodegen.scala b/samples/client/petstore/csharp/CSharpPetstoreCodegen.scala deleted file mode 100644 index 4dcab9050d8..00000000000 --- a/samples/client/petstore/csharp/CSharpPetstoreCodegen.scala +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import com.wordnik.swagger.codegen.BasicCSharpGenerator - -object CSharpPetstoreCodegen extends BasicCSharpGenerator { - def main(args: Array[String]) = generateClient(args) - - // location of templates - override def templateDir = "csharp" - - // where to write generated code - override def destinationDir = "samples/client/petstore/csharp/src" - - // package for api invoker, error files - override def invokerPackage = Some("Com.Wordnik.Petstore") - - // package for models - override def modelPackage = Some("Com.Wordnik.Petstore.Model") - - // package for api classes - override def apiPackage = Some("Com.Wordnik.Petstore.Api") - - // supporting classes - override def supportingFiles = - List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.cs"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.cs"), - ("Newtonsoft.Json.dll", "samples/client/petstore/csharp/bin", "Newtonsoft.Json.dll"), - ("compile.mustache", "samples/client/petstore/csharp", "compile.bat")) -} - diff --git a/samples/client/petstore/csharp/bin/Com.Wordnik.Petstore.dll b/samples/client/petstore/csharp/bin/Com.Wordnik.Petstore.dll deleted file mode 100644 index f4656a1bf40..00000000000 Binary files a/samples/client/petstore/csharp/bin/Com.Wordnik.Petstore.dll and /dev/null differ diff --git a/samples/client/petstore/csharp/bin/Newtonsoft.Json.dll b/samples/client/petstore/csharp/bin/Newtonsoft.Json.dll index 26fdaffec14..687d26fd9e0 100644 Binary files a/samples/client/petstore/csharp/bin/Newtonsoft.Json.dll and b/samples/client/petstore/csharp/bin/Newtonsoft.Json.dll differ diff --git a/samples/client/petstore/csharp/compile.bat b/samples/client/petstore/csharp/compile.bat index c62b990f5c5..18a85febb70 100644 --- a/samples/client/petstore/csharp/compile.bat +++ b/samples/client/petstore/csharp/compile.bat @@ -1,2 +1,2 @@ SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/Com.Wordnik.Petstore.dll /recurse:src\*.cs /doc:bin/Com.Wordnik.Petstore.xml +%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/io.swagger.client.dll /recurse:src\*.cs /doc:bin/io.swagger.client.xml \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs deleted file mode 100644 index acb3abb2d66..00000000000 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs +++ /dev/null @@ -1,348 +0,0 @@ - using System; - using System.Collections.Generic; - using Com.Wordnik.Petstore; - using Com.Wordnik.Petstore.Model; - namespace Com.Wordnik.Petstore.Api { - public class PetApi { - string basePath = "http://petstore.swagger.wordnik.com/api"; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { - this.basePath = basePath; - } - - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; - } - - /// - /// Find pet by ID Returns a pet based on ID - /// - /// ID of pet that needs to be fetched - /// - public Pet getPetById (long petId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (petId == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (Pet) ApiInvoker.deserialize(response, typeof(Pet)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Deletes a pet - /// - /// Pet id to delete - /// - public void deletePet (string petId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (petId == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// partial updates to a pet - /// - /// ID of pet that needs to be fetched - /// Pet object that needs to be added to the store - /// - public List partialUpdate (string petId, Pet body) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (petId == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, body, headerParams); - if(response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Updates a pet in the store with form data - /// - /// ID of pet that needs to be updated - /// Updated name of the pet - /// Updated status of the pet - /// - public void updatePetWithForm (string petId, string name, string status) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (petId == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// uploads an image - /// - /// Additional data to pass to server - /// file to upload - /// - public void uploadFile (string additionalMetadata, File body) { - // create path and map variables - var path = "/pet/uploadImage".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Add a new pet to the store - /// - /// Pet object that needs to be added to the store - /// - public void addPet (Pet body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Update an existing pet - /// - /// Pet object that needs to be updated in the store - /// - public void updatePet (Pet body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Finds Pets by status Multiple status values can be provided with comma seperated strings - /// - /// Status values that need to be considered for filter - /// - public List findPetsByStatus (string status) { - // create path and map variables - var path = "/pet/findByStatus".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (status == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - if (status != null){ - paramStr = (status != null && status is DateTime) ? ((DateTime)(object)status).ToString("u") : Convert.ToString(status); - queryParams.Add("status", paramStr); - } - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - /// - /// Tags to filter by - /// - public List findPetsByTags (string tags) { - // create path and map variables - var path = "/pet/findByTags".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (tags == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - if (tags != null){ - paramStr = (tags != null && tags is DateTime) ? ((DateTime)(object)tags).ToString("u") : Convert.ToString(tags); - queryParams.Add("tags", paramStr); - } - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - } - } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/StoreApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/StoreApi.cs deleted file mode 100644 index 22c36a411ca..00000000000 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/StoreApi.cs +++ /dev/null @@ -1,130 +0,0 @@ - using System; - using System.Collections.Generic; - using Com.Wordnik.Petstore; - using Com.Wordnik.Petstore.Model; - namespace Com.Wordnik.Petstore.Api { - public class StoreApi { - string basePath = "http://petstore.swagger.wordnik.com/api"; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { - this.basePath = basePath; - } - - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; - } - - /// - /// Find purchase order by ID For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors - /// - /// ID of pet that needs to be fetched - /// - public Order getOrderById (string orderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.escapeString(orderId.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (orderId == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - /// - /// ID of the order that needs to be deleted - /// - public void deleteOrder (string orderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.escapeString(orderId.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (orderId == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Place an order for a pet - /// - /// order placed for purchasing the pet - /// - public void placeOrder (Order body) { - // create path and map variables - var path = "/store/order".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - } - } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs deleted file mode 100644 index 23a58501579..00000000000 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs +++ /dev/null @@ -1,310 +0,0 @@ - using System; - using System.Collections.Generic; - using Com.Wordnik.Petstore; - using Com.Wordnik.Petstore.Model; - namespace Com.Wordnik.Petstore.Api { - public class UserApi { - string basePath = "http://petstore.swagger.wordnik.com/api"; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { - this.basePath = basePath; - } - - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; - } - - /// - /// Updated user This can only be done by the logged in user. - /// - /// name that need to be deleted - /// Updated user object - /// - public void updateUser (string username, User body) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Delete user This can only be done by the logged in user. - /// - /// The name that needs to be deleted - /// - public void deleteUser (string username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Get user by user name - /// - /// The name that needs to be fetched. Use user1 for testing. - /// - public User getUserByName (string username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (User) ApiInvoker.deserialize(response, typeof(User)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Logs user into the system - /// - /// The user name for login - /// The password for login in clear text - /// - public string loginUser (string username, string password) { - // create path and map variables - var path = "/user/login".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null || password == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - if (username != null){ - paramStr = (username != null && username is DateTime) ? ((DateTime)(object)username).ToString("u") : Convert.ToString(username); - queryParams.Add("username", paramStr); - } - if (password != null){ - paramStr = (password != null && password is DateTime) ? ((DateTime)(object)password).ToString("u") : Convert.ToString(password); - queryParams.Add("password", paramStr); - } - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (string) ApiInvoker.deserialize(response, typeof(string)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Logs out current logged in user session - /// - /// - public void logoutUser () { - // create path and map variables - var path = "/user/logout".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Create user This can only be done by the logged in user. - /// - /// Created user object - /// - public void createUser (User body) { - // create path and map variables - var path = "/user".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Creates list of users with given input array - /// - /// List of user object - /// - public void createUsersWithArrayInput (List body) { - // create path and map variables - var path = "/user/createWithArray".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Creates list of users with given list input - /// - /// List of user object - /// - public void createUsersWithListInput (List body) { - // create path and map variables - var path = "/user/createWithList".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - } - } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/ApiInvoker.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/ApiInvoker.cs deleted file mode 100644 index b61fec1687c..00000000000 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/ApiInvoker.cs +++ /dev/null @@ -1,100 +0,0 @@ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Text; - using Newtonsoft.Json; - - namespace Com.Wordnik.Petstore { - public class ApiInvoker { - private static readonly ApiInvoker _instance = new ApiInvoker(); - private Dictionary defaultHeaderMap = new Dictionary(); - - public static ApiInvoker GetInstance() { - return _instance; - } - - public void addDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } - - public string escapeString(string str) { - return str; - } - - public static object deserialize(string json, Type type) { - try - { - return JsonConvert.DeserializeObject(json, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - - } - - public static string serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - - public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams) { - var b = new StringBuilder(); - - foreach (var queryParamItem in queryParams) - { - var value = queryParamItem.Value; - if (value == null) continue; - b.Append(b.ToString().Length == 0 ? "?" : "&"); - b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); - } - - var querystring = b.ToString(); - - host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; - - var client = WebRequest.Create(host + path + querystring); - client.ContentType = "application/json"; - client.Method = method; - - foreach (var headerParamsItem in headerParams) - { - client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); - } - foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) - { - client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); - } - - switch (method) - { - case "GET": - break; - case "POST": - case "PUT": - case "DELETE": - var swRequestWriter = new StreamWriter(client.GetRequestStream()); - swRequestWriter.Write(serialize(body)); - swRequestWriter.Close(); - break; - default: - throw new ApiException(500, "unknown method type " + method); - } - var webResponse = (HttpWebResponse) client.GetResponse(); - if (webResponse.StatusCode != HttpStatusCode.OK) throw new ApiException((int) webResponse.StatusCode, webResponse.StatusDescription); - - var responseReader = new StreamReader(webResponse.GetResponseStream()); - var responseData = responseReader.ReadToEnd(); - responseReader.Close(); - return responseData; - } - - } - } - diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs deleted file mode 100644 index ae5012193e7..00000000000 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Text; -using System.Collections; -using System.Collections.Generic; - -namespace Com.Wordnik.Petstore.Model { - public class Order { - public long id { get; set; } - - public long petId { get; set; } - - public int quantity { get; set; } - - /* Order Status */ - public string status { get; set; } - - public DateTime shipDate { get; set; } - - public override string ToString() { - var sb = new StringBuilder(); - sb.Append("class Order {\n"); - sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" petId: ").Append(petId).Append("\n"); - sb.Append(" quantity: ").Append(quantity).Append("\n"); - sb.Append(" status: ").Append(status).Append("\n"); - sb.Append(" shipDate: ").Append(shipDate).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - } - } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs deleted file mode 100644 index 8bd8f260601..00000000000 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Text; -using System.Collections; -using System.Collections.Generic; - -namespace Com.Wordnik.Petstore.Model { - public class Pet { - /* unique identifier for the pet */ - public long id { get; set; } - - public Category category { get; set; } - - public string name { get; set; } - - public List photoUrls { get; set; } - - public List tags { get; set; } - - /* pet status in the store */ - public string status { get; set; } - - public override string ToString() { - var sb = new StringBuilder(); - sb.Append("class Pet {\n"); - sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" category: ").Append(category).Append("\n"); - sb.Append(" name: ").Append(name).Append("\n"); - sb.Append(" photoUrls: ").Append(photoUrls).Append("\n"); - sb.Append(" tags: ").Append(tags).Append("\n"); - sb.Append(" status: ").Append(status).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - } - } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs deleted file mode 100644 index bbbd6eaccc3..00000000000 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Text; -using System.Collections; -using System.Collections.Generic; - -namespace Com.Wordnik.Petstore.Model { - public class User { - public long id { get; set; } - - public string firstName { get; set; } - - public string username { get; set; } - - public string lastName { get; set; } - - public string email { get; set; } - - public string password { get; set; } - - public string phone { get; set; } - - /* User Status */ - public int userStatus { get; set; } - - public override string ToString() { - var sb = new StringBuilder(); - sb.Append("class User {\n"); - sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" firstName: ").Append(firstName).Append("\n"); - sb.Append(" username: ").Append(username).Append("\n"); - sb.Append(" lastName: ").Append(lastName).Append("\n"); - sb.Append(" email: ").Append(email).Append("\n"); - sb.Append(" password: ").Append(password).Append("\n"); - sb.Append(" phone: ").Append(phone).Append("\n"); - sb.Append(" userStatus: ").Append(userStatus).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - } - } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs new file mode 100644 index 00000000000..3230958f3af --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -0,0 +1,461 @@ + using System; + using System.Collections.Generic; + using io.swagger.client; + using io.swagger.Model; + + + + + + + namespace io.swagger.Api { + + public class PetApi { + string basePath; + private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + + public PetApi(String basePath = "http://petstore.swagger.io/v2") + { + this.basePath = basePath; + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + // Sets the endpoint base url for the services being accessed + public void setBasePath(string basePath) { + this.basePath = basePath; + } + + // Gets the endpoint base url for the services being accessed + public String getBasePath() { + return basePath; + } + + + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + + /// + public void updatePet (Pet Body) { + // create path and map variables + var path = "/pet".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + + /// + public void addPet (Pet Body) { + // create path and map variables + var path = "/pet".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + + /// + public List findPetsByStatus (List Status) { + // create path and map variables + var path = "/pet/findByStatus".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + if (Status != null){ + string paramStr = (Status is DateTime) ? ((DateTime)(object)Status).ToString("u") : Convert.ToString(Status); + queryParams.Add("status", paramStr); + } + + + + + + + try { + if (typeof(List) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as List; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return (List) ApiInvoker.deserialize(response, typeof(List)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + + /// + public List findPetsByTags (List Tags) { + // create path and map variables + var path = "/pet/findByTags".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + if (Tags != null){ + string paramStr = (Tags is DateTime) ? ((DateTime)(object)Tags).ToString("u") : Convert.ToString(Tags); + queryParams.Add("tags", paramStr); + } + + + + + + + try { + if (typeof(List) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as List; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return (List) ApiInvoker.deserialize(response, typeof(List)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + + /// + public Pet getPetById (long? PetId) { + // create path and map variables + var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(PetId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(Pet) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as Pet; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return (Pet) ApiInvoker.deserialize(response, typeof(Pet)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated + /// Updated name of the pet + /// Updated status of the pet + + /// + public void updatePetWithForm (string PetId, string Name, string Status) { + // create path and map variables + var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(PetId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + if (Name != null){ + if(Name is byte[]) { + formParams.Add("name", Name); + } else { + string paramStr = (Name is DateTime) ? ((DateTime)(object)Name).ToString("u") : Convert.ToString(Name); + formParams.Add("name", paramStr); + } + } + if (Status != null){ + if(Status is byte[]) { + formParams.Add("status", Status); + } else { + string paramStr = (Status is DateTime) ? ((DateTime)(object)Status).ToString("u") : Convert.ToString(Status); + formParams.Add("status", paramStr); + } + } + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Deletes a pet + /// + /// + /// Pet id to delete + + /// + public void deletePet (string ApiKey, long? PetId) { + // create path and map variables + var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(PetId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + headerParams.Add("api_key", ApiKey); + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// uploads an image + /// + /// ID of pet to update + /// Additional data to pass to server + /// file to upload + + /// + public void uploadFile (long? PetId, string AdditionalMetadata, byte[] File) { + // create path and map variables + var path = "/pet/{petId}/uploadImage".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(PetId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + if (AdditionalMetadata != null){ + if(AdditionalMetadata is byte[]) { + formParams.Add("additionalMetadata", AdditionalMetadata); + } else { + string paramStr = (AdditionalMetadata is DateTime) ? ((DateTime)(object)AdditionalMetadata).ToString("u") : Convert.ToString(AdditionalMetadata); + formParams.Add("additionalMetadata", paramStr); + } + } + if (File != null){ + if(File is byte[]) { + formParams.Add("file", File); + } else { + string paramStr = (File is DateTime) ? ((DateTime)(object)File).ToString("u") : Convert.ToString(File); + formParams.Add("file", paramStr); + } + } + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + } + + } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs new file mode 100644 index 00000000000..55ee956e1af --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -0,0 +1,225 @@ + using System; + using System.Collections.Generic; + using io.swagger.client; + using io.swagger.Model; + + + + + + namespace io.swagger.Api { + + public class StoreApi { + string basePath; + private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + + public StoreApi(String basePath = "http://petstore.swagger.io/v2") + { + this.basePath = basePath; + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + // Sets the endpoint base url for the services being accessed + public void setBasePath(string basePath) { + this.basePath = basePath; + } + + // Gets the endpoint base url for the services being accessed + public String getBasePath() { + return basePath; + } + + + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + + /// + public Dictionary getInventory () { + // create path and map variables + var path = "/store/inventory".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(Dictionary) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as Dictionary; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return (Dictionary) ApiInvoker.deserialize(response, typeof(Dictionary)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + + /// + public Order placeOrder (Order Body) { + // create path and map variables + var path = "/store/order".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(Order) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as Order; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); + if(response != null){ + return (Order) ApiInvoker.deserialize(response, typeof(Order)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + + /// + public Order getOrderById (string OrderId) { + // create path and map variables + var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.escapeString(OrderId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(Order) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as Order; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return (Order) ApiInvoker.deserialize(response, typeof(Order)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + + /// + public void deleteOrder (string OrderId) { + // create path and map variables + var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.escapeString(OrderId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + } + + } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs new file mode 100644 index 00000000000..cfbcb5feeb9 --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -0,0 +1,423 @@ + using System; + using System.Collections.Generic; + using io.swagger.client; + using io.swagger.Model; + + + + + + namespace io.swagger.Api { + + public class UserApi { + string basePath; + private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + + public UserApi(String basePath = "http://petstore.swagger.io/v2") + { + this.basePath = basePath; + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + // Sets the endpoint base url for the services being accessed + public void setBasePath(string basePath) { + this.basePath = basePath; + } + + // Gets the endpoint base url for the services being accessed + public String getBasePath() { + return basePath; + } + + + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + + /// + public void createUser (User Body) { + // create path and map variables + var path = "/user".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Creates list of users with given input array + /// + /// List of user object + + /// + public void createUsersWithArrayInput (List Body) { + // create path and map variables + var path = "/user/createWithArray".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Creates list of users with given input array + /// + /// List of user object + + /// + public void createUsersWithListInput (List Body) { + // create path and map variables + var path = "/user/createWithList".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Logs user into the system + /// + /// The user name for login + /// The password for login in clear text + + /// + public string loginUser (string Username, string Password) { + // create path and map variables + var path = "/user/login".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + if (Username != null){ + string paramStr = (Username is DateTime) ? ((DateTime)(object)Username).ToString("u") : Convert.ToString(Username); + queryParams.Add("username", paramStr); + } + if (Password != null){ + string paramStr = (Password is DateTime) ? ((DateTime)(object)Password).ToString("u") : Convert.ToString(Password); + queryParams.Add("password", paramStr); + } + + + + + + + try { + if (typeof(string) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as string; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return (string) ApiInvoker.deserialize(response, typeof(string)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Logs out current logged in user session + /// + + /// + public void logoutUser () { + // create path and map variables + var path = "/user/logout".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + + /// + public User getUserByName (string Username) { + // create path and map variables + var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(Username.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(User) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ((object)response) as User; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + if(response != null){ + return (User) ApiInvoker.deserialize(response, typeof(User)); + } + else { + return null; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + + + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted + /// Updated user object + + /// + public void updateUser (string Username, User Body) { + // create path and map variables + var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(Username.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + + /// + public void deleteUser (string Username) { + // create path and map variables + var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(Username.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + + + + + + + + + + try { + if (typeof(void) == typeof(byte[])) { + var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); + return ; + } else { + var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); + if(response != null){ + return ; + } + else { + return ; + } + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + + } + + } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs similarity index 53% rename from samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs rename to samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs index dfad92a046f..bfe1c0c4be8 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs @@ -3,19 +3,32 @@ using System.Text; using System.Collections; using System.Collections.Generic; -namespace Com.Wordnik.Petstore.Model { +namespace io.swagger.Model { public class Category { - public long id { get; set; } + - public string name { get; set; } + + public long? Id { get; set; } + + + + + public string Name { get; set; } + + public override string ToString() { var sb = new StringBuilder(); sb.Append("class Category {\n"); - sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" name: ").Append(name).Append("\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); return sb.ToString(); } } - } + + +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs new file mode 100644 index 00000000000..20a6d7367dd --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs @@ -0,0 +1,63 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; + +namespace io.swagger.Model { + public class Order { + + + + public long? Id { get; set; } + + + + + public long? PetId { get; set; } + + + + + public int? Quantity { get; set; } + + + + + public DateTime ShipDate { get; set; } + + + + /* Order Status */ + + public string Status { get; set; } + + + + + public bool? Complete { get; set; } + + + + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class Order {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" PetId: ").Append(PetId).Append("\n"); + + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + + sb.Append(" Status: ").Append(Status).Append("\n"); + + sb.Append(" Complete: ").Append(Complete).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + } + + +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs new file mode 100644 index 00000000000..b0f3573b78c --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs @@ -0,0 +1,63 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; + +namespace io.swagger.Model { + public class Pet { + + + + public long? Id { get; set; } + + + + + public Category Category { get; set; } + + + + + public string Name { get; set; } + + + + + public List PhotoUrls { get; set; } + + + + + public List Tags { get; set; } + + + + /* pet status in the store */ + + public string Status { get; set; } + + + + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class Pet {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Category: ").Append(Category).Append("\n"); + + sb.Append(" Name: ").Append(Name).Append("\n"); + + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + + sb.Append(" Tags: ").Append(Tags).Append("\n"); + + sb.Append(" Status: ").Append(Status).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + } + + +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs similarity index 52% rename from samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs rename to samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs index 61187fbd772..2fbf7070050 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs @@ -3,19 +3,32 @@ using System.Text; using System.Collections; using System.Collections.Generic; -namespace Com.Wordnik.Petstore.Model { +namespace io.swagger.Model { public class Tag { - public long id { get; set; } + - public string name { get; set; } + + public long? Id { get; set; } + + + + + public string Name { get; set; } + + public override string ToString() { var sb = new StringBuilder(); sb.Append("class Tag {\n"); - sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" name: ").Append(name).Append("\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); return sb.ToString(); } } - } + + +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs new file mode 100644 index 00000000000..146ba13c768 --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs @@ -0,0 +1,77 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; + +namespace io.swagger.Model { + public class User { + + + + public long? Id { get; set; } + + + + + public string Username { get; set; } + + + + + public string FirstName { get; set; } + + + + + public string LastName { get; set; } + + + + + public string Email { get; set; } + + + + + public string Password { get; set; } + + + + + public string Phone { get; set; } + + + + /* User Status */ + + public int? UserStatus { get; set; } + + + + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class User {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Username: ").Append(Username).Append("\n"); + + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + + sb.Append(" LastName: ").Append(LastName).Append("\n"); + + sb.Append(" Email: ").Append(Email).Append("\n"); + + sb.Append(" Password: ").Append(Password).Append("\n"); + + sb.Append(" Phone: ").Append(Phone).Append("\n"); + + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + } + + +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/ApiException.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs similarity index 90% rename from samples/client/petstore/csharp/src/Com/Wordnik/Petstore/ApiException.cs rename to samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs index 0da40246867..01648d1607c 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/ApiException.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs @@ -1,6 +1,6 @@ using System; -namespace Com.Wordnik.Petstore { +namespace io.swagger.client { public class ApiException : Exception { private int errorCode = 0; @@ -18,4 +18,4 @@ namespace Com.Wordnik.Petstore { this.errorCode = errorCode; } } -} +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs new file mode 100644 index 00000000000..736b51b81f9 --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs @@ -0,0 +1,207 @@ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using Newtonsoft.Json; + + namespace io.swagger.client { + public class ApiInvoker { + private static readonly ApiInvoker _instance = new ApiInvoker(); + private Dictionary defaultHeaderMap = new Dictionary(); + + public static ApiInvoker GetInstance() { + return _instance; + } + + public void addDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } + + public string escapeString(string str) { + return str; + } + + public static object deserialize(string json, Type type) { + try + { + return JsonConvert.DeserializeObject(json, type); + } + catch (IOException e) { + throw new ApiException(500, e.Message); + } + + } + + public static string serialize(object obj) { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) { + throw new ApiException(500, e.Message); + } + } + + public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + { + return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + } + + public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + { + return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; + } + + private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) { + var b = new StringBuilder(); + + foreach (var queryParamItem in queryParams) + { + var value = queryParamItem.Value; + if (value == null) continue; + b.Append(b.ToString().Length == 0 ? "?" : "&"); + b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); + } + + var querystring = b.ToString(); + + host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; + + var client = WebRequest.Create(host + path + querystring); + client.Method = method; + + byte[] formData = null; + if (formParams.Count > 0) + { + string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); + client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; + formData = GetMultipartFormData(formParams, formDataBoundary); + client.ContentLength = formData.Length; + } + else + { + client.ContentType = "application/json"; + } + + foreach (var headerParamsItem in headerParams) + { + client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); + } + foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) + { + client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); + } + + switch (method) + { + case "GET": + break; + case "POST": + case "PUT": + case "DELETE": + using (Stream requestStream = client.GetRequestStream()) + { + if (formData != null) + { + requestStream.Write(formData, 0, formData.Length); + } + + var swRequestWriter = new StreamWriter(requestStream); + swRequestWriter.Write(serialize(body)); + swRequestWriter.Close(); + } + break; + default: + throw new ApiException(500, "unknown method type " + method); + } + + try + { + var webResponse = (HttpWebResponse)client.GetResponse(); + if (webResponse.StatusCode != HttpStatusCode.OK) + { + webResponse.Close(); + throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); + } + + if (binaryResponse) + { + using (var memoryStream = new MemoryStream()) + { + webResponse.GetResponseStream().CopyTo(memoryStream); + return memoryStream.ToArray(); + } + } + else + { + using (var responseReader = new StreamReader(webResponse.GetResponseStream())) + { + var responseData = responseReader.ReadToEnd(); + return responseData; + } + } + } + catch(WebException ex) + { + var response = ex.Response as HttpWebResponse; + int statusCode = 0; + if (response != null) + { + statusCode = (int)response.StatusCode; + response.Close(); + } + throw new ApiException(statusCode, ex.Message); + } + } + + private static byte[] GetMultipartFormData(Dictionary postParameters, string boundary) + { + Stream formDataStream = new System.IO.MemoryStream(); + bool needsCLRF = false; + + foreach (var param in postParameters) + { + // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. + // Skip it on the first parameter, add it to subsequent parameters. + if (needsCLRF) + formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); + + needsCLRF = true; + + if (param.Value is byte[]) + { + string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", + boundary, + param.Key, + "application/octet-stream"); + formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); + + // Write the file data directly to the Stream, rather than serializing it to a string. + formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); + } + else + { + string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", + boundary, + param.Key, + param.Value); + formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); + } + } + + // Add the end of the request. Start with a newline + string footer = "\r\n--" + boundary + "--\r\n"; + formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); + + // Dump the Stream into a byte[] + formDataStream.Position = 0; + byte[] formData = new byte[formDataStream.Length]; + formDataStream.Read(formData, 0, formData.Length); + formDataStream.Close(); + + return formData; + } + } + }