當前位置: 首頁>>代碼示例>>C#>>正文


C# System.ApplicationException類代碼示例

本文整理匯總了C#中System.ApplicationException的典型用法代碼示例。如果您正苦於以下問題:C# ApplicationException類的具體用法?C# ApplicationException怎麽用?C# ApplicationException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ApplicationException類屬於System命名空間,在下文中一共展示了ApplicationException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的System.ApplicationException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。