Example #1
0
        static void Main(string[] args)
        {
            //EntityFrameworkCache.Initialize(new ServiceStackRedisCache(new ServiceStackRedisCacheOptions
            //{
            //    Host = "172.16.6.40",
            //    Password = "******"
            //}));
            //EntityFrameworkCache.Initialize(new StackExchangeRedisCache(new StackExchangeRedisCacheOptions()
            //{
            //    Configuration="172.16.6.40:6379,serviceName=Sky-Redis01-Cluster01,password=SCFLgskjhb9wqdi0weugbfjpsodkf8"
            //}));
            EntityFrameworkCache.Initialize(new InMemoryCache());

            litlyEntities db   = new litlyEntities();
            var           urls = db.Urls.Where(u => u.CompanyId == 1).Select(u => new { u.ShortUrl, u.LongUrl }).ToList();

            db.Urls.Add(new Url {
                ShortUrl = "test", LongUrl = "test.com", CompanyId = 1, UserId = "54731be8-2b39-4bf7-be15-19ecabbb821e", RegDate = DateTime.Now
            });
            db.SaveChanges();
            var url = db.Urls.First(u => u.ShortUrl == "test");

            url.Hits = 10;
            db.SaveChanges();

            db.Urls.Remove(url);
            db.SaveChanges();

            urls = db.Urls.Where(u => u.CompanyId == 1).Select(u => new { u.ShortUrl, u.LongUrl }).ToList();
        }
Example #2
0
        private static void Main()
        {
            EntityFrameworkCache.Initialize(new InMemoryCache());

            var language = ConfigurationManager.AppSettings["language"];

            Thread.CurrentThread.CurrentCulture   = new System.Globalization.CultureInfo(language);
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (Properties.Settings.Default.firstTime)
            {
                Application.Run(new Ar_Eng());
            }
            else
            {
                Application.Run(new Loginn());
            }
        }
Example #3
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var postgresConnectionString =
                ConnectionStringUrlToResource(_configuration.GetValue <string>("DATABASE_URL")
                                              ?? throw new Exception("DATABASE_URL is null"));

            services.AddOptions();

            services.AddLogging();

            services.AddRouting(options => { options.LowercaseUrls = true; });

            if (_env.IsDevelopment())
            {
                services.AddDistributedMemoryCache();
            }
            else
            {
                services.AddStackExchangeRedisCache(x =>
                                                    x.Configuration = _configuration.GetValue <string>("REDISTOGO_URL"));
            }

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout         = TimeSpan.FromMinutes(50);
                options.Cookie.HttpOnly     = true;
                options.Cookie.Name         = ApiConstants.AuthenticationSessionCookieName;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "oriental-rug-gallery-API", Version = "v1"
                });
            });

            services.AddMvc(x =>
            {
                x.ModelValidatorProviders.Clear();

                // Not need to have https
                x.RequireHttpsPermanent = false;

                // Allow anonymous for localhost
                if (_env.IsDevelopment())
                {
                    x.Filters.Add <AllowAnonymousFilter>();
                }
            }).AddNewtonsoftJson(x =>
            {
                x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                x.SerializerSettings.Converters.Add(new StringEnumConverter());
            }).AddRazorPagesOptions(x => { x.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); });

            services.AddWebMarkupMin(opt =>
            {
                opt.AllowMinificationInDevelopmentEnvironment = true;
                opt.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification()
            .AddHttpCompression();

            services.AddDbContext <EntityDbContext>(opt => opt.UseNpgsql(postgresConnectionString));

            services.AddIdentity <User, IdentityRole <int> >(x => { x.User.RequireUniqueEmail = true; })
            .AddEntityFrameworkStores <EntityDbContext>()
            .AddRoles <IdentityRole <int> >()
            .AddDefaultTokenProviders();

            // L2 EF cache
            if (_env.IsDevelopment())
            {
                EntityFrameworkCache.Initialize(new InMemoryCache());
            }
            else
            {
                var redisConfigurationOptions =
                    ConfigurationOptions.Parse(_configuration.GetValue <string>("REDISTOGO_URL"));

                // Important
                redisConfigurationOptions.AbortOnConnectFail = false;

                EntityFrameworkCache.Initialize(new RedisCache(redisConfigurationOptions));
            }

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x =>
            {
                x.Cookie.MaxAge = TimeSpan.FromMinutes(60);
            });

            // Re-Captcha config
            services.Configure <RecaptchaSettings>(_configuration.GetSection("RecaptchaSettings"));
            services.AddTransient <IRecaptchaService, RecaptchaService>();

            _container = new Container(config =>
            {
                config.For <DocumentStore>().Use(DocumentStore.For(y =>
                {
                    // Important as PLV8 is disabled on Heroku
                    y.PLV8Enabled = false;

                    y.Connection(postgresConnectionString);

                    y.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate;
                }));

                var(accessKeyId, secretAccessKey, url) = (
                    _configuration.GetRequiredValue <string>("CLOUDCUBE_ACCESS_KEY_ID"),
                    _configuration.GetRequiredValue <string>("CLOUDCUBE_SECRET_ACCESS_KEY"),
                    _configuration.GetRequiredValue <string>("CLOUDCUBE_URL")
                    );

                var prefix = new Uri(url).Segments.Skip(1).FirstOrDefault() ?? throw new Exception("S3 url is malformed");
                const string bucketName = "cloud-cube";

                // Generally bad practice
                var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);

                // Create S3 client
                config.For <IAmazonS3>().Use(() => new AmazonS3Client(credentials, RegionEndpoint.USEast1));
                config.For <S3ServiceConfig>().Use(new S3ServiceConfig(bucketName, prefix));

                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.Assembly("Api");
                    _.Assembly("Logic");
                    _.Assembly("Dal");
                    _.WithDefaultConventions();
                });

                // Populate the container using the service collection
                config.Populate(services);
            });

            _container.AssertConfigurationIsValid();

            return(_container.GetInstance <IServiceProvider>());
        }
Example #4
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddHttpsRedirection(options => { options.HttpsPort = 443; });

            services.AddDistributedMemoryCache();

            // If environment is localhost, then enable CORS policy, otherwise no cross-origin access
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder => builder
                                  .AllowAnyOrigin()
                                  .AllowAnyHeader()
                                  .AllowAnyMethod());
            });

            // Add framework services
            // Add functionality to inject IOptions<T>
            services.AddOptions();
            services.Configure <JwtSettings>(_configuration.GetSection("JwtSettings"));

            // Add our Config object so it can be injected
            //services.Configure<SecureHeadersMiddlewareConfiguration>(
            //    _configuration.GetSection("SecureHeadersMiddlewareConfiguration"));

            services.AddLogging();

            services.AddRouting(options => options.LowercaseUrls = true);

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout         = TimeSpan.FromMinutes(50);
                options.Cookie.HttpOnly     = true;
                options.Cookie.Name         = ApiConstants.ApplicationName;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });

            services.AddDbContext <EntityDbContext>(builder =>
            {
                if (_env.IsDevelopment())
                {
                    builder.UseSqlite(_configuration.GetValue <string>("ConnectionStrings:Sqlite"));
                }
                else
                {
                    builder.UseNpgsql(
                        ConnectionStringUrlToResource(_configuration.GetRequiredValue <string>("DATABASE_URL")));
                }
            });

            services.AddIdentity <User, UserRole>(opt => opt.User.RequireUniqueEmail = true)
            .AddRoles <UserRole>()
            .AddEntityFrameworkStores <EntityDbContext>()
            .AddDefaultTokenProviders();

            if (_env.IsDevelopment())
            {
                EntityFrameworkCache.Initialize(new InMemoryCache());
            }
            else
            {
                var redisCacheConfig = ConfigurationOptions.Parse(_configuration.GetValue <string>("REDISTOGO_URL"));

                redisCacheConfig.AbortOnConnectFail = false;    // Needed otherwise redis client will fail

                EntityFrameworkCache.Initialize(new RedisCache(redisCacheConfig));
            }

            var jwtSetting = _configuration
                             .GetSection("JwtSettings")
                             .Get <JwtSettings>();

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(config =>
            {
                config.RequireHttpsMetadata = false;
                config.SaveToken            = true;

                config.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = jwtSetting.Issuer,
                    ValidAudience    = jwtSetting.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.Key))
                };
            });

            services.AddControllers(opt =>
            {
                opt.EnableEndpointRouting = false;

                opt.ModelValidatorProviders.Clear();

                // Not need to have https
                opt.RequireHttpsPermanent = false;

                // Allow anonymous for localhost
                if (_env.IsDevelopment())
                {
                    opt.Filters.Add <AllowAnonymousFilter>();
                }

                opt.Filters.Add <CustomExceptionFilterAttribute>();
                opt.Filters.Add <FileUploadActionFilterAttribute>();
            })
            .AddNewtonsoftJson(option => option.SerializerSettings.Converters.Add(new StringEnumConverter()));

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                                           ForwardedHeaders.XForwardedProto;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            services.AddSwaggerGen(config =>
            {
                config.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "Contractor-Finder-Api",
                    Description = "Contractor finder service API layer, .NET Core + PostgresSQL"
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                if (File.Exists(xmlPath))
                {
                    config.IncludeXmlComments(xmlPath);
                }

                config.OperationFilter <FileUploadOperation>();

                config.AddSecurityDefinition("Bearer", // Name the security scheme
                                             new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme.",
                    Type        = SecuritySchemeType.Http, // We set the scheme type to http since we're using bearer authentication
                    Scheme      = "bearer"                 // The name of the HTTP Authorization scheme to be used in the Authorization header. In this case "bearer".
                });
            });

            var container = new Container(config =>
            {
                if (_env.IsDevelopment())
                {
                    config.For <IS3Service>().Use <InMemoryS3>().Singleton();
                }
                else
                {
                    var(accessKeyId, secretAccessKey, url) = (
                        _configuration.GetRequiredValue <string>("CLOUDCUBE_ACCESS_KEY_ID"),
                        _configuration.GetRequiredValue <string>("CLOUDCUBE_SECRET_ACCESS_KEY"),
                        _configuration.GetRequiredValue <string>("CLOUDCUBE_URL")
                        );

                    var prefix = new Uri(url).Segments.Skip(1).FirstOrDefault() ?? throw new Exception("S3 url is malformed");
                    const string bucketName = "cloud-cube";

                    // Generally bad practice
                    var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);

                    // Create S3 client
                    config.For <IAmazonS3>().Use(() => new AmazonS3Client(credentials, RegionEndpoint.USEast1));
                    config.For <S3ServiceConfig>().Use(new S3ServiceConfig(bucketName, prefix));
                }

                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.Assembly("Logic");
                    _.Assembly("Dal");
                    _.WithDefaultConventions();
                });

                // Populate the container using the service collection
                config.Populate(services);

                config.For <IMapper>().Use(ctx => ResolveMapper(ctx, Assembly.Load("Logic"))).Singleton();
            });

            // container.AssertConfigurationIsValid();

            return(container.GetInstance <IServiceProvider>());
        }
Example #5
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // services.AddMiniProfiler(opt =>
            // {
            //     // opt.RouteBasePath = "/profiler";
            //     opt.ShouldProfile = _ => true;
            //     opt.ShowControls = true;
            //     opt.StackMaxLength = short.MaxValue;
            //     opt.PopupStartHidden = false;
            //     opt.PopupShowTrivial = true;
            //     opt.PopupShowTimeWithChildren = true;
            // });

            services.AddHttpsRedirection(options => options.HttpsPort = 443);

            // If environment is localhost, then enable CORS policy, otherwise no cross-origin access
            services.AddCors(options => options.AddPolicy("CorsPolicy", builder => builder
                                                          .WithOrigins(_configuration.GetSection("TrustedSpaUrls").Get <string[]>())
                                                          .AllowAnyHeader()
                                                          .AllowAnyMethod()
                                                          .AllowCredentials()));

            // Add framework services
            // Add functionality to inject IOptions<T>
            services.AddOptions();

            services.AddResponseCompression();

            services.Configure <JwtSettings>(_configuration.GetSection("JwtSettings"));

            services.AddLogging();

            services.AddRouting(options => options.LowercaseUrls = true);

            if (_env.IsDevelopment())
            {
                services.AddDistributedMemoryCache();
            }
            else
            {
                var redisConnectionString =
                    ConnectionStringUrlToRedisResource(_configuration.GetValue <string>("REDISTOGO_URL"));

                services.AddStackExchangeRedisCache(c => c.Configuration = redisConnectionString);
            }

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout         = TimeSpan.FromMinutes(60);
                options.Cookie.HttpOnly     = true;
                options.Cookie.Name         = ApiConstants.AuthenticationSessionCookieName;
                options.Cookie.SecurePolicy = CookieSecurePolicy.None;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "dotnet-template", Version = "v1"
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }

                c.AddSecurityDefinition("Bearer", // Name the security scheme
                                        new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme.",
                    Type        = SecuritySchemeType.Http, // We set the scheme type to http since we're using bearer authentication
                    Scheme      = "bearer"                 // The name of the HTTP Authorization scheme to be used in the Authorization header. In this case "bearer".
                });
            });

            services.AddMvc(x =>
            {
                x.ModelValidatorProviders.Clear();

                // Not need to have https
                x.RequireHttpsPermanent = false;

                // Allow anonymous for localhost
                if (_env.IsDevelopment())
                {
                    x.Filters.Add <AllowAnonymousFilter>();
                }

                // Exception filter attribute
                x.Filters.Add <ExceptionFilterAttribute>();
            }).AddNewtonsoftJson(x =>
            {
                x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            })
            .AddRazorPagesOptions(x => x.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()));

            services.AddDbContext <EntityDbContext>(opt =>
            {
                if (_env.IsDevelopment())
                {
                    opt.UseSqlite(_configuration.GetValue <string>("ConnectionStrings:Sqlite"));
                }
                else
                {
                    var postgresConnectionString =
                        ConnectionStringUrlToPgResource(_configuration.GetValue <string>("DATABASE_URL")
                                                        ?? throw new Exception("DATABASE_URL is null"));
                    opt.UseNpgsql(postgresConnectionString);
                }
            });

            services.AddIdentity <User, IdentityRole <int> >(x => x.User.RequireUniqueEmail = true)
            .AddEntityFrameworkStores <EntityDbContext>()
            .AddRoles <IdentityRole <int> >()
            .AddDefaultTokenProviders();

            // L2 EF cache
            if (_env.IsDevelopment())
            {
                EntityFrameworkCache.Initialize(new InMemoryCache());
            }
            else
            {
                var redisConnectionString =
                    ConnectionStringUrlToRedisResource(_configuration.GetValue <string>("REDISTOGO_URL"));

                var redisConfigurationOptions = ConfigurationOptions.Parse(redisConnectionString);

                // Important
                redisConfigurationOptions.AbortOnConnectFail = false;

                EntityFrameworkCache.Initialize(new RedisCache(redisConfigurationOptions));
            }

            var jwtSetting = _configuration
                             .GetSection("JwtSettings")
                             .Get <JwtSettings>();

            if (_env.IsDevelopment() && string.IsNullOrEmpty(jwtSetting.Key))
            {
                jwtSetting.Key = PasswordGenerator.Generate(length: 100, allowed: Sets.Alphanumerics);

                IdentityModelEventSource.ShowPII = true;
            }

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(x => x.Cookie.MaxAge = TimeSpan.FromMinutes(60))
            .AddJwtBearer(config =>
            {
                config.RequireHttpsMetadata = false;
                config.SaveToken            = true;

                config.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = jwtSetting.Issuer,
                    ValidAudience    = jwtSetting.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.Key))
                };
            });

            services.AddSingleton <IUserIdProvider, CustomUserIdProvider>();

            services.AddSignalR(config =>
            {
                config.MaximumReceiveMessageSize = 10 * 1024 * 1024; // 10 mega-bytes
                config.StreamBufferCapacity      = 50;
                config.EnableDetailedErrors      = true;
            });

            // Re-Captcha config
            services.Configure <RecaptchaSettings>(_configuration.GetSection("RecaptchaSettings"));
            services.AddTransient <IRecaptchaService, RecaptchaService>();

            services.AddEfRepository <EntityDbContext>(x => x.Profile(Assembly.Load("Dal")));

            var container = new Container(config =>
            {
                config.For <JwtSettings>().Use(jwtSetting).Singleton();

                // If environment is localhost then use mock email service
                if (_env.IsDevelopment())
                {
                    config.For <IS3Service>().Use(new S3Service()).Singleton();
                }
                else
                {
                    var(accessKeyId, secretAccessKey, url) = (
                        _configuration.GetRequiredValue <string>("CLOUDCUBE_ACCESS_KEY_ID"),
                        _configuration.GetRequiredValue <string>("CLOUDCUBE_SECRET_ACCESS_KEY"),
                        _configuration.GetRequiredValue <string>("CLOUDCUBE_URL")
                        );

                    var prefix = new Uri(url).Segments.GetValue(1)?.ToString();
                    const string bucketName = "cloud-cube";

                    // Generally bad practice
                    var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);

                    // Create S3 client
                    config.For <IAmazonS3>().Use(() => new AmazonS3Client(credentials, RegionEndpoint.USEast1));
                    config.For <S3ServiceConfig>().Use(new S3ServiceConfig(bucketName, prefix));

                    config.For <IS3Service>().Use(ctx => new S3Service(
                                                      ctx.GetInstance <ILogger <S3Service> >(),
                                                      ctx.GetInstance <IAmazonS3>(),
                                                      ctx.GetInstance <S3ServiceConfig>()
                                                      ));
                }

                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.Assembly("Api");
                    _.Assembly("Logic");
                    _.Assembly("Dal");
                    _.WithDefaultConventions();
                });

                // Populate the container using the service collection
                config.Populate(services);
            });

            container.AssertConfigurationIsValid();

            return(container.GetInstance <IServiceProvider>());
        }