/// <summary>
        /// Valida, baseado na exceção disparada, se corresponde a uma exceção de timeout, que pode corresponder a diferentes tipos de exceção.
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public static bool IsTimeoutException(this System.Exception exception)
        {
            if (exception.GetType() == typeof(AggregateException))
            {
                AggregateException aggregateException = (AggregateException)exception;
                if (aggregateException.InnerExceptions.Any(e => e.GetType() == typeof(TaskCanceledException)))
                {
                    return(true);
                }
            }

            if (exception.GetType() == typeof(TimeoutException))
            {
                return(true);
            }

            if (exception.GetType() == typeof(System.Net.WebException))
            {
                System.Net.WebException webException = (System.Net.WebException)exception;
                if (webException.Status == System.Net.WebExceptionStatus.Timeout)
                {
                    return(true);
                }
            }
            return(false);
        }
 internal AsyncOrganizationServiceConfiguration(Uri serviceUri, bool enableProxyTypes, Assembly assembly)
 {
     try {
         this.service = new ServiceConfigurationWrapper <IWcfAsyncOrganizationService>(serviceUri, true);
         if (enableProxyTypes && assembly != null)
         {
             this.EnableProxyTypes(assembly);
         }
         else if (enableProxyTypes)
         {
             this.EnableProxyTypes();
         }
     } catch (InvalidOperationException ex2) {
         bool flag = true;
         System.Net.WebException ex = ex2.InnerException as System.Net.WebException;
         if (ex != null)
         {
             System.Net.HttpWebResponse httpWebResponse = ex.Response as System.Net.HttpWebResponse;
             if (httpWebResponse != null && httpWebResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
             {
                 flag = !this.AdjustServiceEndpoint(serviceUri);
             }
         }
         if (flag)
         {
             throw;
         }
     }
 }
示例#3
0
 private void lstDbs_Click(object sender, EventArgs ev)
 {
     try
     {
         lsttables.Items.Clear();
         if ((MainWindow.username != null) && (MainWindow.pass != null))
         {
             this.lsttables.Items.AddRange(Program.client.ListTables(MainWindow.username, MainWindow.pass, lstDbs.Text).ToArray());
         }
         else
         {
             Login log = new Login();
             log.Show();
             this.lsttables.Items.AddRange(Program.client.ListTables(MainWindow.username, MainWindow.pass, lstDbs.Text).ToArray());
         }
     }
     catch (Exception ex)
     {
         System.Net.WebException webex = new System.Net.WebException();
         if (ex.GetType() != webex.GetType())
         {
             Program.errorreport(ex);
         }
         else
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
        public UnhandledExceptionDialog(ILogProvider fileLogProvider, Exception e)
        {
            InitializeComponent();

            if (e != null)
            {
                _UnhandledException = e;

                if (e.GetType() == typeof(System.Net.WebException))
                {
                    System.Net.WebException webException = (System.Net.WebException)e;
                    Stream responseStream = webException.Response.GetResponseStream();
                    responseStream.Position = 0;
                    StreamReader sr           = new StreamReader(responseStream);
                    string       responseBody = sr.ReadToEnd();
                    textBox1.Text = responseBody + Environment.NewLine + Environment.NewLine + webException.Message + Environment.NewLine + Environment.NewLine + webException.StackTrace;
                }
                else
                {
                    textBox1.Text = e.Message + Environment.NewLine + e.StackTrace;
                }
            }

            if (fileLogProvider != null)
            {
                _LogProvider = fileLogProvider;
                _LogProvider.WriteLog("UnhandledExceptionDialog", textBox1.Text);
            }
        }
示例#5
0
        public void DbEntityValidationFailureProducesUsableMessage()
        {
            using (TestWebRequest request = TestWebRequest.CreateForInProcess())
            {
                request.DataServiceType    = ContextType;
                request.ForceVerboseErrors = true;
                request.RequestContentType = UnitTestsUtil.AtomFormat;

                string       uri          = "/Elevators(2)";
                XName        elementName  = XName.Get("SerialNumber", ODataNamespace);
                const string changedValue = "123456";

                request.HttpMethod       = "GET";
                request.Accept           = "application/atom+xml,application/xml";
                request.RequestStream    = null;
                request.RequestUriString = uri;
                request.SendRequest();

                XDocument entry = request.GetResponseStreamAsXDocument();

                XElement element = entry.Descendants(elementName).Single();

                element.Value = changedValue;

                request.HttpMethod    = "PATCH";
                request.Accept        = "application/atom+xml,application/xml";
                request.RequestStream = IOUtil.CreateStream(entry.ToString(SaveOptions.DisableFormatting));

                System.Net.WebException exception = TestUtil.RunCatching <System.Net.WebException>(() => request.SendRequest());

                Assert.IsNotNull(exception, "Expected an exception, but none occurred.");
                Assert.IsNotNull(exception.InnerException, "Expected an inner exception, but found none");
                Assert.AreEqual("The field SerialNumber must be a string with a minimum length of 5 and a maximum length of 5.", exception.InnerException.Message, "Didn't get the expected error message");
            }
        }
示例#6
0
        public override void ExceptionHandler(Exception ex)
        {
#if DEBUG
            Console.Error.WriteLine(ex.ToString());
#endif

            Console.Error.WriteLine();

            ArgumentException aex = ex as ArgumentException;
            if (aex != null)
            {
                Console.Error.WriteLine("ERROR: {0}", ex.Message);
                ShowHelp();
                Environment.Exit(1);
            }

            System.Net.WebException wex = ex as System.Net.WebException;
            if (wex != null)
            {
                Console.Error.WriteLine("An error occurred while accessing the network:");
                Console.Error.WriteLine("{0} ({1})", wex.Message, wex.Status);
                if (wex.Response != null)
                {
                    Console.Error.WriteLine("URI: {0}", wex.Response.ResponseUri);
                }

                Environment.Exit(2);
            }

            Console.Error.WriteLine("ERROR: {0}", ex);
            Environment.Exit(2);
        }
示例#7
0
        private static void ContactHosts()
        {
            if ((HostList == null) || (HostList.Count <= 0))
            {
                return;
            }
            foreach (HostInfo info in HostList)
            {
                if (string.IsNullOrEmpty(info.URL) || (info.Func == null))
                {
                    continue;
                }

                MelonDebug.Msg($"ContactURL = {info.URL}");

                string Response = null;
                try { Response = Core.webClient.DownloadString(info.URL); }
                catch (Exception ex)
                {
                    if (!(ex is System.Net.WebException) || ((System.Net.WebException)ex).Response == null)
                    {
                        MelonLogger.Error($"Exception while Contacting RemoteAPI Host ({info.URL}): {ex}");
                        continue;
                    }

                    System.Net.WebException    we       = (System.Net.WebException)ex;
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        MelonDebug.Msg($"Game Not Found on RemoteAPI Host ({info.URL})");
                        break;
                    }

                    MelonLogger.Error($"WebException ({Enum.GetName(typeof(System.Net.HttpStatusCode), response.StatusCode)}) while Contacting RemoteAPI Host ({info.URL}): {ex}");
                    continue;
                }

                bool is_response_null = string.IsNullOrEmpty(Response);
                MelonDebug.Msg($"Response = {(is_response_null ? "null" : Response) }");
                if (is_response_null)
                {
                    break;
                }

                InfoStruct returnInfo = info.Func(Response);
                if (returnInfo == null)
                {
                    continue;
                }

                if (returnInfo.ForceDumperVersion != null && SemVersion.Parse(returnInfo.ForceDumperVersion) <= SemVersion.Parse("2022.0.2"))
                {
                    returnInfo.ForceDumperVersion = null;
                }

                Info = returnInfo;
                break;
            }
        }
示例#8
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.WebRequest r = null;
            try
            {
                r = System.Net.WebRequest.Create(textBox1.Text);
            }catch (Exception cv)
            {
                textBox2.Text = cv.Message;
                return;
            }
            r.ContentType = "text/xml";
            //r.Headers.Add("Content-Type:  application/soap+xml; charset=utf-8");
            //r.Headers.Add("Content-Length:  " + textBox2.Text.Length.ToString());
            r.Method = "POST";
            if (!String.IsNullOrWhiteSpace(textBox4.Text))
            {
                r.Headers.Add("SOAPAction: \"" + textBox4.Text + "\"");
            }
            System.IO.Stream       reqstream = r.GetRequestStream();
            System.IO.StreamWriter sw        = new System.IO.StreamWriter(reqstream);
            sw.Write(textBox2.Text);
            sw.Flush();
            try
            {
                //r.ContentLength = textBox2.Text.Length; //reqstream.Position;
                System.Net.WebResponse resp = r.GetResponse();

                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                textBox3.Text = sr.ReadToEnd();
                sr.Dispose();
                resp.Dispose();
            }
            catch (Exception ext)
            {
                textBox3.Text  = ext.Message + "\r\n" + ext.StackTrace;
                textBox3.Text += "\r\n";
                if (ext is System.Net.WebException)
                {
                    System.Net.WebException webex = (System.Net.WebException)ext;
                    try
                    {
                        using (System.IO.StreamReader exceptionreader = new System.IO.StreamReader(webex.Response.GetResponseStream()))
                        {
                            textBox3.Text += exceptionreader.ReadToEnd();
                        }
                    }catch (Exception ffff)
                    {
                        textBox3.Text += "\r\n Unknown Error trying to read response from Server";
                    }
                }
            }
            finally
            {
                sw.Dispose();
            }
            tabControl1.SelectedTab = tabPage2;
        }
示例#9
0
 public void FilmLookup_handles_timeout_by_passing_status()
 {
     var exception = new System.Net.WebException("The operation has timed out", System.Net.WebExceptionStatus.Timeout);
     var result = new FilmLookupService(new MockHttpService(s => { throw exception; })).Search("The Usual Status");
     var message = result.FailureMessage();
     Assert.IsTrue(message.Contains("timed out"));
     Assert.IsTrue(message.Contains("myapifilms"));
     Assert.IsTrue(message.Contains("Usual"));
 }
 private void GetOrthoOrder()
 {
     Orderlist_Ortho = new List <Dll_Airdental.Main._orthoOrder>();
     System.Net.WebException Exception_ortho = orthoBase_AirDental.GetOrthoOrder(ref Orderlist_Ortho, orthoProjectInfo.Pid);
     if (Exception_ortho == null)
     {
         LoadOrthoOrders();
     }
 }
示例#11
0
 private void GetCADOrder()
 {
     Orderlist_CAD = new List <Dll_Airdental.Main._cadOrder>();
     System.Net.WebException Exception_implant = cadBase_AirDental.GetCADOrder(ref Orderlist_CAD, cadProjectInfo.Pid);
     if (Exception_implant == null)
     {
         LoadCADOrders();
     }
 }
        void _proxy_OnWebException(System.Net.WebException exception)
        {
            var handler = OnWebException;

            if (handler != null)
            {
                handler(exception);
            }
        }
 private void GetImplantOrder()
 {
     Orderlist_Implant = new List <Dll_Airdental.Main._implantOrder>();
     System.Net.WebException Exception_implant = implantBase_AirDental.GetImplantOrder(ref Orderlist_Implant, implantProjectInfo.Pid);
     if (Exception_implant == null)
     {
         LoadImplantOrders();
     }
 }
示例#14
0
        public void FilmLookup_handles_timeout_by_passing_status()
        {
            var exception = new System.Net.WebException("The operation has timed out", System.Net.WebExceptionStatus.Timeout);
            var result    = new FilmLookupService(new MockHttpService(s => { throw exception; })).Search("The Usual Status");
            var message   = result.FailureMessage();

            Assert.IsTrue(message.Contains("timed out"));
            Assert.IsTrue(message.Contains("myapifilms"));
            Assert.IsTrue(message.Contains("Usual"));
        }
示例#15
0
        public static void SongNameNotFoundLog(System.Net.WebException e, string songname)
        {
            List <string> log = new List <string>();

            log.Add("SongNameNotFoundError");
            log.Add("Fehlermeldung: " + e.Message);
            log.Add("Der Song \"" + songname + "\" konnte nicht in der CCLI-Datenbank gefunden werden.");
            log.Add("Fehlerbehebung: CCLI-Nummer überprüfen, ggf. ändern und Programm neustarten");
            Errorlogs.PrintLogs(log);
        }
示例#16
0
        public static void AnalyseDotNetOpenAuth(DotNetOpenAuth.Messaging.ProtocolException ex)
        {
            Dictionary <String, String> errors = null;
            String webExceptionStr_orig        = "";

            System.Net.WebException webException = null;
            //Process exact error
            try {
                webException         = ex.InnerException as System.Net.WebException;
                webExceptionStr_orig = extractResponseString(webException);
            } catch (System.Exception subEx) {
                log.Error("Failed to retrieve WebException: " + subEx.Message);
                log.Debug(ex.Message);
                throw ex;
            }
            if (string.IsNullOrEmpty(webExceptionStr_orig))
            {
                //Not an OAuthErrorMsg
                log.Error(webException.Message);
                throw ex;
            }
            try {
                /* Could treat this properly with JSON but would be another dll just to handle this situation.
                 * OAuthErrorMsg error =
                 * JsonConvert.DeserializeObject<OAuthErrorMsg>(ExtractResponseString(webException));
                 * var errorMessage = error.error_description;
                 */
                //String webExceptionStr = "{\n  \"error\" : \"invalid_client\",\n  \"error_description\" : \"The OAuth client was not found.\"\n}";
                String webExceptionStr = webExceptionStr_orig.Replace("\"", "");
                webExceptionStr = webExceptionStr.TrimStart('{'); webExceptionStr = webExceptionStr.TrimEnd('}');
                errors          = webExceptionStr.Split(new String[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
                                  .Select(s => s.Split(':')).ToDictionary(x => x[0].Trim(), x => x[1].Trim().TrimEnd(','));
            } catch (System.Exception subEx) {
                log.Error("Failed to process exact WebException: " + subEx.Message);
                log.Debug(webExceptionStr_orig);
                throw ex;
            }

            if (errors.ContainsKey("error"))
            {
                String instructions = "On the Settings > Google tab, please disconnect and re-authenticate your account.";
                if ("invalid_client;unauthorized_client".Contains(errors["error"]))
                {
                    throw new System.Exception("Invalid authentication token. Account requires reauthorising.\r\n" + instructions, ex);
                }
                else if (errors["error"] == "invalid_grant")
                {
                    throw new System.Exception("Google has revoked your authentication token. Account requires reauthorising.\r\n" + instructions, ex);
                }
            }
            log.Debug("Unknown web exception.");
            throw ex;
        }
示例#17
0
        private static bool ContactHosts(Dictionary <string, Func <string, InfoStruct, bool> > hostsdict)
        {
            if ((hostsdict == null) || (hostsdict.Count <= 0))
            {
                return(false);
            }
            foreach (KeyValuePair <string, Func <string, InfoStruct, bool> > pair in hostsdict)
            {
                if (string.IsNullOrEmpty(pair.Key) || (pair.Value == null))
                {
                    continue;
                }

                MelonDebug.Msg($"ContactURL = {pair.Key}");

                string Response = null;
                try { Response = Core.webClient.DownloadString(pair.Key); }
                catch (Exception ex)
                {
                    if (!(ex is System.Net.WebException))
                    {
                        MelonLogger.Error($"Exception while Contacting RemoteAPI Host ({pair.Key}): {ex}");
                        continue;
                    }

                    System.Net.WebException    we       = (System.Net.WebException)ex;
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        MelonDebug.Msg($"Game Not Found on RemoteAPI Host ({pair.Key})");
                        break;
                    }

                    MelonLogger.Error($"WebException ({Enum.GetName(typeof(System.Net.HttpStatusCode), response.StatusCode)}) while Contacting RemoteAPI Host ({pair.Key}): {ex}");
                    continue;
                }

                bool is_response_null = string.IsNullOrEmpty(Response);
                MelonDebug.Msg($"Response = {(is_response_null ? "null" : Response) }");
                if (is_response_null)
                {
                    break;
                }
                if (pair.Value(Response, ReturnedInfo))
                {
                    return(true);
                }
            }
            return(false);
        }
示例#18
0
 private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     if (!e.Handled)
     {
         System.Net.WebException ex = e.Exception as System.Net.WebException;
         if (ex != null)
         {
             e.Handled = true;
             Pages.ErrorPage errorPage = new Mubox.QuickLaunch.Pages.ErrorPage();
             errorPage.DataContext = ex;
             frameContentPage.Navigate(errorPage);
         }
     }
 }
示例#19
0
        public void TestExceptionExtensions ()
        {
            Exception nullException = null;
            var normalException = new Exception ();
            var networkException = new System.Net.WebException ();
            var nestedNetworkException = new Exception ("", new System.Net.Sockets.SocketException ());
            var nestedNonNetworkException = new Exception ("", new Exception ());

            Assert.IsFalse (nullException.IsNetworkFailure ());
            Assert.IsFalse (normalException.IsNetworkFailure ());
            Assert.IsTrue (networkException.IsNetworkFailure ());
            Assert.IsTrue (nestedNetworkException.IsNetworkFailure ());
            Assert.IsFalse (nestedNonNetworkException.IsNetworkFailure ());
        }
示例#20
0
        public void TestExceptionExtensions()
        {
            Exception nullException             = null;
            var       normalException           = new Exception();
            var       networkException          = new System.Net.WebException();
            var       nestedNetworkException    = new Exception("", new System.Net.Sockets.SocketException());
            var       nestedNonNetworkException = new Exception("", new Exception());

            Assert.IsFalse(nullException.IsNetworkFailure());
            Assert.IsFalse(normalException.IsNetworkFailure());
            Assert.IsTrue(networkException.IsNetworkFailure());
            Assert.IsTrue(nestedNetworkException.IsNetworkFailure());
            Assert.IsFalse(nestedNonNetworkException.IsNetworkFailure());
        }
        static StackObject *get_Status_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Net.WebException instance_of_this_method = (System.Net.WebException) typeof(System.Net.WebException).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.Status;

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
示例#22
0
        protected bool DownloadFile(string sFile, string sTargetFolder)
        {
            const int MAXATTEMPTS = 3;
            int       iAttempts   = 0;
            string    sSource     = GetShortestAbsolutePath(sFile);

            while (iAttempts++ < MAXATTEMPTS)
            {
                try
                {
                    string sTarget = GetShortestAbsolutePath(sTargetFolder + UrlUtil.GetFileName(sSource));
                    KeePassLib.Serialization.IOConnectionInfo ioc = KeePassLib.Serialization.IOConnectionInfo.FromPath(sSource);
                    Stream s = KeePassLib.Serialization.IOConnection.OpenRead(ioc);
                    if (s == null)
                    {
                        throw new InvalidOperationException();
                    }
                    MemoryStream ms = new MemoryStream();
                    MemUtil.CopyStream(s, ms);
                    s.Close();
                    byte[] pb = ms.ToArray();
                    ms.Close();
                    //Create target folder, Directory.CreateDirectory internally checks for existance of the folder
                    Directory.CreateDirectory(sTargetFolder);
                    File.WriteAllBytes(sTarget, pb);
                    m_lDownloaded.Add(sTarget);
                    PluginDebug.AddInfo("Download success", 0, "Source: " + sSource, "Target: " + sTargetFolder, "Download attempt: " + iAttempts.ToString());
                    return(true);
                }
                catch (Exception ex)
                {
                    PluginDebug.AddInfo("Download failed", 0, "Source: " + sSource, "Target: " + sTargetFolder, "Download attempt: " + iAttempts.ToString(), ex.Message);

                    System.Net.WebException exWeb = ex as System.Net.WebException;
                    if (exWeb == null)
                    {
                        continue;
                    }
                    System.Net.HttpWebResponse wrResponse = exWeb.Response as System.Net.HttpWebResponse;
                    if ((wrResponse == null) || (wrResponse.StatusCode != System.Net.HttpStatusCode.NotFound))
                    {
                        continue;
                    }
                    iAttempts = MAXATTEMPTS;
                }
            }
            return(false);
        }
示例#23
0
        public void LogException(Exception e)
        {
            string webExceptionStatus = String.Empty;
            if (WebExceptionType.Equals(e.GetType()))
            {
                System.Net.WebException we = (System.Net.WebException)e;
                webExceptionStatus = " " + we.Status;
            }

            Log(
                LogType.EXCEPTION,
                e.GetType().FullName + ":" +
                webExceptionStatus + NEWLINE +
                e.Message + NEWLINE +
                e.StackTrace);
        }
示例#24
0
        private static string GetExceptionDetails(System.Net.WebException exception)
        {
            string details = null;

            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)exception.Response;

            using (System.IO.Stream strm = response.GetResponseStream())
            {
                if (strm != null)
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(strm))
                    {
                        details = sr.ReadToEnd();
                    } // End Using sr
                }     // End if (strm != null)
            }         // End Using strm

            return(details);
        } // End Function GetExceptionDetails
示例#25
0
        /// <summary>
        /// Tests the connection.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public bool TestConnection(out string message, UserType type)
        {
            bool isSuccessful = false;

            message = string.Empty;
            try
            {
                ReportingService2010SoapClient client = GetClient(UserType.ContentManager);

                Property[] userProperties = null;

                if (TestPath())
                {
                    message      = "Succesfully connected.";
                    isSuccessful = true;
                }
                else
                {
                    message = "Connection Error";
                }
            }
            catch (Exception ex)
            {
                bool caught = false;
                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(System.Net.WebException))
                {
                    System.Net.WebException webEx = (System.Net.WebException)ex.InnerException;
                    if (((System.Net.HttpWebResponse)webEx.Response).StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        message = "User is not authorized.";
                        caught  = true;
                    }
                }
                if (!caught)
                {
                    message = string.Format("An error has occurred when Loading Reporting Services. {0}", ex.Message);
                }
                isSuccessful = false;
            }

            return(isSuccessful);
        }
示例#26
0
        private static String extractResponseString(System.Net.WebException webException)
        {
            if (webException == null || webException.Response == null)
            {
                return(null);
            }

            var responseStream =
                webException.Response.GetResponseStream() as MemoryStream;

            if (responseStream == null)
            {
                return(null);
            }

            var responseBytes = responseStream.ToArray();

            var responseString = Encoding.UTF8.GetString(responseBytes);

            return(responseString);
        }
示例#27
0
        public void BadUrls()
        {
            FileDownloader downloader = new FileDownloader();

            foreach (String badUrl in badUrls)
            {
                System.Net.WebException webException = null;
                try
                {
                    downloader.Download(badUrl, OUTPUT_DIRECTORY);
                }
                catch (System.Net.WebException e)
                {
                    webException = e;
                }

                finally
                {
                    Assert.IsNotNull(webException);
                }
            }
        }
 public static System.Net.HttpWebResponse Retry(
     this System.Net.WebException ex,
     System.Net.HttpWebRequest request)
 {
     //Check if the response header contains a Retry-After value.
     if (!string.IsNullOrEmpty(ex.Response.Headers["Retry-After"]))
     {
         bool   executeOK = false;
         string accept    = request.Accept;
         string method    = request.Method;
         while (!executeOK)
         {
             System.Threading.Thread.Sleep((
                                               Convert.ToInt32(
                                                   ex.Response.Headers["Retry-After"]) + 60) * 1000);
             //We add 60 seconds to the wait time for good measure.
             request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(
                 ex.Response.ResponseUri.ToString()
                 .TrimStart('{')
                 .TrimEnd('}'));
             request.Method = method;
             request.Accept = accept;
             System.Net.WebHeaderCollection headers;
             System.Net.WebResponse         response;
             try
             {
                 response  = request.GetResponse();
                 executeOK = true;
                 return(response as System.Net.HttpWebResponse);
             }
             catch (System.Net.WebException ex2)
             {
                 return(ex2.Retry(request));
             }
         }
     }
     throw ex;  //There is no Retry-After header so just rethrow.
 }
示例#29
0
 bool IsDeploymentDownloadException(Exception ex)
 {
     if (ex == null)
     {
         return(false);
     }
     System.Deployment.Application.DeploymentDownloadException dex = ex as System.Deployment.Application.DeploymentDownloadException;
     if (dex == null)
     {
         return(IsDeploymentDownloadException(ex.InnerException));
     }
     else
     {
         if (ex.InnerException != null)
         {
             System.Net.WebException we = ex.InnerException as System.Net.WebException;
             return(we != null);
         }
         else
         {
             return(false);
         }
     }
 }
示例#30
0
 public ExceptionHandling(System.Net.WebException webEx)
 {
     webExcept = webEx;
 }
示例#31
0
 public SharingFailedException(string id, System.Net.WebException innerException) : base(string.Format(errorMessage, id), innerException)
 {
 }
示例#32
0
        ///<summary>
        ///<para>
        ///Generates an HTTP call to the specified URL with the URL encoded parameters in postData
        ///</para>       
        ///</summary>
        private string PostDataToURL(string URL, string postData)
        {
            try
            {
                Byte[] data = (new System.Text.ASCIIEncoding()).GetBytes(postData);
                var webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
                webRequest.UserAgent = _agent;
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = data.Length;
                var newStream = webRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                return
                    new System.IO.StreamReader(webRequest.GetResponse().GetResponseStream(),
                                               System.Text.Encoding.Default).ReadToEnd();
            }
            catch (System.Net.WebException e)
            {
                string content = "";
                if (e.Response == null)
                    content = e.Message;
                else
                    content = (new System.IO.StreamReader(e.Response.GetResponseStream())).ReadToEnd();

                var ex = new System.Net.WebException("Error trying to POST to " + URL + Environment.NewLine + content, e);
                throw ex;
            }
        }
示例#33
0
 /// <summary>
 /// Return the results of a Get to the WebAddresss
 /// </summary>
 /// <returns></returns>
 public string Get()
 {
     string Url = this.Url;
     try
     {
         var webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Url);
         webRequest.UserAgent = _agent;
         return
             new System.IO.StreamReader(webRequest.GetResponse().GetResponseStream(),
                                        System.Text.Encoding.Default).ReadToEnd();
     }
     catch (System.Net.WebException e)
     {
         string content = "";
         if (e.Response == null)
             content = e.Message;
         else
             content = (new System.IO.StreamReader(e.Response.GetResponseStream())).ReadToEnd();
         var ex = new System.Net.WebException("Error trying to GET " + Url + Environment.NewLine + content, e);
         throw ex;
     }
 }
示例#34
0
 private static void ThrowProtocolViolation(string message)
 {
     var we = new System.Net.WebException(message, null, System.Net.WebExceptionStatus.ServerProtocolViolation, null);
     throw we;
 }
示例#35
0
        private static void ThrowProtocolViolation(string message)
        {
            var we = new System.Net.WebException(message, null, System.Net.WebExceptionStatus.ServerProtocolViolation, null);

            throw we;
        }
        /// <summary>
        /// This function is responsible for creating a VM Network
        /// with one VM Subnet on the VSEM.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder(" \"IPSubnets\":" + JavaScriptSerializer.Serialize(this.IPSubnets));
            json.Append("\"MaxNumberOfPorts\":\"" + this.MaxNumberOfPorts + "\"");
            json.Append("\"VMSubnetName\":\"" + this.VMSubnetName + "\"");
            json.Append("\"VMNetworkName\":\"" + this.VMNetworkName + "\"");
            json.Append("\"LogicalNetworkDefinitionId\":\"" + this.LogicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                   "VM Network creation process started.",
                   json.ToString());
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            VMNetwork nw = null;
            string vtnName = string.Empty;
            string connectionString =
                this.conn.ConnectionString.Split(',').FirstOrDefault();
            VSEMVMNetworkManagement vSEMVmNetworkManagement =
                new VSEMVMNetworkManagement(connectionString, this.conn.Credential);
            try {
                nw = vSEMVmNetworkManagement.CreateVMNetwork(txnMng,
                    this.VMSubnetName,
                    this.VMNetworkName,
                    this.MaxNumberOfPorts,
                    this.IPSubnets,
                    this.LogicalNetworkDefinitionId,
                    this.conn,
                    out vtnName);
                ODLVSEMETW.EventWriteReturnLibrary("VM network is created.",
                    string.Empty);

                ope = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                Exception userException = ex;
                ODLVSEMETW.EventWriteFailedCmdlet(
                    "VM network creation is failed. ODL changes rollback is started.",
                    string.Empty);
                ope = TransactionManager.Operation.Rollback;
                try {
                    if (!string.IsNullOrEmpty(vtnName)) {
                        vSEMVmNetworkManagement.RemoveVmNetwork(vtnName);
                        ODLVSEMETW.EventWriteFailedCmdlet(
                            "VM network creation is failed. ODL changes are successfully rolled back.",
                            string.Empty);
                    }
                } catch (Exception except) {
                    ODLVSEMETW.EventWriteFailedCmdlet(
                        string.Format(CultureInfo.CurrentCulture,
                        "Due to some problem in connection with ODL, VSEM VM Network creation process is terminated in the middle of the request. VTN '{0}' may have been created on ODL, Please check. Please delete the VTN from ODL to maintain the consistency between ODL and SCVMM.\n{1}",
                        vtnName,
                        except.Message),
                        string.Empty);
                    userException =
                        new System.Net.WebException(string.Format(CultureInfo.CurrentCulture,
                            "Due to some problem in connection with ODL, VSEM VM Network creation process is terminated in the middle of the request. VTN '{0}' may have been created on ODL, Please check. Please delete the VTN from ODL to maintain the consistency between ODL and SCVMM.",
                            vtnName),
                            ex);
                }

                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(userException);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                ope = TransactionManager.Operation.Rollback;
                throw exception;
            } finally {
                txnMng.EndTransaction(ope);

                string output = "\"VM Network\":" + JavaScriptSerializer.Serialize(nw);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
                this.WriteObject(nw);
            }
        }
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="message"></param>
 /// <param name="inner"></param>
 public WeiboException(string message, System.Net.WebException inner)
     : base(message, inner)
 {
 }