예제 #1
0
        public Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            var obj      = JsonConvert.DeserializeObject <IDictionary <string, object> >(xchangeFile.Data, new DictionaryConverter());
            var jsonHash = Hash.FromDictionary(obj);

            var    fileNameTemplate = Runner.StartupValueOf(CommonProperties.FileNameTemplate);
            string fileName         = null;

            if (fileNameTemplate != null)
            {
                var fileNameTemplateData = Runner.StartupValueOf(CommonProperties.FileNameTemplate);

                var parsedFileNameTemplate = Template.Parse(fileNameTemplateData);

                fileName = parsedFileNameTemplate.Render(jsonHash);
            }


            var templateData = Runner.StartupValueOf(CommonProperties.DataTemplate);

            var parsedTemplate = Template.Parse(templateData);

            var result = parsedTemplate.Render(jsonHash);


            return(Task.FromResult(new XchangeFile(result, fileName)));
        }
예제 #2
0
        public async Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            using var cloudFiles = new CloudFilesService(new CloudFilesOptions
            {
                AccessKeyId     = Runner.StartupValueOf(CommonProperties.AccessKeyId),
                SecretAccessKey = Runner.StartupValueOf(CommonProperties.SecretAccessKey),
                ServiceUrl      = Runner.StartupValueOf(CommonProperties.Url),
                BucketName      = Runner.StartupValueOf(CommonProperties.TargetPath),
            });

            var key = "";

            if (Runner.StartupValueOf(CommonProperties.FileName) != "")
            {
                key = Runner.StartupValueOf("FileName");
            }
            else
            {
                key = string.Concat(Runner.StartupValueOf(CommonProperties.FolderName), "/", DateTime.UtcNow.ToString("yyyyMMddHHmmss") + "." + Runner.StartupValueOf(CommonProperties.FileExtension));
            }

            await cloudFiles.WriteTextAsync(xchangeFile.Data, new WriteFileSettings
            {
                Key         = key,
                ContentType = Runner.StartupValueOf(CommonProperties.ContentType),
            });

            return(new XchangeFile(key, xchangeFile.Filename));
        }
예제 #3
0
        public async Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            var client = new BlobContainerClient(Runner.StartupValueOf(CommonProperties.ConnectionString), Runner.StartupValueOf(CommonProperties.TargetPath));

            if (client == null)
            {
                throw new Exception("Container not found");
            }

            var fileName = "";

            if (Runner.StartupValueOf(CommonProperties.FileName) != "")
            {
                fileName = Runner.StartupValueOf("FileName");
            }
            else
            {
                fileName = string.Concat(DateTime.UtcNow.ToString("yyyyMMddHHmmss"), ".", Runner.StartupValueOf(CommonProperties.FileExtension));
            }

            var blockBlob = client.GetBlobClient(fileName);

            byte[] byteArray = Encoding.UTF8.GetBytes(xchangeFile.Data);
            using MemoryStream stream = new MemoryStream(byteArray);
            await blockBlob.UploadAsync(stream);

            return(new XchangeFile(string.Empty));
        }
예제 #4
0
        public async Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            Rebex.Licensing.Key = Runner.StartupValueOf(CommonProperties.LicenseKey);

            switch (Runner.StartupValueOf(CommonProperties.Protocol).ToLower())
            {
            case "sftp":

                var sftp     = new Sftp();
                int sftpPort = string.IsNullOrWhiteSpace(Runner.StartupValueOf(CommonProperties.Port)) ? 22 : Convert.ToInt32(Runner.StartupValueOf(CommonProperties.Port));
                await sftp.ConnectAsync(Runner.StartupValueOf(CommonProperties.Host), sftpPort);

                ftpOrSftp = sftp;
                break;

            case "ftp":

                var ftp     = new Rebex.Net.Ftp();
                int ftpPort = string.IsNullOrWhiteSpace(Runner.StartupValueOf(CommonProperties.Port)) ? 21 : Convert.ToInt32(Runner.StartupValueOf(CommonProperties.Port));
                await ftp.ConnectAsync(Runner.StartupValueOf(CommonProperties.Host), ftpPort);

                ftpOrSftp = ftp;
                break;

            default:
                throw new ArgumentException($"Unknown protocol '{Runner.StartupValueOf(CommonProperties.Protocol)}'");
            }

            await ftpOrSftp.LoginAsync(Runner.StartupValueOf(CommonProperties.Username), Runner.StartupValueOf(CommonProperties.Password));

            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(xchangeFile.Data));
            //Stream str = stream;

            var filename = xchangeFile.Filename;

            if (string.IsNullOrWhiteSpace(filename))
            {
                var currentDate = DateTime.UtcNow;
                filename = $"{currentDate.Year:0000}{currentDate.Month:00}{currentDate.Day:00}{currentDate.Hour:00}{currentDate.Minute:00}{currentDate.Second:00}{currentDate.Millisecond:000}";
            }

            //if (!string.IsNullOrWhiteSpace(Runner.StartupValueOf(CommonProperties.FileNamePrefix)))
            //    filename += Runner.StartupValueOf(CommonProperties.FileNamePrefix) + "_";
            //filename += Runner.StartupValueOf(CommonProperties.FileNamePrefix) + "_" + DateTime.UtcNow.Day + DateTime.UtcNow.Month + DateTime.UtcNow.Year + DateTime.UtcNow.Hour + DateTime.UtcNow.Minute + DateTime.UtcNow.Second + DateTime.UtcNow.Millisecond;

            await ftpOrSftp.PutFileAsync(stream, Runner.StartupValueOf($"{CommonProperties.TargetPath}/{filename}"));

            await ftpOrSftp.DisconnectAsync();

            return(new XchangeFile(string.Empty));
        }
예제 #5
0
        public async Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            IList <IEnumerable <byte> > attachmentsData = new List <IEnumerable <byte> >();
            MailGunSendRequest          mailgunRequest  = JsonConvert.DeserializeObject <MailGunSendRequest>(xchangeFile.Data);


            HttpClient client = new HttpClient();
            string     key    = Runner.StartupValueOf <string>(CommonProperties.ApiKey);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", key);

            MultipartFormDataContent formContent = new MultipartFormDataContent();

            formContent.Add(new StringContent(mailgunRequest.To), "to");
            formContent.Add(new StringContent(mailgunRequest.From), "from");
            formContent.Add(new StringContent(mailgunRequest.Subject), "subject");



            if (mailgunRequest.Template != null)
            {
                formContent.Add(new StringContent(mailgunRequest.Template), "template");
                formContent.Add(new StringContent(JsonConvert.SerializeObject(mailgunRequest.TemplateVariables ?? new {})), "h:X-Mailgun-variables");
            }
            else if (mailgunRequest.Body != null)
            {
                formContent.Add(new StringContent(mailgunRequest.Body), "text");
            }
            else
            {
                throw new Exception("Both Body and Template can not be null.");
            }

            if (mailgunRequest.AttachmentLocations != null)
            {
                foreach (var pair in mailgunRequest.AttachmentLocations)
                {
                    Stream stream = await client.GetStreamAsync(pair.Value);

                    formContent.Add(new StreamContent(stream), "attachment", pair.Key);
                }
            }

            string mailgunEndpoint = Runner.StartupValueOf <string>(CommonProperties.Url);

            HttpResponseMessage message = await client.PostAsync(mailgunEndpoint, formContent);

            return(message.IsSuccessStatusCode ?
                   new XchangeFile(await message.Content.ReadAsStringAsync())
                : new XchangeFile(await message.Content.ReadAsStringAsync(), null, true));
        }
예제 #6
0
        public async Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            StringWriter csvString = new StringWriter();

            using (var csv = new CsvWriter(csvString, CultureInfo.InvariantCulture))
            {
                csv.Configuration.Delimiter = Runner.StartupValueOf(CommonProperties.FieldsDelimiter);

                JToken jToken = JObject.Parse(xchangeFile.Data);
                var    doc    = jToken.SelectToken(Runner.StartupValueOf(CommonProperties.TargetPath)).ToString();

                if (!doc.StartsWith("["))
                {
                    doc = "[" + doc + "]";
                }

                var     jArray = JArray.Parse(doc);
                JObject header = (JObject)(jArray).First();

                foreach (JProperty prop in header.Properties())
                {
                    csv.WriteField(prop.Name);
                }
                csv.NextRecord();


                foreach (JObject item in jArray)
                {
                    var props1 = item.Properties();
                    foreach (JProperty prop in props1)
                    {
                        csv.WriteField(prop.Value.ToString());
                    }
                    csv.NextRecord();
                }
            }

            return(new XchangeFile(csvString.ToString(), xchangeFile.Filename));
        }
예제 #7
0
        public async Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            var options = new Options();

            var client = new HttpClient();

            if (options.AuthType == "ApiKey")
            {
                client.DefaultRequestHeaders.Add("ApiKey", options.ApiKey);
            }
            else if (options.AuthType == "Bearer")
            {
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", options.LoginPassword);
            }
            else if (options.AuthType == "Login")
            {
                var loginJson = JsonConvert.SerializeObject(new UserLoginModel()
                {
                    Email    = options.LoginUsername,
                    Password = options.LoginPassword
                });

                var loginResponse = await client.PostAsync(new Uri(options.LoginUrl), new StringContent(loginJson, Encoding.UTF8, "application/json"));

                loginResponse.EnsureSuccessStatusCode();

                if (loginResponse.StatusCode == HttpStatusCode.OK)
                {
                    var rs = await loginResponse.Content.ReadAsStringAsync();

                    LoginResponse rsDeserialized = JsonConvert.DeserializeObject <LoginResponse>(rs);
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer", rsDeserialized.Jwt);
                }
                else
                {
                    throw new Exception(loginResponse.StatusCode.ToString());
                }
            }

            HttpContent content;

            switch (options.ContentType.ToLower())
            {
            case "application/x-www-form-urlencoded":
                content = new FormUrlEncodedContent(JsonConvert.DeserializeObject <Dictionary <string, string> >(xchangeFile.Data));
                break;

            case "multipart/form-data":
                MultipartFormDataContent multipartTmp = new MultipartFormDataContent();
                byte[] fileContent = Encoding.UTF8.GetBytes(xchangeFile.Data);
                multipartTmp.Add(new ByteArrayContent(fileContent), "file", xchangeFile.Filename ?? "file");
                content = multipartTmp;
                break;

            case "application/json":
                content = new StringContent(xchangeFile.Data, Encoding.UTF8, "application/json");
                break;

            default:
                content = new StringContent(xchangeFile.Data, Encoding.UTF8, options.ContentType);
                break;
            }

            Uri uri = null;

            if (!string.IsNullOrEmpty(xchangeFile.Data) && options.Url.Contains("{{"))
            {
                string   templateData            = Runner.StartupValueOf(CommonProperties.Url);
                Template parsedTemplate          = Template.Parse(templateData);
                IDictionary <string, object> obj =
                    JsonConvert.DeserializeObject <IDictionary <string, object> >(xchangeFile.Data, new DictionaryConverter());
                Hash jsonHash = Hash.FromDictionary(obj);
                uri = new Uri(parsedTemplate.Render(jsonHash));
            }
            else
            {
                uri = new Uri(options.Url);
            }

            var request = new HttpRequestMessage
            {
                RequestUri = uri,
                Method     = HttpMethodFromString(options.Verb),
                Content    = content,
            };

            var headers = options.Headers?.Split(',').Select(h =>
            {
                var split = h.Split(':');
                return(new KeyValuePair <string, string>(split[0], split[1]));
            });

            if (headers != null)
            {
                foreach (var keyValuePair in headers)
                {
                    request.Headers.Add(keyValuePair.Key, keyValuePair.Value);
                }
            }

            var response = await client.SendAsync(request);

            if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 500)
            {
                var resp = await response.Content.ReadAsStringAsync();

                return((int)response.StatusCode < 400 ?
                       new XchangeFile(resp) :
                       new XchangeFile(resp, badData: true));
            }

            throw new Exception(response.StatusCode.ToString());



            //if (response.IsSuccessStatusCode)
            //{
            //    var resp = await response.Content.ReadAsStringAsync();
            //    return new XchangeFile(resp);
            //}
            //else
            //{
            //    throw new Exception(response.StatusCode.ToString());
            //}
        }
예제 #8
0
        public async Task <XchangeFile> Handle(XchangeFile xchangeFile)
        {
            var request = JsonConvert.DeserializeObject <EmailRequest>(xchangeFile.Data);

            var client = new SendGridClient(Runner.StartupValueOf <string>(CommonProperties.ApiKey));

            var msg = new SendGridMessage()
            {
                From             = new EmailAddress(request.From),
                Subject          = request.Subject,
                TrackingSettings = new TrackingSettings
                {
                    ClickTracking = new ClickTracking {
                        Enable = false
                    }
                },
            };

            msg.AddTo(new EmailAddress(request.To));

            if (request.Template != null)
            {
                msg.SetTemplateId(request.Template);
                msg.SetTemplateData(request.TemplateVariables);
            }
            else if (request.Body != null)
            {
                msg.HtmlContent      = request.Body;
                msg.PlainTextContent = request.Body;
            }
            else
            {
                throw new Exception("Both Body and Template can not be null.");
            }


            if (request.AttachmentLocations != null)
            {
                var attachments = new List <Attachment>();
                foreach (var(key, value) in request.AttachmentLocations)
                {
                    var fileBytes = await GetFileBytes(value);

                    attachments.Add(new Attachment
                    {
                        Content  = Convert.ToBase64String(fileBytes, 0, fileBytes.Length),
                        Filename = key,
                    });
                }

                msg.Attachments = attachments;
            }

            var response = await client.SendEmailAsync(msg);

            if (response.StatusCode < HttpStatusCode.BadRequest)
            {
                return(new XchangeFile(response.StatusCode.ToString()));
            }

            throw new Exception(response.StatusCode.ToString());
        }