本文整理汇总了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;
}
}
示例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);
}
示例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);
}
}
示例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;
}
示例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;
}
示例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();
}
示例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);
}
示例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")));
}
示例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);
}
示例10: CreateMethodThrowsExceptionIfConfigured
public void CreateMethodThrowsExceptionIfConfigured()
{
ApplicationException ex = new ApplicationException("message");
factory.ExceptionToThrowWhenCreateXmlSchemaCalled = ex;
Assert.Throws<ApplicationException>(delegate { factory.CreateXmlSchemaCompletionData(String.Empty, String.Empty); });
}
示例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"));
}
示例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);
}
示例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();
}
}
示例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));
}
示例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");
}