예제 #1
0
        /// <summary>
        /// Explicitly load a manifest and create the process-default activation 
        /// context. It takes effect immediately and stays there until the process exits. 
        /// </summary>
        static public void CreateActivationContext()
        {
            string rootFolder = AppDomain.CurrentDomain.BaseDirectory;
            string manifestPath = Path.Combine(rootFolder, "webapp.manifest");
            UInt32 dwError = 0;

            // Build the activation context information structure 
            ACTCTX info = new ACTCTX();
            info.cbSize = Marshal.SizeOf(typeof(ACTCTX));
            info.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT;
            info.lpSource = manifestPath;
            if (null != rootFolder && "" != rootFolder)
            {
                info.lpAssemblyDirectory = rootFolder;
                info.dwFlags |= ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;
            }

            dwError = 0;

            // Create the activation context 
            IntPtr result = CreateActCtx(ref info);
            if (-1 == result.ToInt32())
            {
                dwError = (UInt32)Marshal.GetLastWin32Error();
            }

            if (-1 == result.ToInt32() && ActivationContext.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET != dwError)
            {
                string err = string.Format("Cannot create process-default win32 sxs context, error={0} manifest={1}", dwError, manifestPath);
                ApplicationException ex = new ApplicationException(err);
                throw ex;
            }
        }
예제 #2
0
파일: CMenu.cs 프로젝트: cordovaGabri/AYSSA
        public DataSet DetalleOpciones(string CodigoUsuario, string Menu, string SubMenu, string Pantalla, int OpcionConsulta)
        {
            DataSet objDataset = new DataSet();

            try
            {
                ObjConnection = new SqlConnection(_ConexionData);
                ObjAdapter    = new SqlDataAdapter("SP_TB_OPCION_USUARIO", ObjConnection);
                ObjAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;

                ObjAdapter.SelectCommand.Parameters.AddWithValue("@ID_USUARIO", CodigoUsuario);
                ObjAdapter.SelectCommand.Parameters.AddWithValue("@MENU", Menu);
                ObjAdapter.SelectCommand.Parameters.AddWithValue("@SUBMENU", SubMenu);
                ObjAdapter.SelectCommand.Parameters.AddWithValue("@PANTALLA", Pantalla);
                ObjAdapter.SelectCommand.Parameters.AddWithValue("@OPCI_CONS", OpcionConsulta);

                ObjAdapter.Fill(objDataset);

                ObjConnection.Close();

                if (ObjConnection.State != ConnectionState.Closed)
                {
                    ObjConnection.Close();
                }
            }
            catch (Exception ex)
            {
                System.ApplicationException appEx = new System.ApplicationException(ex.Message);
                throw appEx;
            }
            return(objDataset);
        }
예제 #3
0
        public void PlaySound(string soundLocation, int volume)
        {
            if (string.IsNullOrEmpty(soundLocation)) return;

            try
            {
                Log.DebugFormat("Playing sound '{0}' at volume", soundLocation, volume);

                try
                {
                    if (currentWaveOutVolume == null || currentWaveOutVolume.Value != volume)
                    {
                        int newVolume = ((ushort.MaxValue / 100) * volume);
                        uint newVolumeAllChannels = (((uint)newVolume & 0x0000ffff) | ((uint)newVolume << 16)); //Set the volume on left and right channels
                        PInvoke.waveOutSetVolume(IntPtr.Zero, newVolumeAllChannels);
                        currentWaveOutVolume = volume;
                    }
                }
                catch (Exception exception)
                {
                    var customException = new ApplicationException(
                        string.Format("There was a problem setting the wave out volume to '{0}'", volume), exception);

                    PublishError(this, customException);
                }

                var player = new System.Media.SoundPlayer(soundLocation);
                player.Play();
            }
            catch (Exception exception)
            {
                PublishError(this, exception);
            }
        }
예제 #4
0
        public void TestRetryWithDuration()
        {
            bool result = false;
            DateTime firstCallAt = DateTime.Now;
            DateTime secondCallAt = DateTime.Now;
            bool exceptionThrown = false;

            var ex = new ApplicationException("Test exception");
            var logger = MockLoggerForException(ex);
            Assert.DoesNotThrow(() =>
                {
                    AspectF.Define.Retry(5000, logger.Object).Do(() =>
                    {
                        if (!exceptionThrown)
                        {
                            firstCallAt = DateTime.Now;
                            exceptionThrown = true;
                            throw ex;
                        }
                        else
                        {
                            secondCallAt = DateTime.Now;
                            result = true;
                        }
                    });
                });
            logger.VerifyAll();

            Assert.True(exceptionThrown, "Assert.Retry did not invoke the function at all");
            Assert.True(result, "Assert.Retry did not retry the function after exception was thrown");
            Assert.InRange<Double>((secondCallAt - firstCallAt).TotalSeconds, 4.9d, 5.1d);
        }
예제 #5
0
            public Folder getFolderDetails(String folderId)
        {

            AccessTokenDao accesstokenDao = new AccessTokenDao();
            String token = accesstokenDao.getAccessToken(Common.userName);

            String url = Resource.endpoint + "wittyparrot/api/folders/" + folderId + "";
            var client = new RestClient();
            client.BaseUrl = new Uri(url);

            var request = new RestRequest();
            request.Method = Method.GET;
            request.Parameters.Clear();
            request.AddParameter("Authorization", "Bearer " + token, ParameterType.HttpHeader);
            request.RequestFormat = DataFormat.Json;

            // execute the request
            IRestResponse response = client.Execute(request);
            String content = response.Content;

            if (response.ErrorException != null)
            {
                var statusMessage = RestUtils.getErrorMessage(response.StatusCode);
                MessageBox.Show(statusMessage == "" ? response.StatusDescription : statusMessage);
                var myException = new ApplicationException(response.StatusDescription, response.ErrorException);
                throw myException;
            }

           
           Folder  folderDetails = JsonConvert.DeserializeObject<Folder>(content);
           return folderDetails;

        } 
        public void CopyFileMethodThrowsExceptionIfConfigured()
        {
            ApplicationException ex = new ApplicationException("message");
            fileSystem.ExceptionToThrowWhenCopyFileCalled = ex;

            Assert.Throws<ApplicationException>(delegate {	fileSystem.CopyFile(FileName.Create(@"c:\temp\a.xsd"), FileName.Create(@"c:\temp\b.xsd")); });
        }
        public static ProcessState FromException(string message, ApplicationException ex)
        {
            var state = new ProcessState(ex);
            state.Messages = new List<string>() { message };

            return state;
        }
 public static void Ctor_String()
 {
     string message = "Created ApplicationException";
     var exception = new ApplicationException(message);
     Assert.Equal(message, exception.Message);
     Assert.Equal(COR_E_APPLICATION, exception.HResult);
 }
 public static void Ctor_Empty()
 {
     var exception = new ApplicationException();
     Assert.NotNull(exception);
     Assert.NotEmpty(exception.Message);
     Assert.Equal(COR_E_APPLICATION, exception.HResult);
 }
예제 #10
0
        //private static double FindMax(double[][] ia, int limit1, int limit2)
        //{
        //    double iMax = ia[0][0];
        //    for (int i = 0; i < limit1; i++)
        //        for (int j = 0; j < limit2; j++)
        //        {
        //            if (ia[i][j] > iMax)
        //                iMax = ia[i][j];
        //        }
        //    return iMax;
        //}

        //private static double FindMin(double[][] ia, int limit1, int limit2)
        //{
        //    double iMin = ia[0][0];
        //    for (int i = 0; i < limit1; i++)
        //        for (int j = 0; j < limit2; j++)
        //        {
        //            if (ia[i][j] < iMin)
        //                iMin = ia[i][j];
        //        }
        //    return iMin;
        //}

        private void occHeight_TextChanged(object sender, EventArgs e)
        {
            double convlength = 1;

            try
            {
                double heighttemp = Double.Parse(occHeight.Text);
                if (heighttemp < 0)
                {
                    System.ApplicationException ex = new System.ApplicationException("Height of occupied zone must be positive!");
                    throw ex;
                }
                else
                {
                    if (globalcontrol.units == 1)
                    {
                        convlength = 3.28084;
                    }
                    globalcontrol.occheight  = Double.Parse(occHeight.Text) / convlength;
                    this.occHeight.BackColor = Color.White;
                }
            }
            catch (Exception)
            {
                this.occHeight.BackColor = Color.PaleVioletRed;
            }
            this.mySPane.CurveList.Clear();
            this.mySPane.GraphObjList.Clear();
            this.threshHoldY = globalcontrol.occheight * convlength;
            LineObj threshHoldLine = new LineObj(Color.Red, mySPane.XAxis.Scale.Min, threshHoldY, mySPane.XAxis.Scale.Max, threshHoldY);

            this.mySPane.GraphObjList.Add(threshHoldLine);
            this.refreshPlot();
        }
예제 #11
0
        public void UpdateManagedClients()
        {
            try
            {
                var user = new AdWordsUser();
                // Get the ManagedCustomerService.
                ManagedCustomerService managedCustomerService =
                    (ManagedCustomerService)user.GetService(AdWordsService.v201609.ManagedCustomerService);
                managedCustomerService.RequestHeader.clientCustomerId = Settings.Default.RootMCCClientCustomerId;

                // Create selector.
                var selector = new Selector()
                {
                    fields = new string[]
                    {
                        ManagedCustomer.Fields.CanManageClients,
                        ManagedCustomer.Fields.CurrencyCode,
                        ManagedCustomer.Fields.CustomerId,
                        ManagedCustomer.Fields.DateTimeZone,
                        ManagedCustomer.Fields.Name,
                        ManagedCustomer.Fields.TestAccount,
                    },
                    paging = new Paging
                    {
                        numberResults = 5000,
                        startIndex    = 0
                    }
                };

                // list to build up all pages from api
                var managedCustomerPageList = new List <ManagedCustomerPage>();

                // holds the page between each call to the api
                ManagedCustomerPage page = null;

                // get all pages
                do
                {
                    // get current page
                    page = managedCustomerService.get(selector);

                    // add page to list
                    managedCustomerPageList.Add(page);

                    // advance paging to next page
                    selector.paging.IncreaseOffset();
                } while (selector.paging.startIndex < page.totalNumEntries);

                // serialize as xml
                var managedCustomerPageXml = managedCustomerPageList.ToArray().ToXml();

                // send to db for processing
                Repository.UploadMagagedClients(managedCustomerPageXml);
            }
            catch (Exception ex)
            {
                var newEx = new System.ApplicationException("Failed to Refresh Managed Client List", ex);
                Repository.LogError(newEx.ToString(), "ManagedClientProcessor");
            }
        }
예제 #12
0
 public virtual void Add(BackgroundImageClass image)
 {
     var imageKey = new ImageMetadata(image);
     if (spriteList.ContainsKey(imageKey))
         return;
     SpritedImage spritedImage = null;
     try
     {
         spritedImage = SpriteContainer.AddImage(image);
     }
     catch (InvalidOperationException ex)
     {
         var message = string.Format("There were errors reducing {0}", image.ImageUrl);
         var wrappedException =
             new ApplicationException(message, ex);
         RRTracer.Trace(message);
         RRTracer.Trace(ex.ToString());
         if (RequestReduceModule.CaptureErrorAction != null)
             RequestReduceModule.CaptureErrorAction(wrappedException);
         return;
     }
     spriteList.Add(imageKey, spritedImage);
     if (SpriteContainer.Size >= config.SpriteSizeLimit || (SpriteContainer.Colors >= config.SpriteColorLimit && !config.ImageQuantizationDisabled && !config.ImageOptimizationDisabled))
         Flush();
 }
예제 #13
0
 public virtual void Add(BackgroundImageClass image)
 {
     var imageKey = new ImageMetadata(image);
     if (RRContainer.Current.GetAllInstances<IFilter>().Where(x => x is SpriteFilter).FirstOrDefault(y => y.IgnoreTarget(new SpriteFilterContext(image))) != null || spriteList.ContainsKey(imageKey))
         return;
     SpritedImage spritedImage;
     try
     {
         spritedImage = SpriteContainer.AddImage(image);
     }
     catch (InvalidOperationException ex)
     {
         var message = string.Format("There were errors reducing {0}", image.ImageUrl);
         var wrappedException =
             new ApplicationException(message, ex);
         RRTracer.Trace(message);
         RRTracer.Trace(ex.ToString());
         if (Registry.CaptureErrorAction != null)
             Registry.CaptureErrorAction(wrappedException);
         return;
     }
     spriteList.Add(imageKey, spritedImage);
     if (SpriteContainer.Size >= config.SpriteSizeLimit || (SpriteContainer.Colors >= config.SpriteColorLimit && !config.ImageQuantizationDisabled && !config.ImageOptimizationDisabled))
         Flush();
 }
예제 #14
0
        public void InnerExceptionTest()
        {
            _loggingService = new LoggingService();
            _loggingService.Initialise(1000000);
            _loggingService.Recycle();

            Thread.Sleep(1000);// Ensure unique archive file name!

            var ex7 = new ApplicationException("Ex_Seventh");
            var ex6 = new ApplicationException("Ex_Sixth", ex7);
            var ex5 = new ApplicationException("Ex_Fifth", ex6);
            var ex4 = new ApplicationException("Ex_Fourth", ex5);
            var ex3 = new ApplicationException("Ex_Third", ex4);
            var ex2 = new ApplicationException("Ex_Second", ex3);
            var ex1 = new ApplicationException("Ex_First", ex2);

            _loggingService.Error(ex1);

            var logs = _loggingService.ListLogFile();

            // Only log down to 5 inner exceptions
            Assert.IsTrue(logs.Any(item => item.ErrorMessage.Contains("Ex_Fifth")));
            Assert.IsTrue(logs.Any(item => item.ErrorMessage.Contains("Ex_Fourth")));
            Assert.IsTrue(logs.Any(item => item.ErrorMessage.Contains("Ex_Third")));
            Assert.IsTrue(logs.Any(item => item.ErrorMessage.Contains("Ex_Second")));
            Assert.IsTrue(logs.Any(item => item.ErrorMessage.Contains("Ex_First")));
            Assert.IsTrue(logs.Any(item => item.ErrorMessage.Contains("Ex_Sixth")));
            Assert.IsFalse(logs.Any(item => item.ErrorMessage.Contains("Ex_Seventh")));
        }
		public void ErrorsWithSameErrorMessageAndExceptionAreEqual()
		{
			ApplicationException ex = new ApplicationException();
			RegisteredXmlSchemaError lhs = new RegisteredXmlSchemaError("message", ex);
			RegisteredXmlSchemaError rhs = new RegisteredXmlSchemaError("message", ex);
			Assert.IsTrue(lhs.Equals(rhs));
		}
		public void CreateMethodThrowsExceptionIfConfigured()
		{
			ApplicationException ex = new ApplicationException("message");
			factory.ExceptionToThrowWhenCreateXmlSchemaCalled = ex;
			
			Assert.Throws<ApplicationException>(delegate {	factory.CreateXmlSchemaCompletionData(String.Empty, String.Empty); });
		}
예제 #17
0
        public void ShowExceptionMessage()
        {
            try
            {
                // Do something that you don't expect to generate an exception.
                throw new ApplicationException(ExceptionMessage);
            }
            catch (ApplicationException ex)
            {
                // Define a new top-level error message.
                string str = "An Error has ocurred in while logging the Exception Information on System. " + Environment.NewLine
                             + "Please contact support";

                // Add the new top-level message to the handled exception.
                ApplicationException exTop = new ApplicationException(str, ex);
                ExceptionMessageBox box = new ExceptionMessageBox(exTop);
                box.Buttons = ExceptionMessageBoxButtons.OK;
                box.Caption = title;
                box.ShowCheckBox = false;
                box.ShowToolBar = true;
                box.Symbol = ExceptionMessageBoxSymbol.Stop;
                box.Show(this);
                this.Close();
            }
        }
예제 #18
0
		public void Correctly_handles_when_service_agent_aggregator_throws_exception()
		{
			ApplicationException exception = new ApplicationException();

			MockRepository mocks = new MockRepository();
			IApplicationSettings settings = mocks.CreateMock<IApplicationSettings>();
			IServiceAgentAggregator aggregator = mocks.CreateMock<IServiceAgentAggregator>();

			IServiceRunner runner = new ServiceRunner(aggregator, settings);

			using (mocks.Record())
			{

				aggregator.ExecuteServiceAgentCycle();
				LastCall.Throw(exception);

			}

			using (mocks.Playback())
			{
				runner.Start();
				Thread.Sleep(500);
				runner.Stop();
			}

			mocks.VerifyAll();
		}
예제 #19
0
        private LanguageType GetLanguageType()
        {
            var defaultLanguage = LanguageType.Russian;

            var language = _configuration.AppSettings.Settings["Language"]?.Value;

            if (language.IsNullOrEmpty())
            {
                var ex = new ApplicationException<MissingKeyInAppConfigExceptionArgs>
                    (new MissingKeyInAppConfigExceptionArgs("Language"), "Отсутствует ключ в файле App.config");

                _logger.Warning(ex);

                return defaultLanguage;
            }

            LanguageType languageType;
            var success = Enum.TryParse(language, true, out languageType);

            if (!success)
            {
                var ex = new ApplicationException<IncorrectLanguageInAppConfigExceptionArgs>
                    (new IncorrectLanguageInAppConfigExceptionArgs(language),
                        "Некорректное название языка. Язык будет установлен по умолчанию.");

                _logger.Warning(ex);

                return defaultLanguage;
            }

            return languageType;
        }
예제 #20
0
        private static void ReportJavascriptError(string detailsJson)
        {
            string detailsMessage;
            string detailsStack;

            try
            {
                var details = DynamicJson.Parse(detailsJson);
                detailsMessage = details.message;
                detailsStack   = details.stack;
            }
            catch (Exception e)
            {
                // Somehow a problem here seems to kill Bloom. So in desperation we catch everything.
                detailsMessage = "Javascript error reporting failed: " + e.Message;
                detailsStack   = detailsJson;
            }

            var ex = new ApplicationException(detailsMessage + Environment.NewLine + detailsStack);

            // For now unimportant JS errors are still quite common, sadly. Per BL-4301, we don't want
            // more than a toast, even for developers.
            // It would seem logical that we should consider Browser.SuppressJavaScriptErrors here,
            // but somehow none are being reported while making an epub preview, which was its main
            // purpose. So I'm leaving that out until we know we need it.
            NonFatalProblem.Report(ModalIf.None, PassiveIf.Alpha, "A JavaScript error occurred", detailsMessage, ex);
        }
예제 #21
0
        ////////////////////////////////////////////
        // Internals

        private void CreateReplayRenderer(ref ReplayRenderer renderer, ref RemoteRenderer remote)
        {
            if (m_ProxyRenderer < 0)
            {
                renderer = StaticExports.CreateReplayRenderer(m_Logfile, ref LoadProgress);
                return;
            }

            remote = StaticExports.CreateRemoteReplayConnection(m_ReplayHost);

            if (remote == null)
            {
                var e = new System.ApplicationException("Failed to connect to remote replay host");
                e.Data.Add("status", ReplayCreateStatus.UnknownError);
                throw e;
            }

            renderer = remote.CreateProxyRenderer(m_ProxyRenderer, m_Logfile, ref LoadProgress);

            if (renderer == null)
            {
                remote.Shutdown();

                var e = new System.ApplicationException("Failed to connect to remote replay host");
                e.Data.Add("status", ReplayCreateStatus.UnknownError);
                throw e;
            }
        }
예제 #22
0
        void Application_Error(object sender, EventArgs e)
        {
            HttpContext httpContext = ((WebApiApplication)sender).Context;
            Exception exception = Server.GetLastError();
            if (exception == null)
                exception = new ApplicationException("Unknown error");

            //try to retrieve controller/action
            var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            string controllerName = null;
            string actionName = null;
            if (routeData != null)
            {
                if ((routeData.Values["controller"] != null) &&
                    (!String.IsNullOrEmpty(routeData.Values["controller"].ToString())))
                {
                    controllerName = routeData.Values["controller"].ToString();
                }

                if ((routeData.Values["action"] != null) &&
                    (!String.IsNullOrEmpty(routeData.Values["action"].ToString())))
                {
                    actionName = routeData.Values["action"].ToString();
                }
            }

            string requestUrl = httpContext.Request.RawUrl;

            //write log entry
            Logger.AddEntry(exception, controllerName, actionName, requestUrl);
        }
예제 #23
0
 /// <summary>
 /// Serialize ApplicationException type error response into JSON String
 /// </summary>
 public void PackErrorMessage(ApplicationException ex, out string result)
 {
     KwasantPackagedMessage curError = new KwasantPackagedMessage();
     curError.Name = "LIKI API Error";
     curError.Message = ex.Message;
     result = jsonSerializer.Serialize(curError);
 }
예제 #24
0
        public void TestRetry()
        {
            bool result = false;
            bool exceptionThrown = false;

            var ex = new ApplicationException("Test exception");
            var mockLoggerForException = MockLoggerForException(ex);
                    
            Assert.DoesNotThrow(() =>
                {
                    AspectF.Define.Retry(mockLoggerForException.Object).Do(() =>
                    {
                        if (!exceptionThrown)
                        {
                            exceptionThrown = true;
                            throw ex;
                        }
                        else
                        {
                            result = true;
                        }
                    });

                });
            mockLoggerForException.VerifyAll();

            Assert.True(exceptionThrown, "Assert.Retry did not invoke the function at all");
            Assert.True(result, "Assert.Retry did not retry the function after exception was thrown");
        }
예제 #25
0
파일: AlchemyAPI.cs 프로젝트: xiyuanHou/nlp
        private string DoRequest(HttpWebRequest wreq, AlchemyAPI_BaseParams.OutputMode outputMode)
        {
            using (HttpWebResponse wres = wreq.GetResponse() as HttpWebResponse)
            {
                StreamReader r = new StreamReader(wres.GetResponseStream());

                string xml = r.ReadToEnd();

                if (string.IsNullOrEmpty(xml))
                {
                    throw new XmlException("The API request returned back an empty response. Please verify that the url is correct.");
                }

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);

                XmlElement root = xmlDoc.DocumentElement;

                if (AlchemyAPI_BaseParams.OutputMode.XML == outputMode)
                {
                    XmlNode status = root.SelectSingleNode("/results/status");

                    if (status.InnerText != "OK")
                    {
                        string errorMessage = "Error making API call.";

                        try
                        {
                            XmlNode statusInfo = root.SelectSingleNode("/results/statusInfo");
                            errorMessage = statusInfo.InnerText;
                        }
                        catch
                        {
                            // some problem with the statusInfo.  Return the generic message.
                        }

                        System.ApplicationException ex = new System.ApplicationException(errorMessage);

                        throw ex;
                    }
                }
                else if (AlchemyAPI_BaseParams.OutputMode.RDF == outputMode)
                {
                    XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);
                    nm.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
                    nm.AddNamespace("aapi", "http://rdf.alchemyapi.com/rdf/v1/s/aapi-schema#");
                    XmlNode status = root.SelectSingleNode("/rdf:RDF/rdf:Description/aapi:ResultStatus", nm);

                    if (status.InnerText != "OK")
                    {
                        System.ApplicationException ex =
                            new System.ApplicationException("Error making API call.");

                        throw ex;
                    }
                }

                return(xml);
            }
        }
예제 #26
0
 public void ExceptionReflectorTest()
 {
     var ex = new ApplicationException("ex1", new TestException("ex2"));
     var refl = new ExceptionReflector(ex);
     Assert.IsTrue(refl.ReflectedText.Contains("ex1"));
     Assert.IsTrue(refl.ReflectedText.Contains("ex2"));
 }
예제 #27
0
        public RootObject login(String username, String password)
        {

            if (username == null || username.Trim().Length == 0 || password == null || password.Trim().Length == 0)
            {
                MessageBox.Show("invalid User credentials");
            }

           
            var client = new RestClient(Resource.endpoint + "wittyparrot/api/auth/login");
            var strJSONContent = "{\"userId\":\"" + username + "\" ,\"password\":\"" + password + "\"}";
            
            var request = new RestRequest();
            request.Method = Method.POST;
            request.AddHeader("Accept", "application/json");
            request.Parameters.Clear();
            request.AddParameter("application/json", strJSONContent, ParameterType.RequestBody);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");

            // If the response has exception the applocation will half and throw Application exception
            IRestResponse response = client.Execute(request);
            if (response.ErrorException != null || response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                var statusMessage = RestUtils.getErrorMessage(response.StatusCode);
                MessageBox.Show(statusMessage == "" ? response.StatusDescription : statusMessage);
                var myException = new ApplicationException(response.StatusDescription, response.ErrorException);
                throw myException;
            }
           
            var content = response.Content;
            RootObject rootObj = new RootObject();
            rootObj = JsonConvert.DeserializeObject<RootObject>(content);
            return rootObj;
        }
예제 #28
0
        private string deleteAssessmentById(string token, string id)
        {
            var client = new RestClient("https://api.sandbox.inbloom.org/api/rest/v1.2/");

            var endpoint = "assessments/" + id;

            var request = inBloomRestRequest(token, endpoint, Method.DELETE);

            RestResponse response = (RestResponse)client.Execute(request);

            // RestSharp recommended error code
            if (response.ErrorException != null)
            {
                const string message = "Error rectrieving response. Check details in exception for more info.";
                var inBLoomException = new ApplicationException(message, response.ErrorException);
                throw inBLoomException;
            }

            if (response.ResponseStatus == ResponseStatus.Completed)
            {
                return response.ResponseStatus.ToString();
            }
            else
            {
                return "Delete was not successful: " + response.ResponseStatus.ToString();
            }
        }
		public void ErrorsWithSameMessageButDifferentExceptionsAreNotEqual()
		{
			ApplicationException firstEx = new ApplicationException();
			ApplicationException secondEx = new ApplicationException();
			RegisteredXmlSchemaError lhs = new RegisteredXmlSchemaError("message", firstEx);
			RegisteredXmlSchemaError rhs = new RegisteredXmlSchemaError("message", secondEx);
			Assert.IsFalse(lhs.Equals(rhs));
		}
        /// <summary>
        /// http kivétel visszaadása
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage ThrowHttpError(string message, string source)
        {
            ApplicationException ex = new ApplicationException(message);

            ex.Source = source;

            return ThrowHttpError(ex);
        }
예제 #31
0
		public void IsInstanceOf()
		{
            ApplicationException ex = new ApplicationException();

			Assert.IsInstanceOf(typeof(System.Exception), ex );
            Assert.That( ex, Is.InstanceOf(typeof(Exception)));
            Assert.IsInstanceOf<Exception>( ex );
		}
 private void AssertStartFailsAndDropsSubscriptionWithException(ApplicationException expectedException)
 {
     Assert.That(() => _subscription.Start().Wait(TimeoutMs), Throws.TypeOf<AggregateException>());
     Assert.That(_isDropped);
     Assert.That(_dropReason, Is.EqualTo(SubscriptionDropReason.CatchUpError));
     Assert.That(_dropException, Is.SameAs(expectedException));
     Assert.That(_liveProcessingStarted, Is.False);
 }
예제 #33
0
        public void ReasonIsSet()
        {
            var ex = new ApplicationException("Exception error message");
            var error = new ErrorRecord(ex, "errorId", ErrorCategory.AuthenticationError, "foo");
            error.CategoryInfo.Reason = "Reason";

            Assert.AreEqual("AuthenticationError: (foo:String) [], Reason", error.CategoryInfo.ToString());
        }
예제 #34
0
 public static void LogError(Payment payment, PaymentResponse response)
 {
     var context = HttpContext.Current;
     var log = ErrorLog.GetDefault(context);
     var ex = new ApplicationException(string.Format("{0} {1}'s donation of {2:C} was unable to be processed. Error Code: {3}. Description: {4}",
         payment.FirstName, payment.LastName, payment.Amount, response.ResponseCode, response.ReasonText));
     log.Log(new Error(ex, context));
 }
        public void FlattenException_SingleException_ReturnsExpectedResult()
        {
            ApplicationException ex = new ApplicationException("Incorrectly configured setting 'Foo'");
            ex.Source = "Acme.CloudSystem";

            string formattedResult = Utility.FlattenException(ex);
            Assert.Equal("Acme.CloudSystem: Incorrectly configured setting 'Foo'.", formattedResult);
        }
예제 #36
0
 public void StackTraceInclusion()
 {
     ApplicationException exception = new ApplicationException();
     JsonObject error = JsonRpcError.FromException(ThrowAndCatch(exception), true);
     string trace = (string) error["stackTrace"];
     Assert.IsNotNull(trace);
     Assert.IsNotEmpty(trace);
 }
예제 #37
0
        private void CheckText(string text)
        {
            if (text.Length < 5)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Enter some text to analyze.");

                throw ex;
            }
        }
예제 #38
0
    private void PageBase_Error(object sender, EventArgs e)
    {
        Exception currentErr = Server.GetLastError();

        if (!(currentErr is System.ApplicationException))
        {
            string strMsg = "에러발생시각: " + DateTime.Now.ToString();
            System.ApplicationException appException = new System.ApplicationException(strMsg, currentErr);
        }
    }
예제 #39
0
        private void CheckURL(string url)
        {
            if (url.Length < 10)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Enter a web URL to analyze.");

                throw ex;
            }
        }
예제 #40
0
 /// <summary>
 /// Capture this exception as log4net FAIL (not ERROR) when logged
 /// </summary>
 public static void LogAsFail(ref System.ApplicationException ex)
 {
     if (ex.Data.Contains(LogAs))
     {
         ex.Data[LogAs] = OGCSexception.LogLevel.FAIL;
     }
     else
     {
         ex.Data.Add(LogAs, OGCSexception.LogLevel.FAIL);
     }
 }
예제 #41
0
        public void SetAPIHost(string apiHost)
        {
            if (apiHost.Length < 2)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Error setting API host.");

                throw ex;
            }

            _requestUri = "http://" + apiHost + ".alchemyapi.com/calls/";
        }
예제 #42
0
        public void SetAPIKey(string apiKey)
        {
            _apiKey = apiKey;

            if (_apiKey.Length < 5)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Error setting API key.");

                throw ex;
            }
        }
예제 #43
0
        public static RemoteAccess CreateRemoteAccessConnection(string host, UInt32 ident, string clientName, bool forceConnection)
        {
            IntPtr rendPtr = RENDERDOC_CreateRemoteAccessConnection(host, ident, clientName, forceConnection);

            if (rendPtr == IntPtr.Zero)
            {
                var e = new System.ApplicationException("Failed to open remote access connection");
                e.Data.Add("status", ReplayCreateStatus.UnknownError);
                throw e;
            }

            return(new RemoteAccess(rendPtr));
        }
예제 #44
0
        public string URLGetConstraintQuery(string url, AlchemyAPI_ConstraintQueryParams parameters)
        {
            CheckURL(url);
            if (parameters.getCQuery().Length < 2)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Invalid constraint query specified.");

                throw ex;
            }

            parameters.setUrl(url);

            return(POST("URLGetConstraintQuery", "url", parameters));
        }
예제 #45
0
        static StackObject *Ctor_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.String @message = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);


            var result_of_this_method = new System.ApplicationException(@message);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
예제 #46
0
        public static ReplayRenderer CreateReplayRenderer(string logfile, ref float progress)
        {
            IntPtr rendPtr = IntPtr.Zero;

            ReplayCreateStatus ret = RENDERDOC_CreateReplayRenderer(logfile, ref progress, ref rendPtr);

            if (rendPtr == IntPtr.Zero || ret != ReplayCreateStatus.Success)
            {
                var e = new System.ApplicationException("Failed to load log for local replay");
                e.Data.Add("status", ret);
                throw e;
            }

            return(new ReplayRenderer(rendPtr));
        }
예제 #47
0
        public ReplayRenderer CreateProxyRenderer(int proxyid, string logfile, ref float progress)
        {
            IntPtr rendPtr = IntPtr.Zero;

            ReplayCreateStatus ret = RemoteRenderer_CreateProxyRenderer(m_Real, (UInt32)proxyid, logfile, ref progress, ref rendPtr);

            if (rendPtr == IntPtr.Zero || ret != ReplayCreateStatus.Success)
            {
                var e = new System.ApplicationException("Failed to set up local proxy replay with remote connection");
                e.Data.Add("status", ret);
                throw e;
            }

            return(new ReplayRenderer(rendPtr));
        }
예제 #48
0
        public static RemoteRenderer CreateRemoteReplayConnection(string host)
        {
            IntPtr rendPtr = IntPtr.Zero;

            ReplayCreateStatus ret = RENDERDOC_CreateRemoteReplayConnection(host, ref rendPtr);

            if (rendPtr == IntPtr.Zero || ret != ReplayCreateStatus.Success)
            {
                var e = new System.ApplicationException("Failed to connect to remote replay host");
                e.Data.Add("status", ret);
                throw e;
            }

            return(new RemoteRenderer(rendPtr));
        }
        public String RegistrarExcepcion(Exception excepcion, String origen)
        {
            string mensaje = "";

            try
            {
                if (excepcion is System.ApplicationException)
                {
                    System.ApplicationException exc = (System.ApplicationException)excepcion;
                    mensaje = EscribirApplicationException(exc, origen);
                }
                else if (excepcion is System.IO.InvalidDataException)
                {
                    System.IO.InvalidDataException exc = (System.IO.InvalidDataException)excepcion;
                    mensaje = EscribirInvalidDataException(exc, origen);
                }
                else if (excepcion is System.IO.IOException)
                {
                    System.IO.IOException exc = (System.IO.IOException)excepcion;
                    mensaje = EscribirIOEx(exc, origen);
                }
                else if (excepcion is System.FormatException)
                {
                    System.FormatException exc = excepcion as System.FormatException;
                    mensaje = EscribirFormatException(exc, origen);
                }
                else if (excepcion is System.Data.SqlClient.SqlException)
                {
                    System.Data.SqlClient.SqlException exc = excepcion as System.Data.SqlClient.SqlException;
                    mensaje = EscribirSqlEx(exc, origen);
                }
                else if (excepcion is System.Data.OleDb.OleDbException)
                {
                    System.Data.OleDb.OleDbException exc = excepcion as System.Data.OleDb.OleDbException;
                    mensaje = EscribirOleDbEx(exc, origen);
                }
                else
                {
                    mensaje = EscribirGenericEx(excepcion, origen);
                }
            }
            catch (Exception ex)
            {
                mensaje = "Error interno de la Aplicación. Por favor informar a Sopórte Técnico.\n\n";
                mensaje = mensaje + EscribirLocalEx(ex, this.ToString() + ".RegistrarExcepcion");
            }
            return(mensaje);
        }
예제 #50
0
        //---------------------------------------------------------------------

        private void Inner_NoMultiLineMessage()
        {
            string innerMessage = "The quick brown fox";

            System.ApplicationException inner = new System.ApplicationException(innerMessage);

            string             myMessage = "Four score and seven years ago ...";
            MultiLineException exception = new MultiLineException(myMessage,
                                                                  inner);

            Assert.AreEqual(inner, exception.InnerException);
            Assert.AreEqual(2, exception.MultiLineMessage.Count);
            Assert.AreEqual(myMessage + ":", exception.MultiLineMessage[0]);
            Assert.AreEqual(MultiLineException.Indent + innerMessage,
                            exception.MultiLineMessage[1]);
        }
예제 #51
0
        /// <summary>
        /// CheckReturnCode iterates through the Bytes of a return
        /// Array and throws Exceptions as necessary.
        /// </summary>
        /// <param name="command">The type of command that was sent</param>
        /// <param name="bytesToRead">The amount of memory to read from the Brick</param>
        /// <param name="suppressExceptions">Determines if an exception is thrown or just a return code</param>
        private Byte[] CheckReturnCode(Byte command, Int32 bytesToRead, Boolean suppressExceptions)
        {
            //Create a return code
            Byte[] rtnCode = this._device.Read(this._inPipe, bytesToRead);

            //Create an Exception object to throw
            Exception e = null;

            //If no return code was found...Exception
            if (rtnCode == null)
            {
                e = new System.ApplicationException("Could not read Error Code from NXT Brick.");
            }

            //If the code isn't exactly right...Exception
            else if (rtnCode.GetLength(0) != bytesToRead)
            {
                e = new System.ApplicationException("Error Code return was not returned properly.");
            }

            //If the first Bytes isn't 2...Exception
            else if (rtnCode[0] != 2)
            {
                e = new System.ApplicationException("Error Code return is not valid LEGO return code.");
            }

            //IF the commands don't match up...Exception
            else if (rtnCode[1] != Convert.ToByte(command))
            {
                e = new System.ApplicationException("Command was not replied successfully.");
            }

            //Finally, if the error code isn't 0...Exception
            else if (rtnCode[2] != 0)
            {
                e = new System.ApplicationException("Error in performing Command -- Error Code: " + rtnCode[2].ToString());
            }

            //Throw the Exception if it shouldn't be suppressed
            if (e != null && suppressExceptions == false)
            {
                throw e;
            }

            //Return the code
            return(rtnCode);
        }
        protected void Initialize(IDTSComponentMetaData100 dtsComponentMetadata, IServiceProvider serviceProvider)
        {
            this.componentMetaData = dtsComponentMetadata;
            this.serviceProvider   = serviceProvider;

            Debug.Assert(this.serviceProvider != null, "The service provider was null!");

            this.errorCollector = this.serviceProvider.GetService(
                typeof(IErrorCollectionService)) as IErrorCollectionService;
            Debug.Assert(this.errorCollector != null, "The errorCollector was null!");

            if (this.errorCollector == null)
            {
                Exception ex = new System.ApplicationException(Properties.Resources.NotAllEditingServicesAvailable);
                throw ex;
            }
        }
예제 #53
0
        /// <summary>
        /// Arguments to Run
        /// /a:Path to assembly file to decompile
        /// /o:Path to JSON file to create
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            ArgsHelper oArgsHelp = new ArgsHelper(args);

            System.ApplicationException ex = new System.ApplicationException(ERROR_MSG);
            if (args.Count() == 0)
            {
                throw ex;
            }

            string AssemblyFileAndPath = oArgsHelp["a"];
            string OutPutPath          = oArgsHelp["o"];

            Decompiler decompiler = new Decompiler(AssemblyFileAndPath, OutPutPath);

            decompiler.Decompile();
        }
예제 #54
0
        public string HTMLGetConstraintQuery(string html, string url, string query)
        {
            CheckHTML(html, url);
            if (query.Length < 2)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Invalid constraint query specified.");

                throw ex;
            }

            AlchemyAPI_ConstraintQueryParams cqParams = new AlchemyAPI_ConstraintQueryParams();

            cqParams.setCQuery(query);

            return(HTMLGetConstraintQuery(html, url, cqParams));
        }
예제 #55
0
        public void LayoutDynamicRenderExceptionTypeTest()
        {
            // Arrange
            Layout <Type> layout        = "${exception:format=type:norawvalue=true}";
            var           exception     = new System.ApplicationException("Test");
            var           stringBuilder = new System.Text.StringBuilder();

            // Act
            var logevent      = LogEventInfo.Create(LogLevel.Info, null, exception, null, "");
            var exceptionType = layout.RenderTypedValue(logevent, stringBuilder, null);

            stringBuilder.Length = 0;

            // Assert
            Assert.Equal(exception.GetType(), exceptionType);
            Assert.Same(exceptionType, layout.RenderTypedValue(logevent, stringBuilder, null));
        }
예제 #56
0
        /// <summary>
        /// Called before Edit, New and Delete to pass in the necessary parameters.
        /// </summary>
        /// <param name="dtsComponentMetadata">The components metadata</param>
        /// <param name="serviceProvider">The SSIS service provider</param>
        void IDtsComponentUI.Initialize(IDTSComponentMetaData100 dtsComponentMetadata, IServiceProvider serviceProvider)
        {
            this.componentMetadata = dtsComponentMetadata;
            this.serviceProvider   = serviceProvider;

            Debug.Assert(this.serviceProvider != null, "The service provider was null!");

            this.errorCollector = this.serviceProvider.GetService(
                typeof(IErrorCollectionService)) as IErrorCollectionService;
            Debug.Assert(this.errorCollector != null, "The errorCollector was null!");

            if (this.errorCollector == null)
            {
                Exception ex = new System.ApplicationException("Not all editing services are available.");
                throw ex;
            }
        }
예제 #57
0
        private void CheckHTML(string html, string url)
        {
            if (html.Length < 10)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Enter a HTML document to analyze.");

                throw ex;
            }

            if (url.Length < 10)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Enter a web URL to analyze.");

                throw ex;
            }
        }
예제 #58
0
        private string DoRequest(HttpWebRequest wreq, AlchemyAPI_BaseParams.OutputMode outputMode)
        {
            using (HttpWebResponse wres = wreq.GetResponse() as HttpWebResponse)
            {
                StreamReader r = new StreamReader(wres.GetResponseStream());

                string xml = r.ReadToEnd();

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);

                XmlElement root = xmlDoc.DocumentElement;

                if (AlchemyAPI_BaseParams.OutputMode.XML == outputMode)
                {
                    XmlNode status = root.SelectSingleNode("/results/status");

                    if (status.InnerText != "OK")
                    {
                        System.ApplicationException ex =
                            new System.ApplicationException("Error making API call.");

                        throw ex;
                    }
                }
                else if (AlchemyAPI_BaseParams.OutputMode.RDF == outputMode)
                {
                    XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);
                    nm.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
                    nm.AddNamespace("aapi", "http://rdf.alchemyapi.com/rdf/v1/s/aapi-schema#");
                    XmlNode status = root.SelectSingleNode("/rdf:RDF/rdf:Description/aapi:ResultStatus", nm);

                    if (status.InnerText != "OK")
                    {
                        System.ApplicationException ex =
                            new System.ApplicationException("Error making API call.");

                        throw ex;
                    }
                }

                return(xml);
            }
        }
예제 #59
0
        public static RemoteRenderer CreateRemoteReplayConnection(string host, uint port)
        {
            IntPtr rendPtr = IntPtr.Zero;

            IntPtr host_mem = CustomMarshal.MakeUTF8String(host);

            ReplayCreateStatus ret = RENDERDOC_CreateRemoteReplayConnection(host_mem, port, ref rendPtr);

            CustomMarshal.Free(host_mem);

            if (rendPtr == IntPtr.Zero || ret != ReplayCreateStatus.Success)
            {
                var e = new System.ApplicationException("Failed to connect to remote replay host");
                e.Data.Add("status", ret);
                throw e;
            }

            return(new RemoteRenderer(rendPtr));
        }
예제 #60
0
        public void LoadAPIKey(string filename)
        {
            StreamReader reader;

            reader = File.OpenText(filename);

            string line = reader.ReadLine();

            reader.Close();

            _apiKey = line.Trim();

            if (_apiKey.Length < 5)
            {
                System.ApplicationException ex =
                    new System.ApplicationException("Error loading API key.");

                throw ex;
            }
        }