• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# System.ApplicationException类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.ApplicationException的典型用法代码示例。如果您正苦于以下问题:C# ApplicationException类的具体用法?C# ApplicationException怎么用?C# ApplicationException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ApplicationException类属于System命名空间,在下文中一共展示了ApplicationException类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: CreateActivationContext

        /// <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;
            }
        }
开发者ID:Fedorm,项目名称:core-master,代码行数:37,代码来源:ActivationContext.cs


示例2: PackErrorMessage

 /// <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);
 }
开发者ID:alexed1,项目名称:dtrack,代码行数:10,代码来源:KwasantPackager.cs


示例3: PlaySound

        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);
            }
        }
开发者ID:tqphan,项目名称:OptiKey,代码行数:34,代码来源:AudioService.cs


示例4: GetLanguageType

        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;
        }
开发者ID:ukionik,项目名称:VDesktopeNew,代码行数:32,代码来源:AppConfig.cs


示例5: getFolderDetails

            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;

        } 
开发者ID:soumyaansh,项目名称:Outlook-Widget,代码行数:33,代码来源:RestClientFolder.cs


示例6: Add

 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();
 }
开发者ID:goreckm,项目名称:RequestReduce,代码行数:25,代码来源:SpriteManager.cs


示例7: Ctor_String

 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);
 }
开发者ID:geoffkizer,项目名称:corefx,代码行数:7,代码来源:ApplicationExceptionTests.cs


示例8: InnerExceptionTest

        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")));
        }
开发者ID:kangjh0815,项目名称:test,代码行数:29,代码来源:LoggingServiceTests.cs


示例9: Ctor_Empty

 public static void Ctor_Empty()
 {
     var exception = new ApplicationException();
     Assert.NotNull(exception);
     Assert.NotEmpty(exception.Message);
     Assert.Equal(COR_E_APPLICATION, exception.HResult);
 }
开发者ID:geoffkizer,项目名称:corefx,代码行数:7,代码来源:ApplicationExceptionTests.cs


示例10: CreateMethodThrowsExceptionIfConfigured

		public void CreateMethodThrowsExceptionIfConfigured()
		{
			ApplicationException ex = new ApplicationException("message");
			factory.ExceptionToThrowWhenCreateXmlSchemaCalled = ex;
			
			Assert.Throws<ApplicationException>(delegate {	factory.CreateXmlSchemaCompletionData(String.Empty, String.Empty); });
		}
开发者ID:Bombadil77,项目名称:SharpDevelop,代码行数:7,代码来源:MockXmlSchemaCompletionDataFactoryTests.cs


示例11: ExceptionReflectorTest

 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"));
 }
开发者ID:holinov,项目名称:Zen.Core,代码行数:7,代码来源:ExceptionReflectorTests.cs


示例12: TestRetryWithDuration

        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);
        }
开发者ID:modulexcite,项目名称:dropthings,代码行数:32,代码来源:AspectTest.cs


示例13: ShowExceptionMessage

        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();
            }
        }
开发者ID:iMutex,项目名称:MediPOS,代码行数:25,代码来源:ExceptionMessageShow.cs


示例14: ErrorsWithSameErrorMessageAndExceptionAreEqual

		public void ErrorsWithSameErrorMessageAndExceptionAreEqual()
		{
			ApplicationException ex = new ApplicationException();
			RegisteredXmlSchemaError lhs = new RegisteredXmlSchemaError("message", ex);
			RegisteredXmlSchemaError rhs = new RegisteredXmlSchemaError("message", ex);
			Assert.IsTrue(lhs.Equals(rhs));
		}
开发者ID:Bombadil77,项目名称:SharpDevelop,代码行数:7,代码来源:RegisteredXmlSchemaErrorTests.cs


示例15: TestRetry

        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");
        }
开发者ID:modulexcite,项目名称:dropthings,代码行数:29,代码来源:AspectTest.cs


示例16: FromException

        public static ProcessState FromException(string message, ApplicationException ex)
        {
            var state = new ProcessState(ex);
            state.Messages = new List<string>() { message };

            return state;
        }
开发者ID:digimonsta,项目名称:FeatureDemandPlanning,代码行数:7,代码来源:ProcessState.cs


示例17: deleteAssessmentById

        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();
            }
        }
开发者ID:jatpannu,项目名称:cookbook,代码行数:27,代码来源:Recipe7.cs


示例18: Application_Error

        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);
        }
开发者ID:RomanAnosov,项目名称:Repo,代码行数:31,代码来源:Global.asax.cs


示例19: Correctly_handles_when_service_agent_aggregator_throws_exception

		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();
		}
开发者ID:joaomajesus,项目名称:Tarantino,代码行数:27,代码来源:ServiceRunnerTester.cs


示例20: login

        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;
        }
开发者ID:soumyaansh,项目名称:Outlook-Widget,代码行数:35,代码来源:RestClientLogin.cs



注:本文中的System.ApplicationException类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# System.ApplicationIdentity类代码示例发布时间:2022-05-26
下一篇:
C# System.AppDomainSetup类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap