Exemple #1
0
        public async Task WhenSpecContainsFormDataInSingleMultipartFile_ThenFormDataIsUsedInTypeScript()
        {
            var json = @"{
  ""x-generator"": ""NSwag v13.5.0.0 (NJsonSchema v10.1.15.0 (Newtonsoft.Json v11.0.0.0))"",
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""title"": ""My Title"",
    ""version"": ""1.0.0""
  },
  ""paths"": {
    ""/api/FileUpload/UploadFile"": {
      ""post"": {
        ""tags"": [
          ""FileUpload""
        ],
        ""operationId"": ""FileUpload_UploadFile"",
        ""requestBody"": {
          ""content"": {
            ""multipart/form-data"": {
              ""schema"": {
                ""properties"": {
                  ""file"": {
                    ""type"": ""string"",
                    ""format"": ""binary""
                  },
                  ""test"": {
                    ""type"": ""string""
                  }
                }
              }
            }
          }
        },
        ""responses"": {
          ""200"": {
            ""description"": """",
            ""content"": {
              ""application/octet-stream"": {
                ""schema"": {
                  ""type"": ""string"",
                  ""format"": ""binary""
                }
              }
            }
          }
        }
      }
    },
    
  },
  ""components"": {}
}";

            var document = await OpenApiDocument.FromJsonAsync(json);

            // Act
            var codeGenerator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            // Assert
            Assert.Contains("const content_ = new FormData();", code);
            Assert.Contains("interface FileParameter", code);
            Assert.Contains("content_.append(\"file\", file.data, file.fileName ? file.fileName : \"file\");", code);
        }
Exemple #2
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            app.UseSession();

            app.UseExceptionHandler(appBuilder =>
            {
                appBuilder.Use(async(context, next) =>
                {
                    IExceptionHandlerFeature error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;
                    if (error != null && error.Error is SecurityTokenExpiredException)
                    {
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                        {
                            State   = 401,
                            Message = "Token Expired"
                        }));
                    }
                    else if (error != null && error.Error != null)
                    {
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                        {
                            State   = 500,
                            Message = error.Error.Message
                        }));
                    }
                    else
                    {
                        await next();
                    }
                });
            });

            app.UseResponseCompression();
            app.UseCors(
                builder =>
                builder
                .AllowCredentials()
                .AllowAnyHeader().AllowAnyMethod()
                .WithOrigins("http://wearereading20200721193701.azurewebsites.net/").Build());

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "WeAreReading V1");
            });


            app.UseStaticFiles(new StaticFileOptions()
            {
                ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary <string, string>()
                {
                    { ".xlf", "application/x-msdownload" },
                    { ".exe", "application/octect-stream" },
                }),
            });
            app.UseHttpsRedirection();

            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseStatusCodePages();
            // app.UseDefaultFiles(); // so index.html is not required

            app.UseFileServer(new FileServerOptions()
            {
                EnableDirectoryBrowsing = false
            });

            app.UseAuthentication();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                    spa.Options.StartupTimeout = TimeSpan.FromMinutes(5);
                }
            });

            if (env.IsDevelopment())
            {
                Task.Run(() =>
                {
                    using HttpClient httpClient       = new HttpClient();
                    string SourceDocumentAbsoluteUrl  = Configuration["SwaggerToTypeScriptSettings:SourceDocumentAbsoluteUrl"];
                    string OutputDocumentRelativePath = Configuration["SwaggerToTypeScriptSettings:OutputDocumentRelativePath"];
                    using Stream contentStream        = httpClient.GetStreamAsync(SourceDocumentAbsoluteUrl).Result;
                    using StreamReader streamReader   = new StreamReader(contentStream);
                    string json = streamReader.ReadToEnd();

                    var document = NSwag.OpenApiDocument.FromJsonAsync(json).Result;

                    var settings = new TypeScriptClientGeneratorSettings
                    {
                        ClassName            = "SwaggerClient",
                        Template             = TypeScriptTemplate.Angular,
                        RxJsVersion          = 6.0M,
                        HttpClass            = HttpClass.HttpClient,
                        InjectionTokenType   = InjectionTokenType.InjectionToken,
                        BaseUrlTokenName     = "API_BASE_URL",
                        UseSingletonProvider = true
                    };

                    var generator = new TypeScriptClientGenerator(document, settings);
                    var code      = generator.GenerateFile();
                    new FileInfo(OutputDocumentRelativePath).Directory.Create();
                    try
                    {
                        File.WriteAllText(OutputDocumentRelativePath, code);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                });
            }
        }
        public async Task when_content_is_formdata_with_property_object_then_content_should_be_json_typescript()
        {
            var json = @"{
              ""x-generator"": ""NSwag v13.5.0.0 (NJsonSchema v10.1.15.0 (Newtonsoft.Json v11.0.0.0))"",
              ""openapi"": ""3.0.0"",
              ""info"": {
                ""title"": ""My Title"",
                ""version"": ""1.0.0""
              },
              ""paths"": {
                ""/api/FileUpload/UploadFile"": {
                  ""post"": {
                    ""tags"": [
                      ""FileUpload""
                    ],
                    ""operationId"": ""FileUpload_UploadFile"",
                    ""requestBody"": {
                      ""content"": {
                        ""multipart/form-data"": {
                          ""schema"": {
                            ""properties"": {
                              ""file"": {
                                ""type"": ""string"",
                                ""format"": ""binary""
                              },
                              ""propertyDto"": {
                                ""type"": ""object"",
                                ""description"": ""Configurable properties""
                              },
                              ""test"": {
                                ""type"": ""string""
                              }
                            }
                          }
                        }
                      }
                    },
                    ""responses"": {
                      ""200"": {
                        ""description"": """",
                        ""content"": {
                          ""application/octet-stream"": {
                            ""schema"": {
                              ""type"": ""string"",
                              ""format"": ""binary""
                            }
                          }
                        }
                      }
                    }
                  }
                },
    
              },
              ""components"": {}
            }";

            var document = await OpenApiDocument.FromJsonAsync(json);

            // Act
            var codeGenerator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            // Assert
            Assert.Contains("const content_ = new FormData();", code);
            Assert.Contains("content_.append(\"propertyDto\", JSON.stringify(propertyDto))", code);
        }
Exemple #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireNonAlphanumeric = false;
            });

            services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
            services.AddDbContext <UnderSeaDatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <User>()
            .AddEntityFrameworkStores <UnderSeaDatabaseContext>();

            services.AddIdentityServer()
            .AddCorsPolicyService <IdentityServerCorsPolicyService>()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources(Configuration))
            .AddInMemoryClients(IdentityServerConfig.GetClients(Configuration))
            .AddAspNetIdentity <User>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority                 = Configuration["Authority"];
                options.Audience                  = Configuration["ApiName"];
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name
                };
            });

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSignalR();

            services.AddSwaggerDocument(options =>
            {
                options.Title       = "Undersea API";
                options.Version     = "1.0";
                options.Description = "API for the game called Under sea, which is a turn based online multiplayer strategy game.";

                options.PostProcess = document =>
                {
                    var settings = new TypeScriptClientGeneratorSettings
                    {
                        ClassName = "{controller}Client",
                        Template  = TypeScriptTemplate.Axios
                    };

                    var generator = new TypeScriptClientGenerator(document, settings);
                    var code      = generator.GenerateFile();

                    var path      = Directory.GetCurrentDirectory();
                    var directory = new DirectoryInfo(path + @"\TypeScript");
                    if (!directory.Exists)
                    {
                        directory.Create();
                    }

                    var filePath = path + @"\TypeScript\Client.ts";
                    File.WriteAllText(filePath, code);
                };
            });

            services.AddAutoMapper(typeof(KnownValues).Assembly);

            services.AddSingleton(new ModifierParserContainer(new AbstractEffectModifierParser[]
            {
                new BarrackSpaceEffectParser(),
                new CoralProductionEffectParser(),
                new PearlProductionEffectParser(),
                new HarvestModifierEffectParser(),
                new PopulationEffectParser(),
                new TaxModifierEffectParser(),
                new UnitDefenseEffectParser(),
                new UnitAttackEffectParser(),
                new AddBuildingEffectParser(),
                new IncreaseUnitAttackEffectParser(),
                new BuildingCoralProductionEffectParser()
            }));

            services.AddSingleton <IUserTracker, UserTracker>();

            services.AddTransient <ITurnHandlingService, TurnHandlingService>();
            services.AddTransient <ICountryService, CountryService>();
            services.AddTransient <IResearchService, ResearchService>();
            services.AddTransient <IBuildingService, BuildingService>();
            services.AddTransient <IUnitService, UnitService>();
            services.AddTransient <ICommandService, CommandService>();
            services.AddTransient <IExceptionLogger, ExceptionLogger>();

            // User ID provider for SignalR Hub
            services.AddTransient <IUserIdProvider, UserIdProvider>();
        }
        public async Task When_parameter_is_array_then_TypeScript_is_correct()
        {
            // Arrange
            var swagger  = @"{
  ""swagger"" : ""2.0"",
  ""info"" : {
    ""version"" : ""1.0.2"",
    ""title"" : ""Test API""
  },
  ""host"" : ""localhost:8080"",
  ""basePath"" : ""/"",
  ""tags"" : [ {
    ""name"" : ""api""
  } ],
  ""schemes"" : [ ""http"" ],
  ""paths"" : {
     ""/removeElement"" : {
      ""delete"" : {
        ""tags"" : [ ""api"" ],
        ""summary"" : ""Removes elements"",
        ""description"" : ""Removes elements"",
        ""operationId"" : ""removeElement"",
        ""consumes"" : [ ""application/json"" ],
        ""produces"" : [ ""application/json"" ],
        ""parameters"" : [ {
          ""name"" : ""X-User"",
          ""in"" : ""header"",
          ""description"" : ""User identifier"",
          ""required"" : true,
          ""type"" : ""string""
        }, {
          ""name"" : ""elementId"",
          ""in"" : ""query"",
          ""description"" : ""The ids of existing elements that should be removed"",
          ""required"" : false,
          ""type"" : ""array"",
          ""items"" : {
            ""type"" : ""integer"",
            ""format"" : ""int64""
          },
        } ],
        ""responses"" : {
          ""default"" : {
            ""description"" : ""successful operation""
          }
        }
      }
    }
  },
    ""definitions"" : { }
}
";
            var document = await OpenApiDocument.FromJsonAsync(swagger);

            // Act
            var settings = new TypeScriptClientGeneratorSettings {
                ClassName = "MyClass"
            };
            var generator = new TypeScriptClientGenerator(document, settings);
            var code      = generator.GenerateFile();

            // Assert
            Assert.Contains(@"elementId.forEach(item => { url_ += ""elementId="" + encodeURIComponent("""" + item) + ""&""; });", code);
        }
        public async Task when_content_is_formdata_with_property_array_then_content_should_be_added_in_foreach_in_typescript()
        {
            var json = @"{
              ""x-generator"": ""NSwag v13.5.0.0 (NJsonSchema v10.1.15.0 (Newtonsoft.Json v11.0.0.0))"",
              ""openapi"": ""3.0.0"",
              ""info"": {
                ""title"": ""My Title"",
                ""version"": ""1.0.0""
              },
              ""paths"": {
                ""/api/FileUpload/UploadFile"": {
                  ""post"": {
                    ""tags"": [
                      ""FileUpload""
                    ],
                    ""operationId"": ""FileUpload_UploadFile"",
                    ""requestBody"": {
                      ""content"": {
                        ""multipart/form-data"": {
                          ""schema"": {
                            ""properties"": {
                              ""file"": {
                                ""type"": ""string"",
                                ""format"": ""binary""
                              },
                              ""arrayOfIds"": {
                                ""uniqueItems"": true,
                                ""type"": ""array"",
                                ""items"": {
                                  ""type"": ""string""
                                },
                                ""description"": ""Hash Set of of strings in the DTO request"",
                                ""nullable"": true
                              },
                              ""test"": {
                                ""type"": ""string""
                              }
                            }
                          }
                        }
                      }
                    },
                    ""responses"": {
                      ""200"": {
                        ""description"": """",
                        ""content"": {
                          ""application/octet-stream"": {
                            ""schema"": {
                              ""type"": ""string"",
                              ""format"": ""binary""
                            }
                          }
                        }
                      }
                    }
                  }
                },
    
              },
              ""components"": {}
            }";

            var document = await OpenApiDocument.FromJsonAsync(json);

            // Act
            var codeGenerator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            // Assert
            Assert.Contains("const content_ = new FormData();", code);
            Assert.Contains("arrayOfIds.forEach(item_ => content_.append(\"arrayOfIds\", item_.toString()));", code);
        }