Esempio n. 1
0
        private void Broker_CommandReceived(object sender, CommandReceivedEventArgs e)
        {
            var client = sender as IClient;

            // do lazy initialization of images so we dont slowdown startup for a stupid plugin
            if (_images.Count == 0)
            {
                var web = new HtmlWeb();
                var doc = web.Load("http://www.textfiles.com/underconstruction/");

                var imageNodes = doc.DocumentNode.SelectNodes("//img/@src");

                _images = (from image in imageNodes select image.GetAttributeValue("src", "help")).ToList();
            }

            var imgName = _images[_random.Next(_images.Count)];
            var imgUrl  = $"{baseUrl}{imgName}";

            if (client?.InlineOrOembedSupported == true)
            {
                var img = new ImageAttachment()
                {
                    Name       = "UNDERCONSTRUCTION.gif",
                    DataStream = _webClient.OpenRead(imgUrl)
                };
                e.ReplyTarget.Send(String.Empty, img);
            }
            else
            {
                e.ReplyTarget.Send(imgUrl);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Shows the image attachment, asynchronously.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns>
        /// The completion task.
        /// </returns>
        public async Task ShowImageAttachmentAsync(ImageAttachment target)
        {
            target.ThrowIfNull(nameof(target));

            bool error = false;

            try
            {
                IStorageFile file = await target.LoadAsync();

                LauncherOptions options = new LauncherOptions();
                options.DesiredRemainingView = ViewSizePreference.UseMore;
                options.TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe";
                bool result = await Launcher.LaunchFileAsync(file, options);

                if (!result)
                {
                    options = new LauncherOptions();
                    options.DisplayApplicationPicker = true;
                    error = !await Launcher.LaunchFileAsync(file, options);
                }
            }
            catch (Exception exception)
            {
                error = true;
                Logger.Instance.LogException(exception);
            }

            if (error)
            {
                MessageDialog dialog     = new MessageDialog("Unable to open attachment.", "Attachment Error");
                var           dialogTask = dialog.ShowAsync();
            }
        }
Esempio n. 3
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var areaPath       = HttpContext.Current.Request.Params["areaPath"].ToString(CultureInfo.InvariantCulture);
                var wuYeYongTu     = HttpContext.Current.Request.Params["wuYeYongTu"].ToString(CultureInfo.InvariantCulture);
                var wuYeBianHao    = HttpContext.Current.Request.Params["wuYeBianHao"].ToString(CultureInfo.InvariantCulture);
                var wuYeMingCheng  = HttpContext.Current.Request.Params["wuYeMingCheng"].ToString(CultureInfo.InvariantCulture);
                var zhaoPianLeiXin = HttpContext.Current.Request.Params["zhaoPianLeiXin"].ToString(CultureInfo.InvariantCulture);
                //var importDataType = HttpContext.Current.Request.Params["importDataType"].ToString(CultureInfo.InvariantCulture);

                string shi = GetCity(areaPath);
                for (int i = 0; i < context.Request.Files.Count; ++i)
                {
                    HttpPostedFile file = context.Request.Files[i];
                    if (file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName))
                    {
                        continue;
                    }
                    string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                    //string fileFullName = HttpContext.Current.Server.MapPath(filePath + "/" + fileName);
                    //file.SaveAs(fileFullName);
                    var imageAttachment =
                        new ImageAttachment(GetFilePath(ChinesePinYin.GetPinYin(shi),
                                                        ChinesePinYin.GetPinYin(wuYeYongTu), GetZhaoPianBaseFolder(), wuYeBianHao));


                    string url = GetUrl(ChinesePinYin.GetPinYin(shi), ChinesePinYin.GetPinYin(wuYeYongTu), wuYeBianHao,
                                        GetZhaoPianMuLu(), fileName);

                    string imageFileFullPath = imageAttachment.GetFileName(fileName);

                    var img = new WebImage(file.InputStream);
                    SetImageDirection(img);
                    img.Save(imageFileFullPath);
                    SaveImageFilePathToDb(wuYeYongTu, shi, wuYeBianHao, wuYeMingCheng, zhaoPianLeiXin, imageFileFullPath,
                                          url, fileName, areaPath, img.GetBytes());

                    HttpContext.Current.Response.ContentType = "application/json";

                    var json = new JObject {
                        { "fileName", fileName }
                    };
                    HttpContext.Current.Response.Write(json.ToString());

                    context.Response.Flush();
                }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = 500;
                context.Response.Write(ex.Message);
                context.Response.End();
            }
            finally
            {
                context.Response.End();
            }
        }
        public ImageAttachmentView(ImageAttachment Source)
        {
            InitializeComponent();

            DataContext = Source;

            if (Source.MaxHeight <= 1) return;
            MaxHeight = Source.MaxHeight;
            MaxWidth = Source.MaxWidth;
        }
Esempio n. 5
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>
        /// The object value.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var result     = default(Attachment);
            var attachment = JObject.Load(reader);
            var type       = (attachment["type"] as JValue).Value.ToString();

            switch (type)
            {
            case "image":
                result = new ImageAttachment();
                break;

            case "audio":
                result = new AudioAttachment();
                break;

            case "video":
                result = new VideoAttachment();
                break;

            case "file":
                result = new FileAttachment();
                break;

            case "location":
                result = new LocationAttachment();
                break;

            case "fallback":
                result = new FallbackAttachment();
                break;

            case "template":
                var templateType = (attachment["payload"]["template_type"] as JValue).Value.ToString();
                switch (templateType)
                {
                case "generic":
                    result = new GenericTemplateAttachment();
                    break;

                case "button":
                    result = new ButtonTemplateAttachment();
                    break;

                case "receipt":
                    result = new ReceiptTemplateAttachment();
                    break;
                }
                break;
            }
            serializer.Populate(attachment.CreateReader(), result);

            return(result);
        }
Esempio n. 6
0
        /// <summary>
        /// Handles the Click event of the ImageAttachment control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Windows.UI.Xaml.Controls.ItemClickEventArgs" /> instance containing the event data.</param>
        private async void ImageAttachment_Click(object sender, ItemClickEventArgs e)
        {
            Frame           frame      = (Frame)Window.Current.Content;
            MainPage        page       = (MainPage)frame.Content;
            ImageAttachment attachment = (ImageAttachment)e.ClickedItem;

            if (!attachment.IsBusy)
            {
                await page.ShowImageAttachmentAsync(attachment);
            }
        }
Esempio n. 7
0
        public async Task DeleteSingleFile(ImageAttachment file)
        {
            try
            {
                await filesClient.Delete(file.GetPath(), file.Name);

                imageRepository.Delete(file.Id);
                imageRepository.Save();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"Exception when deleting file /{file.GetPath()}/{file.Name}");
            }
        }
Esempio n. 8
0
        public async Task GetThumbnail(ImageAttachment file)
        {
            try
            {
                file.Thumbnail =
                    await filesClient.DownloadThumbnail($"{file.GetPath()}", file.Name);

                imageRepository.Update(file);
                imageRepository.Save();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Exception when creating thumbnail");
            }
        }
Esempio n. 9
0
        public ActionResult ImageUploadClick(string areaPath, string wuYeYongTu, string wuYeBianHao,
                                             string wuYeMingCheng, string zhaoPianLeiXin, string importDataType)
        {
            var result          = new DirectResult();
            var fileUploadField = this.GetCmp <FileUploadField>("fileUploadField");

            if (fileUploadField.HasFile)
            {
                //string strFileName = Path.GetExtension(fileUploadField.PostedFile.FileName).ToUpper();//获取文件后缀
                //if (!(strFileName == ".BMP" || strFileName == ".GIF" || strFileName == ".JPG"))
                //{
                //    result.IsUpload = true;
                //    X.Msg.Show(MessageBoxErrorFormatConfig());
                //}
                try
                {
                    string shi            = GetCity(areaPath).Description;
                    string postedFileName = GetPostedFileName(fileUploadField.PostedFile.FileName);
                    postedFileName = ChinesePinYin.GetPinYin(postedFileName);
                    //wuYeYongTu = ChinesePinYin.GetPinYin(wuYeYongTu);
                    var imageAttachment =
                        new ImageAttachment(GetFilePath(ChinesePinYin.GetPinYin(shi),
                                                        ChinesePinYin.GetPinYin(wuYeYongTu), GetZhaoPianBaseFolder(), wuYeBianHao));
                    string imageFileFullPath = imageAttachment.GetFileName(postedFileName);
                    var    img = new WebImage(fileUploadField.PostedFile.InputStream);
                    SetImageDirection(img);
                    img.Save(imageFileFullPath);

                    //string url = GetUrl(areaPath, wuYeYongTu, wuYeMingCheng, zhaoPianLeiXin, postedFileName);
                    string url = GetUrl(ChinesePinYin.GetPinYin(shi), ChinesePinYin.GetPinYin(wuYeYongTu), wuYeBianHao,
                                        GetZhaoPianMuLu(), postedFileName);
                    SaveImageFilePathToDb(wuYeYongTu, shi, wuYeBianHao, wuYeMingCheng, zhaoPianLeiXin, imageFileFullPath,
                                          url, postedFileName, areaPath, img.GetBytes());

                    X.Msg.Show(MessageBoxConfig(Success, TiShi, MessageBox.Icon.INFO));
                }
                catch (Exception ex)
                {
                    X.Msg.Show(MessageBoxConfig(ex.ToString(), Fail, MessageBox.Icon.INFO));
                }
            }
            else
            {
                result.IsUpload = true;
                X.Msg.Show(MessageBoxConfig(NoFile, TiShi, MessageBox.Icon.ERROR));
            }
            return(result);
        }
Esempio n. 10
0
        private async void LoadDownloadImageFile(string sImageName)
        {
            var webClient = new WebClient();


            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //string localFilename = "AudioCheck.mp3";

            string localPath = Path.Combine(documentsPath, sImageName);

            await webClient.DownloadFileTaskAsync(
                new Uri("http://service.jewelxchange.com/chatimages/Image/" + sImageName),
                localPath);

            ImageAttachment.SetBackgroundImage(UIImage.FromFile(sImageName), UIControlState.Normal);
        }
Esempio n. 11
0
        public async Task GetLinkToFile(ImageAttachment image)
        {
            //TODO Message = "There is already an open DataReader associated with this Command which must be closed first."
            //TODO need to aad getting links from exisiting list if exception occurs
            //TODO add MultipleActiveResultSets=true and think further
            var imagePath = $"{image.GetPath()}/{image.Name}";

            try
            {
                var url = await urlClient.CreateLinkToFileWithMissingBasePath(imagePath);

                image.Url = TurnIntoSourceLink(url);
                imageRepository.Update(image);
                imageRepository.Save();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"Exception when generating link for file: {imagePath}");
            }
        }
Esempio n. 12
0
        public ActionResult ZhuanYeRenShiUploadClick(string areaPath)
        {
            var result = new DirectResult();

            var fileUploadField = this.GetCmp <FileUploadField>("fileUploadField");

            if (fileUploadField.HasFile)
            {
                try
                {
                    var    shi            = GetCity(areaPath).Description;
                    string postedFileName = GetPostedFileName(fileUploadField.PostedFile.FileName);
                    postedFileName = ChinesePinYin.GetPinYin(postedFileName);
                    const string type     = "zhuanyerenshi";
                    var          folder   = Path.Combine(GetZhaoPianMuLu(), ChinesePinYin.GetPinYin(shi), type);
                    var          fileName = Path.GetFileNameWithoutExtension(postedFileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(postedFileName);

                    var    imageAttachment   = new ImageAttachment(Server.MapPath("~/" + folder));
                    string imageFileFullPath = imageAttachment.GetFileName(fileName);
                    var    img = new WebImage(fileUploadField.PostedFile.InputStream);
                    img.Save(imageFileFullPath);
                    X.Msg.Show(MessageBoxConfig(Success, TiShi, MessageBox.Icon.INFO));
                    X.GetCmp <TextField>("ZhaoPian").Value = imageFileFullPath;

                    var url = WebPathUtility.Path.ToURI(imageFileFullPath);// "/" + Path.Combine(folder, fileName).Replace("\\", "/");
                    X.GetCmp <Image>("ZhaoPianImage").ImageUrl = url;
                    X.GetCmp <Hidden>("ZhaoPianUrl").Value     = url;
                }
                catch (Exception ex)
                {
                    X.Msg.Show(MessageBoxConfig(ex.ToString(), Fail, MessageBox.Icon.INFO));
                }
            }
            else
            {
                result.IsUpload = true;
                X.Msg.Show(MessageBoxConfig(NoFile, TiShi, MessageBox.Icon.ERROR));
            }
            return(result);
        }
Esempio n. 13
0
        public async Task <string> Upload(ImageAttachment image)
        {
            using (HttpClient client = new HttpClient())
            {
                MultipartFormDataContent content = new MultipartFormDataContent();
                content.Add(new ByteArrayContent(image.Data), "image");

                client.DefaultRequestHeaders.Add("Authorization", "Client-ID " + _config.GetValue <string>("imgur_client_id"));

                HttpResponseMessage response = await client.PostAsync("https://api.imgur.com/3/image", content);

                string jsonSource = await response.Content.ReadAsStringAsync();

                JObject jsonObj = JsonConvert.DeserializeObject <JObject>(jsonSource);

                if ((bool)jsonObj.GetValue("success"))
                {
                    return(jsonObj.SelectToken("data.link").ToString());
                }
                return(null);
            }
        }
Esempio n. 14
0
        public ActionResult XiTongImageUploadClick(string areaPath, string zhaoPianLeiXin, string importDataType)
        {
            var result = new DirectResult();

            var fileUploadField = this.GetCmp <FileUploadField>("fileUploadField");

            if (fileUploadField.HasFile)
            {
                try
                {
                    var    shi            = GetCity(areaPath).Description;
                    string postedFileName = GetPostedFileName(fileUploadField.PostedFile.FileName);
                    postedFileName = ChinesePinYin.GetPinYin(postedFileName);
                    const string type            = "system";
                    var          imageAttachment =
                        new ImageAttachment(GetFilePath(ChinesePinYin.GetPinYin(shi), type, GetZhaoPianBaseFolder()));
                    string imageFileFullPath = imageAttachment.GetFileName(postedFileName);
                    var    img = new WebImage(fileUploadField.PostedFile.InputStream);
                    SetImageDirection(img);
                    img.Save(imageFileFullPath);
                    string url = GetUrl(ChinesePinYin.GetPinYin(shi), type, GetZhaoPianMuLu(), postedFileName);
                    SaveXiTongImageFilePathToDb(shi, zhaoPianLeiXin, imageFileFullPath,
                                                url, postedFileName, areaPath);

                    X.Msg.Show(MessageBoxConfig(Success, TiShi, MessageBox.Icon.INFO));
                }
                catch (Exception ex)
                {
                    X.Msg.Show(MessageBoxConfig(ex.ToString(), Fail, MessageBox.Icon.INFO));
                }
            }
            else
            {
                result.IsUpload = true;
                X.Msg.Show(MessageBoxConfig(NoFile, TiShi, MessageBox.Icon.ERROR));
            }
            return(result);
        }
Esempio n. 15
0
        private void AddAttachment(AttachmentViewModel attachment, Post parent)
        {
            Attachment attachmentToAdd;

            switch (Enum.Parse <FileType>(attachment.Type))
            {
            case FileType.image:
                attachmentToAdd = new ImageAttachment
                {
                    Parent    = parent,
                    Owner     = attachment.Owner,
                    Name      = Guid.ParseExact(attachment.Name, "D"),
                    Extension = Enum.Parse <FilenameExtension>(attachment.Extension),
                };
                break;

            default:
                return;
            }

            context.Attachments.Add(attachmentToAdd);
            context.SaveChanges();
        }
Esempio n. 16
0
 public static string GetPath(this ImageAttachment image)
 {
     if (image.ImageAttachmentTypeId == ImageTypes.Detection)
     {
         return($"{nameof(ImageTypes.Detection)}/{image.DetectionId}");
     }
     if (image.ImageAttachmentTypeId == ImageTypes.DetectionResult)
     {
         return($"{nameof(ImageTypes.DetectionResult)}/{image.DetectionResultId}");
     }
     if (image.ImageAttachmentTypeId == ImageTypes.Person)
     {
         return($"{nameof(ImageTypes.Person)}/{image.PersonId}");
     }
     if (image.ImageAttachmentTypeId == ImageTypes.Recognition)
     {
         return($"{nameof(ImageTypes.Recognition)}/{image.RecognitionId}");
     }
     if (image.ImageAttachmentTypeId == ImageTypes.Movement)
     {
         return($"{nameof(ImageTypes.Movement)}/{image.MovementId}");
     }
     throw new ArgumentException("Wrong value of ImageAttachmentTypeId");
 }
Esempio n. 17
0
        /// <summary>
        /// Gets the image attachment file, asynchronously.
        /// </summary>
        /// <param name="targetUrl">The target URL.</param>
        /// <param name="attachment">The attachment.</param>
        /// <returns>
        /// The image attachment file task.
        /// </returns>
        public async Task <IStorageFile> GetImageAttachmentFileAsync(string targetUrl, ImageAttachment attachment)
        {
            targetUrl.ThrowIfEmpty(nameof(targetUrl));
            attachment.ThrowIfNull(nameof(attachment));

            StorageFolder tempFolder  = ApplicationData.Current.TemporaryFolder;
            StorageFolder cacheFolder = await tempFolder.CreateFolderAsync("Cache", CreationCollisionOption.OpenIfExists);

            StorageFolder attachmentsFolder = await cacheFolder.CreateFolderAsync("Attachments", CreationCollisionOption.OpenIfExists);

            StorageFile attachmentFile = null;

            // use only the id since it's a safer name as otherwise there may be unsafe characters to prune?
            string id = string.Concat(attachment.Id.ToString(), Path.GetExtension(attachment.Name));

            try
            {
                attachmentFile = await attachmentsFolder.CreateFileAsync(id, CreationCollisionOption.FailIfExists);

                using (HttpResponseMessage response = await this.Client.GetAsync(targetUrl, HttpCompletionOption.ResponseContentRead))
                {
                    response.EnsureSuccessStatusCode();
                    using (Stream stream = await attachmentFile.OpenStreamForWriteAsync())
                    {
                        await response.Content.CopyToAsync(stream);
                    }
                }
            }
            catch (Exception e) when(e.HResult == -2147024713)
            {
                attachmentFile = await attachmentsFolder.GetFileAsync(id);
            }

            return(attachmentFile);
        }
 public async Task PostStatusUpdateAsync(IEnumerable <string> hosts, string text, ImageAttachment image = null)
 {
     await PostStatusUpdateAsync(hosts, text, new[] { image }.Where(x => x != null));
 }
Esempio n. 19
0
        /// <summary>
        /// Sends the attachment asynchronous.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public async Task <MessageResult> SendFileAttachmentAsync(string userId, Stream stream, string filename, string mimeType, string type = "file")
        {
            var attachment = (Attachment)null;

            switch (type)
            {
            case "image":
                attachment = new ImageAttachment();
                break;

            case "video":
                attachment = new VideoAttachment();
                break;

            case "audio":
                attachment = new AudioAttachment();
                break;

            default:
                attachment = new FileAttachment();
                break;
            }

            (attachment as Attachment <MediaPayload>).Payload.IsReusable = true;

            var result = new MessageResult();

            try
            {
                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);

                    using (var content = new MultipartFormDataContent())
                    {
                        var recipient = JsonConvert.SerializeObject(new Identity(userId));
                        var message   = JsonConvert.SerializeObject(new AttachmentMessage(attachment));

                        content.Add(new StringContent(recipient), "recipient");
                        content.Add(new StringContent(message), "message");

                        var fileContent = new StreamContent(stream);
                        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);

                        content.Add(fileContent, "filedata", filename);

                        using (var response = await client.PostAsync($"https://graph.facebook.com/v{_apiVersion}/me/messages?access_token={_accessToken}", content))
                        {
                            if (response.StatusCode != HttpStatusCode.OK &&
                                response.StatusCode != HttpStatusCode.BadRequest)
                            {
                                result.Success = false;
                                result.Error   = new ResultError
                                {
                                    Code         = -1,
                                    ErrorSubcode = (int)response.StatusCode,
                                    Message      = response.ReasonPhrase ?? response.StatusCode.ToString(),
                                };
                            }
                            else
                            {
                                var returnValue = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                                result.Error = CreateResultError(returnValue);
                                if (result.Error == null)
                                {
                                    result.RecipientId  = returnValue.Value <string>("recipient_id");
                                    result.MessageId    = returnValue.Value <string>("message_id");
                                    result.AttachmentId = returnValue.Value <string>("attachment_id");
                                    result.Success      = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex, result);
            }

            return(result);
        }
Esempio n. 20
0
        /// <summary>
        /// Sends the attachment asynchronous.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public async Task <MessageResult> SendAttachmentAsync(string userId, Stream stream, string filename, string type = "file")
        {
            var fileType       = string.Empty;
            var contenFilename = $"@/tmp/{filename}";
            var attachment     = (new FileAttachment() as Attachment);

            switch (type)
            {
            case "image":
                var ext = Path.GetExtension(filename).Replace(".", string.Empty);
                if (ext.ToLower() == "jpg")
                {
                    ext = "jpeg";
                }

                fileType       = $"image/{ext}";
                contenFilename = $"{contenFilename};type={fileType}";
                attachment     = new ImageAttachment();
                break;

            case "video":
                fileType       = "video/mp4";
                contenFilename = $"{contenFilename};type={fileType}";
                attachment     = new VideoAttachment();
                break;

            case "audio":
                fileType       = "audio/mp3";
                contenFilename = $"{contenFilename};type={fileType}";
                attachment     = new AudioAttachment();
                break;
            }

            var result = new MessageResult();

            try
            {
                using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        var recipient = JsonConvert.SerializeObject(new Identity(userId));
                        var message   = JsonConvert.SerializeObject(new AttachmentMessage(attachment));

                        content.Add(new StringContent(recipient), "recipient");
                        content.Add(new StringContent(message), "message");

                        var imageContent = new StreamContent(stream);
                        if (!string.IsNullOrWhiteSpace(fileType))
                        {
                            imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(fileType);
                        }

                        content.Add(imageContent, "filedata", contenFilename);

                        using (var response = await client.PostAsync($"https://graph.facebook.com/v{_apiVersion}/me/messages?access_token={AccessToken}", content))
                        {
                            var returnValue = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());

                            result.Error = CreateResultError(returnValue);
                            if (result.Error == null)
                            {
                                result.RecipientId = returnValue.Value <string>("recipient_id");
                                result.MessageId   = returnValue.Value <string>("message_id");
                                result.Success     = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex, result);
            }

            return(result);
        }
Esempio n. 21
0
 public Task PostStatusUpdateAsync(IEnumerable <string> hosts, string text, ImageAttachment image = null) => Task.CompletedTask;
Esempio n. 22
0
 public async Task PostStatusUpdateAsync(IEnumerable <string> hosts, string text, ImageAttachment image = null)
 {
     await Task.WhenAll(_sources.Select(x => x.PostStatusUpdateAsync(hosts, text, image)));
 }
        /// <summary>
        /// Parse the command line and return a configuration object for use by the program.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        internal static Configuration Parse(string[] args)
        {
            Configuration result = new Configuration();

            try
            {
                if (args.Length == 0)
                {
                    throw new ArgumentException();
                }

                ImageAttachment currentAttachment = null;

                for (int pos = 0; pos < args.Length; pos++)
                {
                    switch (args[pos++])
                    {
                    case "-from":
                        result.FromAddress = args[pos];
                        break;

                    case "-to":
                        result.ToAddress.Add(args[pos]);
                        break;

                    case "-host":
                        result.Host = args[pos];
                        break;

                    case "-port":
                        result.Port = Int32.Parse(args[pos]);
                        break;

                    case "-subject":
                        result.Subject = args[pos];
                        break;

                    case "-html":
                        result.HtmlFile = args[pos];
                        break;

                    case "-image":

                        if (currentAttachment != null)
                        {
                            result.ImageAttachments.Add(currentAttachment);
                        }

                        currentAttachment = new ImageAttachment();
                        pos--;
                        break;

                    case "-filePath":
                        currentAttachment.FilePath = args[pos];
                        break;

                    case "-mimeType":
                        currentAttachment.MimeType = args[pos];
                        break;

                    case "-identifier":
                        currentAttachment.Identifier = args[pos];
                        break;
                    }
                }

                if (currentAttachment != null)
                {
                    result.ImageAttachments.Add(currentAttachment);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Usage: ConsoleMail.exe");
                Console.WriteLine("-from fromAddress");
                Console.WriteLine("-to toAddress");
                Console.WriteLine("-host SMTP host");
                Console.WriteLine("-port SMTP port");
                Console.WriteLine("-subject mail subject");
                Console.WriteLine("-html container html file");
                Console.WriteLine("-image start a new image, do this once for each image you want to add");
                Console.WriteLine("       and follow with -filePath -mimeType -identifier for each image");
                Console.WriteLine("-filePath path to next image");
                Console.WriteLine("-mimeType mimetype of next image (i.e. image/jpeg)");
                Console.WriteLine("-identifier CID for next image");
                result = null;
            }

            return(result);
        }