コード例 #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors(
                builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            #region  InitStaticFiles Images
            string pathRoot = InitStaticFiles
                              .CreateFolderServer(env, this.Configuration,
                                                  new string[] { "ImagesPath" });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathRoot),
                RequestPath  = new PathString('/' + Configuration.GetValue <string>("UrlImages"))
            });
            #endregion
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            SeederDB.SeedDataByAS(app.ApplicationServices);
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
コード例 #2
0
        public IActionResult ChangeImage([FromBody] ChangeImage model)
        {
            string image = null;

            var userId = User.Claims.ToList()[0].Value;
            var user   = _context.BaseProfiles.FirstOrDefault(u => u.Id == userId);

            if (user != null)
            {
                string imageName      = user.Image ?? Guid.NewGuid().ToString() + ".jpg";
                string pathSaveImages = InitStaticFiles
                                        .CreateImageByFileName(_env, _configuration,
                                                               new string[] { "ImagesPath", "ImagesUserPath" },
                                                               imageName, model.Image);

                if (pathSaveImages != null)
                {
                    image      = imageName;
                    user.Image = image;
                    _context.SaveChanges();
                }
                else
                {
                    image = user.Image;
                }
            }

            string path      = $"{_configuration.GetValue<string>("UserUrlImages")}/250_";
            string imagePath = image != null ? path + image :
                               path + _configuration.GetValue <string>("DefaultImage");

            return(Ok(imagePath));
        }
コード例 #3
0
        public async Task <IActionResult> RegisterTeacher([FromBody] TeacherRegisterVM model)
        {
            return(await HandleRequestAsync(async() =>
            {
                string imageName = Path.GetRandomFileName() + ".jpg";
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Uploaded\Users");

                string pathSaveImages = InitStaticFiles
                                        .CreateImageByFileName(_env, _configuration,
                                                               new string[] { Directory.GetCurrentDirectory(), @"wwwroot", "Uploaded", "Users" },
                                                               imageName,
                                                               model.Photo);

                //+38 (098) 665 34 18
                model.Photo = imageName;

                var rezult = await _teacherService.Create(model);
                if (rezult)
                {
                    var user = _userManager.FindByEmailAsync(model.Email).Result;
                    var teacher = await _teacherService.GetTeacherById(user.Id);
                    JwtInfo jwtInfo;
                    if (teacher != null)
                    {
                        // Return token
                        jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user),
                            SchoolId = teacher.SchoolId.ToString()
                        };
                    }
                    else
                    {
                        // Return token
                        jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user),
                        };
                    }

                    this._logger.LogDebug("End method LoginUser...");

                    return Ok(jwtInfo);
                }
                else
                {
                    var invalid = new Dictionary <string, string>
                    {
                        { "email", "Користувач з даною електронною поштою уже зареєстрований" }
                    };
                    return BadRequest(invalid);
                }
            }));
        }
コード例 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            #region CORS
            app.UseCors(x => x
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            #endregion

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            #region  InitStaticFiles Images
            string pathRootForPhotos = InitStaticFiles
                                       .CreateFolderServer(env, this.Configuration,
                                                           new string[] { "ImagesPath" });

            string pathRootForBooks = InitStaticFiles.CreateFolderServer(env, this.Configuration,
                                                                         new string[] { "BooksPath" });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathRootForPhotos),
                RequestPath  = new PathString('/' + Configuration.GetValue <string>("UrlImages"))
            });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathRootForBooks),
                RequestPath  = new PathString('/' + Configuration.GetValue <string>("UrlBooks"))
            });
            #endregion

            app.UseMiddleware <GlobalExceptionHandlerMiddleware>();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.IndexStream = () => GetType().Assembly.GetManifestResourceStream("LibShare.Api.Swagger.index.html");
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "LIBSHARE API V1");
            });
            #endregion

            SeederDB.SeedDataByAS(app.ApplicationServices);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
コード例 #5
0
        public IActionResult ChangeUserProfile([FromBody] UserProfileModel model)
        {
            if (!ModelState.IsValid)
            {
                var errrors = CustomValidator.GetErrorsByModel(ModelState);
                return(BadRequest(errrors));
            }

            var userid = (User.Claims.ToList()[0].Value).ToString();
            // var i = "fe623d77-2603-4787-99f6-e13337cc4083";
            var user = _context.UserProfile.SingleOrDefault(a => a.User.Id == userid);

            string image = null;

            if (user != null)
            {
                string imageName = "";
                if (user.Avatar == "")
                {
                    imageName = Guid.NewGuid().ToString() + ".jpg";
                }
                else
                {
                    imageName = user.Avatar + ".jpg";
                }
                string pathSaveImages = InitStaticFiles
                                        .CreateImageByFileName(_env, _configuration,
                                                               new string[] { "ImagesPath", "ImagesPathUsers" },
                                                               imageName,
                                                               model.Avatar);
                if (pathSaveImages != null)
                {
                    image       = imageName;
                    user.Avatar = image;
                    _context.SaveChanges();
                }
                else
                {
                    image = user.Avatar;
                }
            }

            //string imageName = user.Avatar ?? Guid.NewGuid().ToString() + ".jpg";
            //string path = $"{_configuration.GetValue<string>("UserUrlImages")}/600_";
            //string imagePath = image != null ?
            //    path + image :
            //    _configuration.GetValue<string>("UrlImages") +
            //    "300_" + _configuration.GetValue<string>("DefaultImage");
            //return Ok(imagePath);

            _context.Users.Where(a => a.Id == user.Id).SingleOrDefault().Email           = model.Email;
            _context.Users.Where(a => a.Id == user.Id).SingleOrDefault().NormalizedEmail = model.Email.ToUpper();
            _context.SaveChanges();
            return(Ok());
        }
コード例 #6
0
        public async Task <ActionResult <Product> > Edit(int id, [FromBody] ProductModel model)
        {
            Product product = _context.Products.Include("Photos").FirstOrDefault(x => x.ID == id);

            using (CTX db = _context)
            {
                if (product != null)
                {
                    List <Photo> added_photos = new List <Photo>();
                    try
                    {
                        foreach (var x in product.Photos)
                        {
                            InitStaticFiles.DeleteImageByFileName(_env, _configuration,
                                                                  new string[] { "ImagesPath", "ImagesPathProduct" },
                                                                  x.Path);
                        }
                        foreach (var photo in model.ImgsBase64)
                        {
                            string imageName = Path.GetRandomFileName() + ".jpg";

                            string pathSaveImages = InitStaticFiles
                                                    .CreateImageByFileName(_env, _configuration,
                                                                           new string[] { "ImagesPath", "ImagesPathProduct" },
                                                                           imageName,
                                                                           photo);
                            added_photos.Add(new Photo
                            {
                                Path = imageName
                            });
                        }
                    }
                    catch (Exception)
                    {
                        return(BadRequest());
                    }

                    product.Name        = model.Name;
                    product.Description = model.Description;
                    product.Price       = model.Price;
                    product.Photos.Clear();
                    product.Photos = added_photos;


                    db.SaveChanges();
                    return(Ok(product));
                }
                else
                {
                    return(BadRequest());
                }
            }
        }
コード例 #7
0
        public IActionResult ChangeImage([FromBody] ChangeImageModel model)
        {
            string image = null;

            if (User.Identity.IsAuthenticated)
            {
                var userId = User.Claims.ToList()[0].Value.ToString();
                var user   = _context.UserProfile.SingleOrDefault(c => c.Id == userId);
                if (user != null)
                {
                    string imageName = "";
                    if (user.Avatar == "")
                    {
                        imageName = Guid.NewGuid().ToString() + ".jpg";
                    }
                    else
                    {
                        imageName = user.Avatar + ".jpg";
                    }

                    string pathSaveImages = InitStaticFiles
                                            .CreateImageByFileName(_env, _configuration,
                                                                   new string[] { "ImagesPath", "ImagesPathUsers" },
                                                                   imageName,
                                                                   model.Avatar);
                    if (pathSaveImages != null)
                    {
                        image       = imageName;
                        user.Avatar = image;
                        _context.SaveChanges();
                    }
                    else
                    {
                        image = user.Avatar;
                    }
                }
            }

            string path      = $"{_configuration.GetValue<string>("UserUrlImages")}/300_";
            string imagePath = image != "" ?
                               path + image :
                               _configuration.GetValue <string>("UrlImages") +
                               "300_" + _configuration.GetValue <string>("DefaultImage");

            return(Ok(imagePath));
        }
コード例 #8
0
ファイル: Startup.cs プロジェクト: rad4949/mvc
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/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();
            }
            // app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            #region  InitStaticFiles Images
            string pathRoot = InitStaticFiles
                              .CreateFolderServer(env, this.Configuration,
                                                  new string[] { "ImagesPath" });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathRoot),
                RequestPath  = new PathString('/' + Configuration.GetValue <string>("UrlImages"))
            });
            #endregion

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            SeederDB.SeedData(app.ApplicationServices, env, this.Configuration);
        }
コード例 #9
0
        public ActionResult DeleteProduct(int id)
        {
            Product dproduct = _context.Products.Include("Photos").FirstOrDefault(x => x.ID == id);

            if (dproduct != null)
            {
                _context.Products.Remove(dproduct);
                foreach (var x in dproduct.Photos)
                {
                    InitStaticFiles.DeleteImageByFileName(_env, _configuration,
                                                          new string[] { "ImagesPath", "ImagesPathProduct" },
                                                          x.Path);
                }
                _context.SaveChanges();
                return(Ok());
            }
            else
            {
                return(BadRequest());
            }
        }
コード例 #10
0
        public async Task <ActionResult <Product> > AddProduct([FromBody] ProductModel product)
        {
            Product p;

            try
            {
                List <Photo> added_photos = new List <Photo>();
                foreach (var photo in product.ImgsBase64)
                {
                    string imageName = Path.GetRandomFileName() + ".jpg";

                    string pathSaveImages = InitStaticFiles
                                            .CreateImageByFileName(_env, _configuration,
                                                                   new string[] { "ImagesPath", "ImagesPathProduct" },
                                                                   imageName,
                                                                   photo);
                    added_photos.Add(new Photo
                    {
                        Path = imageName
                    });
                }
                p = new Product
                {
                    Name        = product.Name,
                    Category    = _context.Categories.FirstOrDefault(x => x.Name == product.Category),
                    Description = product.Description,
                    Price       = product.Price,
                    Photos      = added_photos
                };
                _context.Products.Add(p);
                _context.SaveChanges();
            }
            catch (Exception)
            {
                return(BadRequest());
            }
            return(p);
        }
コード例 #11
0
        public async Task <IActionResult> RegisterUser([FromBody] RegisterDTO model)
        {
            // Auto return errors from viewModel and other global errors
            return(await HandleRequestAsync(async() =>
            {
                if (!CaptchaHelper.VerifyAndExpireSolution(this.HttpContext,
                                                           model.CaptchaKey,
                                                           model.CaptchaText))
                {
                    var invalid = new Dictionary <string, string>();
                    invalid.Add("captchaText", "Помилка вводу зображення на фото");
                    return BadRequest(invalid);
                }
                var user = _userManager.FindByEmailAsync(model.Email).Result;
                if (user != null)
                {
                    var invalid = new Dictionary <string, string>();
                    invalid.Add("email", "Користувач з даною електронною поштою уже зареєстрований");
                    return BadRequest(invalid);
                }

                string imageName = Path.GetRandomFileName() + ".jpg";

                try
                {
                    this._logger.LogDebug("Start register method RegisterUser...");
                    string pathSaveImages = InitStaticFiles
                                            .CreateImageByFileName(_env, _configuration,
                                                                   new string[] { "ImagesPath", "ImagesPathUser" },
                                                                   imageName,
                                                                   model.Photo);
                    this._logger.LogDebug("Save image complete method RegisterUser...");
                    if (pathSaveImages != null)
                    {
                        var profile = new UserProfile()
                        {
                            RegistrationDate = DateTime.Now,
                            FirstName = model.FirstName,
                            LastName = model.LastName,
                            Photo = imageName,
                        };
                        user = new DbUser()
                        {
                            UserName = model.Email,
                            Email = model.Email,
                            PhoneNumber = model.Phone,
                            UserProfile = profile
                        };
                        var result = _userManager.CreateAsync(user, model.Password).Result;
                        if (!result.Succeeded)
                        {
                            var errors = CustomValidator.GetErrorsByIdentityResult(result);
                            return BadRequest(errors);
                        }
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        // Return token
                        JwtInfo jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user)
                        };

                        this._logger.LogDebug("End method RegisterUser...");

                        return Ok(jwtInfo);
                    }
                    else
                    {
                        throw new Exception("Помила додавання фото в БД");
                    }
                }
                catch (Exception ex)
                {
                    InitStaticFiles.DeleteImageByFileName(_env, _configuration,
                                                          new string[] { "ImagesPath", "ImagesPathUser" },
                                                          imageName);
                    var errors = new Dictionary <string, string>();
                    errors.Add("invalid", ex.Message);
                    return BadRequest(errors);
                }
            }));
        }
コード例 #12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            //app.UseCors(
            //  builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            app.UseSignalR(
                routes =>
            {
                routes.MapHub <ChatHub>("/chat");
            });

            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            //app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseSession();

            #region InitStaticFiles Images
            string pathRoot = InitStaticFiles
                              .CreateFolderServer(env, this.Configuration,
                                                  new string[] { "ImagesPath" });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathRoot),
                RequestPath  = new PathString("/" + Configuration.GetValue <string>("ImagesUrl"))
            });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathRoot),
                RequestPath  = new PathString("/" + Configuration.GetValue <string>("ImagesHotelUrl"))
            });

            #endregion ;

            if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), @"UserImages")))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), @"UserImages"));
            }

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"UserImages")),
                RequestPath  = new PathString("/UserImages")
            });

            if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), @"Uploaded")))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), @"Uploaded"));
            }

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "Uploaded")),
                RequestPath = "/Uploaded"
            });


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

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

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });

            SeederDB.SeedDataByAS(app.ApplicationServices, env, this.Configuration);
            SendEmailService.SendInfoStartApp(Configuration, env);
        }
コード例 #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ///app.UseSwagger();
            //app.UseSwaggerUI(c =>
            //{
            //    c.SwaggerEndpoint("v1/swagger.json", "My API V1");
            //});

            app.UseCors(
                builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseSpaStaticFiles();
            app.UseSession();
            #region  InitStaticFiles Images
            string pathRoot = InitStaticFiles
                              .CreateFolderServer(env, this.Configuration,
                                                  new string[] { "ImagesPath" });
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathRoot),
                RequestPath  = new PathString('/' + Configuration.GetValue <string>("UrlImages"))
            });
            #endregion

            #region  InitStaticFiles UserImages
            string pathuser = InitStaticFiles
                              .CreateFolderServer(env, this.Configuration,
                                                  new string[] { "ImagesPath", "ImagesUserPath" });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathuser),
                RequestPath  = new PathString('/' + Configuration.GetValue <string>("UserUrlImages"))
            });
            #endregion
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

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

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });

            //await Seed.SeedData(app.ApplicationServices, env, this.Configuration);
        }
コード例 #14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            app.UseCors(
                builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }



            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseSession();



            //  SeederDB.SeedData(app.ApplicationServices, env, this.Configuration);



            #region InitStaticFiles ClientImages
            string pathClient = InitStaticFiles
                                .CreateFolderServer(env, this.Configuration,
                                                    new string[] { "ImagesPath", "ImagesPathUsers" });



            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathClient),
                RequestPath  = new PathString("/" + Configuration.GetValue <string>("UserUrlImages"))
            });
            #endregion ;



            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });



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



                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
            //app.UseSignalR(routes =>
            //{
            //    routes.MapHub<ChatHub>("/chat");
            //});
            //app.UseSignalR(route =>
            //{
            //    route.MapHub<ChatService>("/api/clientwaiter");
            //});
        }