UploadDataAsync() public method

public UploadDataAsync ( System address, byte data ) : void
address System
data byte
return void
Example #1
0
        private bool UploadRange(Range r)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers.Add("Content-Range",
                               "bytes " + r.pos.ToString() + "-" + (r.end - 1).ToString() + "/" + fileSize.ToString());

            byte[] data = new byte[r.Len()];
            fs.Seek(r.pos, SeekOrigin.Begin);
            int len = fs.Read(data, 0, (int)r.Len());

            if (len != r.Len())
            {
                throw new IOException("unable read expected size.");
            }

            client.Headers.Add("Content-MD5", CalcMD5Hex(data));


            client.UploadProgressChanged += new System.Net.UploadProgressChangedEventHandler(OnRangeUploadProgressChanged);
            client.UploadDataCompleted   += new System.Net.UploadDataCompletedEventHandler(OnRangeUploadDataCompleted);

            UploadInfo info = new UploadInfo();

            info.wc             = client;
            info.totalBytes     = len;
            info.uploadedBytes  = 0;
            uploadInfos[client] = info;

            client.UploadDataAsync(new Uri(uploadUrl), "POST", data, client);

            return(true);
        }
Example #2
0
        public string Upload(string imagePath)
        {
            m_Holder = null;

            GrabbieEngine.Instance.UploadNotificationSystem.UpdateStatus("Uploading", 0);

            var host = PropertyService.Get("Grabbie.FtpUploader.Host");
            var ftpPath = PropertyService.Get("Grabbie.FtpUploader.FtpPath");
            var userName = PropertyService.Get("Grabbie.FtpUploader.UserName");
            var password = PropertyService.Get("Grabbie.FtpUploader.Password");
            var httpPath = PropertyService.Get("Grabbie.FtpUploader.HttpPath");

            var webClient = new WebClient {
                Credentials = new NetworkCredential(userName, password)
            };

            webClient.UploadProgressChanged += webClient_UploadProgressChanged;
            webClient.UploadDataCompleted += webClient_UploadDataCompleted;

            var stream = File.OpenRead(imagePath);
            var buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Close();

            m_Uploading = true;

            webClient.UploadDataAsync(new Uri("ftp://" + host + ftpPath + Path.GetFileName(imagePath)), buffer);

            while (m_Uploading) Thread.Sleep(500);

            if (m_Holder != null)
                throw new WebException("Error during upload: " + m_Holder.Message, m_Holder);

            return httpPath + Path.GetFileName(imagePath);
        }
        public void CreateStationAsync(string musicId)
        {
            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("content-type", "text-xml");
                client.UploadDataCompleted += new UploadDataCompletedEventHandler(CreateStation_UploadDataCompleted);
                Uri uri = new Uri(String.Format(BASE_URL_LID, _rid, _lid, "createStation"));

                List<object> parameters = new List<object>();
                parameters.Add(GetTimestamp());
                parameters.Add(_authenticationToken);
                parameters.Add("mi" + musicId);
                parameters.Add(String.Empty);

                string xml = GetXml("station.createStation", parameters);
                string encryptedXml = EncryptionHelper.EncryptString(xml);
                client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml));
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
            }
        }
Example #4
0
        public void Process(Printer printer, string document)
        {
            // https://www.voipbuster.com/myaccount/sendsms.php?username=USERNAME&password=PASS&from=FROM&to=@nummer@&text=@SMS@
            var settingsObject = GetSettingsObject(printer.CustomPrinterData) as UrlPrinterSettings;
            if (settingsObject == null) return;
            var tokenChar = !string.IsNullOrEmpty(settingsObject.TokenChar) ? settingsObject.TokenChar : "@";
            var url = ReplaceValues(document, settingsObject.UrlFormat, tokenChar);
            if (url.Contains(tokenChar)) return;
            url = Uri.UnescapeDataString(url);

            var data = "";
            if (!string.IsNullOrEmpty(settingsObject.DataFormat))
            {
                data = ReplaceValues(document, settingsObject.DataFormat, tokenChar);
                if (data.Contains(tokenChar)) return;
                data = Uri.UnescapeDataString(data);
            }

            if (settingsObject.LiveMode)
            {
                var c = new WebClient();
                if (!string.IsNullOrEmpty(data))
                {
                    c.UploadDataAsync(new Uri(url), Encoding.GetEncoding(printer.CodePage).GetBytes(data));
                }
                else
                    c.DownloadDataAsync(new Uri(url));
            }
            else MessageBox.Show(url);
        }
Example #5
0
        /// <summary>Uploads data to the specified resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI to which the data should be uploaded.</param>
        /// <param name="method">The HTTP method that should be used to upload the data.</param>
        /// <param name="data">The data to upload.</param>
        /// <returns>A Task containing the data in the response from the upload.</returns>
        public static Task <byte[]> UploadDataTask(this WebClient webClient, Uri address, string method, byte [] data)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <byte[]>(address);

            // Setup the callback event handler
            UploadDataCompletedEventHandler handler = null;

            handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadDataCompleted -= handler);
            webClient.UploadDataCompleted += handler;

            // Start the async work
            try
            {
                webClient.UploadDataAsync(address, method, data, tcs);
            }
            catch (Exception exc)
            {
                // If something goes wrong kicking off the async work,
                // unregister the callback and cancel the created task
                webClient.UploadDataCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task that represents the async operation
            return(tcs.Task);
        }
 public void Notify(RelaxNotificationMessage relaxNotificationMessage)
 {
     var client = new WebClient();
     client.Headers.Add("Content-Type", "application/json");
     client.UploadDataAsync(new Uri(String.Format("{0}/{1}/{2}", ConfigurationManager.AppSettings["RelaxForTfs.WebServiceApi.BaseUrl"],"api", "messaging")),
                            "POST",
                            System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(relaxNotificationMessage)));
 }
Example #7
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }
Example #8
0
File: Logger.cs Project: oisy/scada
 public void Send(string fileName, string content)
 {
     using (var client = new WebClient())
     {
         // client.UploadDataCompleted += UploadDataCompleted;
         byte[] msgBytes = BuildMessage(fileName, content);
         client.UploadDataAsync(loggerApi, "POST", msgBytes, client);
     }
 }
Example #9
0
		private void GetJson(string url, string post, object token)
		{
			var client = new WebClient();
			client.UploadDataCompleted += client_UploadDataCompleted_json;
			client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
			client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			client.Headers.Add("Referer", "http://tool.17mon.cn/ip.php");
			client.Headers.Add("X-Requested-With", "XMLHttpRequest");
			var postString = post;
			var postData = Encoding.Default.GetBytes(postString);
			client.UploadDataAsync(new Uri(url), "POST", postData, token);
			//var srcString = Encoding.Default.GetString(await responseData);
			//return JObject.Parse(srcString);
		}
Example #10
0
		private void GetHtml(string url, string post, object token)
		{
			var client = new WebClient();
			client.UploadDataCompleted += client_UploadDataCompleted_html;
			//client.Headers.Add("Accept-Language", "zh-CN");
			client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
			client.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			client.Headers.Add("Referer", "http://tool.17mon.cn/ip.php");
			var postString = post;
			var postData = Encoding.Default.GetBytes(postString);
			client.UploadDataAsync(new Uri(url), "POST", postData, token);
			//var srcString = Encoding.UTF8.GetString(responseData);
			//return srcString;
		}
    //API PUT request to update the save data
    public void saveSaveData(UserInfo update)
    {
        string json = JsonUtility.ToJson(update);

        byte[] data = Encoding.ASCII.GetBytes(json);
        Uri    uri  = new Uri(string.Format("http://localhost:3000/users/username&{0}", update.username));

        Debug.Log(json);

        using (var client = new System.Net.WebClient())
        {
            client.Headers.Add("Content-Type", "application/json");
            client.UploadDataAsync(uri, "PUT", data);                   //May halt things, not sure if it properly implements asynchronity
        }
    }
Example #12
0
        public void CreatePackage(string apiKey, Stream packageStream, IObserver<int> progressObserver, IPackageMetadata metadata = null)
        {
            var state = new PublishState {
                PublishKey = apiKey,
                PackageMetadata = metadata,
                ProgressObserver = progressObserver
            };

            var url = new Uri(String.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/nupkg", _baseGalleryServerUrl, CreatePackageService, apiKey));

            WebClient client = new WebClient();
            client.Proxy = _cachedProxy;
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
            client.Headers[HttpRequestHeader.UserAgent] = _userAgent;
            client.UploadProgressChanged += OnUploadProgressChanged;
            client.UploadDataCompleted += OnCreatePackageCompleted;
            client.UploadDataAsync(url, "POST", packageStream.ReadAllBytes(), state);
        }
Example #13
0
        static void SendPing(string vehicle)
        {
            var client = new System.Net.WebClient();

            try
            {
                var pingVehicleTo = new Uri(string.Format(PingMonitorAddress, vehicle));
                client.UploadDataAsync(pingVehicleTo, "PUT", new byte[0]);
            }
            catch (WebException ex)
            {
                Console.WriteLine($"Failed to send ping for vehicle: {vehicle}");
            }
            finally
            {
                client.Dispose();
            }
        }
        /// <summary>
        /// Uploads a <see cref="byte"/> array to the specified resource.
        /// </summary>
        /// <param name="client">The object that uploads to the resource.</param>
        /// <param name="address">The URI of the resource to receive the data.</param>
        /// <param name="method">The HTTP method used to send data to the resource.  If <see langword="null"/>, the default is POST for HTTP and STOR for FTP.</param>
        /// <param name="data">The bytes to upload to the resource.</param>
        /// <returns>An observable that caches the response from the server and replays it to observers.</returns>
        public static IObservable <byte[]> UploadDataObservable(
            this WebClient client,
            Uri address,
            string method,
            byte[] data)
        {
            Contract.Requires(client != null);
            Contract.Requires(address != null);
            Contract.Requires(data != null);
            Contract.Ensures(Contract.Result <IObservable <byte[]> >() != null);

            return(Observable2.FromEventBasedAsyncPattern <UploadDataCompletedEventHandler, UploadDataCompletedEventArgs>(
                       handler => handler.Invoke,
                       handler => client.UploadDataCompleted += handler,
                       handler => client.UploadDataCompleted -= handler,
                       token => client.UploadDataAsync(address, method, data, token),
                       client.CancelAsync)
                   .Select(e => e.EventArgs.Result));
        }
        private void btnUploadAsync_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] content  = GetByteArray();
                string filename = Path.GetFileName(openFileDialog1.FileName);

                System.Net.WebClient webClient = new System.Net.WebClient();
                System.Uri           uri       = new Uri("http://SP/DNATestLibrary/" + filename);

                webClient.UploadDataCompleted += new UploadDataCompletedEventHandler(webClient_UploadDataCompleted);
                webClient.Credentials          = new NetworkCredential("username", "pwd", "domain");

                webClient.UploadDataAsync(uri, "PUT", content);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public static void AsyncSendRequest(string url, string postData)
        {
            var webClient = new WebClient();
            webClient.Encoding = Encoding.GetEncoding(REQUEST_ENCODING);
            webClient.Headers.Add("Content-Type", CONTENT_TYPE);
            webClient.Headers.Add("User-Agent", USER_AGENT);
            //webClient.Headers.Add("Content-Length", postData.Length.ToString());

            byte[] sendData = Encoding.GetEncoding(REQUEST_ENCODING).GetBytes(postData);
            webClient.UploadDataAsync(new Uri(url), "POST", sendData);

            webClient.UploadDataCompleted += (sender, args) =>
                                                 {

                                                     if (_firstRequestTime == DateTime.MinValue)
                                                         _firstRequestTime = DateTime.Now;
                                                     _lastRequestTime = DateTime.Now;
                                                     _requestCounts++;
                                                     Console.WriteLine(CaculateSpentTime());
                                                 };
        }
Example #17
0
        public void UploadDocumentAsync(string fileUpArchivo, string remoteFile)
        {
            // Leemos el archivo
            FileStream fs = new FileStream(fileUpArchivo, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            //Subimos el archivo de manera asíncrona
            WebClient wc = new WebClient();
            wc.Credentials = System.Net.CredentialCache.DefaultCredentials;

            //Manejador de evento para obtener información sobre el progreso
            wc.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressChanged);
            //Manejador de evento para saber cuando se completo la subida del archivo
            wc.UploadDataCompleted += new UploadDataCompletedEventHandler(UploadDataCompleted);
            //Iniciamos la subida del archivo asincronamente
            wc.UploadDataAsync(new Uri(remoteFile), "PUT", buffer);
            //Podriamos cancelar la carga del archivo
            //wc.CancelAsync();
        }
Example #18
0
        /// <summary>Uploads data to the specified resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI to which the data should be uploaded.</param>
        /// <param name="method">The HTTP method that should be used to upload the data.</param>
        /// <param name="data">The data to upload.</param>
        /// <returns>A Task containing the data in the response from the upload.</returns>
        public static Task <byte[]> UploadDataTask(this WebClient webClient, Uri address, string method, byte[] data)
        {
            TaskCompletionSource <byte[]>   tcs     = new TaskCompletionSource <byte[]>(address);
            UploadDataCompletedEventHandler handler = null;

            handler = delegate(object sender, UploadDataCompletedEventArgs e) {
                EAPCommon.HandleCompletion <byte[]>(tcs, e, () => e.Result, delegate {
                    webClient.UploadDataCompleted -= handler;
                });
            };
            webClient.UploadDataCompleted += handler;
            try
            {
                webClient.UploadDataAsync(address, method, data, tcs);
            }
            catch (Exception exception)
            {
                webClient.UploadDataCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Example #19
0
        /// <summary>
        /// Upload byte array content asynchron.
        /// Progress is signaled via UploadProgressChanged and UploadDataCompleted event.
        /// </summary>
        /// <param name="data">Byte array</param>
        public void UploadDataEvents(byte[] data)
        {
            lock (_syncRootAsync)
            {
                // Abort other operation.
                if (_gettAsync != null)
                {
                    _gettAsync.DownloadDataCompleted -= Gett_DownloadDataCompleted;
                    _gettAsync.DownloadFileCompleted -= Gett_DownloadFileCompleted;
                    _gettAsync.DownloadProgressChanged -= Gett_DownloadProgressChanged;
                    _gettAsync.UploadDataCompleted -= Gett_UploadDataCompleted;
                    _gettAsync.UploadFileCompleted -= Gett_UploadFileCompleted;
                    _gettAsync.UploadProgressChanged -= Gett_UploadProgressChanged;

                    if (_gettAsync.IsBusy)
                        _gettAsync.CancelAsync();
                }

                // GET request
                _gettAsync = new WebClient();
                _gettAsync.UploadDataCompleted += Gett_UploadDataCompleted;
                _gettAsync.UploadProgressChanged += Gett_UploadProgressChanged;

                _gettAsync.UploadDataAsync(new Uri(_gettFileInfo.Upload.PutUrl), "PUT", data);
            }
        }
Example #20
0
        void UploadImage(BitmapSource img_wpf)
        {
            System.Drawing.Image img = ImageWpfToGDI(img_wpf);
            string UID = Guid.NewGuid().ToString().Replace("-", "");
            int lastprogress = 0;

            MemoryStream ImageStream = new MemoryStream();
            img.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Png);

            byte[] image = BlazeGames.IM.Client.Core.Utilities.Compress(ImageStream.ToArray());
            if (image.Length > 10485760)
            {
                NotificationWindow.ShowNotification("Upload Failed", "The image you are trying to upload is larger than 10MB when compressed.");
                return;
            }

            HandleMessage(App.FullName, @"<Span xmlns=""default"">
            <Grid Name=""upload_" + UID + @"_control"" Background=""Transparent"" Width=""400"" Height=""100"">
            <Grid.ColumnDefinitions>
            <ColumnDefinition Width=""100""/>
            <ColumnDefinition Width=""*""/>
            </Grid.ColumnDefinitions>
            <ProgressBar Name=""upload_" + UID + @"_progress"" HorizontalAlignment=""Stretch"" Height=""20"" Margin=""15,42,15,15"" VerticalAlignment=""Center"" Grid.Column=""1""/>
            <Image Name=""upload_" + UID + @"_thumbnail"" Grid.Column=""0"" HorizontalAlignment=""Stretch"" Margin=""15"" VerticalAlignment=""Stretch""/>
            <Label Name=""upload_" + UID + @"_filename"" Content=""UploadedImage.png"" Grid.Column=""1"" Margin=""15,15,15,40"" VerticalAlignment=""Center"" FontSize=""18"" Foreground=""#FF363636""  />
            <Label Name=""upload_" + UID + @"_progresstxt"" Content=""Uploading (0%)..."" Grid.Column=""1"" Margin=""15,42,15,15"" VerticalAlignment=""Center"" FontSize=""14"" Foreground=""#FF5F5F5F""  />
            </Grid>
            <LineBreak />
            </Span>");
            UpdateUploadThumbnail(UID, img_wpf);

            using (WebClient wc = new WebClient())
            {
                Uploads.Add(UID);

                wc.UploadDataCompleted += (sender, e) =>
                    {
                        Uploads.Remove(UID);
                        string Url = Encoding.Default.GetString(e.Result);
                        UpdateUploadComplete(UID, Url);

                        ChattingWith.SendMessage(@"<Span xmlns=""default"">
            <Grid Name=""upload_" + UID + @"_control"" Cursor=""Hand"" Background=""Transparent"" Width=""400"" Height=""100"" Tag=""" + Url + @""">
            <Grid.ColumnDefinitions>
            <ColumnDefinition Width=""100""/>
            <ColumnDefinition Width=""*""/>
            </Grid.ColumnDefinitions>
            <Image Name=""upload_" + UID + @"_thumbnail"" Grid.Column=""0"" HorizontalAlignment=""Stretch"" Margin=""15"" VerticalAlignment=""Stretch"" Source=""" + Url + @"""/>
            <Label Name=""upload_" + UID + @"_filename"" Content=""UploadedImage.png"" Grid.Column=""1"" Margin=""15,15,15,40"" VerticalAlignment=""Center"" FontSize=""18"" Foreground=""#FF363636""  />
            <Label Name=""upload_" + UID + @"_progresstxt"" Content=""" + Url + @""" Grid.Column=""1"" Margin=""15,42,15,15"" VerticalAlignment=""Center"" FontSize=""14"" Foreground=""#FF5F5F5F""  />
            </Grid>
            <LineBreak />
            </Span>");
                    };

                wc.UploadProgressChanged += (sender, e) =>
                    {

                        if (lastprogress != e.ProgressPercentage)
                        {
                            UpdateUploadProgress(UID, (e.ProgressPercentage * 2) - 1);
                        }

                        lastprogress = e.ProgressPercentage;
                    };

                wc.UploadDataAsync(new Uri("http://blaze-games.com/files/upload/&file_name=UploadedImage.png"), image);
            }
        }
Example #21
0
        private void rtf_DragDrop(object s, DragEventArgs ev)
        {
            if (ev.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] docPath = (string[])ev.Data.GetData(DataFormats.FileDrop);
                foreach (string file in docPath)
                {
                    FileInfo fi = new FileInfo(file);
                    if(!fi.Exists)
                        continue;

                    bool IsImage = (fi.Extension == ".png" || fi.Extension == ".jpg" || fi.Extension == ".gif");

                    string icon = "http://blaze-games.com/files/icon/file-" + fi.Name + "/";

                    string UID = Guid.NewGuid().ToString().Replace("-", "");
                    int lastprogress = 0;
                    byte[] DeCompressedFileData = File.ReadAllBytes(fi.FullName);
                    byte[] filedata = BlazeGames.IM.Client.Core.Utilities.Compress(DeCompressedFileData);

                    if(filedata.Length >= 10485760)
                    {
                        NotificationWindow.ShowNotification("Upload Failed", "The file " + fi.Name + " is larger than 10MB when compressed.");
                        return;
                    }

                    HandleMessage(App.FullName, @"<Span xmlns=""default"">
            <Grid Name=""upload_" + UID + @"_control"" Background=""Transparent"" Width=""400"" Height=""100"">
            <Grid.ColumnDefinitions>
            <ColumnDefinition Width=""100""/>
            <ColumnDefinition Width=""*""/>
            </Grid.ColumnDefinitions>
            <ProgressBar Name=""upload_" + UID + @"_progress"" HorizontalAlignment=""Stretch"" Height=""20"" Margin=""15,42,15,15"" VerticalAlignment=""Center"" Grid.Column=""1""/>
            <Image Name=""upload_" + UID + @"_thumbnail"" Grid.Column=""0"" HorizontalAlignment=""Stretch"" Margin=""15"" VerticalAlignment=""Stretch""/>
            <Label Name=""upload_" + UID + @"_filename"" Content=""" + fi.Name + @""" Grid.Column=""1"" Margin=""15,15,15,40"" VerticalAlignment=""Center"" FontSize=""18"" Foreground=""#FF363636""  />
            <Label Name=""upload_" + UID + @"_progresstxt"" Content=""Uploading (0%)..."" Grid.Column=""1"" Margin=""15,42,15,15"" VerticalAlignment=""Center"" FontSize=""14"" Foreground=""#FF5F5F5F""  />
            </Grid>
            <LineBreak />
            </Span>");
                    if(IsImage)
                        UpdateUploadThumbnail(UID, new System.Windows.Media.Imaging.BitmapImage(new Uri(fi.FullName)));
                    else
                        UpdateUploadThumbnail(UID, new System.Windows.Media.Imaging.BitmapImage(new Uri(icon)));

                    using (WebClient wc = new WebClient())
                    {
                        Uploads.Add(UID);

                        wc.UploadDataCompleted += (sender, e) =>
                        {
                            Uploads.Remove(UID);
                            string Url = Encoding.Default.GetString(e.Result);
                            UpdateUploadComplete(UID, Url);

                            if (IsImage)
                                icon = Url;

                            ChattingWith.SendMessage(@"<Span xmlns=""default"">
            <Grid Name=""upload_" + UID + @"_control"" Cursor=""Hand"" Background=""Transparent"" Width=""400"" Height=""100"" Tag=""" + Url + @""">
            <Grid.ColumnDefinitions>
            <ColumnDefinition Width=""100""/>
            <ColumnDefinition Width=""*""/>
            </Grid.ColumnDefinitions>
            <Image Name=""upload_" + UID + @"_thumbnail"" Grid.Column=""0"" HorizontalAlignment=""Stretch"" Margin=""15"" VerticalAlignment=""Stretch"" Source=""" + icon + @"""/>
            <Label Name=""upload_" + UID + @"_filename"" Content=""" + fi.Name + @""" Grid.Column=""1"" Margin=""15,15,15,40"" VerticalAlignment=""Center"" FontSize=""18"" Foreground=""#FF363636""  />
            <Label Name=""upload_" + UID + @"_progresstxt"" Content=""" + Url + @""" Grid.Column=""1"" Margin=""15,42,15,15"" VerticalAlignment=""Center"" FontSize=""14"" Foreground=""#FF5F5F5F""  />
            </Grid>
            <LineBreak />
            </Span>");
                        };

                        wc.UploadProgressChanged += (sender, e) =>
                        {

                            if (lastprogress != e.ProgressPercentage)
                            {
                                UpdateUploadProgress(UID, (e.ProgressPercentage * 2) - 1);
                            }

                            lastprogress = e.ProgressPercentage;
                        };

                        wc.UploadDataAsync(new Uri("http://blaze-games.com/files/upload/&file_name=" + fi.Name), filedata);
                    }
                }
            }

            ev.Handled = false;
        }
Example #22
0
        private void Send(string api, Packet packet, DateTime time)
        {
            try
            {
                Uri uri = new Uri(this.GetUrl(api));
                byte[] data = Encoding.ASCII.GetBytes(packet.ToString());
                WebClient wc = new WebClient();
                wc.UploadDataCompleted += (object sender, UploadDataCompletedEventArgs e) =>
                    {
                        if (e.Error != null)
                        {
                            return;
                        }
                        Packet p = (Packet)e.UserState;
                        if (p != null)
                        {
                            string result = Encoding.ASCII.GetString(e.Result);
                            // TODO: with result
                        }

                    };
                wc.UploadDataAsync(uri, Post, data, packet);

            }
            catch (Exception e)
            {

            }
        }
Example #23
0
        // 撮影画像の準備完了時のイベントメソッド:撮影画像を保存し、保存完了時に【writeImgFileCallback】Hubを呼び出す。
        void device_ImageReady(NikonDevice sender, NikonImage image)
        {
            using (MemoryStream memStream = new MemoryStream(image.Buffer)) {
                // 画像データの検証オン
                _PhotImg = System.Drawing.Image.FromStream(memStream);

                //保存する写真画像のユーニークなファイル名
                //確認用に、フォームに撮った写真をフォームに表示
                picBoxPhotImage.Image = _PhotImg;

                //写真画像保存時のファイル名にユニークな名前を付ける。
                string fileUnqNm = "phot" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + "_" + DateTime.Now.Millisecond.ToString() + ".jpg";

                #region 条件分岐:ローカルサーバへのファイル保存がONなら
                if (chkBxFileSave.Checked == true) {
                    try {//ファイル保存
                        Console.WriteLine("写真画像保存開始");

                        //flStream.BeginWriteイベントハンド呼び出し時に使用するステイタスパラメータクラスのインスタンスを作成
                        using (EvHndParamClass param = new EvHndParamClass()) {

                            // ファイル書き込み終了時のイベントハンドラで実行されるコールバックメソッド内でファイル名を利用すため
                            //そのイベントハンドラに渡すパラメータの、stプロパティにファイル名をセット
                            param.str = fileUnqNm;

                            //非同期書き込み用のファイルストリームを作成
                            using (FileStream flStream = new FileStream(@"C:\inetpub\wwwroot\images/" + fileUnqNm, FileMode.Create,
                                                                        FileAccess.Write, FileShare.ReadWrite, image.Buffer.Length, true)) {
                                //非同期書き込み、書き込み終了時に呼び出されるメソッド【writeFileCallback】
                                //flStream.BeginWrite(image.Buffer, 0, image.Buffer.Length, new AsyncCallback(writeImgFileCallback), flStream);
                                flStream.BeginWrite(image.Buffer, 0, image.Buffer.Length, new AsyncCallback(writeImgFileCallback), param);
                                //							await writer.WriteAsync(input);
                            }
                        }
                    } catch (Exception ex) {
                        Console.WriteLine("err:" + ex.Message + " 写真画像ファイル書き込み失敗!");
                    }
                }
                #endregion

                #region 条件分岐: FTPアップロードチェックボックスがONなら
                if (chkBxFtpUpLoad.Checked == true) {
                    try {//↓は、FTPにて写真アップロードの【場合】です。
                        WebClient wc = new WebClient();
                        //アップロード完了時イベントを登録
                        wc.UploadDataCompleted += (s, e) => {
                            Console.WriteLine("アップロード完了");
                            _HubProxy.Invoke("PhotChange", fileUnqNm).Wait();
                        };

                        //Uri u = new Uri("" + fileUnqNm);
                        Uri u = new Uri("ftp://waws-prod-os1-001.ftp.azurewebsites.windows.net/site/wwwroot/images/" + fileUnqNm);

                        //認証設定
            //						wc.Credentials = new NetworkCredential(@"", "");
                        wc.Credentials = new NetworkCredential(@"picUpSignalR\$picUpSignalR", FtpCredentials);

                        Console.WriteLine("写真画像FTPアップロード開始");
                        wc.UploadDataAsync(u, image.Buffer);
                    } catch (Exception ex) {
                        //MessageBox.Show(ex.ToString());
                        Console.WriteLine("err:" + ex.Message + " 写真画像FTPアップロード失敗!");
                    }
                }
                #endregion
            }
        }
Example #24
0
        /// <summary>
        /// Publishes a photo to the current user's wall with an async method
        /// </summary>
        /// <param name="photo">photo to be published</param>
        /// <param name="message">message with this photo</param>
        public void PublishPhotoAsync(Bitmap photo, string message) {
            MemoryStream MS = new MemoryStream();
            photo.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] Imagebytes = MS.ToArray();
            MS.Dispose();

            //Set up basic variables for constructing the multipart/form-data data
            string newline = "\r\n";
            string boundary = DateTime.Now.Ticks.ToString("x");
            string data = "";

            //Construct data
            data += "--" + boundary + newline;
            data += "Content-Disposition: form-data; name=\"message\"" + newline + newline;
            data += message + newline;

            data += "--" + boundary + newline;
            data += "Content-Disposition: form-data; filename=\"test.jpg\"" + newline;
            data += "Content-Type: image/jpeg" + newline + newline;

            string ending = newline + "--" + boundary + "--" + newline;

            //Convert data to byte[] array
            MemoryStream finaldatastream = new MemoryStream();
            byte[] databytes = Encoding.UTF8.GetBytes(data);
            byte[] endingbytes = Encoding.UTF8.GetBytes(ending);
            finaldatastream.Write(databytes, 0, databytes.Length);
            finaldatastream.Write(Imagebytes, 0, Imagebytes.Length);
            finaldatastream.Write(endingbytes, 0, endingbytes.Length);
            byte[] finaldatabytes = finaldatastream.ToArray();
            finaldatastream.Dispose();

            //Make the request
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
            client.UploadDataAsync(new Uri("https://graph.facebook.com/me/photos?access_token=" + AccessToken), "POST", finaldatabytes);
        }
Example #25
0
        public void UploadFileAsync(string filePath, byte[] fileByteArray, StatusChanged uploadCompleted)
        {
            if (CurrentSecret == null)
                                return;

                        var destinationPath = String.Format ("/api/{0}/{1}", CurrentSecret, UrlHelper.GetFileName (filePath));
                        var client = new WebClient ();
                        client.Headers ["content-type"] = "application/octet-stream";
                        client.Encoding = Encoding.UTF8;

                        client.UploadDataCompleted += (sender, e) => {
                                uploadCompleted ();
                                if (e.Cancelled) {
                                        Console.Out.WriteLine ("Upload file cancelled.");
                                        return;
                                }

                                if (e.Error != null) {
                                        Console.Out.WriteLine ("Error uploading file: {0}", e.Error.Message);
                                        return;
                                }

                                var response = System.Text.Encoding.UTF8.GetString (e.Result);

                                if (!String.IsNullOrEmpty (response)) {
                                }
                        };
                        Send (destinationPath);
                        client.UploadDataAsync (new Uri (SERVER + destinationPath), "POST", fileByteArray);
        }
        public void SubmitFeedbackAsync(Song song, Ratings rating)
        {
            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("content-type", "text-xml");
                client.UploadDataCompleted += new UploadDataCompletedEventHandler(SubmitFeedback_UploadDataCompleted);
                Uri uri = new Uri(String.Format(BASE_URL_LID, _rid, _lid, "addFeedback"));

                List<object> parameters = new List<object>();
                parameters.Add(GetTimestamp());
                parameters.Add(_authenticationToken);
                parameters.Add(song.StationId);
                parameters.Add(song.MusicId);
                parameters.Add(song.UserSeed);
                parameters.Add(String.Empty);//TestStrategy--wtf?
                parameters.Add(rating == Ratings.Like);
                parameters.Add(false); //IsCreatorQuickMix
                parameters.Add(song.SongType);

                string xml = GetXml("station.addFeedback", parameters);
                string encryptedXml = EncryptionHelper.EncryptString(xml);
                client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml));
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
            }
        }
        public void RetrieveSongsAsync(string stationId, AudioFormats audioFormat)
        {
            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("content-type", "text-xml");
                client.UploadDataCompleted += new UploadDataCompletedEventHandler(RetrieveSongs_UploadDataCompleted);
                Uri uri = new Uri(String.Format(BASE_URL_LID, _rid, _lid, "getFragment"));

                List<object> parameters = new List<object>();
                parameters.Add(GetTimestamp());
                parameters.Add(_authenticationToken);
                parameters.Add(stationId);
                parameters.Add("0"); //total listening time
                parameters.Add(String.Empty); //time since last session
                parameters.Add(String.Empty); //tracking code

                switch (audioFormat)
                {
                    case AudioFormats.AAC_PLUS:
                        parameters.Add("aacplus");
                        break;
                    case AudioFormats.MP3:
                        parameters.Add("mp3");
                        break;
                    case AudioFormats.MP3_HIFI:
                        parameters.Add("mp3-hifi");
                        break;
                }

                parameters.Add("0"); //delta listening time
                parameters.Add("0"); //listening timestamp

                string xml = GetXml("playlist.getFragment", parameters);
                string encryptedXml = EncryptionHelper.EncryptString(xml);
                client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml));
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
            }
        }
 private static void LogPageView(PageRequest preq)
 {
     try
     {
       using (var client = new WebClient())
      {
        client.Headers.Add("X-CloudMine-ApiKey", appSecret);
        client.Headers.Add("Content-Type", "application/json");
        var serializer = new JavaScriptSerializer();
        var data = serializer.Serialize(preq);
        var payload = "{\"PV_" + DateTime.Now.Ticks + "\":" + data + "}";
        var bytes = Encoding.Default.GetBytes(payload);
        client.UploadDataAsync(new Uri("https://api.cloudmine.me/v1/app/" + appId + "/text"), "PUT", bytes);
       }
     }
     catch (Exception e)
     {
         //log error
     }
 }
Example #29
0
        private void PublishPackage(PublishState state)
        {
            var url = new Uri(String.Format(CultureInfo.InvariantCulture, "{0}/{1}", _baseGalleryServerUrl, PublishPackageService));

            using (Stream requestStream = new MemoryStream()) {
                var data = new PublishData {
                    Key = state.PublishKey,
                    Id = state.PackageMetadata.Id,
                    Version = state.PackageMetadata.Version.ToString()
                };

                var jsonSerializer = new DataContractJsonSerializer(typeof(PublishData));
                jsonSerializer.WriteObject(requestStream, data);
                requestStream.Seek(0, SeekOrigin.Begin);

                WebClient client = new WebClient();
                client.Proxy = _cachedProxy;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.UserAgent] = _userAgent;
                client.UploadProgressChanged += OnUploadProgressChanged;
                client.UploadDataCompleted += OnPublishPackageCompleted;
                client.UploadDataAsync(url, "POST", requestStream.ReadAllBytes(), state);
            }
        }
Example #30
0
        public void Upload(FileInformation info, byte[] raw, bool retry = true)
        {
            string fileName = info.FileName.Replace(@"\", "/");

            if (fileName != "AutoPatcher.gz" && fileName != "PList.gz")
                fileName += ".gz";

            using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential(Settings.Login, Settings.Password);

                byte[] data = !retry ? raw : raw;
                info.Compressed = data.Length;

                client.UploadProgressChanged += (o, e) =>
                    {
                        int value = (int)(100 * e.BytesSent / e.TotalBytesToSend);
                        progressBar2.Value = value > progressBar2.Maximum ? progressBar2.Maximum : value;

                        FileLabel.Text = fileName;
                        SizeLabel.Text = string.Format("{0} KB / {1} KB", e.BytesSent / 1024, e.TotalBytesToSend  / 1024);
                        SpeedLabel.Text = ((double) e.BytesSent/1024/_stopwatch.Elapsed.TotalSeconds).ToString("0.##") + " KB/s";
                    };

                client.UploadDataCompleted += (o, e) =>
                    {
                        _completedBytes += info.Length;

                        if (e.Error != null && retry)
                        {
                            CheckDirectory(Path.GetDirectoryName(fileName));
                            Upload(info, data, false);
                            return;
                        }

                        if (info.FileName == PatchFileName)
                        {
                            FileLabel.Text = "Complete...";
                            SizeLabel.Text = "Complete...";
                            SpeedLabel.Text = "Complete...";
                            return;
                        }

                        progressBar1.Value = (int)(_completedBytes * 100 / _totalBytes) > 100 ? 100 : (int)(_completedBytes * 100 / _totalBytes);
                        BeginUpload();
                    };

                _stopwatch = Stopwatch.StartNew();

                client.UploadDataAsync(new Uri(Settings.Host + fileName), data);
            }
        }
Example #31
0
        /// <summary>
        /// Uploads the build data to the server.
        /// </summary>
        private static void c_UploadThread_Run()
        {
            // Initalize the process.
            WebClient client = new WebClient();
            MemoryStream stream = new MemoryStream();
            ZipOutputStream zip = new ZipOutputStream(stream);
            zip.SetLevel(9);

            // Add all the files.
            Program.AddFiles(zip, "*.dll");
            Program.AddFiles(zip, "*.pdb");
            Program.AddFiles(zip, "*.exe");
            zip.IsStreamOwner = true;
            zip.Close();

            // Send the data.
            Program.SetStatus("Uploading " + ((double)stream.ToArray().Length / 1024 / 1024).ToString("F") + "MB...");
            client.UploadDataCompleted += new UploadDataCompletedEventHandler(client_UploadDataCompleted);
            client.UploadDataAsync(new Uri("http://www.redpointsoftware.com.au/builds/upload/termkit"), "PUT", stream.ToArray());
        }
Example #32
0
 public static void AsyncHttpRequest(string maiurl, string paramurl)
 {
     using (WebClient client = new WebClient())
     {
         var Postbyte = Encoding.ASCII.GetBytes(paramurl);
         client.UploadDataAsync(new Uri(maiurl), "POST", Postbyte);
     }
 }
Example #33
0
        public static void UploadImage(System.Drawing.Image img, Contact SendTo)
        {
            MemoryStream ImageStream = new MemoryStream();
            img.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Png);

            byte[] image = Compress(ImageStream.ToArray());
            using (WebClient wc = new WebClient())
            {
                wc.UploadDataCompleted += (sender, e) =>
                {
                    string Url = Encoding.UTF8.GetString(e.Result);
                    SendTo.SendMessage(string.Format("<Span xmlns=\"default\"><Image Source=\"{0}\" /></Span>", Url));
                    System.Windows.MessageBox.Show(Url);
                };

                wc.UploadDataAsync(new Uri("http://blaze-games.com/files/upload/&file_name=UploadedImage.png"), image);
            }
        }
        private void AuthenticateListenerAsync()
        {
            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("content-type", "text-xml");
                client.UploadDataCompleted += new UploadDataCompletedEventHandler(AuthenticateListener_UploadDataCompleted);
                Uri uri = new Uri(String.Format(BASE_URL_RID, _rid, "authenticateListener"));

                List<object> parameters = new List<object>();
                parameters.Add(GetTimestamp());
                parameters.Add(_username);
                parameters.Add(_password);
                parameters.Add("html5tuner"); //??
                parameters.Add(String.Empty); //??
                parameters.Add(String.Empty); //??
                parameters.Add("HTML5"); //??
                parameters.Add(true); //??

                string xml = GetXml("listener.authenticateListener", parameters);
                string encryptedXml = EncryptionHelper.EncryptString(xml);
                client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml));
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
            }
        }
Example #35
0
        public void TestUploadDataAsync()
        {
            if (!Runtime.IsRunningOnMono)
            Assert.Ignore("supported only on Mono");

              using (var server = InitializeAppendServer()) {
            using (var client = new System.Net.WebClient()) {
              using (var waitHandle = new AutoResetEvent(false)) {
            client.UploadDataCompleted += delegate(object sender, UploadDataCompletedEventArgs e) {
              try {
                Assert.IsNull(e.Error);
                Assert.AreEqual(new byte[0], e.Result);
              }
              finally {
                waitHandle.Set();
              }
            };

            client.UploadDataAsync(new Uri(string.Format("imap://{0}/INBOX", server.HostPort)), ImapWebRequestMethods.Append, Encoding.ASCII.GetBytes(message));

            if (!waitHandle.WaitOne(5000))
              Assert.Fail("timed out");

            AssertAppendRequest(server);
              }
            }
              }
        }
 private void SyncAsync()
 {
     try
     {
         WebClient client = new WebClient();
         client.Headers.Add("content-type", "text-xml");
         client.UploadDataCompleted += new UploadDataCompletedEventHandler(Sync_UploadDataCompleted);
         Uri uri = new Uri(String.Format(BASE_URL_RID, _rid, "sync"));
         string xml = GetXml("misc.sync", null);
         string encryptedXml = EncryptionHelper.EncryptString(xml);
         client.UploadDataAsync(uri, "POST", System.Text.Encoding.ASCII.GetBytes(encryptedXml));
     }
     catch (Exception exception)
     {
         if (ExceptionReceived != null)
             ExceptionReceived(this, new EventArgs<Exception>(exception));
     }
 }
Example #37
0
        private bool UploadRange(Range r)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers.Add("Content-Range",
                    "bytes " + r.pos.ToString() + "-" + (r.end - 1).ToString() + "/" + fileSize.ToString());

            byte[] data = new byte[r.Len()];
            fs.Seek(r.pos, SeekOrigin.Begin);
            int len = fs.Read(data, 0, (int)r.Len());
            if (len != r.Len())
                throw new IOException("unable read expected size.");

            client.Headers.Add("Content-MD5", CalcMD5Hex(data));

            client.UploadProgressChanged += new System.Net.UploadProgressChangedEventHandler(OnRangeUploadProgressChanged);
            client.UploadDataCompleted += new System.Net.UploadDataCompletedEventHandler(OnRangeUploadDataCompleted);

            UploadInfo info = new UploadInfo();
            info.wc = client;
            info.totalBytes = len;
            info.uploadedBytes = 0;
            uploadInfos[client] = info;

            client.UploadDataAsync(new Uri(uploadUrl), "POST", data, client);

            return true;
        }
Example #38
0
        // タイマー割り込みでライブビューを表示するイベントメソッド(画像ファイルのローカル保存 Or FTP)
        void liveViewTimer_Tick(object sender, EventArgs e)
        {
            // Get live view image
            NikonLiveViewImage image = null;

            try {
                //ここんとこ、修正必要かも。_Device.GetLiveViewImage()を呼び出す前にnullかどうか確認してくださいとのこと
                image = _Device.GetLiveViewImage();
            } catch (NikonException) {
                _LiveViewTimer.Stop();
            }

            if (image != null) {
                MemoryStream memStream = new MemoryStream(image.JpegBuffer);
                //確認用に、フォームに撮った写真をフォームに表示
                _LiveViewImg = System.Drawing.Image.FromStream(memStream);
                picBoxPhotImage.Image = _LiveViewImg;

                #region 条件分岐:ローカルサーバへのファイル保存がONなら
                if (chkBxFileSave.Checked == true) {
                    try {//ファイルを上書きで保存(ファイル名固定)

                        Console.WriteLine("ライブ画像保存開始");

                        //非同期書き込み用のファイルストリームを作成
                        using (FileStream flStream = new FileStream(@"C:\inetpub\wwwroot\images/" + _LiveViewImgFlNm, FileMode.Create,
                                                                    FileAccess.Write, FileShare.ReadWrite, image.JpegBuffer.Length, true)) {

                            //flStream.BeginWriteイベントハンド呼び出し時に使用するステイタスパラメータクラスのインスタンスを作成
                            using (EvHndParamClass param = new EvHndParamClass()) {
                                //ファイル書き込み終了時のイベントハンドラで実行されるコールバックメソッド内でファイル名を利用すため
                                //そのイベントハンドラに渡すパラメータの、stプロパティにファイル名をセット
                                param.str = _LiveViewImgFlNm;

                                //非同期に書き込み処理を実行する。当該イベント完了時に呼び出されるメソッド【writeImgFileCallback】を設定
                                flStream.BeginWrite(image.JpegBuffer, 0, image.JpegBuffer.Length, new AsyncCallback(writeImgFileCallback), param);
                                //	await writer.WriteAsync(input);//←Frame Work 4.5以上でないと使えない?
                            }
                        }
                    } catch (Exception ex) {
                        Console.WriteLine("err:" + ex.Message + " ライブ画像ファイル書き込み失敗!");
                    }
                }
                #endregion

                #region 条件分岐: FTPアップロードチェックボックスがONなら
                if (chkBxFtpUpLoad.Checked == true) {
                    try {//↓は、FTPにて写真アップロードの【場合】です。
                        WebClient wc = new WebClient();
                        //アップロード完了時イベントを登録
                        wc.UploadDataCompleted += (s, ev) => {
                            Console.WriteLine("アップロード完了");
                            //ファイル名に、"?"+時間を付け加えて送信することで、同名ファイルでも異なるファイルとブラウザに認識させる。
                            _HubProxy.Invoke("PhotChange", _LiveViewImgFlNm+"?"+DateTime.Now.Millisecond.ToString()).Wait();
                        };

                        Uri u = new Uri("ftp://waws-prod-os1-001.ftp.azurewebsites.windows.net/site/wwwroot/images/" + _LiveViewImgFlNm);
                        //認証設定
                        wc.Credentials = new NetworkCredential(@"picUpSignalR\$picUpSignalR", FtpCredentials);

                        Console.WriteLine("写真画像FTPアップロード開始");
                        wc.UploadDataAsync(u, image.JpegBuffer);

                    } catch (Exception ex) {
                        MessageBox.Show(ex.ToString());
                        Console.WriteLine("err:" + ex.Message + " 写真画像FTPアップロード失敗!");

                    }
                }
                #endregion

            }
        }