protected Uploader_S3(Config_S3 settings) { AmazonS3Config config = new AmazonS3Config(); config.ServiceURL = settings.Provider; config.ForcePathStyle = settings.ForcePathStyle; if (settings.Proxy != null) { logger.Info($"Используем прокси: {settings.Proxy.Host}:{settings.Proxy.Port}"); config.ProxyHost = settings.Proxy.Host; config.ProxyPort = settings.Proxy.Port; if (settings.Proxy.Login != null && settings.Proxy.Password != null) { config.ProxyCredentials = new NetworkCredential(settings.Proxy.Login, settings.Proxy.Password); var maskedPass = new string('#', settings.Proxy.Password.Length); logger.Info($"С логином {settings.Proxy.Login} и паролем {maskedPass}"); } } client = new AmazonS3Client(settings.Login, settings.Password, config); transferUtility = new TransferUtility(client); ListBucketsResponse response = client.ListBuckets(); bucket = response.Buckets.First(x => x.BucketName == settings.Container); if (bucket == null) { throw new InvalidOperationException($"Can't find S3 bucket: {settings.Container}"); } logger.Info($"Подключены к S3 хранилищу от имени '{settings.Login}' к контейнеру '{settings.Container}'"); }
/// <summary> /// Extracts a bucket name from a supplied parameter object, which should be /// a string or S3Bucket instance. /// </summary> /// <param name="paramValue"></param> /// <param name="paramName"></param> /// <returns></returns> public static string BucketNameFromParam(object paramValue, string paramName) { string bucketName = null; if (paramValue is string) { bucketName = (paramValue as string).Trim(); } else { PSObject bucketObject = paramValue as PSObject; if (bucketObject != null && bucketObject.BaseObject != null) { S3Bucket s3Bucket = bucketObject.BaseObject as S3Bucket; if (s3Bucket != null) { bucketName = s3Bucket.BucketName; } } } if (!string.IsNullOrEmpty(bucketName)) { return(bucketName); } throw new ArgumentException(string.Format("Expected bucket name or S3Bucket instance for {0} parameter", paramName)); }
public async Task CRUDTest() { string bucket1 = "testbucket-" + Guid.NewGuid(); string bucket2 = "testbucket-" + Guid.NewGuid(); await BucketClient.PutBucketAsync(bucket1, AwsRegion.EUWest1).ConfigureAwait(false); await BucketClient.PutBucketAsync(bucket2, AwsRegion.EUWest1).ConfigureAwait(false); List <S3Bucket> list = await ServiceClient.GetServiceAllAsync().ToListAsync().ConfigureAwait(false); Assert.True(list.Count >= 2); //Larger than because other tests might have run at the same time S3Bucket bucket1obj = Assert.Single(list, x => x.Name == bucket1); Assert.Equal(DateTime.UtcNow, bucket1obj.CreationDate.DateTime, TimeSpan.FromSeconds(5)); S3Bucket bucket2obj = Assert.Single(list, x => x.Name == bucket2); Assert.Equal(DateTime.UtcNow, bucket2obj.CreationDate.DateTime, TimeSpan.FromSeconds(5)); //Cleanup await BucketClient.DeleteBucketAsync(bucket1).ConfigureAwait(false); await BucketClient.DeleteBucketAsync(bucket2).ConfigureAwait(false); }
private static string PrintBucketName(AmazonS3Client s3Client) { ListBucketsResponse response = s3Client.ListBuckets(); S3Bucket bucket = response.Buckets[0]; return(bucket.BucketName); }
private async Task DiscoverAsync(AmazonS3Client client, S3Bucket bucket) { GetBucketLocationResponse bucketLocation = await client.GetBucketLocationAsync(bucket.BucketName); string location = bucketLocation.Location.Value; Children.Add(new AwsS3Bucket(bucket.BucketName, DisplayName, location)); }
//--Methods-- public override Task InitializeAsync(LambdaConfig config) { _rand = new Random(); _textBucket = new S3Bucket(config.ReadText("TextForPolly")); _audioBucket = new S3Bucket(config.ReadText("AudioForTranscribe")); _pollyClient = new AmazonPollyClient(); _transcribeClient = new AmazonTranscribeServiceClient(); return(Task.CompletedTask); }
private async void ButtonSubmit_Click(object sender, RoutedEventArgs e) { try { bool isFilePathEmpty = string.IsNullOrEmpty(uploadFilePath); if (!isFilePathEmpty) { ProgressDialogController controller = await this.ShowProgressAsync("Please wait...", "Uploading data"); controller.SetIndeterminate(); controller.SetCancelable(false); string[] temp = uploadFilePath.Split('.'); string fileId = $"{myId}.{temp[temp.Length - 1]}"; string BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; string filePath = BaseDirectoryPath + $"Resources\\Images\\{fileId}"; Item item = Dynamodb.GetItem(myId, MyAWSConfigs.AdminDBTableName); string oldImage = item["aPropic"]; Console.WriteLine("><><><><><><><><><><>" + oldImage); //Delete old profile pic in local //string oldFilePath = BaseDirectoryPath + $"Resources\\Images\\{oldImage}"; //DeleteOldPic(oldFilePath); //Delete old profile pic in s3Bucket S3Bucket.DeleteFile(oldImage, MyAWSConfigs.AdminS3BucketName); item["aPropic"] = fileId; await Task.Run(() => Models.S3Bucket.UploadFile(uploadFilePath, fileId, MyAWSConfigs.AdminS3BucketName)); MessageBox.Show(fileId); await Task.Run(() => Models.Dynamodb.UpdateItem(item, Models.MyAWSConfigs.AdminDBTableName)); await controller.CloseAsync(); await this.ShowMessageAsync("Success", "Changed Successfully..", MessageDialogStyle.Affirmative); //activity recorded Models.ActivityLogs.Activity(Models.Components.AdminComponent, "User Changed Profile Picture"); //imgUploadImage.Source = null; } else { await this.ShowMessageAsync("Error", "Please check all fields", MessageDialogStyle.Affirmative); } } catch { await this.ShowMessageAsync("Error", "Task not completed", MessageDialogStyle.Affirmative); } }
/// <summary> /// Creates a bucket if the bucket does not exist /// </summary> /// <param name="bucketName">Name of the bucket to create. Use only text and dashes, no slashes or periods.</param> /// <returns>The bucket object, whether preexisting or newly created</returns> public S3Bucket CreateBucketIfNotExists(string bucketName) { S3Bucket bucket = GetBucket(bucketName); if (bucket == null) { bucket = CreateBucket(bucketName); } return(bucket); }
public static void Main() { var options = new CredentialProfileOptions { AccessKey = "放在rdisk", SecretKey = "放在rdisk" }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("gino355140", options); profile.Region = RegionEndpoint.APNortheast3; //var netSDKFile = new NetSDKCredentialsFile(); //netSDKFile.RegisterProfile(profile); using (var client = new AmazonS3Client(options.AccessKey, options.SecretKey, profile.Region)) { clientS3 = client; var response = client.ListBucketsAsync(); var list = response.Result; //可列出所有Bucket,範例先以自己的做測試 S3Bucket s3Bucket = list.Buckets.Find(x => x.BucketName == bucketName); Console.WriteLine("S3 Start"); Console.WriteLine("---------------------"); //"2021/01/SQL_Test.csv","123.csv" 測試用檔名 string fileName = "2021/02/SQL_Test_big.csv"; string sqlStr = "Select * from S3Object"; //除from S3Object固定外,其餘皆和一般SQL語法相同 //列出bucket and bucket內的東西 DateTime start = new DateTime(2021, 01, 01); //起始時間 DateTime end = new DateTime(2021, 03, 30); //結束時間 List <string> keys = getYearMotnhs(start, end); //時間區間轉字串 foreach (string key in keys) { ListingObjectsAsync(key).Wait(); } Console.WriteLine("---------------------"); //讀取bucket and bucket內的東西 var result = ReadObjectDataAsync(fileName).Result; Console.WriteLine("---------------------"); //讀取bucket內的東西 by sql var result2 = GetSelectObjectContent("2021/01/SQL_Test.csv", sqlStr); Console.WriteLine("---------------------"); //上傳物件,測試前請先看一下上傳內容 //WritingAnObjectAsync().Wait(); Console.WriteLine("---------------------"); Console.WriteLine("S3 End"); } }
public async Task ListBuckets() { string tempBucketName = "testbucket-" + Guid.NewGuid(); await BucketClient.CreateBucketAsync(tempBucketName).ConfigureAwait(false); ListBucketsResponse listResp = await BucketClient.ListBucketsAsync().ConfigureAwait(false); Assert.True(listResp.Buckets.Count > 0); S3Bucket bucketObj = Assert.Single(listResp.Buckets, bucket => bucket.Name == tempBucketName); Assert.Equal(bucketObj.CreatedOn.UtcDateTime, DateTime.UtcNow, TimeSpan.FromSeconds(5)); }
public static void ClassInitialize(TestContext context) { try { client = ClientTests.CreateClient(); var buckets = client.ListBuckets(); bucket = buckets.Buckets.First(); } catch (Exception e) { Assert.Inconclusive("prerequisite: unable to create client or bucket. Error: {0}", e.Message); } }
private static void Main() { byte[] data = null; var r53Client = new AmazonS3Client(AwsAccessKeyId, AwsSecretAccessKey, EndPoint); ListObjectsRequest request = new ListObjectsRequest(); request.BucketName = BucketName; ListObjectsResponse response = r53Client.ListObjects(request); if (response.IsTruncated) { // Set the marker property request.Marker = response.NextMarker; } else { request = null; } foreach (S3Object obj in response.S3Objects) { S3Bucket bk = new S3Bucket(); S3FileInfo s3f = new S3FileInfo(r53Client, BucketName, obj.Key); TryGetFileData(obj.Key, ref data); string result = System.Text.Encoding.UTF8.GetString(data); Console.WriteLine("data - " + result); //File.Create("D:\\Mail.text").Write(data,0,0); Log_text_File(result); var ddf = s3f.OpenText(); var teest = (ddf.BaseStream); var ss = s3f.OpenRead(); using (StreamReader reader = new StreamReader(ddf.BaseStream)) { Console.WriteLine(reader.ReadLine()); } Console.WriteLine("Object - " + obj.Key); Console.WriteLine(" Size - " + obj.Size); Console.WriteLine(" LastModified - " + obj.LastModified); Console.WriteLine(" Storage class - " + obj.StorageClass); } Console.ReadKey(); }
private Exception EnsureBucketExists(AmazonS3 client) { try { S3Bucket bucket = GetBucket(client); if (bucket == null) { CreateBucket(client); } return(null); } catch (Exception exception) { Logging.Error("Amazon S3 exception occured", exception); return(exception); } }
public static void CheckForBucket(string itemKey, IAmazonS3 s3Client) { if (HttpContext.Current.User.Identity.IsAuthenticated) { string userBucketName = String.Format(Settings.Default.BucketNameFormat, HttpContext.Current.User.Identity.Name, itemKey); ListBucketsResponse listBucketsResponse = s3Client.ListBuckets(); S3Bucket bucket = listBucketsResponse.Buckets.FirstOrDefault(b => b.BucketName == userBucketName); if (bucket == null) { PutBucketRequest putBucketRequest = new PutBucketRequest() { BucketName = userBucketName, UseClientRegion = true }; s3Client.PutBucket(putBucketRequest); } } }
private static void deleteUnusedFiles(Func <string, bool> matches) { var bucketName = Environment.GetEnvironmentVariable("S3_BUCKET_NAME"); var S3Bucket = new S3Bucket(bucketName); S3Bucket.fetchKeys(); while (S3Bucket.moveNext()) { var currentKey = S3Bucket.getCurrentKey(); if (matches.Invoke(currentKey)) { var S3Object = new S3ObjectMetadata(bucketName, currentKey); S3Object.remove(); } } }
public async Task <VerificationResult> VerifyContent() { VerificationResult verificationResult = new VerificationResult(); S3Bucket selectedBucket = bucketDataGrid.SelectedItem as S3Bucket; verificationResult.IsVerified = selectedBucket != null; if (verificationResult.IsVerified) { NewBucketSelected?.Invoke(this, selectedBucket); } else { verificationResult.ErrorMessage = "No bucket selected"; } return(verificationResult); }
private ScannerResult CheckBuckets(ScannerRequest request, StringBuilder sb, StringBuilder linkBuilder = null) { ScannerResult result = S3Bucket.BucketCheck(request); if (result.Success) { sb.Append("\tUnclaimed S3 Buckets Found! " + String.Join(", ", result.Results.ToArray()) + "! Email sent." + Environment.NewLine); SendEmail("Unclaimed S3 Buckets Used", request.URL + " appears to use buckets " + String.Join(", " + Environment.NewLine, result.Results.ToArray())); if (linkBuilder != null) { linkBuilder.Append(request.URL + Environment.NewLine); } } else { sb.Append("\tNo Unclaimed S3 buckets found." + Environment.NewLine); } return(result); }
public async Task Should_FetchFileNameList() { var list = await client.ListBucketsAsync(); var bucketName = "myBucket/devs"; S3Bucket bucket = list.Buckets.Where(item => item.BucketName == bucketName).FirstOrDefault(); var request = new ListObjectsV2Request { BucketName = bucketName, Delimiter = "/" }; ListObjectsV2Response objectList = await client.ListObjectsV2Async(request); foreach (S3Object obj in objectList.S3Objects) { Console.WriteLine(obj.Key); } }
public void MarshalResponse(IConfig config, ListBucketsRequest request, ListBucketsResponse response, IDictionary <string, string> headers, Stream responseStream) { XmlSerializer s = new XmlSerializer(typeof(ListAllMyBucketsResult)); using (XmlTextReader r = new XmlTextReader(responseStream)) { r.Namespaces = false; ListAllMyBucketsResult listResult = (ListAllMyBucketsResult)s.Deserialize(r); if (listResult.Owner != null) { response.Owner = new S3Identity(); response.Owner.Id = listResult.Owner.Id; response.Owner.Name = listResult.Owner.DisplayName; } if (listResult.Buckets != null) { response.Buckets = new List <S3Bucket>(listResult.Buckets.Count); foreach (Network.Responses.XmlTypes.Bucket lb in listResult.Buckets) { S3Bucket b = new S3Bucket(); b.Name = lb.Name; b.CreatedOn = lb.CreationDate; response.Buckets.Add(b); } } else { response.Buckets = Array.Empty <S3Bucket>(); } } }
// Function Main static async Task Main(string[] args) { // Create an S3 client object. var client = new AmazonS3Client(); S3Bucket activeBucket = new S3Bucket(); // List the buckets owned by the user. try { Console.WriteLine(); Console.WriteLine("Getting a list of your buckets..."); Console.WriteLine(); var response = await client.ListBucketsAsync(); //This application should return only ONE bucket Console.WriteLine($"Number of buckets: {response.Buckets.Count}"); activeBucket = response.Buckets[0]; Console.WriteLine("ACTIVE BUCKET: {0}", activeBucket.BucketName); Console.WriteLine("Files in bucket:"); ListObjectsV2Response ListObjectsResponse = new ListObjectsV2Response(); // Retrieve the files in the bucket try { ListObjectsV2Request request = new ListObjectsV2Request { BucketName = activeBucket.BucketName, MaxKeys = 10 }; do { ListObjectsResponse = await client.ListObjectsV2Async(request); string keyName = ""; long bufferSize = 0; // Process the response. int keyIndex = 0; foreach (S3Object entry in ListObjectsResponse.S3Objects) { Console.WriteLine("File ID = {0} key = {1} size = {2}", ++keyIndex, entry.Key, entry.Size);; keyName = entry.Key; bufferSize = entry.Size; } //End of get the Object } while (ListObjectsResponse.IsTruncated); } catch (AmazonS3Exception amazonS3Exception) { Console.WriteLine("S3 error occurred. Exception: " + amazonS3Exception.ToString()); Console.ReadKey(); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.ReadKey(); } Console.Write("Enter File ID to download or 0 to continue without Downloading: "); int numberOfFilesInBucket = ListObjectsResponse.S3Objects.Count; // Get a value from the user to select a downloadable file int downloadFileIndex = Convert.ToInt32(Console.ReadLine()); while (downloadFileIndex < 0 || downloadFileIndex > numberOfFilesInBucket) { Console.Write("Enter File ID to download or 0 to continue without Downloading: "); downloadFileIndex = Convert.ToInt32(Console.ReadLine()); } if (downloadFileIndex > 0) { //valid File Index List <S3Object> FileObjects = ListObjectsResponse.S3Objects; try { GetObjectRequest objectRequest = new GetObjectRequest { BucketName = activeBucket.BucketName, Key = FileObjects[downloadFileIndex - 1].Key }; using (GetObjectResponse objectResponse = await client.GetObjectAsync(objectRequest)) using (Stream responseStream = objectResponse.ResponseStream) using (BinaryReader reader = new BinaryReader(responseStream)) { using (FileStream fileStream = new FileStream(FileObjects[downloadFileIndex - 1].Key, FileMode.Create)) { byte[] chunk; chunk = reader.ReadBytes(1024); while (chunk.Length > 0) { foreach (byte segment in chunk) { fileStream.WriteByte(segment); } chunk = reader.ReadBytes(1024); } } } } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } } catch (Exception e) { Console.WriteLine("Caught exception when getting the list of buckets:"); Console.WriteLine(e.Message); } //Upload a file try { string uploadFilePath = ""; string formatedDate = DateTime.Now.ToString(); formatedDate = Regex.Replace(formatedDate, "[^a-zA-Z0-9]", "_"); string fileName = ""; Console.Write("Upload file? (Y/N): "); string input = Console.ReadLine(); input = input.Trim().ToLower(); if (input.Equals("y") == true) { Console.Write("Enter a valid filepath to the file you wish to upload: "); uploadFilePath = Console.ReadLine(); char[] delimiterChars = { '\\', '/' }; string[] pathSplit = uploadFilePath.Split(delimiterChars); fileName = formatedDate + "_" + pathSplit[pathSplit.Length - 1]; } else { Console.WriteLine("Goodbye.."); return; } var putRequest1 = new PutObjectRequest { BucketName = activeBucket.BucketName, Key = fileName, FilePath = uploadFilePath }; PutObjectResponse response1 = await client.PutObjectAsync(putRequest1); } catch (AmazonS3Exception e) { Console.WriteLine( "Error encountered ***. Message:'{0}' when writing an object" , e.Message); } catch (Exception e) { Console.WriteLine( "Unknown encountered on server. Message:'{0}' when writing an object" , e.Message); } }
public async Task <IHttpActionResult> PostInvoice(InvoiceCreateDTO invoiceData) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } string reg = User.Identity.GetUserId(); Order order = await db.Orders.FindAsync(invoiceData.orderid); Accountant accountant = db.Accountants.Where(b => b.user_id == reg).SingleOrDefault(); /*int inv = await db.Invoices.CountAsync(b => b.invoiceNumber== invoiceData.invoiceNumber || b.orderid==order.id); * if (inv != 0) * { * return BadRequest("Invoice number exists or invoice for this order was already made"); * }**/ if (accountant == null) { return(BadRequest("Accountant does not exist")); } TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById("South Africa Standard Time"); DateTime userTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeInfo); Invoice invoice = new Invoice { accountant_id = accountant.id, date = userTime, // invoiceNumber= invoiceData.invoiceNumber, orderid = invoiceData.orderid, status = "not_paid", }; // critical section generate invoice number lock (Lock) { string year = DateTime.Now.Year.ToString(); string reference = "INV-" + year + "-"; int invo = db.Invoices.Count(); if (invo == 0) { invo += 1; reference += String.Format("{0:00000}", invo); } else { invo = db.Invoices.Count(b => b.invoiceNumber.Substring(4, 4) == year); invo += 1; reference += String.Format("{0:00000}", invo); } while (db.Invoices.Count(d => d.invoiceNumber == reference) != 0) { reference = "INV-" + year + "-" + String.Format("{0:00000}", ++invo); } order.status = "processing"; order.warehouseLocation = invoiceData.warehouseLocation; order.invoiceNumber = reference; db.Entry(order).State = EntityState.Modified; invoice.invoiceNumber = reference; db.Invoices.Add(invoice); db.SaveChanges(); } InvoiceGenerator inv = new InvoiceGenerator(); Stream invPdf = inv.CreateInvoicePDF(order); FileDTO file; string filename = Guid.NewGuid().ToString() + "invoice.pdf"; string bucket = "supremebrands"; StringWriter s = new StringWriter(); if (S3Bucket.UploadFileToS3(filename, invPdf, bucket)) { file = new FileDTO() { url = "https://s3-us-west-2.amazonaws.com/supremebrands/" + filename }; string body = string.Format(@" <!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http://www.w3.org/TR/html4/strict.dtd""> <html> <body> <h2> Dear sir/madam</h2> <br> <p>This email contains the link of the Invoice pdf created by the system</p> <p><a href='{0}'>Click here</a> to open the pdf </p> <p>Or copy and paste this link in your browser </p> <p>{1}</p> <br> <p>Kind Regards</p> <p>Supreme Brands Team<p> </body> </html> ", file.url, file.url); Email.sendEmail("*****@*****.**", "invoice " + order.invoiceNumber, body); invoice.invoiceUrl = file.url; db.Entry(invoice).State = EntityState.Modified; db.SaveChanges(); } return(Ok(invoice.invoiceNumber)); }
public Bucket(S3Bucket s3Bucket) { Name = s3Bucket.BucketName; CreationDate = s3Bucket.CreationDate; }
private async void ButtonSubmit_Click(object sender, RoutedEventArgs e) { //MessageBox.Show("this is submit button"); String name = txtName.Text; //MessageBox.Show(name); try { bool isNameEmpty = string.IsNullOrEmpty(txtName.Text); bool isPhoneEmpty = string.IsNullOrEmpty(txtPhone.Text); bool isDescriptionEmpty = string.IsNullOrEmpty(txtDescription.Text); bool isFilePathEmpty = string.IsNullOrEmpty(uploadFilePath); bool isFileIdEmpty = string.IsNullOrEmpty(txtId.Text); if (!isNameEmpty && !isDescriptionEmpty && !isPhoneEmpty) { string tableName = MyAWSConfigs.ReaderDBtableName; Table table = Table.LoadTable(client, tableName); ProgressDialogController controller = await this.ShowProgressAsync("Please wait...", ""); controller.SetIndeterminate(); controller.SetCancelable(false); string partitionKey = txtId.Text; Console.WriteLine("oooooooooooooooooooooooooooooooo" + partitionKey); var item = new Document(); Document doc = new Document(); doc["id"] = partitionKey; doc["name"] = txtName.Text; doc["phone"] = txtPhone.Text; doc["description"] = txtDescription.Text; /////////////////////////////////////////////////// //#ToDo : Add readerList //item["readerList"] = readerList; UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; if (uploadFilePath != null) { string[] temp = uploadFilePath.Split('.'); string BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; string filePath = BaseDirectoryPath + $"Resources\\Images\\{partitionKey}"; item = table.GetItem(partitionKey); string oldImage = item["aPropic"]; Console.WriteLine("><><><><><><><><><><>" + oldImage); //Delete old profile pic in local string oldFilePath = BaseDirectoryPath + $"Resources\\Images\\{oldImage}"; DeleteOldPic(oldFilePath); //Delete old profile pic in s3Bucket controller.SetMessage("Deleting File"); await Task.Run(() => S3Bucket.DeleteFile(oldImage, MyAWSConfigs.RefImagesBucketName)); controller.SetMessage("Uploading file"); await Task.Run(() => Models.S3Bucket.UploadFile(uploadFilePath, partitionKey, Models.MyAWSConfigs.RefImagesBucketName)); } controller.SetMessage("Adding database record"); await Task.Run(() => table.UpdateItem(doc, config)); Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); //MessageBox.Show("Successfully Updated!"); await controller.CloseAsync(); await this.ShowMessageAsync("Success", "Person Updated !", MessageDialogStyle.Affirmative); } else { await this.ShowMessageAsync("Error", "Please check all fields", MessageDialogStyle.Affirmative); } } catch { await this.ShowMessageAsync("Error", "Task not completed", MessageDialogStyle.Affirmative); } }
//public AETN.CloudWrapper.FileStore.AWSS3Provider clsProvide = new AETN.CloudWrapper.FileStore.AWSS3Provider(AccessKey, SecretKey, AWSURL); public void GetObjects(int id = 0) { try { //var res = fs.GetFile(bucketName, @"Archive_Docs/LIFETIME/MISC/I+WANT+A+BABY+AKA+REAL+WOMEN+SYNOPSIS.PDF"); //var client = new AmazonIdentityManagementServiceClient(credentials); //var response = client.GetUser(new GetUserRequest //{ // //UserName = "******" // UserName = "******" //}); //User user = response.User; //var requestgroups = new ListGroupsForUserRequest(user.UserName); //var groups = client.ListGroupsForUser(requestgroups); //var perm = client.ListPolicies(new ListPoliciesRequest { }); //string name = ""; //foreach (var item in groups.Groups) //{ // name = item.GroupName; //} //var requestPolicies = new ListUserPoliciesRequest //{ // UserName = user.UserName //}; //var p = new ListGroupPoliciesRequest //{ // GroupName = name, // MaxItems=10 //}; //var poli = client.ListGroupPolicies(p); //var responsePolicies = client.ListUserPolicies(requestPolicies); //string policyname =""; //foreach (var policy in responsePolicies.PolicyNames) //{ // policyname = policy[0].ToString(); //} config.RegionEndpoint = RegionEndpoint.USEast1; config.ServiceURL = ConfigurationManager.AppSettings["AWSServiceURL"].ToString(); s3Client = new AmazonS3Client(credentials, config); using (s3Client) { //Uri uri = s3Client.GetPreSignedURL( ListObjectsRequest req = new ListObjectsRequest { BucketName = bucketName }; var result = s3Client.ListObjects(req); //S3Bucket bucket = s3Client.getbucket List <string> keysList = new List <string>(); //for (int i = 0; i < result.S3Objects.Count; i++) //{ // string fileName = result.S3Objects[i].Key; // if (fileName.Contains("/")) // { // fileName = fileName.Substring(fileName.LastIndexOf("/") + 1); // } // keysList.Add(fileName); // if (i == id) // { // keyName = "TestingFile.pdf"; // // UploadImages(id); // } //} //GetObjectRequest request = new GetObjectRequest //{ // BucketName = bucketName, // Key = keyName //}; //using (GetObjectResponse response = s3Client.GetObject(request)) //{ keysList.Add("Forward_Entertainment.pdf"); keysList.Add("Forward_Entertainment1.pdf"); keysList.Add("Forward_Entertainment2.pdf"); ListObjectsRequest listRequest = new ListObjectsRequest { BucketName = bucketName }; List <string> keyNames = new List <string>(); S3Bucket bucket = new S3Bucket(); Dictionary <string, object> dicObj = new Dictionary <string, object>(); //s3Client.DownloadToFilePath(bucketName, keyName, destPath,dicObj); var listResponse = s3Client.ListObjects(listRequest); for (int i = 0; i < listResponse.S3Objects.Count; i++) { keyNames.Add(listResponse.S3Objects[i].Key.ToString()); if (!Directory.Exists(directorypath)) { dInfo = new DirectoryInfo(directorypath); dInfo.Create(); } GetObjectRequest getrequest = new GetObjectRequest { BucketName = bucketName, Key = keyNames[i] }; GetObjectResponse response = s3Client.GetObject(getrequest); dest = Path.Combine(directorypath, keyNames[i]); if (!System.IO.File.Exists(dest)) { response.WriteResponseStreamToFile(dest); } } } } catch (Exception ex) { throw new Exception(ex.Message + ex.StackTrace); } }
private async void BtnChangePropic_Click(object sender, RoutedEventArgs e) { //ChangeAdminPropic changeAdminPassword = new ChangeAdminPropic(myId); //changeAdminPassword.ShowDialog(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Image files | *.jpg; *.jpeg; *.png"; openFileDialog.FilterIndex = 1; openFileDialog.Multiselect = false; //open file dialog if (openFileDialog.ShowDialog() == true) { uploadFilePath = openFileDialog.FileName; AdminDp.Source = null; } try { bool isFilePathEmpty = string.IsNullOrEmpty(uploadFilePath); if (!isFilePathEmpty) { tableName = MyAWSConfigs.AdminDBTableName; string[] temp = uploadFilePath.Split('.'); string fileId = $"{myId}.{temp[temp.Length - 1]}"; string BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; //get current dp name item = Dynamodb.GetItem(myId, tableName); string oldImage = item["aPropic"]; Console.WriteLine("><><><><><><><><><><>" + oldImage); //Delete old profile pic in local string oldFilePath = BaseDirectoryPath + $"Resources\\Images\\{oldImage}"; DeleteOldPic(oldFilePath); //Delete old profile pic in s3Bucket S3Bucket.DeleteFile(oldImage, MyAWSConfigs.AdminS3BucketName); item["aPropic"] = fileId; //activity recorded Models.ActivityLogs.Activity(Models.Components.AdminComponent, "User Changed Profile Picture"); await Task.Run(() => S3Bucket.UploadFile(uploadFilePath, fileId, MyAWSConfigs.AdminS3BucketName)); MessageBox.Show("Success", "Successfully Updated!"); } else { MessageBox.Show("Error", "Please check all fields"); } } catch { MessageBox.Show("Error", "Task not completed"); } }
public Ess3Bucket(S3Bucket bucket) : this(bucket.BucketName, bucket.CreationDate) { }