Inheritance: System.ComponentModel.AsyncCompletedEventArgs
Esempio n. 1
0
		private void client_UploadDataCompleted_json(object sender, UploadDataCompletedEventArgs e)
		{
			if (OnQueryCompleted != null)
			{
				var token = e.UserState is string ? (string) e.UserState : "";
				var data = "";
				if (e.Error == null)
				{
					var srcString = Encoding.UTF8.GetString(e.Result);
					var json = JObject.Parse(srcString);
					switch (token)
					{
						case "taobao":
							data = NormalizeTaobao(json);
							break;
						case "sina":
							data = NormalizeSina(json);
							break;
						case "tencent":
							data = NormalizeTencent(json);
							break;
					}
				}
				else
				{
					data = e.Error.Message;
				}
				OnQueryCompleted(sender, new QueryCompletedEventArgs(data, token));
			}
		}
Esempio n. 2
0
        private void OnUploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                byte[] result = e.Result;
                if (result.Length > 0)
                {
                    string response = ASCIIEncoding.UTF8.GetString(result);

                    JObject jo = JObject.Parse(response);

                }
            }
        }
Esempio n. 3
0
        private void OnRangeUploadDataCompleted(Object sender, System.Net.UploadDataCompletedEventArgs e)
        {
            lock (infoLock) {
                WebClient client = (WebClient)sender;

                this.uploadedBytes += uploadInfos[client].totalBytes;

                uploadInfos.Remove(client);

                if (e.Cancelled || e.Error != null)
                {
                    if (e.Cancelled)
                    {
                        cancelled = true;
                    }

                    if (e.Error != null)
                    {
                        lastError = e.Error;
                    }
                }
                else
                {
                    int statusCode = GetStatusCode(client);

                    if (statusCode == 206)
                    {
                        UploadNextRange();
                    }
                    else if (statusCode == 200)
                    {
                    }
                }

                if (uploadInfos.Count == 0)
                {
                    UploadCompletedEventArgs ee = new UploadCompletedEventArgs();
                    ee.Cancelled = cancelled;
                    ee.Error     = lastError;

                    uploadCompletedEvent.Set();

                    UploadCompleted(this, ee);
                }

                client.Dispose();
            }
        }
Esempio n. 4
0
 private void ReceivedClientRequesterData(Object sender, UploadDataCompletedEventArgs e)
 {
     if (!e.Cancelled && e.Error == null)
     {
         byte[] result = (byte[])e.Result;
         Hashtable info;
         try
         {
             info = (Hashtable)PHPSerializer.UnSerialize(result);
             info["__func__"] = this._func;
             info["__index__"] = this._val;
         }
         catch (Exception)
         {
             info = new Hashtable();
             info["__func__"] = "failed";
             info["__index__"] = this._val;
         }
         this.OnClientRequest(new HoNClientRequesterEventArgs(info));
     }
 }
Esempio n. 5
0
		private void client_UploadDataCompleted_html(object sender, UploadDataCompletedEventArgs e)
		{
			if (OnQueryCompleted != null)
			{
				var token = e.UserState is string ? (string) e.UserState : "";
				var data = "";
				if (e.Error == null)
				{
					var srcString = Encoding.UTF8.GetString(e.Result);
					switch (token)
					{
						case "17mon":
							data = Normalize17Mon(srcString);
							break;
					}
				}
				else
				{
					data = e.Error.Message;
				}
				OnQueryCompleted(sender, new QueryCompletedEventArgs(data, token));
			}
		}
Esempio n. 6
0
 static void client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     try
     {
         Program.SetStatus(Encoding.ASCII.GetString(e.Result));
         Program.SetStatus("Upload Complete.");
         Program.c_Icon.ShowBalloonTip(1000, "Upload Complete", "The nightly build of TermKit for Windows is complete.", ToolTipIcon.Info);
         Program.c_Icon.BalloonTipClosed += new EventHandler(c_Icon_BalloonTipClosed);
     }
     catch (System.Reflection.TargetInvocationException ex)
     {
         Program.SetStatus("Upload Failed.");
         Program.c_Icon.ShowBalloonTip(1000, "Upload Failed", "The nightly build of TermKit for Windows failed.", ToolTipIcon.Info);
         Program.c_Icon.BalloonTipClosed += new EventHandler(c_Icon_BalloonTipClosed);
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Manejador de evento que recibe información sobre
 /// el resultado de la operación de carga del fichero
 /// cuando esa se completa
 /// </summary>
 void UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     if (e.Cancelled == true)
     {
     String msg = string.Format("Se cancelo la operación");
     //Trace.WriteLine("Se cancelo la operación");
     }
     else if (e.Error != null)
     {
     String msg = string.Format("Se produjo una excepción durante la operación: {0}",e.Error.ToString());
     //Trace.WriteLine(msg);
     }
 }
Esempio n. 8
0
 void DepositCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     toolStripProgressBar.Value = 100;
     toolStripStatusLabel.Text = "Deposit complete, 'in progress' is set to 'false'";
 }
Esempio n. 9
0
 private void Webclient_UploadDataCompleted(object sender, System.Net.UploadDataCompletedEventArgs e)
 {
     throw new NotImplementedException();
 }
        private void RetrieveSongs_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                if (ExceptionReceived != null)
                {
                    Exception exception = new Exception("Request was cancelled.");
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
                }

                return;
            }

            if (e.Error != null)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(e.Error));

                return;
            }

            List<Song> songs = null;

            try
            {
                String response = System.Text.Encoding.ASCII.GetString(e.Result);

                string faultString = GetFaultString(response);

                if (!String.IsNullOrEmpty(faultString))
                {
                    if (ExceptionReceived != null)
                        ExceptionReceived(this, new EventArgs<Exception>(new Exception(faultString)));

                    return;
                }

                songs = ParseSongXml(response);

                //Decrypt last 48 characters of URL
                foreach (Song song in songs)
                {
                    string decryptedString = EncryptionHelper.DecryptUrlHex(song.AudioUrl.Substring(song.AudioUrl.Length - 48, 48));
                    song.AudioUrl = song.AudioUrl.Substring(0, song.AudioUrl.Length - 48) + decryptedString;
                }
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));

                return;
            }

            if (RetrieveStationsComplete != null)
                RetrieveSongsComplete(this, new EventArgs<List<Song>>(songs));
        }
        private void SubmitFeedback_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                if (ExceptionReceived != null)
                {
                    Exception exception = new Exception("Request was cancelled.");
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
                }

                return;
            }

            if (e.Error != null)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(e.Error));

                return;
            }

            String xml = null;

            try
            {
                String response = System.Text.Encoding.ASCII.GetString(e.Result);

                string faultString = GetFaultString(response);

                if (!String.IsNullOrEmpty(faultString))
                {
                    if (ExceptionReceived != null)
                        ExceptionReceived(this, new EventArgs<Exception>(new Exception(faultString)));

                    return;
                }

                xml = response;
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));

                return;
            }

            if (SubmitFeedbackComplete != null)
                SubmitFeedbackComplete(this, new EventArgs());
        }
Esempio n. 12
0
        private void Client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            LLSDArray events = null;
            int ack = 0;

            if (e.Error != null)
            {
                // Error occurred
                string message = e.Error.Message.ToLower();

                // Check what kind of exception happened
                if (Helpers.StringContains(message, "404") || Helpers.StringContains(message, "410"))
                {
                    SecondLife.LogStatic("Closing event queue at " + _Client.Location  + " due to missing caps URI",
                        Helpers.LogLevel.Info);

                    _Running = false;
                    _Dead = true;
                }
                else if (!e.Cancelled && !Helpers.StringContains(message, "502"))
                {
                    SecondLife.LogStatic("Unrecognized caps exception from " + _Client.Location  +
                        ": " + e.Error.Message, Helpers.LogLevel.Warning);
                }
            }
            else if (!e.Cancelled && e.Result != null)
            {
                // Got a response
                LLSD result = LLSDParser.DeserializeXml(e.Result);
                if (result != null && result.Type == LLSDType.Map)
                {
                    // Parse any events returned by the event queue
                    LLSDMap map = (LLSDMap)result;

                    events = (LLSDArray)map["events"];
                    ack = map["id"].AsInteger();
                }
            }
            else if (e.Cancelled)
            {
                // Connection was cancelled
                SecondLife.DebugLogStatic("Cancelled connection to event queue at " + _Client.Location);
            }

            if (_Running)
            {
                LLSDMap request = new LLSDMap();
                if (ack != 0) request["ack"] = LLSD.FromInteger(ack);
                else request["ack"] = new LLSD();
                request["done"] = LLSD.FromBoolean(_Dead);

                byte[] postData = LLSDParser.SerializeXmlBytes(request);

                _Client.UploadDataAsync(_Client.Location, postData);

                // If the event queue is dead at this point, turn it off since
                // that was the last thing we want to do
                if (_Dead)
                {
                    _Running = false;
                    SecondLife.DebugLogStatic("Sent event queue shutdown message");
                }
            }

            if (OnEvent != null && events != null && events.Count > 0)
            {
                // Fire callbacks for each event received
                foreach (LLSDMap evt in events)
                {
                    string msg = evt["message"].AsString();
                    LLSDMap body = (LLSDMap)evt["body"];

                    try { OnEvent(msg, body); }
                    catch (Exception ex) { SecondLife.LogStatic(ex.ToString(), Helpers.LogLevel.Error); }
                }
            }
        }
 protected virtual new void OnUploadDataCompleted(UploadDataCompletedEventArgs e)
 {
 }
Esempio n. 14
0
 void client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     Process(new MemoryStream(e.Result));
 }
Esempio n. 15
0
 void wc_uploader_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     //TODO: Update the profile image client sided
     BlazeGames.IM.Client.MainWindow.Instance.profile_image_source.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("https://blaze-games.com/api/image/nocompress/?nickname=" + App.NickName), new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore));
 }
Esempio n. 16
0
        /// <summary>
        /// <c>m_WC_UploadDataCompleted</c> Event handler
        /// WebCLinet Async completed event
        /// executes oncompleting uploading and call method to update grid row. and 
        /// GetListItemsAsyncWrapper method to complete the process of uploading in sharepoint 2007.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_WC_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            try
            {
                int test = sendingRequestCount;
                string outMessage = string.Empty;
                string sucessURL = string.Empty;
                UploadItemsData uploadData = (UploadItemsData)e.UserState;
                try
                {
                    receivingRequestCount++;

                    // execute the CopyIntoItems method

                    //Set the file name to global variable
                    m_uploadingFileName = uploadData.UploadFileName;
                    if (e.Error != null)
                    {
                        Exception ex = e.Error;
                        if (Convert.ToString(ex.Message) == "Object reference not set to an instance of an object.")
                        {
                            outMessage = "Cause :: No prermission to access the List.(OR) List or Library is deleted or moved";
                        }
                        else if (Convert.ToString(ex.Message) == "InvalidUrl")
                        {
                            outMessage = "Upload Falied.Filename contains some special characters." + ex.Message;
                        }
                        else
                        {
                            outMessage = ex.Message;
                        }
                        m_isUploadingCompleted = true;
                        UpdataGridRows(false, outMessage, sucessURL, uploadData);

                        //return false;
                    }
                    else
                    {
                        Byte[] result = e.Result;

                        XmlDocument xmlDoc = new XmlDocument();
                        XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");

                        XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
                        XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

                        ndQueryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" +
                            "<DateInUtc>TRUE</DateInUtc>";
                        //send required fields information
                        ndViewFields.InnerXml = "<FieldRef Name='ID'/> <FieldRef Name='LinkTitle'/>";

                        ndQuery.InnerXml = "<Where><Eq><FieldRef Name='FileLeafRef'></FieldRef><Value Type='Text'>" + uploadData.UploadFileName + "</Value></Eq></Where>";

                        //Call items details ASYNC
                        // listService.GetListItemsAsync(m_uploadDocLibraryName, null, ndQuery, ndViewFields, "2", ndQueryOptions, null, uploadData);
                        //  lstwebclass.GetListItemsAsync(m_uploadDocLibraryName, null, ndQuery, ndViewFields, "2", ndQueryOptions, null, uploadData, cmproperties);
                        if (SPVersionClass.SPSiteVersion == SPVersionClass.SiteVersion.SP2007.ToString())
                        {
                            GetListItemsAsyncWrapper(m_uploadDocLibraryName, null, ndQuery, ndViewFields, "2", ndQueryOptions, null, uploadData, cmproperties);
                        }
                        m_isUploadingCompleted = false;
                        // HideProgressPanel(true);

                    }

                }
                catch (Exception ex)
                {
                    outMessage = ex.Message;
                    if (ex.InnerException != null)
                    {
                        outMessage = ex.InnerException.Message;
                    }
                    m_isUploadingCompleted = true;
                    DelegateUpdateGridRow pdSteps = new DelegateUpdateGridRow(UpdataGridRows);
                    this.Invoke(pdSteps, new object[] { false, "Exception in CopyIntoItemsCompleted Event." + outMessage, sucessURL, uploadData });
                    // ShowMessageBox(ex.Message, MessageBoxIcon.Error);
                }

            }
            catch (Exception ex)
            {
                EncodingAndDecoding.ShowMessageBox("UploadDataAsync", ex.Message, MessageBoxIcon.Error);
            }
        }
Esempio n. 17
0
 void AtomEntryCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     toolStripProgressBar.Value = 100;
     toolStripStatusLabel.Text = "Atom entry created successfully";
 }
Esempio n. 18
0
 void UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     MessageBox.Show("Your previous deposit was successfully deleted");
     toolStripProgressBar.Value = 100;
     toolStripStatusLabel.Text = "Delete successful ";
 }
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// uploaddatacompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this UploadDataCompletedEventHandler uploaddatacompletedeventhandler, Object sender, UploadDataCompletedEventArgs e, AsyncCallback callback)
        {
            if(uploaddatacompletedeventhandler == null) throw new ArgumentNullException("uploaddatacompletedeventhandler");

            return uploaddatacompletedeventhandler.BeginInvoke(sender, e, callback, null);
        }
Esempio n. 20
0
 /// <summary>
 /// This event is raised each time an asynchronous data upload operation completes
 /// </summary>
 private void Gett_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     UploadDataCompletedEventHandler copyUploadDataCompleted = UploadDataCompleted;
     if (copyUploadDataCompleted != null)
         copyUploadDataCompleted(this, e);
 }
 protected virtual new void OnUploadDataCompleted(UploadDataCompletedEventArgs e)
 {
 }
Esempio n. 22
0
 void PostComplete(object sender, UploadDataCompletedEventArgs e)
 {
     var upload = (UploadState)e.UserState;
     if ( upload.Scrape != null ) {
         var result = upload.Client.Encoding.GetString(e.Result);
         Match m = upload.Scrape.Match(result);
         bool success = m.Success;
         if ( success ) View.BeginTryPasteLink(m.Groups[1].Value);
     } else {
         View.BeginTryPasteLink( upload.Client.ResponseUri.ToString() );
     }
     upload.Client.Dispose();
 }
        private void AuthenticateListener_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                if (ExceptionReceived != null)
                {
                    Exception exception = new Exception("Request was cancelled.");
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
                }

                return;
            }

            if (e.Error != null)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(e.Error));

                return;
            }

            AuthenticationResult authenticationResult = null;

            try
            {
                String response = System.Text.Encoding.ASCII.GetString(e.Result);

                string faultString = GetFaultString(response);

                if (!String.IsNullOrEmpty(faultString))
                {
                    if (ExceptionReceived != null)
                        ExceptionReceived(this, new EventArgs<Exception>(new Exception(faultString)));

                    return;
                }

                Dictionary<string, string> dict = ParseAuthListenerXml(response);

                _lid = dict["listenerId"];
                _authenticationToken = dict["authToken"];

                authenticationResult = new AuthenticationResult();

                int daysLeft = 0;
                int.TryParse(dict["subscriptionDaysLeft"], out daysLeft);

                authenticationResult.SubscriptionDaysLeft = daysLeft;
                authenticationResult.Subscriber = dict["listenerState"] == "SUBSCRIBER" && daysLeft > 0;
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));

                return;
            }

            if (AuthenticateComplete != null)
                AuthenticateComplete(this, new EventArgs<AuthenticationResult>(authenticationResult));
        }
Esempio n. 24
0
 private void webClient_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     if (e.Error != null)
         m_Holder = e.Error;
     m_Uploading = false;
 }
        private void Search_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                if (ExceptionReceived != null)
                {
                    Exception exception = new Exception("Request was cancelled.");
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
                }

                return;
            }

            if (e.Error != null)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(e.Error));

                return;
            }

            List<SearchResult> searchResults = null;

            try
            {
                String response = System.Text.Encoding.ASCII.GetString(e.Result);

                string faultString = GetFaultString(response);

                if (!String.IsNullOrEmpty(faultString))
                {
                    if (ExceptionReceived != null)
                        ExceptionReceived(this, new EventArgs<Exception>(new Exception(faultString)));

                    return;
                }

                searchResults = ParseSearchResultsXml(response);
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));

                return;
            }

            if (SearchComplete != null)
                SearchComplete(this, new EventArgs<List<SearchResult>>(searchResults));
        }
Esempio n. 26
0
        private void Client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (OnComplete != null && !e.Cancelled)
            {
                if (e.Error == null)
                {
                    LLSD result = LLSDParser.DeserializeXml(e.Result);

                    try { OnComplete(this, result, e.Error); }
                    catch (Exception ex) { SecondLife.LogStatic(ex.ToString(), Helpers.LogLevel.Error); }
                }
                else
                {
                    if (Helpers.StringContains(e.Error.Message, "502"))
                    {
                        // These are normal, retry the request automatically
                        SecondLife.DebugLogStatic("502 error from capability " + _Client.Location);
                        StartRequest(_PostData, _ContentType);
                    }
                    else
                    {
                        try { OnComplete(this, null, e.Error); }
                        catch (Exception ex) { SecondLife.LogStatic(ex.ToString(), Helpers.LogLevel.Error); }
                    }
                }
            }
            else if (e.Cancelled)
            {
                SecondLife.DebugLogStatic("Capability action at " + _Client.Location + " cancelled");
            }
        }
        private void Sync_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                if (ExceptionReceived != null)
                {
                    Exception exception = new Exception("Request was cancelled.");
                    ExceptionReceived(this, new EventArgs<Exception>(exception));
                }

                return;
            }

            if (e.Error != null)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(e.Error));

                return;
            }

            try
            {
                String response = System.Text.Encoding.ASCII.GetString(e.Result);

                string faultString = GetFaultString(response);

                if (!String.IsNullOrEmpty(faultString))
                {
                    if (ExceptionReceived != null)
                        ExceptionReceived(this, new EventArgs<Exception>(new Exception(faultString)));

                    return;
                }

                Dictionary<string, string> dict = ParseSyncXml(response);

                _time = int.Parse(EncryptionHelper.DecryptUrlHex(dict["time"]).Substring(4, 10));
            }
            catch (Exception exception)
            {
                if (ExceptionReceived != null)
                    ExceptionReceived(this, new EventArgs<Exception>(exception));

                return;
            }

            AuthenticateListenerAsync();
        }
Esempio n. 28
0
 private void uploadSyncXmlCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     var res = e.Result;
       try
       {
     var resXml = enc_.GetString(res);
     OperaLink.Utils.ODS(resXml);
     readServerInfo(resXml);
     { typeds_.FromOperaLinkXml(resXml); typeds_.SyncDone(); }
     { ses_.FromOperaLinkXml(resXml); ses_.SyncDone(); }
     { sds_.FromOperaLinkXml(resXml); sds_.SyncDone(); }
     { notes_.FromOperaLinkXml(resXml); notes_.SyncDone(); }
     { bms_.FromOperaLinkXml(resXml); bms_.SyncDone(); }
     LastStatus = "Sync Success.";
     OnSyncSuccessed(new EventArgs());
       }
       catch (WebException wex)
       {
     Utils.ODS(wex.StackTrace);
     LastStatus = "Sync Failed.";
     OnSyncFailed(new EventArgs());
       }
 }
Esempio n. 29
0
 private static void log_update_done(object sender, UploadDataCompletedEventArgs e)
 {
     if (e.Error == null) {
         try
         {
             File.Delete(log_files[cur_upload_index]);
             cur_upload_index++;
             while (log_files != null && log_files.Length > cur_upload_index)
             {
                 if (kickoff_upload(log_files[cur_upload_index]) == true) break; //success, upload in complete callback when it done.
                 cur_upload_index++;
             }
         }
         catch (Exception ex){
             return;
         }
     }
 }
Esempio n. 30
0
        private void OnCreatePackageCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            var state = (PublishState)e.UserState;
            if (e.Error != null) {
                Exception error = e.Error;

                WebException webException = e.Error as WebException;
                if (webException != null) {
                    var response = (HttpWebResponse)webException.Response;
                    if (response.StatusCode == HttpStatusCode.InternalServerError) {
                        // real error message is contained inside the response body
                        using (Stream stream = response.GetResponseStream()) {
                            string errorMessage = stream.ReadToEnd();
                            error = new WebException(errorMessage, webException, webException.Status,
                                                     webException.Response);
                        }
                    }
                }

                state.ProgressObserver.OnError(error);
            }
            else if (!e.Cancelled) {
                if (state.PackageMetadata != null) {
                    PublishPackage(state);
                }
                else {
                    state.ProgressObserver.OnCompleted();
                }
            }

            var client = (WebClient)sender;
            client.Dispose();
        }
        private static void wc_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            ICommand cmd;
            if (!e.Cancelled)
            {
                if (e.Error != null)
                {
                    WebException ex = e.Error as WebException;
                    string title = OtherStrings.Error;
                    if (ex.Response != null)
                    {
                        HttpWebResponse response = (HttpWebResponse)ex.Response;
                        if (response.StatusCode == HttpStatusCode.Conflict && ((TransmissonRequest)e.UserState).allowRecursion)
                        {
                            try
                            {
                                string sessionid = ex.Response.Headers["X-Transmission-Session-Id"];
                                if (sessionid != null && sessionid.Length > 0)
                                {
                                    TransmissionWebClient.X_transmission_session_id = sessionid;
                                    (sender as TransmissionWebClient).UploadDataAsync(
                                        new Uri(Program.Settings.Current.RpcUrl), null,
                                        ((TransmissonRequest)e.UserState).data,
                                        new TransmissonRequest(((TransmissonRequest)e.UserState).requestid,
                                        ((TransmissonRequest)e.UserState).data, false));
                                    return;
                                }
                            }
                            catch { }
                        }
                        else if (response.StatusCode == HttpStatusCode.NotFound)
                        {
                            title = OtherStrings.NotFound;
                            ex = new WebException(OtherStrings.NotFoundError);
                        }
                        else if (response.StatusCode == HttpStatusCode.Forbidden || response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
                            {
                                string s = sr.ReadToEnd();
                                if (s.Contains("Unauthorized IP Address."))
                                {
                                    title = OtherStrings.UnauthorizedIP;
                                    ex = new WebException(OtherStrings.UnauthorizedIPError);
                                }
                                else if (s.Contains("Unauthorized User"))
                                {
                                    title = OtherStrings.UnauthorizedUser;
                                    ex = new WebException(OtherStrings.UnauthorizedUserError);
                                }
                            }
                        }
                    }
                    cmd = new ErrorCommand(title, ex.Message, false);
                }
                else
                {
                    try
                    {
#if LOGRPC
                        Program.LogDebug("RPC response: " + ((TransmissonRequest)e.UserState).requestid, GetString(e.Result));
#endif
                        JsonObject jsonResponse = (JsonObject)JsonConvert.Import(GetString(e.Result));
                        if ((string)jsonResponse["result"] != "success")
                        {
                            string response = (string)jsonResponse["result"];
                            if (response.StartsWith("http error"))
                            {
                                int i = response.IndexOf(':');
                                if (i >= 0)
                                    response = response.Substring(i + 2);
                                else
                                    response = response.Remove(0, 11); /* strlen("http error") = 11 */

                                cmd = new ErrorCommand(OtherStrings.UnsuccessfulRequest, string.Format(OtherStrings.HttpError, Environment.NewLine, response), true);
                            }
                            else
                                cmd = new ErrorCommand(OtherStrings.UnsuccessfulRequest, response, true);
                            if (Toolbox.ToShort(jsonResponse[ProtocolConstants.KEY_TAG]).Equals((short)ResponseTag.UpdateBlocklist))
                                RemoteSettingsDialog.BlocklistUpdateDone(-1);
                        }
                        else
                        {
                            switch (Toolbox.ToShort(jsonResponse[ProtocolConstants.KEY_TAG]))
                            {
                                case (short)ResponseTag.TorrentGet:
                                    cmd = new TorrentGetCommand(jsonResponse);
                                    break;

                                case (short)ResponseTag.SessionGet:
                                    cmd = new SessionCommand(jsonResponse, (sender as WebClient).Headers);
                                    break;

                                case (short)ResponseTag.SessionStats:
                                    cmd = new SessionStatsCommand(jsonResponse);
                                    break;

                                case (short)ResponseTag.UpdateFiles:
                                    cmd = new UpdateFilesCommand(jsonResponse);
                                    break;

                                case (short)ResponseTag.PortTest:
                                    cmd = new PortTestCommand(jsonResponse);
                                    break;

                                case (short)ResponseTag.UpdateBlocklist:
                                    cmd = new UpdateBlocklistCommand(jsonResponse);
                                    break;

                                case (short)ResponseTag.DoNothing:
                                    cmd = new NoCommand();
                                    break;

                                default:
                                    cmd = new ErrorCommand(OtherStrings.UnknownResponseTag, e.Result != null ? GetString(e.Result) : "null", false);
                                    break;
                            }
                        }
                    }
                    catch (InvalidCastException)
                    {
                        cmd = new ErrorCommand(OtherStrings.UnableToParse, e.Result != null ? GetString(e.Result) : "Null", false);
                    }
                    catch (JsonException ex)
                    {
                        cmd = new ErrorCommand(string.Format("{0} ({1})", OtherStrings.UnableToParse, ex.GetType()), GetString(e.Result), false);
                    }
                    catch (Exception ex)
                    {
                        cmd = new ErrorCommand(ex, false);
                    }
                }
                try
                {
                    cmd.Execute();
                }
                catch (Exception ee) // just for debugging...
                {
                    Console.WriteLine(ee.Message);
                    Program.LogDebug(ee.Source, ee.Message);
                }
                (sender as TransmissionWebClient).OnCompleted(cmd);
            }
            else
            {
                if (!Program.Connected)
                {
                    Program.Connected = false;
                    Program.Form.UpdateStatus("", false);
                    Program.Form.connectButton.Enabled = Program.Form.connectToolStripMenuItem.Enabled = true;
                }
            }
        }
Esempio n. 32
0
 void client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e) { ProcessResponse(e, e.Result); }
Esempio n. 33
0
 protected virtual void OnUploadDataCompleted(UploadDataCompletedEventArgs args)
 {
     CompleteAsync();
     if (UploadDataCompleted != null)
         UploadDataCompleted(this, args);
 }
Esempio n. 34
0
 protected virtual void OnUploadDataCompleted(UploadDataCompletedEventArgs e)
 {
     throw new NotImplementedException();
 }