Beispiel #1
0
 /// <summary>
 /// Gets an S3 object as a GetObjectResponse for
 /// access to other response properties.
 /// </summary>
 /// <param name="bucket">The bucket that the object is in.</param>
 /// <param name="key">The path to the object in S3.</param>
 public static Amazon.S3.Model.GetObjectResponse GetObjectResponse(string bucket, string key)
 {
     Amazon.S3.Model.GetObjectResponse response = new  Amazon.S3.Model.GetObjectResponse();
     using (Amazon.S3.IAmazonS3 client = new Factory().S3Client()) {
         Amazon.S3.Model.GetObjectRequest request = new Amazon.S3.Model.GetObjectRequest() {
             BucketName = bucket,
             Key = key
         };
         response = client.GetObject(request);
     }
     return response;
 }
        public ErrorTypes ReadFile(string strPath, System.IO.Stream oStream, out int nReadWriteBytes)
        {
            ErrorTypes eResult = ErrorTypes.StorageRead;

            nReadWriteBytes = 0;
            try
            {
                string strFileKey = GetFilePath(strPath);
                using (Amazon.S3.AmazonS3 oS3Client = Amazon.AWSClientFactory.CreateAmazonS3Client(m_oRegion))
                {
                    Amazon.S3.Model.GetObjectRequest oRequest = new Amazon.S3.Model.GetObjectRequest()
                                                                .WithBucketName(m_strBucketName).WithKey(strFileKey);
                    using (Amazon.S3.Model.GetObjectResponse oResponse = oS3Client.GetObject(oRequest))
                    {
                        using (Stream oResponseStream = oResponse.ResponseStream)
                        {
                            int nNeedReadBytes = (int)oResponse.ContentLength;

                            int          nMemoryStreamSize   = Math.Min(c_nMaxReadBufferSize, nNeedReadBytes);
                            MemoryStream oMemoryStreamOutput = new MemoryStream(nMemoryStreamSize);

                            while (nNeedReadBytes > 0)
                            {
                                int nReadBytesPos             = 0;
                                int nReadBytesCount           = nMemoryStreamSize;
                                int nReadBytesFromStreamCount = 0;
                                while (nReadBytesCount > 0 &&
                                       (nReadBytesFromStreamCount = oResponseStream.Read(oMemoryStreamOutput.GetBuffer(), nReadBytesPos, nReadBytesCount)) > 0)
                                {
                                    nReadBytesPos   += nReadBytesFromStreamCount;
                                    nReadBytesCount -= nReadBytesFromStreamCount;
                                }

                                oStream.Write(oMemoryStreamOutput.GetBuffer(), 0, nReadBytesPos);
                                nReadWriteBytes += nReadBytesPos;
                                nNeedReadBytes  -= nReadBytesPos;
                            }
                        }
                    }
                }
            }
            catch
            {
            }

            return(eResult);
        }
            public override void Close()
            {
                try
                {
                    if (null != m_oStreamOutput)
                    {
                        m_oStreamOutput = null;
                    }
                    if (null != m_oS3Client)
                    {
                        m_oS3Client.Dispose();
                        m_oS3Client = null;
                    }

                    if (null != m_oGetObjectResponse)
                    {
                        m_oGetObjectResponse.Dispose();
                        m_oGetObjectResponse = null;
                    }

                    if (null != m_oListObjectsResponse)
                    {
                        m_oListObjectsResponse.Dispose();
                        m_oListObjectsResponse = null;
                    }

                    if (null != m_oDeleteObjectResponse)
                    {
                        m_oDeleteObjectResponse.Dispose();
                        m_oDeleteObjectResponse = null;
                    }
                }
                catch
                {
                }
            }
Beispiel #4
0
        public static FontFamily GetCaptionFontFamily()
        {
            try
            {
                return(SystemFonts.Find("DejaVu Sans"));
            }
            catch (SixLabors.Fonts.Exceptions.FontFamilyNotFoundException)
            {
                using (Amazon.S3.AmazonS3Client client = new Amazon.S3.AmazonS3Client(Amazon.RegionEndpoint.USEast2))
                    using (Amazon.S3.Model.GetObjectResponse response = client.GetObjectAsync("appraisal-bot", "DejaVuSans-Bold.ttf").GetAwaiter().GetResult())
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            // ResponseStream is a HashStream which doesn't support Seeking
                            // which is required to install a font. So first we copy the
                            // data to a MemoryStream which does support seeking.
                            response.ResponseStream.CopyTo(memoryStream);
                            memoryStream.Seek(0, SeekOrigin.Begin);

                            FontCollection fonts = new FontCollection();
                            FontFamily     font  = fonts.Install(memoryStream);
                            return(font);
                        }
            }
        }
Beispiel #5
0
        public static Bitmap LoadImage(LoadImageType type, string fileName)
        {
            string directory = type == LoadImageType.Source ? "sourceArt" : "testArt";

            Console.WriteLine("LoadImage: " + fileName);

            if (Program.IsRunningTests())
            {
                return(Image.Load <PixelColor>("../../../" + directory + "/" + fileName));
            }
            else
            {
                if (Directory.Exists(directory))
                {
                    return(Image.Load <PixelColor>(directory + "/" + fileName));
                }
                else
                {
                    Amazon.S3.AmazonS3Client          client   = new Amazon.S3.AmazonS3Client(Amazon.RegionEndpoint.USEast2);
                    Amazon.S3.Model.GetObjectResponse response = client.GetObjectAsync("appraisal-bot", fileName).GetAwaiter().GetResult();
                    return(Image.Load <PixelColor>(response.ResponseStream));
                }
            }
        }
            public override void Close()
            {
                try
                {
                    if (null != m_oStreamOutput)
                    {

                       m_oStreamOutput = null;
                    }
                    if (null != m_oS3Client)
                    {
                        m_oS3Client.Dispose();
                        m_oS3Client = null;
                    }

                    if (null != m_oGetObjectResponse)
                    {
                        m_oGetObjectResponse.Dispose();
                        m_oGetObjectResponse = null;
                    }

                    if (null != m_oListObjectsResponse)
                    {
                        m_oListObjectsResponse.Dispose();
                        m_oListObjectsResponse = null;
                    }

                    if (null != m_oDeleteObjectResponse)
                    {
                        m_oDeleteObjectResponse.Dispose();
                        m_oDeleteObjectResponse = null;
                    }
                }
                catch
                {
                }
            }
        /// <summary>
        /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used
        /// to respond to S3 notifications.
        /// </summary>
        /// <param name="evnt"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <string> FunctionHandler(S3Event evnt, ILambdaContext context)
        {
            var s3Event = evnt.Records?[0].S3;

            if (s3Event == null)
            {
                return(null);
            }

            try
            {
                //array for request ID's
                ArrayList requests = new ArrayList();

                var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key);

                //proccess input
                string responseBody = "";
                string patientID    = "";

                Amazon.S3.Model.GetObjectRequest s3Request = new Amazon.S3.Model.GetObjectRequest
                {
                    BucketName = s3Event.Bucket.Name,
                    Key        = s3Event.Object.Key
                };
                using (Amazon.S3.Model.GetObjectResponse respond = await S3Client.GetObjectAsync(s3Request))
                    using (System.IO.Stream responseStream = respond.ResponseStream)
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream))
                        {
                            try
                            {
                                responseBody = reader.ReadToEnd();
                                XmlDocument doc = new XmlDocument();
                                doc.LoadXml(responseBody);

                                //parse XML
                                //evaluates Xpath expressions
                                XPathNavigator nav;
                                //holds xml document
                                XPathDocument docNav;
                                //iterates through selected nodes
                                XPathNodeIterator nodeIter;
                                String            idExpression = "/patient/id";
                                //opens xml
                                docNav = new XPathDocument(new XmlNodeReader(doc));
                                //create a navigator to query with Xpath
                                nav = docNav.CreateNavigator();

                                //gets id
                                nodeIter = nav.Select(idExpression);
                                nodeIter.MoveNext();
                                patientID = nodeIter.Current.Value;
                            }
                            catch (XmlException e)
                            {
                                //file is not xml
                                Console.WriteLine("Error: {0}", e.Message);
                            }
                        }

                //send message to input queue
                String          InputQueueURL   = "https://sqs.us-east-1.amazonaws.com/799289016492/inputQueue";
                AmazonSQSClient amazonSQSClient = new AmazonSQSClient();

                //creating message
                //create requestID
                string requestID = Guid.NewGuid().ToString();
                //Adds id to request id array
                requests.Add(requestID);
                string             message = "{ \"RequestID\":\"" + requestID + "\", \"PatientID\":\"" + patientID + "\"}";
                SendMessageRequest request = new SendMessageRequest
                {
                    QueueUrl    = InputQueueURL,
                    MessageBody = message
                };

                //sending message
                SendMessageResponse sendMessageResponse = amazonSQSClient.SendMessageAsync(request).Result;
                if (sendMessageResponse.HttpStatusCode.Equals(HttpStatusCode.OK))
                {
                    Console.WriteLine("Message successfully sent to queue {0}", InputQueueURL);
                }

                //wait for message from output
                String OutputQueueURL = "	https://sqs.us-east-1.amazonaws.com/799289016492/outputQueue";

                //while the request id array is not empty
                while (requests.Count > 0)
                {
                    ReceiveMessageRequest outRequest = new ReceiveMessageRequest()
                    {
                        QueueUrl        = OutputQueueURL,
                        WaitTimeSeconds = 20
                    };

                    var outResponse = amazonSQSClient.ReceiveMessageAsync(outRequest);
                    foreach (Message m in outResponse.Result.Messages)
                    {
                        //get message from output queue
                        //converts string into JsonPatient object
                        JsonPatient jp = JsonConvert.DeserializeObject <JsonPatient>(m.Body);
                        //removes requestID from array
                        requests.Remove(jp.RequestID);

                        //handles response
                        if (jp.Insurance)
                        {
                            Console.WriteLine("Patient with ID {0} has medical insurance", jp.PatientID);
                        }
                        else
                        {
                            Console.WriteLine("Patient with ID {0}  does not have medical insurance", jp.PatientID);
                        }

                        //delete message from queue
                        DeleteMessageRequest delete = new DeleteMessageRequest()
                        {
                            QueueUrl      = OutputQueueURL,
                            ReceiptHandle = m.ReceiptHandle
                        };
                        amazonSQSClient.DeleteMessageAsync(delete);
                    }
                }

                return(response.Headers.ContentType);
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function.");
                context.Logger.LogLine(e.Message);
                context.Logger.LogLine(e.StackTrace);
                throw;
            }
        }
Beispiel #8
0
        public async System.Threading.Tasks.Task <SoftmakeAll.SDK.OperationResult <System.Byte[]> > DownloadAsync(System.String BucketName, System.Collections.Generic.Dictionary <System.String, System.String> StorageFileNames)
        {
            SoftmakeAll.SDK.CloudStorage.AWS.Environment.Validate();

            SoftmakeAll.SDK.OperationResult <System.Byte[]> OperationResult = new SoftmakeAll.SDK.OperationResult <System.Byte[]>();

            if ((System.String.IsNullOrWhiteSpace(BucketName)) || (StorageFileNames == null) || (StorageFileNames.Count == 0))
            {
                OperationResult.Message = "The BucketName and StorageFileName cannot be null.";
                return(OperationResult);
            }

            try
            {
                if (StorageFileNames.Count == 1)
                {
                    Amazon.S3.Model.GetObjectRequest GetObjectRequest = new Amazon.S3.Model.GetObjectRequest {
                        BucketName = BucketName, Key = StorageFileNames.First().Key
                    };
                    using (Amazon.S3.Model.GetObjectResponse GetObjectResponse = await SoftmakeAll.SDK.CloudStorage.AWS.Environment._S3Client.GetObjectAsync(GetObjectRequest))
                        using (System.IO.Stream Stream = GetObjectResponse.ResponseStream)
                            using (System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream())
                            {
                                await Stream.CopyToAsync(MemoryStream);

                                OperationResult.Data = MemoryStream.ToArray();
                            }
                }
                else
                {
                    using (System.Threading.SemaphoreSlim SemaphoreSlim = new System.Threading.SemaphoreSlim(StorageFileNames.Count))
                    {
                        System.Collections.Generic.List <System.Threading.Tasks.Task> DownloadTasks = new System.Collections.Generic.List <System.Threading.Tasks.Task>();
                        foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                        {
                            await SemaphoreSlim.WaitAsync();

                            DownloadTasks.Add(System.Threading.Tasks.Task.Run(async() =>
                            {
                                Amazon.S3.Model.GetObjectRequest GetObjectRequest = new Amazon.S3.Model.GetObjectRequest {
                                    BucketName = BucketName, Key = StorageFileName.Key
                                };
                                using (Amazon.S3.Model.GetObjectResponse GetObjectResponse = await SoftmakeAll.SDK.CloudStorage.AWS.Environment._S3Client.GetObjectAsync(GetObjectRequest))
                                    await GetObjectResponse.WriteResponseStreamToFileAsync(StorageFileName.Key, false, new System.Threading.CancellationToken());
                                SemaphoreSlim.Release();
                            }));
                        }

                        if (DownloadTasks.Any())
                        {
                            await System.Threading.Tasks.Task.WhenAll(DownloadTasks);
                        }
                    }

                    OperationResult.Data = SoftmakeAll.SDK.Files.Compression.CreateZipArchive(StorageFileNames);

                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                    {
                        if (System.IO.File.Exists(StorageFileName.Key))
                        {
                            try { System.IO.File.Delete(StorageFileName.Key); } catch { }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (StorageFileNames.Count > 0)
                {
                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> StorageFileName in StorageFileNames)
                    {
                        if (System.IO.File.Exists(StorageFileName.Key))
                        {
                            try { System.IO.File.Delete(StorageFileName.Key); } catch { }
                        }
                    }
                }

                OperationResult.Message = ex.Message;
                return(OperationResult);
            }

            OperationResult.ExitCode = 0;
            return(OperationResult);
        }