public async Task <IActionResult> Download(PhotoViewToDownload photoView)
        {
            if (await userManager.FindByIdAsync(photoView.CustomerId) == null)
            {
                return(BadRequest("Kullanıcı bulunamadı!"));
            }
            if (await unitOfWork.Appointments.Get(photoView.AppointmentId) == null)
            {
                return(BadRequest("Randevu Bulunamadı!"));
            }

            var photos = await GetPhotosTemp(photoView.AppointmentId, photoView.CustomerId);

            if (!photos.Any())
            {
                return(UnprocessableEntity("Kullanıcıya ait hiç fotoğraf bulunamadı"));
            }

            var amazon = new AmazonS3Service(
                appSettings.Value.AccessKey,
                appSettings.Value.SecretAccessKey,
                appSettings.Value.BucketName);

            // the output bytes of the zip
            byte[] fileBytes = null;

            // create a working memory stream
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // create a zip
                using (ZipArchive zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    // interate through the source files
                    foreach (var photo in photos)
                    {
                        var    list       = photo.Path.Split(".com/");
                        string keyName    = list[1];
                        var    streamFile = await amazon.Download(keyName);

                        if (streamFile == null)
                        {
                            return(UnprocessableEntity("Dosyalar indirelemedi! Lütfen tekrar deneyiniz."));
                        }
                        // add the item name to the zip
                        ZipArchiveEntry zipItem = zip.CreateEntry(photo.FileName);
                        // add the item bytes to the zip entry by opening the original file and copying the bytes

                        using (System.IO.Stream entryStream = zipItem.Open())
                        {
                            streamFile.CopyTo(entryStream);
                        }
                    }
                }
                fileBytes = memoryStream.ToArray();
            }

            // download the constructed zip
            Response.Headers.Add("Content-Disposition", "attachment; filename=download.zip");
            return(File(fileBytes, "application/zip"));
        }
        public async Task <IActionResult> CreateAmazonAccount(int id)
        {
            var username     = ApplicationUtility.GetTokenAttribute(Request.Headers["Authorization"], "sub");
            var service      = new InstituteRepositoryService(connString);
            var institute    = (await service.GetInstituteById(id)).Name;
            var bucketSevice = new AmazonS3Service();
            var bucketName   = GetName(institute);
            await bucketSevice.CreateBucketToS3(bucketName);

            var iamService   = new AmazonIAMService();
            var iamUserName  = GetName(institute);
            var accesKeyInfo = await iamService.CreateIAMUser("/", iamUserName);

            var amazonAccountModel = new InstituteAmazonAccount()
            {
                AccessKey   = accesKeyInfo.AccessKey,
                Actor       = username,
                BucketName  = bucketName,
                IamUsername = iamUserName,
                InstituteId = id,
                SecretKey   = accesKeyInfo.SecurityKey
            };
            await service.CreateInstituteAmazonAccount(amazonAccountModel);

            var response = new GenericResponse <string>()
            {
                IsSuccess    = true,
                Message      = "Cloud account created successfully.",
                ResponseCode = 200,
                Result       = "Success"
            };

            return(Ok(response));
        }
示例#3
0
 public void LoadBucketContents(AmazonS3Service amazonClient, string bucket)
 {
     _amazon = amazonClient;
     _amazon.FileProgressChanged -= _amazon_FileProgressChanged;
     _amazon.FileProgressChanged += _amazon_FileProgressChanged;
     _selectedBucket              = bucket;
     _amazon.CurrentBucketName    = _selectedBucket;
     GetBucketContents();
 }
示例#4
0
        public AmazonS3ServiceTests()
        {
            _mockEc2Connector = new Mock <IEc2InstanceMetadataConnector>();
            _awsConfig        = new AmazonWebServicesOptions {
                S3Region = "eu-cologne-1"
            };
            var awsOptionsMonitor = Mock.Of <IOptionsMonitor <AmazonWebServicesOptions> >(_ => _.CurrentValue == _awsConfig);

            _service = new AmazonS3Service(_mockEc2Connector.Object, awsOptionsMonitor, _logger);
        }
示例#5
0
        public async Task <IActionResult> PostnewUser(IFormFile file, [FromForm] string jsonData)
        {
            // var content = new homeContent();
            // List<homeContent> content =
            homeContent content = JsonConvert.DeserializeObject <homeContent>(jsonData);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var coinData      = new greenCoins();
                var imageResponse = await AmazonS3Service.UploadObject(file); //promiseAll

                var  data    = this.HttpContext.Items["User"].ToString();
                long id      = long.Parse(data);
                var  newUser = _repo.Profile.FirstOrDefault(u => u.id == id);
                var  now     = DateTime.UtcNow;
                content.profileid    = id;
                content.profilename  = newUser.firstname;
                content.profilemedia = newUser.profilemedia;
                content.createdAt    = now;
                content.updatedAt    = now;
                content.createdBy    = newUser.firstname;
                content.updatedBy    = newUser.firstname;
                content.url          = imageResponse.FileName;

                _repo.Add(content);
                _repo.SaveChanges();

                Random rnd  = new Random();
                int    coin = rnd.Next(1, 11); //random value between 1-10
                coinData.profileid = id;
                coinData.postid    = content.id;
                coinData.createdAt = now;
                coinData.createdBy = newUser.firstname;
                coinData.coins     = coin; //make it random 1-10 //orderby with linkq //descending
                _repo.Add(coinData);
                _repo.SaveChanges();

                return(Ok(coinData));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
        public async Task <IActionResult> CreateBucket(BucketModel model)
        {
            var service = new AmazonS3Service();
            await service.CreateBucketToS3(model.Name);

            var response = new GenericResponse <string>()
            {
                IsSuccess    = true,
                Message      = "Bucket created successfully.",
                ResponseCode = 200,
                Result       = "Success"
            };

            return(Ok(response));
        }
示例#7
0
        public async Task <IActionResult> CreateClothings([FromForm] string name, [FromForm] int idClothingType, [FromForm] string tags, IFormFile image)
        {
            var imageResponse = await AmazonS3Service.UploadObject(image);

            var idUser = User.FindFirstValue(ClaimTypes.NameIdentifier);
            CreateClothesCommand command = new CreateClothesCommand()
            {
                Name           = name,
                idUser         = Int32.Parse(idUser),
                Url            = imageResponse.FileName,
                idClothingType = idClothingType,
                Tags           = tags
            };
            var commandResult = await _mediator.Send(command);

            return(Ok(commandResult));
        }
        public async Task <IActionResult> CreateIAM(IAMModel model)
        {
            var s3service = new AmazonS3Service();
            await s3service.CreateBucketToS3(model.BucketName);

            var iamservice = new AmazonIAMService();
            await iamservice.CreateIAMUser(@"/" + model.BucketName + @"/", model.UserName);

            var response = new GenericResponse <string>()
            {
                IsSuccess    = true,
                Message      = "User created in IIM successfully.",
                ResponseCode = 200,
                Result       = "Success"
            };

            return(Ok(response));
        }
        public async Task <IActionResult> CreateShootType(ShootTypeView shootTypeView)
        {
            if (ModelState.IsValid)
            {
                if (shootTypeView.Photo == null || !shootTypeView.Photo.ContentType.Contains("image"))
                {
                    return(BadRequest("Geçersiz Dosya Türü Lütfen bir fotoğraf seçiniz."));
                }

                try
                {
                    var amazon = new AmazonS3Service(
                        appSettings.Value.AccessKey,
                        appSettings.Value.SecretAccessKey,
                        appSettings.Value.BucketName);


                    var response = await amazon.UploadFileAsync(file : shootTypeView.Photo, subFolderName : "ShootTypePhotos");

                    if (response.Success)
                    {
                        var shootType = new ShootType()
                        {
                            Name        = shootTypeView.Name,
                            IsActive    = shootTypeView.IsActive,
                            Icon        = shootTypeView.Icon,
                            Description = shootTypeView.Description,
                            PhotoPath   = response.ThumbnailUrl
                        };
                        await unitOfWork.ShootTypes.Add(shootType);

                        await unitOfWork.Complete();

                        return(Ok("Çekim Türü başarıyla eklendi."));
                    }
                }
                catch (Exception)
                {
                }
            }
            return(BadRequest("Başarısız. Lütfen eksik alan bırakmayınız. Fotoğraf ve İkon seçilmesi gerek."));
        }
示例#10
0
        public async Task <IActionResult> Create(PublisherModel model)
        {
            var username = ApplicationUtility.GetTokenAttribute(Request.Headers["Authorization"], "sub");
            var service  = new PublisherRepositoryService(connString);
            var pubId    = await service.CreatePublisher(model, username);

            PublisherAmazonAccount amazonAccountModel;

            if (model.CloudAccountRequired)
            {
                var bucketSevice = new AmazonS3Service();
                var bucketName   = GetName(model.PublisherName);
                await bucketSevice.CreateBucketToS3(bucketName);

                var iamService   = new AmazonIAMService();
                var iamUserName  = GetName(model.PublisherName);
                var accesKeyInfo = await iamService.CreateIAMUser("/", iamUserName);

                amazonAccountModel = new PublisherAmazonAccount()
                {
                    AccessKey   = accesKeyInfo.AccessKey,
                    Actor       = username,
                    BucketName  = bucketName,
                    IamUsername = iamUserName,
                    PublisherId = pubId,
                    SecretKey   = accesKeyInfo.SecurityKey
                };
                await service.CreatePublisherAmazonAccount(amazonAccountModel);
            }
            var response = new GenericResponse <int>()
            {
                IsSuccess    = true,
                Message      = "Publisher created successfully.",
                ResponseCode = 200,
                Result       = pubId
            };

            return(Ok(response));
        }
        public async Task <IActionResult> CreateAmazonAccount(int id)
        {
            var actor   = ApplicationUtility.GetTokenAttribute(Request.Headers["Authorization"], "sub");
            var service = new UserRepositoryService(connString);
            var instituteAmazonAccInfo = await service.GetInstituteAmazonAccountDetail(id);

            var amazons3Service = new AmazonS3Service();
            var accname         = instituteAmazonAccInfo.UserName.ToLower();
            await amazons3Service.CreateFolder(instituteAmazonAccInfo.BucketName, accname,
                                               instituteAmazonAccInfo.AccessKey, instituteAmazonAccInfo.SecretKey);

            var amazoniamService = new AmazonIAMService();
            var iamacc           = accname + Guid.NewGuid().ToString().ToLower();
            var path             = "/" + instituteAmazonAccInfo.BucketName + "/" + instituteAmazonAccInfo.UserName.ToLower() + "/";
            var amazonaccount    = await amazoniamService.CreateIAMUser(path, iamacc);

            var model = new UserAmazonAccount()
            {
                AccessKey   = amazonaccount.AccessKey,
                Actor       = actor,
                BucketName  = instituteAmazonAccInfo.BucketName,
                BucketPath  = "/" + instituteAmazonAccInfo.UserName.ToLower(),
                IamUsername = iamacc,
                SecretKey   = amazonaccount.SecurityKey,
                UserId      = instituteAmazonAccInfo.UserId
            };
            await service.CreateUserAmazonAccount(model);

            var response = new GenericResponse <string>()
            {
                IsSuccess    = true,
                Message      = "Amazon account created successfully.",
                ResponseCode = 200,
                Result       = "Success"
            };

            return(Ok(response));
        }
示例#12
0
        protected override TimeSpan OnProcess()
        {
            IBackupService service;

            switch (_settings.Service)
            {
            case BackupServices.AwsS3:
                service = new AmazonS3Service(AmazonExtensions.GetEndpoint(_settings.Address), _settings.ServiceRepo, _settings.Login, _settings.Password.To <string>());
                break;

            case BackupServices.AwsGlacier:
                service = new AmazonGlacierService(AmazonExtensions.GetEndpoint(_settings.Address), _settings.ServiceRepo, _settings.Login, _settings.Password.To <string>());
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var hasSecurities = false;

            this.AddInfoLog(LocalizedStrings.Str2306Params.Put(_settings.StartFrom));

            var startDate = _settings.StartFrom;
            var endDate   = DateTime.Today - TimeSpan.FromDays(_settings.Offset);

            var allDates = startDate.Range(endDate, TimeSpan.FromDays(1)).ToArray();

            var pathEntry = ToEntry(new DirectoryInfo(_settings.Drive.Path));

            var workingSecurities = GetWorkingSecurities().ToArray();

            foreach (var date in allDates)
            {
                foreach (var security in workingSecurities)
                {
                    hasSecurities = true;

                    if (!CanProcess())
                    {
                        break;
                    }

                    var dateEntry = new BackupEntry
                    {
                        Name   = date.ToString("yyyy_MM_dd"),
                        Parent = new BackupEntry
                        {
                            Parent = new BackupEntry
                            {
                                Name   = security.Security.Id.Substring(0, 1),
                                Parent = pathEntry
                            },
                            Name = security.Security.Id,
                        }
                    };

                    var dataTypes = _settings.Drive.GetAvailableDataTypes(security.Security.ToSecurityId(), _settings.StorageFormat);

                    foreach (var dataType in dataTypes)
                    {
                        var storage = StorageRegistry.GetStorage(security.Security, dataType.MessageType, dataType.Arg, _settings.Drive, _settings.StorageFormat);

                        var drive = storage.Drive;

                        var stream = drive.LoadStream(date);

                        if (stream == Stream.Null)
                        {
                            continue;
                        }

                        var entry = new BackupEntry
                        {
                            Name   = LocalMarketDataDrive.GetFileName(dataType.MessageType, dataType.Arg) + LocalMarketDataDrive.GetExtension(StorageFormats.Binary),
                            Parent = dateEntry,
                        };

                        service.Upload(entry, stream, p => { });

                        this.AddInfoLog(LocalizedStrings.Str1580Params, GetPath(entry));
                    }
                }

                if (CanProcess())
                {
                    _settings.StartFrom += TimeSpan.FromDays(1);
                    SaveSettings();
                }
            }

            if (!hasSecurities)
            {
                this.AddWarningLog(LocalizedStrings.Str2292);
                return(TimeSpan.MaxValue);
            }

            if (CanProcess())
            {
                this.AddInfoLog(LocalizedStrings.Str2300);
            }

            return(base.OnProcess());
        }
示例#13
0
        protected override TimeSpan OnProcess()
        {
            IBackupService service;

            switch (_settings.Service)
            {
            case BackupServices.AwsS3:
                service = new AmazonS3Service(AmazonExtensions.GetEndpoint(_settings.Address), _settings.ServiceRepo, _settings.Login, _settings.Password.To <string>());
                break;

            case BackupServices.AwsGlacier:
                service = new AmazonGlacierService(AmazonExtensions.GetEndpoint(_settings.Address), _settings.ServiceRepo, _settings.Login, _settings.Password.To <string>());
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var hasSecurities = false;

            this.AddInfoLog(LocalizedStrings.Str2306Params.Put(_settings.StartFrom));

            var startDate = _settings.StartFrom;
            var endDate   = DateTime.Today - TimeSpan.FromDays(_settings.Offset);

            var allDates = startDate.Range(endDate, TimeSpan.FromDays(1)).ToArray();

            var pathEntry = ToEntry(new DirectoryInfo(_settings.Drive.Path));

            IEnumerable <Tuple <Type, object> > dataTypes = new[]
            {
                Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Tick),
                Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.OrderLog),
                Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Order),
                Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Trade),
                Tuple.Create(typeof(QuoteChangeMessage), (object)null),
                Tuple.Create(typeof(Level1ChangeMessage), (object)null),
                Tuple.Create(typeof(NewsMessage), (object)null)
            };

            var workingSecurities = GetWorkingSecurities().ToArray();

            foreach (var date in allDates)
            {
                foreach (var security in workingSecurities)
                {
                    hasSecurities = true;

                    if (!CanProcess())
                    {
                        break;
                    }

                    var dateEntry = new BackupEntry
                    {
                        Name   = date.ToString("yyyy_MM_dd"),
                        Parent = new BackupEntry
                        {
                            Parent = new BackupEntry
                            {
                                Name   = security.Security.Id.Substring(0, 1),
                                Parent = pathEntry
                            },
                            Name = security.Security.Id,
                        }
                    };

                    var candleTypes = _settings.Drive.GetCandleTypes(security.Security.ToSecurityId(), _settings.StorageFormat);

                    var secDataTypes = dataTypes.Concat(candleTypes.SelectMany(t => t.Item2.Select(a => Tuple.Create(t.Item1, a))));

                    foreach (var tuple in secDataTypes)
                    {
                        var storage = StorageRegistry.GetStorage(security.Security, tuple.Item1, tuple.Item2, _settings.Drive, _settings.StorageFormat);

                        var drive = storage.Drive;

                        var stream = drive.LoadStream(date);

                        if (stream == Stream.Null)
                        {
                            continue;
                        }

                        var entry = new BackupEntry
                        {
                            Name   = LocalMarketDataDrive.CreateFileName(tuple.Item1, tuple.Item2) + LocalMarketDataDrive.GetExtension(StorageFormats.Binary),
                            Parent = dateEntry,
                        };

                        service.Upload(entry, stream, p => { });

                        this.AddInfoLog(LocalizedStrings.Str1580Params, GetPath(entry));
                    }
                }

                if (CanProcess())
                {
                    _settings.StartFrom += TimeSpan.FromDays(1);
                    SaveSettings();
                }
            }

            if (!hasSecurities)
            {
                this.AddWarningLog(LocalizedStrings.Str2292);
                return(TimeSpan.MaxValue);
            }

            if (CanProcess())
            {
                this.AddInfoLog(LocalizedStrings.Str2300);
            }

            return(base.OnProcess());
        }
 public DeployModel(ApplicationDbContext context, UmlParser umlParser, AmazonS3Service amazonS3Service)
 {
     _context         = context;
     _umlParser       = umlParser;
     _amazonS3Service = amazonS3Service;
 }
示例#15
0
        public async Task <IActionResult> AddPhoto(PhotoView photoView)
        {
            if (photoView.AppointmentId < 1 ||
                photoView.CustomerId.Equals("") ||
                string.IsNullOrEmpty(photoView.CustomerId) ||
                photoView.File == null)
            {
                return(BadRequest("Bir sorun var"));
            }

            if (!photoView.File.ContentType.Contains("image") && !photoView.File.ContentType.Contains("video"))
            {
                return(BadRequest("Geçersiz Dosya Türü"));
            }


            var customer = await userManager.FindByIdAsync(photoView.CustomerId);

            if (customer == null)
            {
                return(NotFound("Kullanıcı bulunamadı"));
            }
            var appointment = await unitOfWork.Appointments.Get(photoView.AppointmentId);

            if (appointment == null)
            {
                return(NotFound("Randevu Bulunamadı"));
            }

            var amazon = new AmazonS3Service(
                appSettings.Value.AccessKey,
                appSettings.Value.SecretAccessKey,
                appSettings.Value.BucketName);


            var response = await amazon.UploadFileAsync(file : photoView.File, subFolderName : photoView.CustomerId);

            if (response.Success)
            {
                var photo = new Photo()
                {
                    AppointmentId = appointment.Id,
                    CustomerId    = customer.Id,
                    Path          = response.PhotoUrl,
                    ThumbnailPath = response.ThumbnailUrl
                };
                try
                {
                    await unitOfWork.Photos.Add(photo);

                    await unitOfWork.Complete();

                    return(Ok("Yükleme işlemi başarılı"));
                }
                catch (Exception ex)
                {
                    return(BadRequest("Yüklenemedi Hata oluştu: " + ex.Message));
                }
            }
            return(BadRequest("Amazona yüklenemedi. Hata oluştu."));
            //foreach (IFormFile source in files)
            //{
            //    string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');


            //    using (FileStream output = System.IO.File.Create(this.GetPathAndFilename(filename)))
            //        await source.CopyToAsync(output);
            //}
        }