WCF
Installation
Step 1 - Install the NuGet package
The best way to install Raygun4Net is to use the NuGet package manager. With the NuGet Visual Studio extension installed, right-click on your project and select "Manage NuGet Packages..." Ensure that "Online" is highlighted in the left hand pane, then use the top right search box to find Mindscape.Raygun4Net and install the latest version.
Alternatively, visit https://nuget.org/packages/Mindscape.Raygun4Net/ for instructions on installation using the package manager console.
Step 2 - Setup Raygun in Web.config
In your Web.config file, find the configSections
tag and add the following snippet within the tag.
<section name="RaygunSettings" type="Mindscape.Raygun4Net.RaygunSettings, Mindscape.Raygun4Net"/>
Once added you can reference it by adding the following snippet after the configSections
end tag. Ensure that you insert your API key as the value for the following snippet.
<RaygunSettings apikey="paste_your_api_key_here" />
Step 3 - TLS Configuration
Raygun's ingestion nodes require TLS 1.2.
If you are using Mindscape.Raygun4Net < 6.0.3 and are using .NET 4.5 or earlier, you may need to enable these protocols in your application.
This is done by updating the protocol property in the Main
method in your app:
static void Main()
{
// Enable TLS 1.2
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 ;
}
Step 4 - Create a Raygun error handler
Create a new class that implements the IErrorHandler
interface. This new class will be responsible for capturing exceptions thrown by WCF services and reporting them to Raygun. Ensure that you insert your API key into the constructor of the RaygunClient
class.
using Mindscape.Raygun4Net;
public class RaygunErrorHandler : IErrorHandler
{
private RaygunClient _raygunClient = new RaygunClient();
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
}
public bool HandleError(Exception error)
{
_raygunClient.Send(error);
return false;
}
}
Step 4 - Register the Raygun error handler
The custom error handler class can now be registered with any services. This can be done in the form of an attribute that is applied to each service. The attribute then instantiates an instance of that error handler type and installs it into a service. The following snippet demonstrates this behavior.
[ServiceContract]
public interface IMyService
{
// ...
}
[ErrorBehavior(typeof(RaygunErrorHandler))] // Send unhandled exceptions to Raygun
public class MyService : IMyService
{
// ...
}
You can use the following snippet as the implementation for the attribute above.
public class ErrorBehaviorAttribute : Attribute, IServiceBehavior
{
Type errorHandlerType;
public ErrorBehaviorAttribute(Type errorHandlerType)
{
this.errorHandlerType = errorHandlerType;
}
public Type ErrorHandlerType
{
get { return this.errorHandlerType; }
}
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandler;
try
{
errorHandler = (IErrorHandler)Activator.CreateInstance(errorHandlerType);
}
catch (MissingMethodException e)
{
throw new ArgumentException("The errorHandlerType specified in the ErrorBehaviorAttribute constructor must have a public empty constructor.", e);
}
catch (InvalidCastException e)
{
throw new ArgumentException("The errorHandlerType specified in the ErrorBehaviorAttribute constructor must implement System.ServiceModel.Dispatcher.IErrorHandler.", e);
}
foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
channelDispatcher.ErrorHandlers.Add(errorHandler);
}
}
}
Step 5 - Release
Deploy Raygun into your production environment for best results, or raise a test exception. Once we detect your first error event, the Raygun app will automatically update.
Manually sending exceptions
The above instructions will setup Raygun4Net to automatically detect and send all unhandled exceptions. However sometimes you may want to send exceptions manually.
To manually send exceptions, create an instance of the RaygunClient
class. The default constructor will use the API Key that you set up in Web.config.
With the Raygun client, you can call either the Send
or SendInBackground
methods. It's important to note that SendInBackground
method should only be used for handled exceptions, rather than exceptions that will cause the application to crash. Otherwise the application will most likely shutdown all threads before Raygun is able to finish sending. Both the Send
and SendInBackground
methods have many overloads for sending additional data, which are explained in the various feature sections below.
Here's an example of manually sending exceptions from a try/catch block:
try
{
// Do something here that might go wrong
}
catch (Exception e)
{
new RaygunClient().SendInBackground(e);
}
Modify or cancel messages
On a Raygun client instance, attach an event handler to the SendingMessage
event. This event handler will be called just before the Raygun client sends an exception report - either automatically or manually. The event arguments provide the RaygunMessage
object that is about to be sent. There are two different scenarios that this event can handle:
- Modifying the message: You can make changes to the
RaygunMessage
object such as removing, adding or changing values. The changes that you make will affect the report that is sent to Raygun. - Cancelling the message: At times you may get exceptions from parts of the application that you have no control over (such as 3rd party plugins or various bot attacks). In this event handler, you can look through the properties of the
RaygunMessage
to determine if the exception is one that you don't care about. If so, you can then sete.Cancel = true
to prevent Raygun4Net from sending it.
Here is an example of cancelling a message.
public class RaygunErrorHandler : IErrorHandler
{
private RaygunClient _raygunClient = new RaygunClient();
public RaygunErrorHandler()
{
// Attach the event handler:
_raygunClient.SendingMessage += OnSendingMessage;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
}
public bool HandleError(Exception error)
{
_raygunClient.Send(error);
return false;
}
private void OnSendingMessage(object sender, RaygunSendingMessageEventArgs e)
{
// This is an example of cancelling a message:
if (e.Message.Details.Request.Url.StartsWith("/api/v2/breachedaccount/"))
{
e.Cancel = true;
}
}
}
Note that if an exception occurs within your SendingMessage
event handler, Raygun4Net will detect this and send the new exception as well as the original exception that was being processed. When processing the new exception, the event handler will not be called again in order to avoid an infinite loop.
Custom grouping
When exception reports are sent to Raygun, they get grouped using our classification logic. We improve this logic periodically, but sometimes you may come across scenarios where exceptions reports are grouped together or put into separate groups where you were not expecting. This can be from cases we are not yet handling, scenarios that are specific to your application, or unique grouping preferences you have. Raygun4Net lets you provide your own custom grouping logic before exceptions are sent to Raygun.
On a Raygun client instance, attach an event handler to the CustomGroupingKey
event. This event handler will be called just before the the SendingMessage
event described in the section above. The event arguments provide both the original Exception
object and the RaygunMessage
object that is about to be sent.
In the event handler, you can use whatever logic you want to build a grouping key (string) for the given exception. When the key is ready, set it to the CustomGroupingKey
property of the event arguments. Exceptions that end up with the same key will be grouped together.
note: Grouping keys have a limit of 100 characters.
Unless you have extreme grouping logic that needs to be applied to all exceptions, we recommend that you only apply custom grouping logic to scenarios that we are not handling for you. You can include checks in your event handler for certain types of exceptions for example, and only create a custom grouping key for them. Exceptions that you don't provide a custom grouping key for will be grouped in Raygun using the grouping classifiers we provide.
Here is an example of providing a custom grouping key.
public class RaygunErrorHandler : IErrorHandler
{
private RaygunClient _raygunClient = new RaygunClient();
public RaygunErrorHandler()
{
// Attach the event handler:
_raygunClient.CustomGroupingKey += OnCustomGroupingKey;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
}
public bool HandleError(Exception error)
{
_raygunClient.Send(error);
return false;
}
private void OnCustomGroupingKey(object sender, RaygunCustomGroupingKeyEventArgs e)
{
// This example simply performs pure message based grouping on basic Exception instances:
if (e.Message.Details.Error.ClassName.Equals("Exception"))
{
string key = e.Exception.Message;
e.CustomGroupingKey = key;
}
}
}
Note that if an exception occurs within your CustomGroupingKey
event handler, Raygun4Net will detect this and send the new exception as well as the original exception that was being processed. When processing the new exception, the event handler will not be called again in order to avoid an infinite loop.
Exclude errors from a local origin
To prevent Raygun4Net from sending exceptions that originate from a local origin (your debug/development machine), set the excludeErrorsFromLocal
attribute to true as seen in the code below. This is useful if you find that everyone in your team sending exceptions from their local machines is noisy and pointless. This option is a convenient alternative to using Web.config transforms to do the same thing.
<RaygunSettings apikey="paste_your_api_key_here" excludeErrorsFromLocal="true" />
Remove sensitive request data
By default, Raygun4Net will send all form-fields, headers, cookies and server-variables in the current HTTP request. If you have sensitive data in an HTTP request that you wish to prevent being transmitted to Raygun, you can provide a list of possible named values to remove:
<RaygunSettings apikey="paste_your_api_key_here" ignoreFormFieldNames="password,creditcard,cv2" />
Four attributes are available, to remove values from these four properties:
- ignoreFormFieldNames (ignores values from
HttpRequest.Form
) - ignoreHeaderNames (ignores values from
HttpRequest.Headers
) - ignoreCookieNames (ignores values from
HttpRequest.Cookies
) - ignoreServerVariableNames (ignores values from
HttpRequest.ServerVariables
)
Or specify them in code with the following multi-parameter method:
_raygunClient.IgnoreFormFieldNames("password", "creditcard", "cv2");
Setting any of these four options to * will cause Raygun4Net to ignore all values in that category, so none of them are sent to Raygun. Also, by placing * before, after or at both ends of a name, Raygun4Net will use that as an ends-with, starts-with or contains condition respectively when determining what to ignore.
Tags
An overload of Send
and SendInBackground
allows you to include a list of tags with each manually sent exception:
_raygunClient.Send(exception, new List<string>() { "tag1", "tag2" });
Exceptions can be searched in your Raygun dashboard by tags that you've included.
Custom data
You can include key-value custom data using an overload of the Send
or SendInBackground
methods. Values can be primitive types or rich object structures. All properties of objects and their children will be sent to Raygun. Cyclic object references will be detected and handled as appropriate, and any property getter that produces an exception will cause that property value to be displayed as the exception message.
_raygunClient.Send(exception, null, new Dictionary<string, object>() { { "key", "value" } });
The second parameter is the list of tags (mentioned above) which can be null if you don't have tags for the current exception.
Version numbering
By default, Raygun4Net will attempt to send the assembly version of your project with each report. If this is unavailable, or if you need to provide your own custom version value, you can do so by setting the ApplicationVersion
property of the Raygun client.
_raygunClient.ApplicationVersion = "1.2.3.0";
Alternatively, you can set the applicationVersion
in Web.config as follows. If both are set, the property mentioned above takes precedence over the Web.config setting.
<RaygunSettings apikey="paste_your_api_key_here" applicationVersion="1.2.3.0" />
Stripping wrapper exceptions
If you have common outer exceptions that wrap a valuable inner exception which you'd prefer to group by, you can specify these by using the following multi-parameter method:
_raygunClient.AddWrapperExceptions(typeof(MyWrapperException));
The above example will cause MyWrapperException
instances to be stripped away and never be sent to Raygun. Instead, only the inner exception of any stripped exceptions will be sent.
note:
By default HttpUnhandledException
and TargetInvocationException
will always be stripped - see below to override this behavior.
AggregateException support (Only applicable to .NET 4.0 and higher)
The AggregateException
type is a special case as they can hold multiple inner exceptions. By stripping the AggregateException
instances using the method described above, all inner exceptions will be sent to Raygun as separate exception reports. That way, each inner exception can be put into the appropriate individual groups and managed separately.
Prevent wrapper exception stripping
If you want to prevent Raygun4Net from stripping the default wrapper exceptions then you can call the multi-parameter RemoveWrapperExceptions
method as shown below. This can also be useful if you've used the above instructions to cause Raygun4Net to strip a wrapper exception type that you later don't want to strip within a single execution of the app.
_raygunClient.RemoveWrapperExceptions(typeof(TargetInvocationException));
The provider is open source and available at the Raygun4Net repository.