// The EndGetResponseCallback method
        // completes a call to BeginGetResponse.
        private void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState       state    = (FtpState)ar.AsyncState;
            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that
                // the operation is complete.
                state.OperationComplete.Set();
                state.Request.GetResponse();

                Ctrl.Invoke(new Action(delegate
                {
                    if (UploadCompleted != null)
                    {
                        UploadCompleted.Invoke(this, EventArgs.Empty);
                    }
                }));
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                if (UploadError != null)
                {
                    ThreadExceptionEventArgs arg = new ThreadExceptionEventArgs(e);
                    UploadError.Invoke(this, arg);
                }
            }
        }
Exemple #2
0
        void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

            try
            {
                HttpWebResponse response       = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                Stream          streamResponse = response.GetResponseStream();
                StreamReader    streamRead     = new StreamReader(streamResponse);
                #region parse the content
                #endregion
                try
                {
                    DataContractJsonSerializer ser = null;

                    if (Type == SocialType.Tencent)
                    {
                        //{"data":{"id":"84291041886790","time":1337332120},"errcode":0,"imgurl":"http:\/\/t1.qpic.cn\/mblogpic\/c50c86e2a078ec4dfb9c","msg":"ok","ret":0}
                        ser = new DataContractJsonSerializer(typeof(TResponse));
                        TResponse tr = ser.ReadObject(streamResponse) as TResponse;
                        if (tr.errcode == 0)
                        {
                            UploadCompleted.Invoke("ok", null);
                        }
                        else
                        {
                            UploadCompleted.Invoke(new Exception(tr.msg), null);
                        }
                    }
                    else if (Type == SocialType.Weibo)
                    {
                        UploadCompleted.Invoke("ok", null);
                    }
                    else if (Type == SocialType.Renren)
                    {
                        //{"uid":222808196,"src_small":"http://fmn.rrfmn.com/fmn058/20120521/1400/p_main_lHP2_25e400002c051261.jpg","caption":"12312312","pid":6036647931,"src":"http://fmn.rrfmn.com/fmn058/20120521/1400/p_head_W7RI_25e400002c051261.jpg","aid":629133235,"src_big":"http://fmn.rrfmn.com/fmn058/20120521/1400/p_large_6uUE_25e400002c051261.jpg"}
                        UploadCompleted.Invoke("ok", null);
                    }
                    else if (Type == SocialType.Douban)
                    {
                        UploadCompleted.Invoke("ok", null);
                    }
                }
                catch (Exception)
                {
                }
                streamResponse.Close();
                streamRead.Close();
                // Release the HttpWebResponse
                response.Close();
            }
            catch (WebException ex)
            {
                UploadCompleted.Invoke(ex, null);
                return;
            }
        }
Exemple #3
0
        public static async Task ProcessStarter(
            [QueueTrigger(QueueNames.CommProcess)] UploadCompleted uploadCompleted,
            [DurableClient] IDurableOrchestrationClient starter,
            ILogger log)
        {
            var orchestrationId = await starter.StartNewAsync(OrchestratorNames.ProcessMessage, uploadCompleted);

            log.Log(LogLevel.Information,
                    $"Started an orchestration {orchestrationId} for uploaded manifest {uploadCompleted.SessionId}");
        }
Exemple #4
0
        public static async Task <IEnumerable <Message> > ProcessManifestActivity(
            [ActivityTrigger] UploadCompleted uploadCompleted,
            [Blob(BlobNames.UploadDirectory + "/{uploadCompleted.SessionId}/" + CommunicationManifest.FileName)] CloudBlockBlob manifest,
            [Table(TableNames.CommMessage)] CloudTable messageTable,
            [Inject] IMessageIdGenerator idGenerator,
            [Inject] App app,
            ILogger log)
        {
            var communicationManifest = await manifest.DownloadTextAsAsync <CommunicationManifest>();

            var results = await communicationManifest.PrepareCommMessage(uploadCompleted.SessionId, idGenerator, app.DateTimeNow)
                          .CreateIn(messageTable);

            log.Log(LogLevel.Information, communicationManifest.ToJson(Formatting.Indented));

            return(results.GetResult <Message>());
        }
 public void OnUploadEnd(DropZoneFileUploadOutcome file)
 {
     if (file is null)
     {
         throw new ArgumentNullException(nameof(file));
     }
     if (file.Path is null)
     {
         throw new ArgumentException("file's Path Property should not be null.", nameof(file));
     }
     if (file.Name is null)
     {
         throw new ArgumentException("file's Name Property should not be null.", nameof(file));
     }
     if (file.Success)
     {
         UploadCompleted.InvokeAsync(new DropZoneUploadCompletedEventArgs(file.Path, file.Name, file.Size, file.Key, file.SessionId));
     }
     else
     {
         UploadCompleted.InvokeAsync(new DropZoneUploadCompletedEventArgs(file.Path, file.Name, file.Size, file.Key, file.SessionId, file.Reason));
     }
 }
Exemple #6
0
        protected UploadingTaskViewModel()
        {
            ChangeStatusCommand = new DependencyCommand(ChangeStatus, DependencyCommand.AlwaysCan);
            StopCommand         = new DependencyCommand(Stop, DependencyCommand.AlwaysCan);
            WeakEventManager <DispatcherTimer, EventArgs> .AddHandler(timer, nameof(timer.Tick), Callback);

            void Callback(object sender, EventArgs e)
            {
                OnPropertyChanged(nameof(Name));
                OnPropertyChanged(nameof(Status));
                //OnPropertyChanged(nameof(Uploaded));
                OnPropertyChanged(nameof(Total));
                OnPropertyChanged(nameof(Uploaded));
                OnPropertyChanged(nameof(Progress));
                if (Status == UploadStatus.Completed)
                {
                    UploadCompleted?.Invoke(this, new EventArgs());
                }
                else if (Status == UploadStatus.Stop)
                {
                    UploadAborted?.Invoke(this, new EventArgs());
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Uploads a file
        /// </summary>
        /// <param name="filename">The filename we want to upload</param>
        /// <param name="MD5Checksum">The MD5 checksum of a file</param>
        /// <returns>An Image object that describes the image we uploaded</returns>
        public async Task UploadImageAsync(string filename, string MD5Checksum, CancellationToken token)
        {
            const string url = "https://upload.smugmug.com/";

            try
            {
                var file         = new FileInfo(filename);
                var myWebRequest = (HttpWebRequest)WebRequest.Create(url);

                myWebRequest.Method        = WebRequestMethods.Http.Post;
                myWebRequest.ContentLength = file.Length;
                myWebRequest.UserAgent     = "KHainePhotography PhotoStudioManager v1.0";

                switch (file.Extension.ToLower())
                {
                case "mp4":
                    myWebRequest.ContentType = "video/mp4";
                    break;

                case "jpg":
                    myWebRequest.ContentType = "image/jpeg";
                    break;

                default:
                    myWebRequest.ContentType = "binary/octet-stream";
                    break;
                }

                // Add the authorization header
                myWebRequest.Headers.Add("Authorization", oAuthUtility.GetAuthorizationHeader(Album.Token, myWebRequest.RequestUri.AbsoluteUri));

                myWebRequest.Headers.Add("Content-MD5", MD5Checksum);

                myWebRequest.Headers.Add("X-Smug-ResponseType", "JSON");
                myWebRequest.Headers.Add("X-Smug-Version", "v2");

                myWebRequest.Headers.Add("X-Smug-AlbumUri", Album.Uri);
                myWebRequest.Headers.Add("X-Smug-FileName", file.Name);
                myWebRequest.Headers.Add("X-Smug-Title", Path.GetFileNameWithoutExtension(file.FullName));
                myWebRequest.Headers.Add("X-Smug-Caption", Path.GetFileNameWithoutExtension(file.FullName));

                myWebRequest.Headers.Add("X-Smug-Latitude", "53.457920");
                myWebRequest.Headers.Add("X-Smug-Longitude", "-1.464252");
                myWebRequest.Headers.Add("X-Smug-Altitude", "86");

                myWebRequest.Headers.Add("X-Smug-Pretty", "true");

                //we start reading from the file...

                //we have some elements to set
                //- request time out (compute this for 10 kb/sec speed)
                //- the chunk size to use when uploading (how much data to report after)
                UploadStarted?.Invoke(this, new UploadEventArgs()
                {
                    FileName = file.FullName, PercentComplete = 0
                });

                int timeOut = ((int)file.Length / 1024) * 1000;
                myWebRequest.Timeout                   = timeOut;
                myWebRequest.ReadWriteTimeout          = timeOut;
                myWebRequest.AllowWriteStreamBuffering = true;

                long   howMuchRead = 0;
                byte[] buffer      = new byte[chunkSize];
                int    readSoFar   = 0;

                using (FileStream sr = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                {
                    using (var stream = await myWebRequest.GetRequestStreamAsync())
                    {
                        while (howMuchRead < file.Length)
                        {
                            //we try to read a chunk from the file
                            readSoFar    = sr.Read(buffer, 0, chunkSize);
                            howMuchRead += readSoFar;

                            //we now write those files to the web.
                            await stream.WriteAsync(buffer, 0, readSoFar, token);

                            UploadProgress?.Invoke(this, new UploadEventArgs()
                            {
                                FileName = file.FullName, PercentComplete = (float)howMuchRead / (float)file.Length
                            });
                        }
                    }
                }

                var resp = await myWebRequest.GetResponseAsync();

                string rez = string.Empty;
                using (StreamReader ns = new StreamReader(resp.GetResponseStream()))
                {
                    rez = await ns.ReadToEndAsync();
                }

                UploadCompleted?.Invoke(this, new UploadEventArgs()
                {
                    FileName = file.FullName, PercentComplete = (float)howMuchRead / (float)file.Length
                });

                //we deserialize the image
                var response = JsonConvert.DeserializeObject <UploadReponse>(System.Uri.UnescapeDataString(rez));

                if (response.stat != "ok")
                {
                    throw new ApplicationException(response.stat);
                }
            }
            catch (Exception e)
            {
                Debug.Fail(e.Message);
                throw;
            }
        }