Inheritance: HeadObjectResponse, IHasContent, IHasRequestCharged
 /// <summary>
 /// Get expense record by identifier
 /// </summary>
 /// <param name="userId">User identifier</param>
 /// <param name="id">Expense record identifier</param>
 /// <returns>Expense record</returns>
 public GetObjectResponse<ExpenseRecord> GetById(int userId, int id)
 {
     var response = new GetObjectResponse<ExpenseRecord>();
     if (HasUserAccess(userId, id))
     {
         response.Object = context.ExpenseRecords.FirstOrDefault(a => a.Id == id);
     }
     else
     {
         response.IsError = true;
         response.Errors.Add(Error.UserDoesNotHaveAccess);
     }
     return response;
 }
Example #2
0
 /// <summary>
 /// Get entity by identifier
 /// </summary>
 /// <param name="userId">User identifier</param>
 /// <param name="id">Entity identifier</param>
 /// <returns>Returned entity</returns>
 public GetObjectResponse<User> GetById(int userId, int id)
 {
     var response = new GetObjectResponse<User>();
     if (userId == id)
     {
         response.Object = context.Users.FirstOrDefault(a => a.Id == id);
         if (response.Object == null)
         {
             response.IsError = true;
             response.Errors.Add(Error.UserHasNotBeenFound);
         }
     }
     else
     {
         response.IsError = true;
         response.Errors.Add(Error.UserHasNotBeenFound);
     }
     return response;
 }
Example #3
0
        public IServerState Process()
        {
            var bytes = app.LocalObjectStorage.GetBytes(getObjectRequest.ObjectId);
            var response = new GetObjectResponse();
            if (bytes == null)
            {
                response.Error = Error.NotFound;
                Serializer.SerializeWithLengthPrefix(stream, response, PrefixStyle.Base128);
                return null;
            }

            response.Error = Error.Success;
            response.Length = (uint) bytes.Length;

            Serializer.SerializeWithLengthPrefix(stream, response, PrefixStyle.Base128);

            stream.Write(bytes, 0, bytes.Length);
            return null;
        }
Example #4
0
        public async Task ResponseHeaders()
        {
            //Upload a file for tests
            await UploadAsync(nameof(ResponseHeaders)).ConfigureAwait(false);

            GetObjectResponse response = await ObjectClient.GetObjectAsync(BucketName, nameof(ResponseHeaders), request =>
            {
                request.ResponseCacheControl.Set(CacheControlType.MaxAge, 42);
                request.ResponseContentDisposition.Set(ContentDispositionType.Attachment, "filename.txt");
                request.ResponseContentEncoding.Add(ContentEncodingType.Gzip);
                request.ResponseContentLanguage.Add("da-DK");
                request.ResponseContentType.Set("text/html", "utf-8");
                request.ResponseExpires = DateTimeOffset.UtcNow;
            }).ConfigureAwait(false);

            Assert.Equal("max-age=42", response.CacheControl);
            Assert.Equal("attachment; filename*=\"filename.txt\"", response.ContentDisposition);
            Assert.Equal("gzip", response.ContentEncoding);
            Assert.Equal("da-DK", response.ContentLanguage);
            Assert.Equal("text/html; charset=utf-8", response.ContentType);
            Assert.Equal(DateTime.UtcNow, response.Expires.Value.DateTime, TimeSpan.FromSeconds(5));
        }
Example #5
0
        public GetObjectResponse GetFirstWithXML(int id)
        {
            var response = new GetObjectResponse();

            try
            {
                response.Object = (_Ac4yXMLObjectEntityMethods.LoadXmlById(id));
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.Message
                });
            }

            return(response);
        }
Example #6
0
        public async void GetObject(string fileName)
        {
            await CarryOutAWSTask(async() =>
            {
                GetObjectRequest request = new GetObjectRequest()
                {
                    BucketName = S3BucketName,
                    Key        = fileName
                };

                using (GetObjectResponse response = await Client.GetObjectAsync(request))
                {
                    string title = response.Metadata["x-amz-meta-title"];
                    Debug.Log($"The object's title is {title}");
                    string dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);
                    if (!File.Exists(dest))
                    {
                        await response.WriteResponseStreamToFileAsync(dest, true, CancellationToken.None);
                    }
                }
            }, "read object");
        }
        static string ReadObjectData()
        {
            string responseBody = "";

            using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1))
            {
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = bucketName,
                    Key        = keyName
                };
                using (GetObjectResponse response = client.GetObject(request))
                    using (Stream responseStream = response.ResponseStream)
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            string title = response.Metadata["x-amz-meta-title"];
                            Console.WriteLine("The object's title is {0}", title);
                            responseBody = reader.ReadToEnd();
                        }
            }
            return(responseBody);
        }
Example #8
0
        public static async Task DownloadFile(string fileId)
        {
            string localFile = Guid.NewGuid().ToString() + ".csv";

            try
            {
                GetObjectRequest request = new GetObjectRequest()
                {
                    BucketName = bucketName, Key = fileId
                };

                GetObjectResponse response = await service.GetObjectAsync(request);

                await response.WriteResponseStreamToFileAsync(Path.Combine(PostDir, localFile), true, CancellationToken.None);

                firstfileisOk = true;
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                Console.WriteLine(amazonS3Exception.ToString());
            }
        }
Example #9
0
        /**
         * Given a computed digest, returns the respective content.
         * You might need to store the relation digest content during the codeDigest.
         *
         * @param digest A computed digest.
         * @return The content associated to the computed digest. If it is not found, this method should return null.
         */
        public string decodeDigest(string digest)
        {
            string key = FORMULA_FOLDER + "/" + getFolder(digest) + digest + "." + "ini";

            try
            {
                // Retrieve an object from S3.
                // See http://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/T_Amazon_S3_Model_GetObjectResponse.htm for more information.
                using (GetObjectResponse getObjectResponse = s3Client.GetObject(BUCKET_NAME, key))
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(getObjectResponse.ResponseStream))
                    {
                        string contents = reader.ReadToEnd();
                        return(contents);
                    }
                }
            }
            catch (Exception e)
            {
                return(null); // Cache miss.
            }
        }
Example #10
0
File: Program.cs Project: wse/AWS
        async Task ReadingAnObjectAsync()
        {
            await CarryOutAWSTask(async() =>
            {
                GetObjectRequest request = new GetObjectRequest()
                {
                    BucketName = bucketName,
                    Key        = keyName
                };

                using (GetObjectResponse response = await client.GetObjectAsync(request))
                {
                    string title = response.Metadata["x-amz-meta-title"];
                    Console.WriteLine("The object's title is {0}", title);
                    string dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), keyName);
                    if (!File.Exists(dest))
                    {
                        await response.WriteResponseStreamToFileAsync(dest, true, CancellationToken.None);
                    }
                }
            }, "read object");
        }
Example #11
0
        public void GetReturnsDeserializedObjectFromS3Test()
        {
            var obj      = Encoding.UTF8.GetBytes("{\"Id\":1,\"PropOne\":\"some property\",\"PropTwo\":40}");
            var response = new GetObjectResponse
            {
                ResponseStream = new MemoryStream(obj)
            };

            _mockS3Client
            .Setup(
                x => x.GetObjectAsync(
                    It.Is <GetObjectRequest>(
                        y => y.BucketName == "mybucket" && y.Key == "keyprefix/1"),
                    It.IsAny <CancellationToken>()))
            .ReturnsAsync(response);

            var result = _store.Get(1).Result;

            Assert.Equal(1, result.Id);
            Assert.Equal("some property", result.PropOne);
            Assert.Equal(40, result.PropTwo);
        }
Example #12
0
        public async Task MultipartViaClient()
        {
            byte[] data = new byte[10 * 1024 * 1024]; //10 Mb

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % 255);
            }

            using (MemoryStream ms = new MemoryStream(data))
            {
                MultipartUploadStatus resp = await MultipartClient.MultipartUploadAsync(BucketName, nameof(MultipartViaClient), ms, 5 * 1024 * 1024).ConfigureAwait(false);

                Assert.Equal(MultipartUploadStatus.Ok, resp);
            }

            GetObjectResponse getResp = await ObjectClient.GetObjectAsync(BucketName, nameof(MultipartViaClient)).ConfigureAwait(false);

            Assert.True(getResp.IsSuccess);

            using (MemoryStream ms = new MemoryStream())
            {
                await getResp.Content.CopyToAsync(ms).ConfigureAwait(false);

                Assert.Equal(data, ms.ToArray());
            }

            //Try multipart downloading it
            using (MemoryStream ms = new MemoryStream())
            {
                await MultipartClient.MultipartDownloadAsync(BucketName, nameof(MultipartViaClient), ms).ConfigureAwait(false);

                Assert.Equal(data, ms.ToArray());
            }

            HeadObjectResponse headResp = await ObjectClient.HeadObjectAsync(BucketName, nameof(MultipartViaClient), req => req.PartNumber = 1).ConfigureAwait(false);

            Assert.Equal(2, headResp.NumberOfParts);
        }
Example #13
0
        public override void Execute()
        {
            if (!this._request.IsSetBucketName())
            {
                throw new ArgumentNullException("bucketName", "The bucketName Specified is null or empty!");
            }
            if (!this._request.IsSetFilePath())
            {
                throw new ArgumentNullException("filePath", "The filepath Specified is null or empty!");
            }
            if (!this._request.IsSetKey())
            {
                throw new ArgumentNullException("key", "The Key Specified is null or empty!");
            }

            GetObjectRequest  getRequest = ConvertToGetObjectRequest(this._request);
            GetObjectResponse response   = this._s3Client.GetObject(getRequest);

            response.WriteObjectProgressEvent += this._request.EventHandler;

            response.WriteResponseStreamToFile(this._request.FilePath);
        }
        public static async Task AppendMetadataAsync(AmazonS3Client client, string bucketName, Blob blob, CancellationToken cancellationToken)
        {
            if (blob == null)
            {
                return;
            }

            GetObjectResponse obj = await client.GetObjectAsync(bucketName, blob.FullPath, cancellationToken).ConfigureAwait(false);

            blob.Metadata = new Dictionary <string, string>();
            foreach (string key in obj.Metadata.Keys)
            {
                string value  = obj.Metadata[key];
                string putKey = key;
                if (putKey.StartsWith(MetaDataHeaderPrefix))
                {
                    putKey = putKey.Substring(MetaDataHeaderPrefix.Length);
                }

                blob.Metadata[putKey] = value;
            }
        }
        public GetObjectResponse Save(Modul _Modul)
        {
            var response = new GetObjectResponse();

            try
            {
                _ModulEntityMethods.addNew(_Modul);
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.Message
                });
            }

            return(response);
        }
        /// <summary>
        /// Downloads the binary MD5 stream by credential URI.
        /// </summary>
        /// <param name="blobUri">The BLOB URI.</param>
        /// <returns>System.IO.Stream.</returns>
        public override Stream DownloadBinaryStreamByCredentialUri(string blobUri)
        {
            try
            {
                blobUri.CheckEmptyString(nameof(blobUri));
                var bucketName = GetBucketNameByCredentialUri(blobUri);
                var key        = GetKeyByCredentialUri(blobUri);

                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = bucketName,
                    Key        = key
                };
                GetObjectResponse response = blobClient.GetObject(request);

                return(response.ResponseStream);
            }
            catch (Exception ex)
            {
                throw ex.Handle(blobUri);
            }
        }
Example #17
0
        public GetObjectResponse SaveWithXml(TaroltEljarasArgumentum _TaroltEljarasArgumentum)
        {
            var response = new GetObjectResponse();

            try
            {
                _TaroltEljarasArgumentumEntityMethods.SaveWithXml(_TaroltEljarasArgumentum);
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.Message
                });
            }

            return(response);
        }
Example #18
0
        static string ReadObjectData()
        {
            string responseBody = "";

            using (client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast2)) {
                GetObjectRequest request = new GetObjectRequest {
                    BucketName = bucketName,
                    Key        = keyName
                };

                using (GetObjectResponse response = client.GetObject(request)) {
                    // write response to a file
                    // response.WriteResponseStreamToFile(destPath);
                    using (Stream responseStream = response.ResponseStream) {
                        using (StreamReader reader = new StreamReader(responseStream)) {
                            responseBody = reader.ReadToEnd();
                        }
                    }
                }
            }
            return(responseBody);
        }
Example #19
0
        private static async Task GetFileAsync(string bucketName, string keyName, string filePath)
        {
            try
            {
                GetObjectResponse response = await localclient.GetObjectAsync(bucketName, keyName);

                //response.ResponseStream.CopyTo(Console.OpenStandardOutput());
                using (FileStream fs = new FileStream(filePath, FileMode.Create))
                {
                    response.ResponseStream.CopyTo(fs);
                    Console.WriteLine("File successfully saved in {0}", filePath);
                }
            }
            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);
            }
        }
Example #20
0
        public override void Download(FileItem from, FileItem to)
        {
            from.Path = CheckPath(from.Path);

            var mGetObjectRequest = new GetObjectRequest();

            mGetObjectRequest.BucketName = from.BucketName;
            mGetObjectRequest.Key        = from.Path;

            GetObjectResponse response = s3.GetObject(mGetObjectRequest);

            /*FileItem mFileItem = new FileItem();
             * mFileItem.BucketName = response.BucketName;
             * mFileItem.Path = response.Key;
             * mFileItem.LastModified = response.LastModified.Ticks;
             * mFileItem.Size = response.ContentLength;*/
            Stream stream = new MemoryStream();

            response.ResponseStream.CopyTo(stream);
            DataUtils.Download(stream, to);
            // mFileItem.Content = DataUtils.ReadFully(response.ResponseStream);
        }
Example #21
0
        public GetObjectResponse GetFirstWithXML(int id)
        {
            var response = new GetObjectResponse();

            try
            {
                response.Object = (_Ac4ySDSequenceEntityMethods.LoadXmlById(id));
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.StackTrace + "\nBaseName: " + _Ac4ySDSequenceEntityMethods.baseName
                });
            }

            return(response);
        }
        public static async Task GetObject(string id)
        {
            try
            {
                GetObjectRequest request = new GetObjectRequest()
                {
                    BucketName = _bucketName,
                    Key        = id
                };

                using (GetObjectResponse response = await client.GetObjectAsync(request))
                {
                    string title = response.Metadata["x-amz-meta-title"];
                    Console.WriteLine("The object's title is {0}", title);
                    string dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), id);
                    if (!File.Exists(dest))
                    {
                        var cancelSource = new CancellationTokenSource();
                        var token        = cancelSource.Token;

                        await response.WriteResponseStreamToFileAsync(dest, false, token);
                    }
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                     amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Please check the provided AWS Credentials.");
                    Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine("An error occurred with the message '{0}' when reading an object", amazonS3Exception.Message);
                }
            }
        }
Example #23
0
        public GetObjectResponse Save(Ac4ySDSequence _Ac4ySDSequence)
        {
            var response = new GetObjectResponse();

            try
            {
                _Ac4ySDSequenceEntityMethods.addNew(_Ac4ySDSequence);
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.StackTrace
                });
            }

            return(response);
        }
Example #24
0
        private static void DownloadFile(S3Object s3Object)
        {
            System.Console.WriteLine("Downloading " + s3Object.Key);
            GetObjectResponse getObjectResponse = _amazonS3Client.GetObject(new GetObjectRequest {
                BucketName = BucketName, Key = s3Object.Key
            });

            string filePath = Path.Combine(_folder, s3Object.Key);

            using (BufferedStream inputBufferedStream = new BufferedStream(getObjectResponse.ResponseStream))
                using (CryptoStream cryptoStream = new CryptoStream(inputBufferedStream, _aesDecryptor, CryptoStreamMode.Read))
                    using (FileStream outputFileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        int data;
                        while ((data = cryptoStream.ReadByte()) != -1)
                        {
                            outputFileStream.WriteByte((byte)data);
                        }
                    }

            new FileInfo(filePath).LastWriteTime = DateTime.Parse(getObjectResponse.Metadata["x-amz-meta-LWT"]);
        }
Example #25
0
        public void ReadingObject(String bucketName, String keyName, String dest = null)
        {
            try
            {
                GetObjectRequest request = new GetObjectRequest()
                {
                    BucketName = bucketName,
                    Key        = keyName
                };

                using (GetObjectResponse response = client.GetObject(request))
                {
                    string title = response.Metadata["x-amz-meta-title"];
                    Console.WriteLine("The object's title is {0}", title);
                    if (dest == null)
                    {
                        dest = keyName;
                    }
                    if (File.Exists(dest))
                    {
                        File.Delete(dest);
                    }
                    response.WriteResponseStreamToFile(dest);
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                     amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    throw new Exception("Please check the provided AWS Credentials.\r\nIf you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                }
                else
                {
                    throw new Exception(String.Format("An error occurred with the message '{0}' when reading an object", amazonS3Exception.Message));
                }
            }
        }
        public void OpenFile()
        {
            //Arrange
            var stream   = new MemoryStream(Encoding.UTF8.GetBytes("Test123"));
            var response = new GetObjectResponse {
                ResponseStream = stream
            };

            var clientMock = new Mock <IAmazonS3>();

            clientMock.Setup(p => p.GetObject(It.Is <GetObjectRequest>(req => req.Key == "media/1001/media.jpg")))
            .Returns(response);

            var provider = CreateProvider(clientMock);

            //Act
            var actual = provider.OpenFile("1001/media.jpg");

            //Assert
            Assert.AreEqual(new StreamReader(actual).ReadToEnd(), "Test123");
            clientMock.VerifyAll();
        }
Example #27
0
        public GetObjectResponse GetFirstById(int id)
        {
            var response = new GetObjectResponse();

            try
            {
                response.Object = (_TaroltEljarasEntityMethods.findFirstById(id));
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.Message
                });
            }

            return(response);
        }
Example #28
0
        public GetObjectResponse SaveWithXml(Ac4yXMLObject _Ac4yXMLObject)
        {
            var response = new GetObjectResponse();

            try
            {
                _Ac4yXMLObjectEntityMethods.SaveWithXml(_Ac4yXMLObject);
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.Message
                });
            }

            return(response);
        }
Example #29
0
        public GetObjectResponse LoadXmlByGuid(string guid)
        {
            var response = new GetObjectResponse();

            try
            {
                response.Object = (_TaroltEljarasEntityMethods.LoadXmlByGuid(guid));
                response.Result = new Ac4yProcessResult()
                {
                    Code = "1"
                };
            }
            catch (Exception exception)
            {
                response.Result = (new Ac4yProcessResult()
                {
                    Code = "-1", Message = exception.Message
                });
            }

            return(response);
        }
        }  //End of UploadToS3

        public async Task <bool> DownloadFromS3(string filename)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            CancellationToken token = cts.Token;

            try
            {
                IAmazonS3 client = new AmazonS3Client(_awsAccessKey, _awsSecretKey, RegionEndpoint.APSouth1);

                using (client = new AmazonS3Client(_awsAccessKey, _awsSecretKey, RegionEndpoint.APSouth1))
                {
                    GetObjectRequest request = new GetObjectRequest
                    {
                        BucketName = "testinsightdemo",

                        Key = filename,
                    };

                    using (GetObjectResponse response = await client.GetObjectAsync(request))
                    {
                        string dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), filename);

                        if (!File.Exists(dest))
                        {
                            await response.WriteResponseStreamToFileAsync(dest, true, token);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(true);
        }//End of DownloadFromS3
Example #31
0
        public async Task <Response> awsS3_ReadFileAsync(
            AmazonS3Client inputS3Client,
            string inputS3Bucket,
            string inputS3FileKey)
        {
            try
            {
                string responseContent;
                using (GetObjectResponse response = await inputS3Client.GetObjectAsync(inputS3Bucket, inputS3FileKey))
                    using (Stream responseStream = response.ResponseStream)
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            responseContent = reader.ReadToEnd();
                        }

                return(new Response
                {
                    HttpStatus = HttpStatusCode.OK,
                    Payload = (string)responseContent
                });
            }
            catch (AmazonS3Exception e)
            {
                return(new Response
                {
                    HttpStatus = e.StatusCode,
                    ExceptionPayload = e
                });
            }
            catch (Exception e)
            {
                return(new Response
                {
                    HttpStatus = HttpStatusCode.InternalServerError,
                    ExceptionPayload = e
                });
            }
        }
        public override async Task <object> ProcessMessageAsync(S3EventNotification message, ILambdaContext context)
        {
            LogInfo(JsonConvert.SerializeObject(message));

            // Use S3EventNotification to get location of the file which was uploaded
            var bucket = message.Records[0].S3.Bucket.Name;
            var key    = message.Records[0].S3.Object.Key;
            // Read S3 object contents
            var request = new GetObjectRequest {
                BucketName = bucket,
                Key        = key
            };
            var text = "";

            using (GetObjectResponse response = await _s3Client.GetObjectAsync(request))
                using (Stream responseStream = response.ResponseStream)
                    using (StreamReader reader = new StreamReader(responseStream)){
                        text = await reader.ReadToEndAsync();
                    }

            // Separate messages by line ending
            var splitText = text.Split('\n');

            // Use BatchInsertMessagesAsync from the Messages.Tables library to write messages to DynamoDB
            var messages = new List <Message>();

            for (int i = 0; i < splitText.Length; i++)
            {
                LogInfo(splitText[i]);
                var msg = new Message();
                msg.Source = "S3";
                msg.Text   = splitText[i];
                messages.Add(msg);
            }
            await _table.BatchInsertMessagesAsync(messages);

            return(null);
        }
Example #33
0
        private async Task <String> FormatEmailAsync()
        {
            String    emailBody = "";
            IAmazonS3 client    = new AmazonS3Client(bucketRegion);

            try
            {
                GetObjectRequest objectRequest = new GetObjectRequest
                {
                    BucketName = templateBucketName,
                    Key        = "email-non-CXM-service.txt"
                };
                using (GetObjectResponse objectResponse = await client.GetObjectAsync(objectRequest))
                    using (Stream responseStream = objectResponse.ResponseStream)
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            emailBody = reader.ReadToEnd();
                        }

                emailBody = emailBody.Replace("AAA", caseReference);
                emailBody = emailBody.Replace("KKK", HttpUtility.HtmlEncode(caseDetails.emailFrom));

                String tempDetails = "";
                if (caseDetails.CustomerHasUpdated)
                {
                    tempDetails = HttpUtility.HtmlEncode(caseDetails.enquiryDetails) + "<BR><BR>";
                }
                emailBody = emailBody.Replace("FFF", tempDetails + HttpUtility.HtmlEncode(caseDetails.FullEmail));
            }
            catch (Exception error)
            {
                await SendFailureAsync(" Reading Response Template", error.Message);

                Console.WriteLine("ERROR : FormatEmailAsync : Reading Response Template : " + error.Message);
                Console.WriteLine("ERROR : FormatEmailAsync : " + error.StackTrace);
            }
            return(emailBody);
        }
Example #34
0
 /// <summary>
 /// Get tag full name
 /// </summary>
 /// <example>
 /// TagLevel1->TagLevel2->TagLevel3...etc...
 /// </example>>
 /// <param name="userId">User identifier</param>
 /// <param name="tagId">Tag identifier</param>
 /// <returns>Tag full name</returns>
 public GetObjectResponse<string> GetTagFullName(int userId, int tagId)
 {
     var response = new GetObjectResponse<string>();
     if (HasUserAccess(userId, tagId))
     {
         var tag = GetById(userId, tagId).Object;
         response.Object = tag.Name;
         var parent = tag.Parent;
         while (parent != null && parent.Name != "ExpensesTag")
         {
             response.Object = string.Format("{0}->", parent.Name) + response.Object;
             parent = parent.Parent;
         }
     }
     else
     {
         response.IsError = true;
         response.Errors.Add(Error.UserDoesNotHaveAccess);
     }
     
     return response;
 }
 /// <summary>
 /// Get expense records by choosen tag
 /// </summary>
 /// <param name="userId">User identifier</param>
 /// <param name="tagId">Tag identifier</param>
 /// <returns>List of expense records which is in response object</returns>
 public GetObjectResponse<List<ExpenseRecord>> GetExpenseRecordsByTag(int userId, int tagId)
 {
     var response = new GetObjectResponse<List<ExpenseRecord>>();
     
     var tagRepository = new TagRepository(context);
     
     if (tagRepository.HasUserAccess(userId, tagId))
     {
         response.Object = tagRepository.GetById(userId, tagId).Object.ExpenseRecords.ToList();
     }
     else
     {
         response.IsError = true;
         response.Errors.Add(Error.UserDoesNotHaveAccess);
     }
     return response;
 }
Example #36
0
 /// <summary>
 /// Method checks user credentials
 /// </summary>
 /// <param name="login">Login (user name)</param>
 /// <param name="password">Password</param>
 /// <returns>Execution result: if it is true then user has been passed validation otherwise it returns false</returns>
 public GetObjectResponse<User> GetUserByCredentials(string login, string password)
 {
     var response = new GetObjectResponse<User>();
     var users = context.Users.Where(a => a.Login == login && a.Password == password);
     if (users.Count() == 1)
     {
         response.Object = users.First();
     }
     else
     {
         response.IsError = true;
         response.Errors.Add(Error.CredentialsDontExistsInTheSystem);
     }
     return response;
 }
Example #37
0
 /// <summary>
 /// Method get the main tag for all tree of tagg.
 /// </summary>
 /// <param name="userId">User identifier</param>
 /// <returns>Execution result with object as main tag</returns>
 public GetObjectResponse<Tag> GetParentTagByUserId(int userId)
 {
     var response = new GetObjectResponse<Tag>();
     response.Object = context.Tags.FirstOrDefault(a => a.Parent == null && a.User.Id == userId);
     return response;
 }
 public ObjectDescriptorEnumerator(GetObjectResponse response)
 {
     mResponse = response;
     mCurrent = null;
 }
Example #39
0
        /// <summary>
        /// Get spent amount by tag
        /// </summary>
        /// <param name="userId">User identifier</param>
        /// <param name="tagId">Tag identifier</param>
        /// <param name="startDate">Start date</param>
        /// <param name="endDate">End date</param>
        /// <returns>Execution result with sum. by choosen tag</returns>
        public GetObjectResponse<decimal> GetSpentAmountByTag(int userId, int tagId, DateTime startDate, DateTime endDate)
        {
            var response = new GetObjectResponse<decimal>();
            if (HasUserAccess(userId, tagId))
            {
                var tag = GetById(userId, tagId).Object;
                response.Object = tag.ExpenseRecords.Where(a => a.DateStamp >= startDate && a.DateStamp <= endDate).Sum(a => a.Price);
                foreach (var childTag in tag.Children)
                {
                    response.Object += GetSpentAmountByTag(userId, childTag.Id, startDate, endDate).Object;
                }
            }
            else
            {
                response.IsError = true;
                response.Errors.Add(Error.UserDoesNotHaveAccess);
            }

            return response;
        }