コード例 #1
0
ファイル: PhotoRepository.cs プロジェクト: recev/DatingApp
 public PhotoRepository(IOptions <CloudinarySettings> cloudinarySettingOptions, DatingDbContext context, IMapper mapper, ILogger <PhotoRepository> logger)
 {
     this._cloudinarySettings = cloudinarySettingOptions.Value;
     this._context            = context;
     this._mapper             = mapper;
     this._logger             = logger;
 }
コード例 #2
0
        public static void ConfigureCloudinary(this IServiceCollection services, IConfiguration configuration)
        {
            var config = new CloudinarySettings()
            {
                CloudName = Environment.GetEnvironmentVariable("SN_CLOUDINARY_CLOUDNAME"),
                ApiKey    = Environment.GetEnvironmentVariable("SN_CLOUDINARY_APIKEY"),
                ApiSecret = Environment.GetEnvironmentVariable("SN_CLOUDINARY_APISECRET")
            };

            services.AddSingleton(config);
        }
コード例 #3
0
        public PhotosController(IDatingRepository repo, IMapper mapper, IOptions <CloudinarySettings> cloudinaryConfig)
        {
            _cloudinaryConfig = cloudinaryConfig.Value;
            _mapper           = mapper;
            _repo             = repo;

            Account acc = new Account(
                _cloudinaryConfig.CloudName,
                _cloudinaryConfig.ApiKey,
                _cloudinaryConfig.ApiSecret
                );

            _cloudinary = new Cloudinary(acc);
        }
コード例 #4
0
ファイル: PhotoController.cs プロジェクト: Arslan-Munir/tada
        public PhotoController(IMapper mapper, IUserRepository repo, IPhotoRepository photoRepository, IOptions <CloudinarySettings> cloudinaryConfigs)
        {
            _mapper            = mapper;
            _repo              = repo;
            _photoRepository   = photoRepository;
            _cloudinaryConfigs = cloudinaryConfigs.Value;

            Account acc = new Account(
                _cloudinaryConfigs.CloudName,
                _cloudinaryConfigs.ApiKey,
                _cloudinaryConfigs.ApiSecret
                );

            _cloudinary = new Cloudinary(acc);
        }
コード例 #5
0
        public PhotoService(IRepository <User> usersRepository,
                            IOptions <CloudinarySettings> settings)
        {
            this.usersRepository = usersRepository;

            this.cloudinarySettings = settings.Value;

            Account account = new Account
                              (
                cloudinarySettings.CloudName,
                cloudinarySettings.ApiKey,
                cloudinarySettings.ApiSecret
                              );

            this.cloudinary = new Cloudinary(account);
        }
コード例 #6
0
        public PostsController(IRepositoryManager repository, ILoggerManager logger, IMapper mapper,
                               UserManager <User> userManager, CloudinarySettings cloudinarySettings)
        {
            _repository         = repository;
            _logger             = logger;
            _mapper             = mapper;
            _userManager        = userManager;
            _cloudinarySettings = cloudinarySettings;

            Account acc = new Account(
                _cloudinarySettings.CloudName,
                _cloudinarySettings.ApiKey,
                _cloudinarySettings.ApiSecret
                );

            _cloudinary = new Cloudinary(acc);
        }
コード例 #7
0
        public PhotosController(IDatingRepository repo, IMapper mapper, IOptions <CloudinarySettings> cloudinaryConfig
                                , DbContextOptions <DataContext> options)
        {
            this._cloudinaryConfig = cloudinaryConfig.Value;
            // this._cloudinaryConfig = cloudinaryConfig;
            this._mapper = mapper;
            // this._repo = repo;
            _repo = new DatingRepository(options);

            Account acc = new Account(
                _cloudinaryConfig.CloudName,
                _cloudinaryConfig.ApiKey,
                _cloudinaryConfig.ApiSecret
                );

            _cloudinary = new Cloudinary(acc);
        }
コード例 #8
0
        public PictureManager(IPictureRepository pictureRepository,
                              IArticleRepository articleRepository,
                              IMapper mapper,
                              IConfiguration configuration)
        {
            _pictureRepository = pictureRepository;
            _articleRepository = articleRepository;
            _mapper            = mapper;
            _cloudinaryConfig  = configuration.GetSection(AppSettingsSection.Cloudinary).Get <CloudinarySettings>();

            Account account = new Account(
                _cloudinaryConfig.CloudName,
                _cloudinaryConfig.APIKey,
                _cloudinaryConfig.APISecret);

            _cloudinary = new Cloudinary(account);
        }
コード例 #9
0
        public PhotosController(
            IDatingRepository datingRepository,
            IMapper mapper,
            IOptions <CloudinarySettings> cloudinarySettings)
        {
            _datingRepository   = datingRepository;
            _mapper             = mapper;
            _cloudinarySettings = cloudinarySettings.Value;

            Account cloudinaryAccount = new Account(
                _cloudinarySettings.CloudName,
                _cloudinarySettings.ApiKey,
                _cloudinarySettings.ApiSecret
                );

            _cloudinary = new Cloudinary(cloudinaryAccount);
        }
コード例 #10
0
        public static Task <int> Execute(IConsole console, InvocationContext context = null)
        {
            var settingsManager = new CloudinarySettingsManager(new FileSystemRoamingProfileAppEnvironment());

            CloudinarySettings settings = settingsManager.LoadSettings();

            if (settings != null)
            {
                console.Out.WriteLine($"Cloudinary Value:");
                console.Out.WriteLine($"cloud: {settings.Cloud}");
                console.Out.WriteLine($"key: {settings.Key}");
                console.Out.WriteLine($"secret: {settings.Secret}");
            }
            else
            {
                console.Out.WriteLine($"Cloudinary Value cannot be found. Please Run:");
                console.Out.WriteLine($"vellum cloudinary setting update --cloud <VALUE> --key <VALUE> --secret <VALUE>");
            }

            return(Task.FromResult(ReturnCodes.Ok));
        }
コード例 #11
0
        public PhotoService(IOptions <CognitiveServicesFaceConfig> cognitiveServicesConfig,
                            IOptions <CloudinarySettings> settings,
                            IRepository <GoshoSecurityUser> usersRepository,
                            IRepository <Photo> photosRepository)
        {
            this.cognitiveServicesConfig = cognitiveServicesConfig.Value;
            this.cloudinarySettings      = settings.Value;
            this.usersRepository         = usersRepository;
            this.photosRepository        = photosRepository;

            var account = new Account(
                this.cloudinarySettings.CloudName,
                this.cloudinarySettings.ApiKey,
                this.cloudinarySettings.ApiSecret);

            this.cloudinary = new Cloudinary(account);

            faceClient = new FaceClient(new ApiKeyServiceClientCredentials(this.cognitiveServicesConfig.ApiKey))
            {
                Endpoint = this.cognitiveServicesConfig.ApiEndpoint
            };
        }
コード例 #12
0
        private async Task <Photo> UploadPhoto(IFormFile file)
        {
            var    uploadResult = new ImageUploadResult();
            string url;

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File   = new FileDescription(file.Name, stream),
                        Folder = "journalApp"
                    };

                    uploadResult = await _cloudinary.UploadAsync(uploadParams);
                }
                url = uploadResult.Uri.ToString();

                string photoUrl = url.Replace(CloudinarySettings.url, "");
                CloudinarySettings.Transformations(photoUrl, out string urlHuge, out string urlLarge,
                                                   out string urlBig, out string urlMedium, out string urlSmall);

                return(new Photo
                {
                    UrlHuge = urlHuge,
                    UrlLarge = urlLarge,
                    UrlBig = urlBig,
                    UrlMedium = urlMedium,
                    UrlSmall = urlSmall
                });
            }

            else
            {
                return(null);
            }
        }
コード例 #13
0
        public static async Task <int> Execute(UploadOptions options, IConsole console, InvocationContext context = null)
        {
            if (options == null)
            {
                console.Error.WriteLine("Invalid File TemplateRepositoryPath");
                return(ReturnCodes.Error);
            }

            var settingsManager = new CloudinarySettingsManager(new FileSystemRoamingProfileAppEnvironment());

            CloudinarySettings settings = settingsManager.LoadSettings();

            var cloudinary = new Cloudinary(new Account(settings.Cloud, settings.Key, settings.Secret));

            var fileToUpload = new ImageUploadParams
            {
                File           = new FileDescription(options.FilePath.FullName),
                PublicId       = $"assets/images/blog/{DateTime.Now.Year}/{DateTime.Now.Month:00}/{Path.GetFileNameWithoutExtension(options.FilePath.Name.ToLowerInvariant())}",
                UniqueFilename = false,
                UseFilename    = false,
            };

            try
            {
                ImageUploadResult uploadResult = await cloudinary.UploadAsync(fileToUpload).ConfigureAwait(false);

                console.Out.WriteLine("Image uploaded.");
                console.Out.WriteLine($"Use following path in your blog post: /{uploadResult.PublicId}{Path.GetExtension(options.FilePath.Name)}");
            }
            catch (Exception exception)
            {
                console.Error.WriteLine(exception.Message);

                return(ReturnCodes.Error);
            }

            return(ReturnCodes.Ok);
        }
コード例 #14
0
        public UserPhotosControllerTests()
        {
            _repoMock = new Mock <IRecipeRepository>();

            _fileMock = new Mock <IFormFile>();

            _cloudinaryMock = new Mock <Cloudinary>();

            _handler = new Mock <HttpClient>();

            var mockMapper = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperProfiles()); });

            var mapper = mockMapper.CreateMapper();

            var settings = new CloudinarySettings()
            {
                ApiKey    = "A",
                ApiSecret = "B",
                CloudName = "C"
            };

            var someOptions = Options.Create(settings);

            _photosController = new UserPhotosController(_repoMock.Object, mapper, someOptions);

            _userClaims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, "josh"),
                new Claim(ClaimTypes.NameIdentifier, "2")
            }, "mock"));
            _photosController.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = _userClaims
                }
            };
        }
コード例 #15
0
        public static Task <int> Execute(UpdateOptions options, IConsole console, InvocationContext context = null)
        {
            var settingsManager = new CloudinarySettingsManager(new FileSystemRoamingProfileAppEnvironment());

            var settings = new CloudinarySettings
            {
                Cloud  = options.Cloud,
                Key    = options.Key,
                Secret = options.Secret,
            };

            try
            {
                settingsManager.SaveSettings(settings);
                console.Out.WriteLine($"Settings updated.");
            }
            catch
            {
                console.Error.WriteLine($"Settings could not be updated.");
            }

            return(Task.FromResult(ReturnCodes.Ok));
        }
コード例 #16
0
        // 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
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(op => op
                                                         .UseMySql(_config.GetConnectionString("Soapstone"), o => o.ServerVersion(new Version(5, 5), ServerType.MySql)));

            services.AddScoped <IRepository <User>, GenericRepository <User> >();
            services.AddScoped <IRepository <Post>, GenericRepository <Post> >();
            services.AddScoped <IRepository <Upvote>, GenericRepository <Upvote> >();
            services.AddScoped <IRepository <Downvote>, GenericRepository <Downvote> >();
            services.AddScoped <IRepository <SavedPost>, GenericRepository <SavedPost> >();
            services.AddScoped <IRepository <Report>, GenericRepository <Report> >();

            services.AddScoped <PostService>();
            services.AddScoped <ImageUploadService>();
            services.AddScoped <TokenService>();

            var cloudinarySettings     = new CloudinarySettings();
            var cloudinaryConfigurator = new ConfigureFromConfigurationOptions <CloudinarySettings>(_config.GetSection("CloudinarySettings"));

            cloudinaryConfigurator.Configure(cloudinarySettings);
            services.AddSingleton(cloudinarySettings);

            var tokenSettings     = new TokenSettings();
            var tokenConfigurator = new ConfigureFromConfigurationOptions <TokenSettings>(_config.GetSection("TokenSettings"));

            tokenConfigurator.Configure(tokenSettings);
            services.AddSingleton <TokenSettings>(tokenSettings);

            var key = Convert.FromBase64String(tokenSettings.SecretKey);

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.RequireHttpsMetadata      = false;
                o.SaveToken                 = true;
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = tokenSettings.Issuer,
                    ValidateIssuer           = true,
                    ValidAudience            = tokenSettings.Audience,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key)
                };
            });

            services.AddAuthorization(o =>
            {
                o.DefaultPolicy = new AuthorizationPolicyBuilder()
                                  .RequireAuthenticatedUser()
                                  .RequireClaim(DefaultClaims.UserId)
                                  .Build();
            });

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

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Soapstone-Backend", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", Enumerable.Empty <string>() },
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            // TODO serilog
            // TODO post lifespan on map
            // TODO exception message overhaul
            // TODO documentation overhaul
        }
コード例 #17
0
ファイル: TestBase.cs プロジェクト: rajzon/GameShop
        public TestBase()
        {
            // Db Configuration
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            var appsettingsPath = Path.GetFullPath("../../../../GameShop.UI/appsettings.json");

            configurationBuilder.AddJsonFile(appsettingsPath);

            // c:\\Users\\Dawid\\Documents\\GameShop\\TestsLib\\bin\\Debug\\netcoreapp3.1"
            IConfiguration config = configurationBuilder.Build();


            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase("shopappDbTesting")
                          .Options;

            _context = new ApplicationDbContext(options, config);

            _context.Database.EnsureCreated();

            // AutoMapper Configuration
            var mapperProfile = new AutoMapperProfiles();
            var mapperConfig  = new MapperConfiguration(cfg => cfg.AddProfile(mapperProfile));

            _mapper = new Mapper(mapperConfig);



            // ASP Identity Configuration
            _mockedConfig      = new Mock <IConfiguration>();
            _mockedUserManager = new Mock <UserManager <User> >(
                new Mock <IUserStore <User> >().Object,
                new Mock <IOptions <IdentityOptions> >().Object,
                new Mock <IPasswordHasher <User> >().Object,
                new IUserValidator <User> [0],
                new IPasswordValidator <User> [0],
                new Mock <ILookupNormalizer>().Object,
                new Mock <IdentityErrorDescriber>().Object,
                new Mock <IServiceProvider>().Object,
                new Mock <ILogger <UserManager <User> > >().Object);


            _mockedSignInManager = new Mock <SignInManager <User> >(
                _mockedUserManager.Object,
                new Mock <IHttpContextAccessor>().Object,
                new Mock <IUserClaimsPrincipalFactory <User> >().Object,
                new Mock <IOptions <IdentityOptions> >().Object,
                new Mock <ILogger <SignInManager <User> > >().Object,
                new Mock <IAuthenticationSchemeProvider>().Object,
                new Mock <IUserConfirmation <User> >().Object
                );


            _unitOfWork = new UnitOfWork(_context);
            var cloudinaryOptions = Options.Create(config.GetSection("CloudinarySettings").Get <CloudinarySettings>());

            _addPhotoToCloud = new AddPhotoToCloud(cloudinaryOptions);

            //Cloudinary configuration
            CloudinarySettings cloudinarySettings = new CloudinarySettings()
            {
                CloudName = "dbriyaupr",
                ApiKey    = "554769833952559",
                ApiSecret = "r67SKLpl2ky4SoEr7BsHVRwVYQI"
            };

            _cloudinaryConfig = Options.Create <CloudinarySettings>(cloudinarySettings);


            // TO DO , when I want to test Asp Identity
            var mockRoleStore = new Mock <IRoleStore <Role> >();

            _mockedRoleManager = new Mock <RoleManager <Role> >(
                mockRoleStore.Object, null, null, null, null);

            // Seed.SeedUsers(_userManager.Object, _roleManager.Object, config);
            Seed.SeedProductsFKs(_context);
        }
コード例 #18
0
        public ImageUploadService(CloudinarySettings settings)
        {
            var account = new Account(settings.CloudName, settings.ApiKey, settings.ApiSecret);

            _cloudinary = new Cloudinary(account);
        }
コード例 #19
0
        private void AddNews(string section, List <string> imgs, DateTime dateTime)
        {
            News   news;
            int    numberOfDummyNews = 10;
            Random r = new Random();

            imgs.Shuffle();

            for (int i = 0; i < numberOfDummyNews; i++)
            {
                dateTime = dateTime.Add(new TimeSpan(days: 0, hours: r.Next(0, 15), minutes: r.Next(0, 100), seconds: r.Next(0, 100)));

                string title;
                do
                {
                    title = Lorem.Sentence(6);
                } while (title.Length < 35);

                string shortTitle;
                do
                {
                    shortTitle = Lorem.Sentence(5);
                } while (shortTitle.Length < 25);

                news = new News()
                {
                    ShortTitle  = shortTitle,
                    Title       = title,
                    Heading     = Lorem.Sentence(11),
                    Content     = Lorem.Paragraph(35),
                    Section     = section,
                    AddedAt     = dateTime,
                    IsImportant = true,
                    AuthorId    = r.Next(2, 7)
                };

                CloudinarySettings.Transformations(imgs[i], out string urlHuge, out string urlLarge,
                                                   out string urlBig, out string urlMedium, out string urlSmall);

                var photo = new Photo()
                {
                    UrlHuge   = urlHuge,
                    UrlLarge  = urlLarge,
                    UrlBig    = urlBig,
                    UrlMedium = urlMedium,
                    UrlSmall  = urlSmall,
                    NewsId    = i,
                    News      = news
                };

                var comments = new List <Comment>();

                var x = r.Next(0, 10) - 4;
                if (x > 0)
                {
                    for (int z = 0; z < x; z++)
                    {
                        var comment = new Comment()
                        {
                            AuthorId = r.Next(5, 20),
                            Content  = Lorem.Sentence(12),
                            NewsId   = i,
                            News     = news
                        };
                        _dbContext.Add <Comment>(comment);
                        comments.Add(comment);
                    }
                }

                news.Photo    = photo;
                news.Comments = comments;

                _dbContext.Add <News>(news);
                _dbContext.Add <Photo>(photo);
            }
        }
コード例 #20
0
        public void InitializeNews()
        {
            if (!_dbContext.News.Any())
            {
                News          news;
                int           numberOfDummyNews = 150;
                Random        r        = new Random();
                DateTime      dateTime = new DateTime(2019, 04, 01, 0, 0, 0);
                List <string> sections = new List <string>()
                {
                    "poland", "sport", "business", "world", "policy"
                };

                CloudinarySettings.Transformations(_dummyPhoto, out string urlHuge, out string urlLarge,
                                                   out string urlBig, out string urlMedium, out string urlSmall);

                for (int i = 0; i < numberOfDummyNews; i++)
                {
                    dateTime = dateTime.Add(new TimeSpan(days: 0, hours: r.Next(0, 15), minutes: r.Next(0, 100), seconds: r.Next(0, 100)));

                    string title;
                    do
                    {
                        title = Lorem.Sentence(6);
                    } while (title.Length < 35);

                    string shortTitle;
                    do
                    {
                        shortTitle = Lorem.Sentence(5);
                    } while (shortTitle.Length < 25);

                    news = new News()
                    {
                        ShortTitle  = shortTitle,
                        Title       = title,
                        Heading     = Lorem.Sentence(11),
                        Content     = Lorem.Paragraph(35),
                        Section     = sections[r.Next(0, 5)],
                        AddedAt     = dateTime,
                        IsImportant = r.Next(0, 7) > 2 ? true : false,
                        AuthorId    = r.Next(2, 7)
                    };

                    var photo = new Photo()
                    {
                        UrlHuge   = urlHuge,
                        UrlLarge  = urlLarge,
                        UrlBig    = urlBig,
                        UrlMedium = urlMedium,
                        UrlSmall  = urlSmall,
                        NewsId    = i,
                        News      = news
                    };

                    var comments = new List <Comment>();

                    var x = r.Next(0, 10) - 4;
                    if (x > 0)
                    {
                        for (int z = 0; z < x; z++)
                        {
                            var comment = new Comment()
                            {
                                AuthorId = r.Next(5, 20),
                                Content  = Lorem.Sentence(12),
                                NewsId   = i,
                                News     = news
                            };
                            _dbContext.Add <Comment>(comment);
                            comments.Add(comment);
                        }
                    }

                    news.Photo    = photo;
                    news.Comments = comments;

                    _dbContext.Add <News>(news);
                    _dbContext.Add <Photo>(photo);
                }

                AddNews("policy", _policyImgs, dateTime);
                AddNews("poland", _polandImgs, dateTime);
                AddNews("world", _worldImgs, dateTime);
                AddNews("business", _businessImgs, dateTime);
                AddNews("sport", _sportImgs, dateTime);

                _dbContext.SaveChanges();
            }
        }
コード例 #21
0
 private Account CreateAccount(CloudinarySettings settings)
 {
     return(new Account(settings.CloudName, settings.ApiKey, settings.ApiSecret));
 }