Beispiel #1
0
        protected override Task <int> OnExecute(CommandLineApplication app)
        {
            var serverUrl = new Uri("http://localhost/api/package");

            if (ClaimProducer == 0)
            {
                ClaimProducer = 1;
            }

            // Submit claim
            using (var client = new WebClient())
            {
                // Create Claim
                //PackageBuilder
                Package package = null;
                using (var tt = new TimeMe("Create package"))
                {
                    package = CreatePackage(ClaimProducer);
                }

                using (var tt = new TimeMe("Submit package"))
                {
                    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                    app.Out.WriteLine(client.UploadString(serverUrl, "POST", package.ToString()));
                }
            }

            // Repeat
            return(Task.FromResult(0));
        }
Beispiel #2
0
        //        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //            //app.AllServices(_services);
            //            //applicationLifetime.ApplicationStopping.Register(() => applicationEvents.StopAsync().Wait());


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(new DeveloperExceptionPageOptions {
                    SourceCodeLineCount = 100
                });
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
                //                    //if (!"Off".EndsWithIgnoreCase(Configuration.RateLimits()))
                //                    //    rateLimitService.SetZone(Configuration.RateLimits());
            }

            using (TimeMe.Track("DTP apps"))
            {
                //app.DtpCore(); // Ensure configuration of core
                app.DtpGraph(); // Load the Trust Graph from Database
                app.DtpStamp();
            }

            using (TimeMe.Track("Serilog, Swagger and UseMVC"))
            {
                app.UseMiddleware <SerilogDiagnostics>();

                app.UseHttpsRedirection();
                app.UseStaticFiles();

                app.UseRouting();
                app.UseCors("CorsPolicy");
                //app.UseAuthorization();

                //app.UseFileServer(enableDirectoryBrowsing: true);
                //app.UseCookiePolicy();
                app.UseHealthChecks("/ready");

                //Enable middleware to serve generated Swagger as a JSON endpoint.
                // Enable middleware to serve swagger - ui(HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
                });


                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapRazorPages();
                });
            }
        }
Beispiel #3
0
        public void ByteComparerTest()
        {
            Console.WriteLine(String.Format("Before {0} mb", (int)(GC.GetTotalMemory(true) / 1024 / 1024)));
            var max  = 100000;
            var step = max / 10;

            var ids = new List <byte[]>();

            for (int i = 1; i <= max; i++)
            {
                var id = Hashes.SHA256(Encoding.UTF8.GetBytes(i.ToString()));
                ids.Add(id);

                if ((i % step) == 0)
                {
                    Console.Write(string.Format("\r{0}%", i - step));
                }
            }
            Console.WriteLine("\r100%");


            var dd = new Dictionary <byte[], byte[]>(ByteComparer.Standard);

            foreach (var id in ids)
            {
                dd.Add(id, id);
            }

            using (var timer = new TimeMe("Test ByteComparer Safe"))
            {
                foreach (var id in ids)
                {
                    var result = dd[id];
                    var t      = result[0];
                }
            }

            var item = new VisitItem(-1, -1);

            using (var timer = new TimeMe("Test List Index"))
            {
                var visited = new VisitItem[max * 10];
                for (int i = 0; i < max * 10; i++)
                {
                    visited[i] = item;
                }
            }

            Console.WriteLine(String.Format("After {0} mb", (int)(GC.GetTotalMemory(true) / 1024 / 1024)));
        }
        public virtual void AddBackgroundServices(IServiceCollection services)
        {
            using (TimeMe.Track("AddBackgroundServices"))
            {
                services.AddScheduler((sender, args) =>
                {
#if DEBUG
                    Log.Error(args.Exception, args.Exception.Message);
#else
                    Log.Error(args.Exception.Message);
#endif
                    args.SetObserved();
                });
            }
        }
        //public static void StartIPFS(this IApplicationBuilder app)
        //{
        //    var applicationEvent = app.ApplicationServices.GetRequiredService<ApplicationEvents>();
        //    using (var scope = app.ApplicationServices.CreateScope())
        //    {
        //        var ipfsManager = scope.ServiceProvider.GetRequiredService<IpfsManager>();
        //        ipfsManager.StartIpfs();
        //        applicationEvent.StopTasks.Add(async () => await Task.Run(() => ipfsManager.Dispose()));
        //    }
        //}

        public static void DtpGraph(this IApplicationBuilder app)
        {
            var applicationEvent = app.ApplicationServices.GetRequiredService <ApplicationEvents>();

            applicationEvent.BootupTasks.Add(Task.Run(() => {
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    using (TimeMe.Track("Trust load"))
                    {
                        // Load all data into graph, properly async will be an good idea here!
                        var trustLoadService = scope.ServiceProvider.GetRequiredService <IGraphLoadSaveService>();
                        trustLoadService.LoadFromDatabase();
                    }
                }
            }));
        }
        public virtual void ConfigureDbContext(IServiceCollection services)
        {
            using (TimeMe.Track("ConfigureDbContext"))
            {
                var platform      = new PlatformDirectory();
                var dbName        = "trust.db";
                var dbDestination = "./trust.db";
                if (_hostingEnv.IsProduction())
                {
                    dbDestination = Path.Combine(platform.DatabaseDataPath, dbName);
                    platform.EnsureDtpServerDirectory();
                    if (!File.Exists(dbDestination))
                    {
                        File.Copy(Path.Combine(dbName), dbDestination);
                    }
                }

                services.AddDbContext <TrustDBContext>(options =>
                                                       options.UseSqlite($"Filename={dbDestination}", b => b.MigrationsAssembly("DtpCore"))
                                                       .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning))
                                                       );
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            using (TimeMe.Track("ConfigureServices"))
            {
                services.Configure <CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded    = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });

                ConfigureDbContext(services);

                services.AddCors(options =>
                {
                    options.AddPolicy("CorsPolicy",
                                      builder => builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      //.AllowCredentials()
                                      );
                });

                services.AddControllers().AddJsonOptions(options => {
                    options.JsonSerializerOptions.IgnoreNullValues = true;
                    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                });
                services.AddRazorPages(config =>
                {
                });

                //services.AddMvc()
                //    .AddJsonOptions(options => {
                //        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                //        options.JsonSerializerOptions.IgnoreNullValues = true;
                //    });
                ////                services.AddMvc(options =>
                //                {
                //                    //if (!"Off".EndsWithIgnoreCase(Configuration.RateLimits()))
                //                    //    options.Filters.Add(new RateLimitsFilterAttribute("ALL") { Scope = RateLimitsScope.RemoteAddress });

                //                    //options.Filters.Add(new RequestSizeLimitAttribute(10 * 1024 * 1024)); // 10Mb
                //                    options.EnableEndpointRouting = false;
                //                });
                //                .AddNewtonsoftJson(opts =>
                //                //{
                //                //    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //                //    opts.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter
                //                //    {
                //                //        CamelCaseText = true
                //                //    });
                //                //}); //.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

                services.AddHealthChecks()
                .AddDbContextCheck <TrustDBContext>();

                services.AddRateLimits(); // Add Rate limits for against DDOS attacks

                //services.AddSwaggerGen(c =>
                //{
                //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
                //});

                services
                .AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo
                    {
                        Version     = "v1",
                        Title       = "DTP API",
                        Description = "DTP API (ASP.NET Core 3.0)",
                        Contact     = new OpenApiContact()
                        {
                            Name  = "DTP",
                            Url   = new Uri("https://trust.dance"),
                            Email = ""
                        },
                        TermsOfService = new Uri("https://raw.githubusercontent.com/DigitalTrustProtocol/DtpSolution/master/License")
                    });
                    //c.CustomSchemaIds(type => type..FriendlyId(true));
                    //c.DescribeAllEnumsAsStrings();
                    //if(_hostingEnv != null)
                    //    c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml");

                    // Include DataAnnotation attributes on Controller Action parameters as Swagger validation rules (e.g required, pattern, ..)
                    // Use [ValidateModelState] on Actions to actually validate it in C# as well!
                    //c.OperationFilter<GeneratePathParamsValidationFilter>();
                });

                services.AddMediatR(Assembly.GetExecutingAssembly());

                services.DtpCore();
                services.DtpGraphCore();
                services.DtpStrampCore();
                services.DtpPackageCore();
                services.DtpServer();

                AddBackgroundServices(services);

                _services = services;
            }
        }