diff --git a/.gitignore b/.gitignore index fac6c8b..0626272 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,37 @@ -.idea/ -src/RollbarDotNet/obj/ -src/RollbarDotNet/bin/ -.vs/ -*.lock.json -test/RollbarDotNet.Tests/bin/ -test/RollbarDotNet.Tests/obj/ -*.user \ No newline at end of file +*.swp +*.*~ +project.lock.json +.DS_Store +*.pyc +nupkg/ + +# Visual Studio Code +.vscode + +# Rider +.idea + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +msbuild.log +msbuild.err +msbuild.wrn + +# Visual Studio 2015 +.vs/ \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index c813ab9..8ebb8ee 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,18 +1,18 @@ { - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "version": "0.2.0", - "configurations": [ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ { "name": ".NET Core Launch (console)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/test/RollbarDotNet.Tests/bin/Debug/netcoreapp1.0/RollbarDotNet.Tests.dll", + "program": "${workspaceFolder}/RollbarDotNet.Tests/bin/Debug/netcoreapp3.1/RollbarDotNet.Tests.dll", "args": [], - "cwd": "${workspaceFolder}/test/RollbarDotNet.Tests", + "cwd": "${workspaceFolder}/RollbarDotNet.Tests", // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window "console": "internalConsole", "stopAtEntry": false, @@ -23,6 +23,6 @@ "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" - } - ,] + }, + ] } \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 7095026..a1e101c 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -7,7 +7,7 @@ "type": "process", "args": [ "build", - "${workspaceFolder}/test/RollbarDotNet.Tests/RollbarDotNet.Tests.csproj" + "${workspaceFolder}/RollbarDotNet.Tests/RollbarDotNet.Tests.csproj" ], "problemMatcher": "$msCompile" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 8601b7f..379286f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,71 +1,83 @@ -# 0.7.0 +# Releases + +## 0.8.0 + +Released: 2020/03/25 + +- Dropped .NET Standard 1.5 support +- Upgraded to .NET Standard 2.1 +- Change scope of RollbarClient to singleton. + +## 0.7.0 + +Released: 2018/120/08 - Added ILogger support. -# 0.6.4 +## 0.6.4 Released: 2017/10/22 - Fix a null reference exception when no declaring type on thrown exception. -# 0.6.3 +## 0.6.3 Released: 2017/09/04 - Use per-request dependencies for handling RollbarClient to prevent errors. -# 0.6.2 +## 0.6.2 Released: 2017/8/20 - Change method trace string to have full namespace, method name and parameters. -# 0.6.1 +## 0.6.1 Released: 2017/8/20 - Fixed a bug where .NET Core Service extensions were excluded from the library. -# 0.6.0 +## 0.6.0 Released: 2017/8/20 -## Features +### Features - Upgrade to VS2017/CSProj. - Add trace frame support. - Also target NetStandard2.0 -# 0.5.2 +## 0.5.2 Released: 2017/4/21 -## Features +### Features -- Updated documentation. #49 -- Can now disable Rollbar from configuration. #48 +- Updated documentation. ##49 +- Can now disable Rollbar from configuration. ##48 -## Bug Fixes +### Bug Fixes -- Fix issue with trying to access Request.Form variables during POSTs that may not actually support form variables. #54 +- Fix issue with trying to access Request.Form variables during POSTs that may not actually support form variables. ##54 -# 0.5.1 +## 0.5.1 Released: 2017/3/10 -## Features +### Features - More robust testing of sending exceptions to Rollbar (see readme.md for instructions on configuring token for testing). -## Bug Fixes +### Bug Fixes - Fixed issue sending Rollbar exceptions. -# 0.5.0 +## 0.5.0 Released: 2017/2/26 -## Features +### Features - IHttpContextAccessor is no longer assumed to be included as part of `AddIdentity()`, we'll add it. - Testing of dependency injection for web platforms (console apps coming soon). @@ -74,43 +86,43 @@ - Person record support (thank you mkdabrowski). - Exception builder is now injectable. -## Bug Fixes +### Bug Fixes - Sending a message to Rollbar no longer results in a null reference exception being thrown. -# 0.4.0 +## 0.4.0 Released: 2016/9/30 -## Features +### Features - Upgrade for .NET Core 1.0 release. -# 0.3.0 +## 0.3.0 Released: 2016/6/12 -## Features +### Features - Added support for cookies on request body. - Added blacklisting variables by name. -# 0.2.0 +## 0.2.0 Released: 2016/6/9 -## Features +### Features - Rollbar message UUID available after error is reported. - Removed custom parameters from message body. - Documentation for required configuration variables. -# 0.1.0 +## 0.1.0 Released: 2016/5/31 Initial release. -## Features +### Features - Ability to send basic logs to Rollbar diff --git a/Readme.md b/Readme.md index 741c6da..b716ebb 100644 --- a/Readme.md +++ b/Readme.md @@ -1,6 +1,6 @@ # RollbarDotNet -[![NuGet](https://img.shields.io/nuget/v/RollbarDotNet.svg)]() +[![NuGet](https://img.shields.io/nuget/v/RollbarDotNet.svg)]() [![Build](https://img.shields.io/teamcity/https/teamcity.roushtech.net/s/RollbarDotNet_Build.svg)]() [![Maintainability](https://api.codeclimate.com/v1/badges/0b51030e89b49ab252f3/maintainability)](https://codeclimate.com/github/RoushTech/RollbarDotNet/maintainability) @@ -8,13 +8,13 @@ Rollbar support for your .NET Core projects, relies on dependency injection and Inspired by RollbarSharp, great library, just required too many tweaks to make play with .NET core well in my opinion. -# Testing +## Testing Environment variables for testing: - ROLLBAR_TOKEN - Rollbar token for testing. -# Required services +## Required services Please make sure the following services are available for the various builder modules. @@ -22,7 +22,7 @@ Please make sure the following services are available for the various builder mo app.UseRollbarExceptionHandler(); ``` -# Using in ASP.NET Core +## Using in ASP.NET Core Place the following after your error handling code in Startup.Configure: @@ -42,7 +42,7 @@ There is also one that doesn't load the builders for building out environment in services.AddRollbar(Configuration); ``` -Hook up the rollar configuration using the following code: +Hook up the Rollbar configuration using the following code: ``` csharp services.AddOptions(); // Most apps already are using this, but just in case. @@ -54,11 +54,20 @@ Configure Rollbar from your appSettings.json file like so: ``` javascript "Rollbar": { "AccessToken": "[access token here]", - "Environment": "[named environment here]" + "Environment": "[named environment here]", + "Disabled": false } ``` -## Getting Occurrence UUIDs +If you want to use the ILogger implementation add this: + +``` csharp + loggerFactory.AddRollbarDotNetLogger(app.ApplicationServices); +``` + +In your `Configure()` method inside of `Startup.cs` + +## Getting Occurrence UUID Getting the occurrence UUID is easy, just get it from the HttpContext Feature collection: @@ -70,27 +79,27 @@ public IActionResult Error() } ``` -The UUID can be looked up directly via https://rollbar.com/occurrence/uuid/?uuid=[UUID HERE]. This may be really useful if you want to let your users report errors to you, you can include this UUID automatically in the report. +The UUID can be looked up directly via `https://rollbar.com/occurrence/uuid/?uuid=[UUID HERE]`. This may be really useful if you want to let your users report errors to you, you can include this UUID automatically in the report. You can check if Rollbar has reported the exception via the IRollbarResponseFeature.Handled boolean. -# Calling Directly +## Calling Directly You can also post messages/exceptions directly if you so wish. ``` csharp // Send an exception -var response = await this.Rollbar.SendException(exception); +var response = await Rollbar.SendException(exception); response.Uuid //Event UUID that can be looked up on the rollbar site. // Send a message -var response = await this.Rollbar.SendMessage("Hello World!", RollbarLevels.Message); +var response = await Rollbar.SendMessage("Hello World!", RollbarLevels.Message); ``` -# Calling Without Dependency Injection +## Calling Without Dependency Injection -Although I *highly recommend* using depdency injection, you can fairly easily configure Rollbar by hand: +Although I *highly recommend* using dependency injection, you can fairly easily configure Rollbar by hand: ``` csharp var rollbarOptions = Options.Create(new RollbarOptions @@ -120,7 +129,7 @@ catch(Exception exception) } ``` -# Blacklists +## Blacklists Blacklisting will replace variables with asterisks ("**********") when data is sent to Rollbar. @@ -141,23 +150,10 @@ Inside of your appSettings.json you have two options, using plaintext or regular } ``` -Additional Blacklists can be coded by inheriting from the RollbarDotNet.Blacklisters.IBlacklister interface and registering it with your application's dependency injection framework. - +Additional Blacklists can be coded by inheriting from the `RollbarDotNet.Blacklisters.IBlacklister` interface and registering it with your application's dependency injection framework. ## To do -### Implement stack frames - -As of writing this .NET Core does not support walking the stack frames of the exception, means our error messages are pretty weak. - -### Log4net support - -As far as I know log4net is _currently_ implementing .NET Core support. - ### Break out into separate libraries -.NET Core is all about keeping things slim, do we put ASPNETCore code in a different lib? - -### .NET 4.5.1 support - -Would be nice for this to support .NET 4.5.1, no testing and no real effort outside of some basic preprocessor stuff in place. \ No newline at end of file +.NET Core is all about keeping things slim, do we put ASP.NET code in a different lib? diff --git a/test/RollbarDotNet.Tests/BlacklistCollectionTests.cs b/RollbarDotNet.Tests/BlacklistCollectionTests.cs similarity index 85% rename from test/RollbarDotNet.Tests/BlacklistCollectionTests.cs rename to RollbarDotNet.Tests/BlacklistCollectionTests.cs index 32cde67..43661c7 100644 --- a/test/RollbarDotNet.Tests/BlacklistCollectionTests.cs +++ b/RollbarDotNet.Tests/BlacklistCollectionTests.cs @@ -13,7 +13,7 @@ public void Check_Pass() var blacklisterMock = new Mock(); blacklisterMock.Setup(b => b.Check("test")).Returns(true); var blacklistCollection = new BlacklistCollection(new List { blacklisterMock.Object }); - Assert.Equal(true, blacklistCollection.Check("test")); + Assert.True(blacklistCollection.Check("test")); } [Fact] @@ -22,7 +22,7 @@ public void CheckFails() var blacklisterMock = new Mock(); blacklisterMock.Setup(b => b.Check("test")).Returns(true); var blacklistCollection = new BlacklistCollection(new List { blacklisterMock.Object }); - Assert.Equal(false, blacklistCollection.Check("testa")); + Assert.False(blacklistCollection.Check("testa")); } } } \ No newline at end of file diff --git a/test/RollbarDotNet.Tests/Blacklisters/ConfigurationBlacklisterTests.cs b/RollbarDotNet.Tests/Blacklisters/ConfigurationBlacklisterTests.cs similarity index 68% rename from test/RollbarDotNet.Tests/Blacklisters/ConfigurationBlacklisterTests.cs rename to RollbarDotNet.Tests/Blacklisters/ConfigurationBlacklisterTests.cs index f75f304..379cff0 100644 --- a/test/RollbarDotNet.Tests/Blacklisters/ConfigurationBlacklisterTests.cs +++ b/RollbarDotNet.Tests/Blacklisters/ConfigurationBlacklisterTests.cs @@ -26,29 +26,29 @@ protected ConfigurationBlacklister Setup() [Fact] public void RegexFail() { - var configurationBlacklister = this.Setup(); - Assert.Equal(false, configurationBlacklister.Check("regexfail")); + var configurationBlacklister = Setup(); + Assert.False(configurationBlacklister.Check("regexfail")); } [Fact] public void RegexPass() { - var configurationBlacklister = this.Setup(); - Assert.Equal(true, configurationBlacklister.Check("regex")); + var configurationBlacklister = Setup(); + Assert.True(configurationBlacklister.Check("regex")); } [Fact] public void StringFail() { - var configurationBlacklister = this.Setup(); - Assert.Equal(false, configurationBlacklister.Check("testa")); + var configurationBlacklister = Setup(); + Assert.False(configurationBlacklister.Check("testa")); } [Fact] public void StringPass() { - var configurationBlacklister = this.Setup(); - Assert.Equal(true, configurationBlacklister.Check("test")); + var configurationBlacklister = Setup(); + Assert.True(configurationBlacklister.Check("test")); } } } \ No newline at end of file diff --git a/test/RollbarDotNet.Tests/Builder/ConfigurationBuilderTests.cs b/RollbarDotNet.Tests/Builder/ConfigurationBuilderTests.cs similarity index 100% rename from test/RollbarDotNet.Tests/Builder/ConfigurationBuilderTests.cs rename to RollbarDotNet.Tests/Builder/ConfigurationBuilderTests.cs diff --git a/test/RollbarDotNet.Tests/Builder/EnvironmentBuilderTests.cs b/RollbarDotNet.Tests/Builder/EnvironmentBuilderTests.cs similarity index 100% rename from test/RollbarDotNet.Tests/Builder/EnvironmentBuilderTests.cs rename to RollbarDotNet.Tests/Builder/EnvironmentBuilderTests.cs diff --git a/test/RollbarDotNet.Tests/Builder/ExceptionBuilderTests.cs b/RollbarDotNet.Tests/Builder/ExceptionBuilderTests.cs similarity index 79% rename from test/RollbarDotNet.Tests/Builder/ExceptionBuilderTests.cs rename to RollbarDotNet.Tests/Builder/ExceptionBuilderTests.cs index accc461..0231eda 100644 --- a/test/RollbarDotNet.Tests/Builder/ExceptionBuilderTests.cs +++ b/RollbarDotNet.Tests/Builder/ExceptionBuilderTests.cs @@ -12,15 +12,15 @@ public class ExceptionBuilderTests { public ExceptionBuilderTests() { - this.ExceptionBuilder = new ExceptionBuilder(); - this.Payload = new Payload(); + ExceptionBuilder = new ExceptionBuilder(); + Payload = new Payload(); } protected ExceptionBuilder ExceptionBuilder { get; set; } protected Payload Payload { get; set; } - protected void ThrowException(string a, int b) + protected void ThrowException(string _1, int _2) { throw new Exception("test exception"); } @@ -49,8 +49,8 @@ public void BuildsInnerException() } catch (Exception exception) { - this.ExceptionBuilder.Execute(this.Payload, exception); - var body = this.Payload.Data?.Body; + ExceptionBuilder.Execute(Payload, exception); + var body = Payload.Data?.Body; Assert.NotNull(body?.TraceChain); var first = body.TraceChain.First(); Assert.Equal("Exception", first.Exception?.Class); @@ -65,7 +65,7 @@ public void BuildsInnerException() [Fact] public void ExceptionCannotBeNull() { - Assert.Throws(() => this.ExceptionBuilder.Execute(this.Payload, null)); + Assert.Throws(() => ExceptionBuilder.Execute(Payload, null)); } [Fact] @@ -77,7 +77,7 @@ public void PayloadCannotBeNull() } catch (Exception exception) { - Assert.Throws(() => this.ExceptionBuilder.Execute(null, exception)); + Assert.Throws(() => ExceptionBuilder.Execute(null, exception)); } } @@ -86,18 +86,18 @@ public void SetsPayload() { try { - this.ThrowException("", 0); + ThrowException("", 0); } catch (Exception exception) { - this.ExceptionBuilder.Execute(this.Payload, exception); - var payload = this.Payload.Data?.Body?.TraceChain?.FirstOrDefault(); + ExceptionBuilder.Execute(Payload, exception); + var payload = Payload.Data?.Body?.TraceChain?.FirstOrDefault(); Assert.Equal("Exception", payload?.Exception?.Class); Assert.Equal("test exception", payload?.Exception?.Message); Assert.True(payload?.Frames?.Count == 2); var frame = payload?.Frames?.FirstOrDefault(); Assert.Equal( - "RollbarDotNet.Tests.Builder.ExceptionBuilderTests.ThrowException(System.String a, System.Int32 b)", + "RollbarDotNet.Tests.Builder.ExceptionBuilderTests.ThrowException(System.String _1, System.Int32 _2)", frame?.Method); var stackTrace = new StackTrace(exception, true); var stackTraceFrame = stackTrace.GetFrames().FirstOrDefault(); diff --git a/test/RollbarDotNet.Tests/Builder/PersonBuilderTests.cs b/RollbarDotNet.Tests/Builder/PersonBuilderTests.cs similarity index 52% rename from test/RollbarDotNet.Tests/Builder/PersonBuilderTests.cs rename to RollbarDotNet.Tests/Builder/PersonBuilderTests.cs index 4939506..db5221d 100644 --- a/test/RollbarDotNet.Tests/Builder/PersonBuilderTests.cs +++ b/RollbarDotNet.Tests/Builder/PersonBuilderTests.cs @@ -11,9 +11,9 @@ public class PersonBuilderTests { public PersonBuilderTests() { - this._contextAccessor = new Mock(); - this._sut = new PersonBuilder(this._contextAccessor.Object); - this._payload = new Payload(); + _contextAccessor = new Mock(); + _sut = new PersonBuilder(_contextAccessor.Object); + _payload = new Payload(); } private readonly Mock _contextAccessor; @@ -23,29 +23,29 @@ public PersonBuilderTests() [Fact] public void Execute_NoPrincipal_ShouldSetEmptyPerson() { - this._contextAccessor.Setup(accessor => accessor.HttpContext.User).Returns((ClaimsPrincipal) null); + _contextAccessor.Setup(accessor => accessor.HttpContext.User).Returns((ClaimsPrincipal)null); - this._sut.Execute(this._payload); + _sut.Execute(_payload); - var person = this._payload.Data.Person; - Assert.Equal(true, string.IsNullOrEmpty(person.Id)); - Assert.Equal(true, string.IsNullOrEmpty(person.Email)); - Assert.Equal(true, string.IsNullOrEmpty(person.Username)); + var person = _payload.Data.Person; + Assert.True(string.IsNullOrEmpty(person.Id)); + Assert.True(string.IsNullOrEmpty(person.Email)); + Assert.True(string.IsNullOrEmpty(person.Username)); } [Fact] public void Execute_PrincipalWithEmail_ShouldSetEmail() { const string expected = "email"; - this._contextAccessor.Setup(accessor => accessor.HttpContext.User) + _contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, expected) }))); - this._sut.Execute(this._payload); + _sut.Execute(_payload); - var person = this._payload.Data.Person; + var person = _payload.Data.Person; Assert.Equal(expected, person.Email); } @@ -53,15 +53,15 @@ public void Execute_PrincipalWithEmail_ShouldSetEmail() public void Execute_PrincipalWithId_ShouldSetId() { const string expected = "id"; - this._contextAccessor.Setup(accessor => accessor.HttpContext.User) + _contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, expected) }))); - this._sut.Execute(this._payload); + _sut.Execute(_payload); - var person = this._payload.Data.Person; + var person = _payload.Data.Person; Assert.Equal(expected, person.Id); } @@ -69,36 +69,36 @@ public void Execute_PrincipalWithId_ShouldSetId() public void Execute_PrincipalWithName_ShouldSetName() { const string expected = "name"; - this._contextAccessor.Setup(accessor => accessor.HttpContext.User.Identity.Name).Returns(expected); + _contextAccessor.Setup(accessor => accessor.HttpContext.User.Identity.Name).Returns(expected); - this._sut.Execute(this._payload); + _sut.Execute(_payload); - var person = this._payload.Data.Person; + var person = _payload.Data.Person; Assert.Equal(expected, person.Username); } [Fact] public void Execute_PrincipalWithoutEmail_ShouldSetEmailToEmpty() { - this._contextAccessor.Setup(accessor => accessor.HttpContext.User) + _contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity())); - this._sut.Execute(this._payload); + _sut.Execute(_payload); - var person = this._payload.Data.Person; - Assert.Equal(true, string.IsNullOrEmpty(person.Email)); + var person = _payload.Data.Person; + Assert.True(string.IsNullOrEmpty(person.Email)); } [Fact] public void Execute_PrincipalWithoutId_ShouldSetIdToEmpty() { - this._contextAccessor.Setup(accessor => accessor.HttpContext.User) + _contextAccessor.Setup(accessor => accessor.HttpContext.User) .Returns(new ClaimsPrincipal(new ClaimsIdentity())); - this._sut.Execute(this._payload); + _sut.Execute(_payload); - var person = this._payload.Data.Person; - Assert.Equal(true, string.IsNullOrEmpty(person.Id)); + var person = _payload.Data.Person; + Assert.True(string.IsNullOrEmpty(person.Id)); } } } \ No newline at end of file diff --git a/test/RollbarDotNet.Tests/Builder/RequestBuilderTests.cs b/RollbarDotNet.Tests/Builder/RequestBuilderTests.cs similarity index 77% rename from test/RollbarDotNet.Tests/Builder/RequestBuilderTests.cs rename to RollbarDotNet.Tests/Builder/RequestBuilderTests.cs index bcea1fe..1bd1d0a 100644 --- a/test/RollbarDotNet.Tests/Builder/RequestBuilderTests.cs +++ b/RollbarDotNet.Tests/Builder/RequestBuilderTests.cs @@ -28,11 +28,11 @@ public Mock CreateIHttpContextAccessor(string method) httpContextAccessorMock.Setup(h => h.HttpContext.Request.Method).Returns(method); httpContextAccessorMock.Setup(h => h.HttpContext.Features.Get().RemoteIpAddress) .Returns(IPAddress.Loopback); - httpContextAccessorMock.Setup(h => h.HttpContext.Request.Headers).Returns(this.GenerateHeaderDictionary); - httpContextAccessorMock.Setup(h => h.HttpContext.Request.Query).Returns(this.GenerateQueryCollection); + httpContextAccessorMock.Setup(h => h.HttpContext.Request.Headers).Returns(GenerateHeaderDictionary); + httpContextAccessorMock.Setup(h => h.HttpContext.Request.Query).Returns(GenerateQueryCollection); httpContextAccessorMock.Setup(h => h.HttpContext.Request.HasFormContentType).Returns(true); - httpContextAccessorMock.Setup(h => h.HttpContext.Request.Form).Returns(this.GenerateFormCollection); - httpContextAccessorMock.Setup(h => h.HttpContext.Request.Cookies).Returns(this.GenerateCookieCollection); + httpContextAccessorMock.Setup(h => h.HttpContext.Request.Form).Returns(GenerateFormCollection); + httpContextAccessorMock.Setup(h => h.HttpContext.Request.Cookies).Returns(GenerateCookieCollection); httpContextAccessorMock.Setup(h => h.HttpContext.Request.QueryString) .Returns(new QueryString("?query=test&blacklist=here")); return httpContextAccessorMock; @@ -48,8 +48,8 @@ protected IBlacklistCollection GenerateBacklistCollection(bool enableBlacklist = protected Payload GeneratePayload(bool enableBlacklist = false, string method = "GET") { - var requestBuilder = new RequestBuilder(this.GenerateBacklistCollection(enableBlacklist), - this.CreateIHttpContextAccessor(method).Object); + var requestBuilder = new RequestBuilder(GenerateBacklistCollection(enableBlacklist), + CreateIHttpContextAccessor(method).Object); var payload = new Payload(); requestBuilder.Execute(payload); return payload; @@ -60,7 +60,7 @@ protected IHeaderDictionary GenerateHeaderDictionary() var headerDictionaryMock = new Mock(); headerDictionaryMock .Setup(h => h.GetEnumerator()) - .Returns(this.GenerateStringValueEnumerator()); + .Returns(GenerateStringValueEnumerator()); return headerDictionaryMock.Object; } @@ -68,7 +68,7 @@ protected IRequestCookieCollection GenerateCookieCollection() { var cookieCollectionMock = new Mock(); cookieCollectionMock.Setup(h => h.GetEnumerator()) - .Returns(this.GenerateStringEnumerator()); + .Returns(GenerateStringEnumerator()); return cookieCollectionMock.Object; } @@ -76,7 +76,7 @@ protected IQueryCollection GenerateQueryCollection() { var queryCollectionMock = new Mock(); queryCollectionMock.Setup(h => h.GetEnumerator()) - .Returns(this.GenerateStringValueEnumerator()); + .Returns(GenerateStringValueEnumerator()); return queryCollectionMock.Object; } @@ -84,7 +84,7 @@ protected IFormCollection GenerateFormCollection() { var formCollectionMock = new Mock(); formCollectionMock.Setup(h => h.GetEnumerator()) - .Returns(this.GenerateStringValueEnumerator()); + .Returns(GenerateStringValueEnumerator()); return formCollectionMock.Object; } @@ -109,7 +109,7 @@ protected IEnumerator> GenerateStringValueEnu [Fact] public void Blacklists_Payload_Cookies() { - var cookies = this.GeneratePayload(true)?.Data?.Request?.Cookies; + var cookies = GeneratePayload(true)?.Data?.Request?.Cookies; Assert.True(cookies.ContainsKey("blacklist")); Assert.Equal("**********", cookies["blacklist"]); } @@ -117,7 +117,7 @@ public void Blacklists_Payload_Cookies() [Fact] public void Blacklists_Payload_Headers() { - var headers = this.GeneratePayload(true)?.Data?.Request?.Headers; + var headers = GeneratePayload(true)?.Data?.Request?.Headers; Assert.True(headers.ContainsKey("blacklist")); Assert.Equal("**********", headers["blacklist"]); } @@ -125,7 +125,7 @@ public void Blacklists_Payload_Headers() [Fact] public void Blacklists_Payload_Query_Get() { - var query = this.GeneratePayload(true)?.Data?.Request?.Get; + var query = GeneratePayload(true)?.Data?.Request?.Get; Assert.True(query.ContainsKey("blacklist")); Assert.Equal("**********", query["blacklist"]); } @@ -133,7 +133,7 @@ public void Blacklists_Payload_Query_Get() [Fact] public void Blacklists_Payload_Query_Post() { - var query = this.GeneratePayload(true, "POST")?.Data?.Request?.Post; + var query = GeneratePayload(true, "POST")?.Data?.Request?.Post; Assert.True(query.ContainsKey("blacklist")); Assert.Equal("**********", query["blacklist"]); } @@ -141,7 +141,7 @@ public void Blacklists_Payload_Query_Post() [Fact] public void Blacklists_Payload_QueryString() { - var queryString = this.GeneratePayload(true)?.Data?.Request?.QueryString; + var queryString = GeneratePayload(true)?.Data?.Request?.QueryString; Assert.Equal("?query=test&blacklist=**********", queryString); } @@ -153,11 +153,11 @@ public void Blacklists_Payload_QueryString() [Fact] public void Bug_ThrowsIncorrectContentType() { - var mock = this.CreateIHttpContextAccessor("POST"); + var mock = CreateIHttpContextAccessor("POST"); mock.Setup(h => h.HttpContext.Request.HasFormContentType).Returns(false); mock.Setup(h => h.HttpContext.Request.Form) .Throws(new InvalidOperationException("Incorrect Content-Type: application/json; charset=UTF-8")); - var requestBuilder = new RequestBuilder(this.GenerateBacklistCollection(), mock.Object); + var requestBuilder = new RequestBuilder(GenerateBacklistCollection(), mock.Object); var payload = new Payload(); requestBuilder.Execute(payload); } @@ -165,56 +165,56 @@ public void Bug_ThrowsIncorrectContentType() [Fact] public void Builds_Payload_Cookies() { - var query = this.GeneratePayload()?.Data?.Request?.Cookies; - Assert.Equal(this.DefaultDictionary, query); + var query = GeneratePayload()?.Data?.Request?.Cookies; + Assert.Equal(DefaultDictionary, query); } [Fact] public void Builds_Payload_Headers() { - var headers = this.GeneratePayload()?.Data?.Request?.Headers; - Assert.Equal(this.DefaultDictionary, headers); + var headers = GeneratePayload()?.Data?.Request?.Headers; + Assert.Equal(DefaultDictionary, headers); } [Fact] public void Builds_Payload_Method() { - var payload = this.GeneratePayload(); + var payload = GeneratePayload(); Assert.Equal("GET", payload.Data?.Request?.Method); } [Fact] public void Builds_Payload_Query_Get() { - var query = this.GeneratePayload()?.Data?.Request?.Get; - Assert.Equal(this.DefaultDictionary, query); + var query = GeneratePayload()?.Data?.Request?.Get; + Assert.Equal(DefaultDictionary, query); } [Fact] public void Builds_Payload_Query_Post() { - var query = this.GeneratePayload(false, "POST")?.Data?.Request?.Post; - Assert.Equal(this.DefaultDictionary, query); + var query = GeneratePayload(false, "POST")?.Data?.Request?.Post; + Assert.Equal(DefaultDictionary, query); } [Fact] public void Builds_Payload_QueryString() { - var queryString = this.GeneratePayload()?.Data?.Request?.QueryString; + var queryString = GeneratePayload()?.Data?.Request?.QueryString; Assert.Equal("?query=test&blacklist=here", queryString); } [Fact] public void Builds_Payload_Url() { - var payload = this.GeneratePayload(); + var payload = GeneratePayload(); Assert.Equal("http://my.test.domain/request/url/here.txt", payload.Data?.Request?.Url); } [Fact] public void Builds_Payload_UserIp() { - var payload = this.GeneratePayload(); + var payload = GeneratePayload(); Assert.Equal(IPAddress.Loopback.ToString(), payload.Data?.Request?.UserIp); } } diff --git a/test/RollbarDotNet.Tests/Builder/ServerBuilderTests.cs b/RollbarDotNet.Tests/Builder/ServerBuilderTests.cs similarity index 100% rename from test/RollbarDotNet.Tests/Builder/ServerBuilderTests.cs rename to RollbarDotNet.Tests/Builder/ServerBuilderTests.cs diff --git a/RollbarDotNet.Tests/Core/ExcpetionHandlerMiddlewareTests.cs b/RollbarDotNet.Tests/Core/ExcpetionHandlerMiddlewareTests.cs new file mode 100644 index 0000000..95298e3 --- /dev/null +++ b/RollbarDotNet.Tests/Core/ExcpetionHandlerMiddlewareTests.cs @@ -0,0 +1,57 @@ +namespace RollbarDotNet.Tests.Core +{ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Options; + using Moq; + using RollbarDotNet.Builder; + using RollbarDotNet.Configuration; + using RollbarDotNet.Core; + using Xunit; + + public class ExceptionHandlerMiddlewareTests + { + + [Fact] + public async Task OnlyLogsOnce() + { + var uuid = string.Empty; + var optionsMock = new Mock>(); + var rollbarClientMock = new Mock(optionsMock.Object); + rollbarClientMock.SetupSequence(m => m.Send(It.IsAny())) + .Returns(() => ReturnItem("test")) + .Returns(() => ReturnItem("fail")); + var httpContextMock = new Mock(); + httpContextMock + .Setup(h => h.Features.Set(It.IsAny())); + var rollbar = new Rollbar(new IBuilder[] { }, new IExceptionBuilder[] { }, rollbarClientMock.Object); + var middleware = new ExceptionHandlerMiddleware(context => + { + try + { + throw new Exception("Middleware tests"); + } + catch (Exception exception) + { + rollbar.SendException(exception).Wait(); + throw; + } + }); + await Assert.ThrowsAsync(async () => await middleware.Invoke(httpContextMock.Object, rollbar)); + rollbarClientMock.Verify(m => m.Send(It.IsAny()), Times.Once()); + httpContextMock.Verify(m => m.Features.Set(It.Is(f => f.Uuid == "test"))); + } + + private Task ReturnItem(string uuid) + { + return Task.FromResult(new Payloads.Response + { + Result = new Payloads.Result + { + Uuid = uuid + } + }); + } + } +} \ No newline at end of file diff --git a/test/RollbarDotNet.Tests/DependencyInjection/WebDependencyInjectionTests.cs b/RollbarDotNet.Tests/DependencyInjection/WebDependencyInjectionTests.cs similarity index 74% rename from test/RollbarDotNet.Tests/DependencyInjection/WebDependencyInjectionTests.cs rename to RollbarDotNet.Tests/DependencyInjection/WebDependencyInjectionTests.cs index b76cb76..afd39b4 100644 --- a/test/RollbarDotNet.Tests/DependencyInjection/WebDependencyInjectionTests.cs +++ b/RollbarDotNet.Tests/DependencyInjection/WebDependencyInjectionTests.cs @@ -3,11 +3,11 @@ using System; using System.Threading.Tasks; using Configuration; - using Core; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Moq; + using RollbarDotNet.Core; using Xunit; public class WebDependencyInjectionTests @@ -25,9 +25,9 @@ public WebDependencyInjectionTests() o.Environment = "Testing"; }); - this.Services = services; - this.ServiceProvider = this.Services.BuildServiceProvider(); - this.Rollbar = this.ServiceProvider.GetService(); + Services = services; + ServiceProvider = Services.BuildServiceProvider(); + Rollbar = ServiceProvider.GetService(); } protected IServiceCollection Services { get; set; } @@ -39,14 +39,14 @@ public WebDependencyInjectionTests() [Fact] public async Task DisabledRollbar() { - var options = this.ServiceProvider.GetService>().Value; - this.Services.Configure(o => + var options = ServiceProvider.GetService>().Value; + Services.Configure(o => { o.AccessToken = options.AccessToken; o.Disabled = true; o.Environment = options.Environment; }); - var serviceProvider = this.Services.BuildServiceProvider(); + var serviceProvider = Services.BuildServiceProvider(); var rollbar = serviceProvider.GetService(); var response = await rollbar.SendMessage(RollbarLevel.Debug, "Hello"); Assert.Null(response.Result.Uuid); @@ -55,19 +55,21 @@ public async Task DisabledRollbar() [Fact] public async Task SuccessfullyReportMessage() { - var response = await this.Rollbar.SendMessage("Hello"); + var response = await Rollbar.SendMessage("Hello"); Assert.False(string.IsNullOrEmpty(response.Result.Uuid)); } [Fact] public async Task SuccessfullyReportMessageWithLevel() { - var response = await this.Rollbar.SendMessage(RollbarLevel.Debug, "Hello"); + var response = await Rollbar.SendMessage(RollbarLevel.Debug, "Hello"); Assert.False(string.IsNullOrEmpty(response.Result.Uuid)); } - [Fact] - public async Task SucessfullyReportError() + [Theory] + [InlineData(null)] + [InlineData("Test Message For Exception")] + public async Task SuccessfullyReportError(string message) { try { @@ -82,7 +84,7 @@ public async Task SucessfullyReportError() } catch (Exception exception) { - var response = await this.Rollbar.SendException(exception); + var response = await Rollbar.SendException(exception, message); Assert.False(string.IsNullOrEmpty(response.Result.Uuid)); } } diff --git a/RollbarDotNet.Tests/Kestrel/KestrelTests.cs b/RollbarDotNet.Tests/Kestrel/KestrelTests.cs new file mode 100644 index 0000000..f776383 --- /dev/null +++ b/RollbarDotNet.Tests/Kestrel/KestrelTests.cs @@ -0,0 +1,55 @@ +namespace RollbarDotNet.Tests.Kestrel +{ + using System; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Hosting.Server; + using Microsoft.AspNetCore.Server.Kestrel.Core; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; + using Moq; + using RollbarDotNet.Core; + using RollbarDotNet.Logger; + using Xunit; + + public class KestrelTests + { + public KestrelTests() + { + RollbarMock = new Mock(null, null, null); + RollbarMock.Setup(m => m.SendException(It.IsAny(), It.IsAny())).Returns(() => Task.FromResult(null)); + RollbarMock.Setup(m => m.SendMessage(It.IsAny(), It.IsAny())).Returns(() => Task.FromResult(null)); + } + + protected Mock RollbarMock { get; set; } + + [Fact] + public async Task CanAddRollbarDotNetLogger() + { + var webHost = CreateBuilder() + .ConfigureServices(services => + { + services.AddLogging().AddRollbar(); + }) + .Configure(app => + { + app.UseRollbarExceptionHandler(); + var loggerFactory = app.ApplicationServices + .GetRequiredService(); + loggerFactory.AddRollbarDotNetLogger(app.ApplicationServices); + }) + .Build(); + await webHost.StartAsync(); + await webHost.StopAsync(); + } + + private IWebHostBuilder CreateBuilder() => new WebHostBuilder() + .UseDefaultServiceProvider(options => + { + options.ValidateScopes = true; + }) + .UseKestrel(); + } +} \ No newline at end of file diff --git a/RollbarDotNet.Tests/Kestrel/Startup.cs b/RollbarDotNet.Tests/Kestrel/Startup.cs new file mode 100644 index 0000000..cec1268 --- /dev/null +++ b/RollbarDotNet.Tests/Kestrel/Startup.cs @@ -0,0 +1,33 @@ +namespace RollbarDotNet.Tests.Kestrel +{ + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using RollbarDotNet.Core; + + public class Startup + { + + public void ConfigureServices(IServiceCollection services) + { + services + .AddRollbarWeb() + .AddControllers(); + } + + public void Configure(IApplicationBuilder app) + { + app + .UseForwardedHeaders() + .UseHttpsRedirection() + .UseRouting() + .UseCors() + .UseAuthentication() + .UseAuthorization() + .UseDefaultFiles() + .UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} \ No newline at end of file diff --git a/test/RollbarDotNet.Tests/Logger/RollbarDotNetLoggerTests.cs b/RollbarDotNet.Tests/Logger/RollbarDotNetLoggerTests.cs similarity index 69% rename from test/RollbarDotNet.Tests/Logger/RollbarDotNetLoggerTests.cs rename to RollbarDotNet.Tests/Logger/RollbarDotNetLoggerTests.cs index 87dee8b..5b4bf77 100644 --- a/test/RollbarDotNet.Tests/Logger/RollbarDotNetLoggerTests.cs +++ b/RollbarDotNet.Tests/Logger/RollbarDotNetLoggerTests.cs @@ -3,12 +3,7 @@ namespace RollbarDotNet.Tests.Logger using System; using System.Collections.Generic; using System.Threading.Tasks; - using Configuration; - using Core; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; using Moq; using RollbarDotNet.Logger; using Xunit; @@ -17,10 +12,10 @@ public class RollbarDotNetLoggerTests { public RollbarDotNetLoggerTests() { - this.RollbarMock = new Mock(null, null, null); - this.RollbarMock.Setup(m => m.SendException(It.IsAny(), It.IsAny())).Returns(() => Task.FromResult(null)); - this.RollbarMock.Setup(m => m.SendMessage(It.IsAny(), It.IsAny())).Returns(() => Task.FromResult(null)); - this.Logger = new RollbarDotNetLogger(this.RollbarMock.Object); + RollbarMock = new Mock(null, null, null); + RollbarMock.Setup(m => m.SendException(It.IsAny(), It.IsAny())).Returns(() => Task.FromResult(null)); + RollbarMock.Setup(m => m.SendMessage(It.IsAny(), It.IsAny())).Returns(() => Task.FromResult(null)); + Logger = new RollbarDotNetLogger(RollbarMock.Object); } protected Mock RollbarMock { get; set; } @@ -36,40 +31,40 @@ public RollbarDotNetLoggerTests() [InlineData(LogLevel.None, false)] public void IsEnabled_Correctly(LogLevel logLevel, bool isEnabled) { - Assert.Equal(isEnabled, this.Logger.IsEnabled(logLevel)); + Assert.Equal(isEnabled, Logger.IsEnabled(logLevel)); } [Fact] public void BeginScope_ReturnsNull() { - Assert.Null(this.Logger.BeginScope(null)); + Assert.Null(Logger.BeginScope(null)); } [Theory] [MemberData(nameof(Logs))] public void Log_SendsExceptionIfPassed(LogLevel logLevel, RollbarLevel rollbarLevel, Exception ex, bool shouldSendException, bool shouldSendMessage) { - this.Logger.Log(logLevel, 0, (string)null, ex, (s, e) => string.Empty); - RollbarMock.Verify(r => r.SendException(rollbarLevel, ex), Times.Exactly(shouldSendException ? 1 : 0)); + Logger.Log(logLevel, 0, (string)null, ex, (s, e) => string.Empty); + RollbarMock.Verify(r => r.SendException(rollbarLevel, ex, It.IsAny()), Times.Exactly(shouldSendException ? 1 : 0)); RollbarMock.Verify(r => r.SendMessage(rollbarLevel, It.IsAny()), Times.Exactly(shouldSendMessage ? 1 : 0)); } public static IEnumerable Logs() { yield return new object[] { LogLevel.Critical, RollbarLevel.Critical, new Exception(), true, false }; - yield return new object[] { LogLevel.Critical, RollbarLevel.Critical, (Exception)null, false, true }; + yield return new object[] { LogLevel.Critical, RollbarLevel.Critical, null, false, true }; yield return new object[] { LogLevel.Error, RollbarLevel.Error, new Exception(), true, false }; - yield return new object[] { LogLevel.Error, RollbarLevel.Error, (Exception)null, false, true }; + yield return new object[] { LogLevel.Error, RollbarLevel.Error, null, false, true }; yield return new object[] { LogLevel.Warning, RollbarLevel.Warning, new Exception(), true, false }; - yield return new object[] { LogLevel.Warning, RollbarLevel.Warning, (Exception)null, false, true }; + yield return new object[] { LogLevel.Warning, RollbarLevel.Warning, null, false, true }; yield return new object[] { LogLevel.Information, RollbarLevel.Info, new Exception(), true, false }; - yield return new object[] { LogLevel.Information, RollbarLevel.Info, (Exception)null, false, true }; + yield return new object[] { LogLevel.Information, RollbarLevel.Info, null, false, true }; yield return new object[] { LogLevel.Debug, RollbarLevel.Debug, new Exception(), true, false }; - yield return new object[] { LogLevel.Debug, RollbarLevel.Debug, (Exception)null, false, true }; + yield return new object[] { LogLevel.Debug, RollbarLevel.Debug, null, false, true }; yield return new object[] { LogLevel.Trace, RollbarLevel.Debug, new Exception(), true, false }; - yield return new object[] { LogLevel.Trace, RollbarLevel.Debug, (Exception)null, false, true }; + yield return new object[] { LogLevel.Trace, RollbarLevel.Debug, null, false, true }; yield return new object[] { LogLevel.None, RollbarLevel.Debug, new Exception(), false, false }; - yield return new object[] { LogLevel.None, RollbarLevel.Debug, (Exception)null, false, false }; + yield return new object[] { LogLevel.None, RollbarLevel.Debug, null, false, false }; } } } \ No newline at end of file diff --git a/test/RollbarDotNet.Tests/Properties/AssemblyInfo.cs b/RollbarDotNet.Tests/Properties/AssemblyInfo.cs similarity index 100% rename from test/RollbarDotNet.Tests/Properties/AssemblyInfo.cs rename to RollbarDotNet.Tests/Properties/AssemblyInfo.cs diff --git a/test/RollbarDotNet.Tests/RollbarDotNet.Tests.csproj b/RollbarDotNet.Tests/RollbarDotNet.Tests.csproj similarity index 60% rename from test/RollbarDotNet.Tests/RollbarDotNet.Tests.csproj rename to RollbarDotNet.Tests/RollbarDotNet.Tests.csproj index 6f747ad..929e7b7 100644 --- a/test/RollbarDotNet.Tests/RollbarDotNet.Tests.csproj +++ b/RollbarDotNet.Tests/RollbarDotNet.Tests.csproj @@ -1,7 +1,7 @@ - + - 0.6.0 + 0.7.1 RollbarDotNet.Tests RollbarDotNet.Tests true @@ -10,26 +10,23 @@ false false false - netcoreapp1.0;netcoreapp2.0 - - - - 1.0.0 - - - 2.0.0 + net7.0 - + - - + + + - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + diff --git a/RollbarDotNet.sln b/RollbarDotNet.sln index f5d3212..28996d6 100644 --- a/RollbarDotNet.sln +++ b/RollbarDotNet.sln @@ -3,8 +3,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26730.3 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FBE55ED6-5E60-41F8-B5C0-7C97D04A1A6C}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{04899B07-3768-4373-9CB8-1A0DBA28C035}" ProjectSection(SolutionItems) = preProject CHANGELOG.md = CHANGELOG.md @@ -13,11 +11,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .codeclimate.yml = .codeclimate.yml EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RollbarDotNet", "src\RollbarDotNet\RollbarDotNet.csproj", "{6CF5EF94-87E9-4436-AA9B-072C86B7E572}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RollbarDotNet.Tests", "test\RollbarDotNet.Tests\RollbarDotNet.Tests.csproj", "{14F85500-0E09-4DEA-A0D6-DE7B8D4BDED7}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RollbarDotNet", "RollbarDotNet\RollbarDotNet.csproj", "{6CF5EF94-87E9-4436-AA9B-072C86B7E572}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{A7291A6A-8F50-4A1E-BCAC-51A9A88AFDEB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RollbarDotNet.Tests", "RollbarDotNet.Tests\RollbarDotNet.Tests.csproj", "{14F85500-0E09-4DEA-A0D6-DE7B8D4BDED7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -37,10 +33,6 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {6CF5EF94-87E9-4436-AA9B-072C86B7E572} = {FBE55ED6-5E60-41F8-B5C0-7C97D04A1A6C} - {14F85500-0E09-4DEA-A0D6-DE7B8D4BDED7} = {A7291A6A-8F50-4A1E-BCAC-51A9A88AFDEB} - EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {71533B28-842E-4D02-A21A-6BC3B665CAB6} EndGlobalSection diff --git a/src/RollbarDotNet/Abstractions/IDateTime.cs b/RollbarDotNet/Abstractions/IDateTime.cs similarity index 100% rename from src/RollbarDotNet/Abstractions/IDateTime.cs rename to RollbarDotNet/Abstractions/IDateTime.cs diff --git a/src/RollbarDotNet/Abstractions/IEnvironment.cs b/RollbarDotNet/Abstractions/IEnvironment.cs similarity index 100% rename from src/RollbarDotNet/Abstractions/IEnvironment.cs rename to RollbarDotNet/Abstractions/IEnvironment.cs diff --git a/src/RollbarDotNet/Abstractions/SystemDateTime.cs b/RollbarDotNet/Abstractions/SystemDateTime.cs similarity index 100% rename from src/RollbarDotNet/Abstractions/SystemDateTime.cs rename to RollbarDotNet/Abstractions/SystemDateTime.cs diff --git a/src/RollbarDotNet/Abstractions/SystemEnvironment.cs b/RollbarDotNet/Abstractions/SystemEnvironment.cs similarity index 100% rename from src/RollbarDotNet/Abstractions/SystemEnvironment.cs rename to RollbarDotNet/Abstractions/SystemEnvironment.cs diff --git a/src/RollbarDotNet/BlacklistCollection.cs b/RollbarDotNet/BlacklistCollection.cs similarity index 77% rename from src/RollbarDotNet/BlacklistCollection.cs rename to RollbarDotNet/BlacklistCollection.cs index 63fc85a..4ec77db 100644 --- a/src/RollbarDotNet/BlacklistCollection.cs +++ b/RollbarDotNet/BlacklistCollection.cs @@ -10,12 +10,12 @@ public class BlacklistCollection : IBlacklistCollection public BlacklistCollection(IEnumerable blacklisters) { - this.Blacklisters = blacklisters.ToList(); + Blacklisters = blacklisters.ToList(); } public bool Check(string name) { - return this.Blacklisters.Any(b => b.Check(name)); + return Blacklisters.Any(b => b.Check(name)); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Blacklisters/ConfigurationBlacklister.cs b/RollbarDotNet/Blacklisters/ConfigurationBlacklister.cs similarity index 56% rename from src/RollbarDotNet/Blacklisters/ConfigurationBlacklister.cs rename to RollbarDotNet/Blacklisters/ConfigurationBlacklister.cs index 589eef8..7735572 100644 --- a/src/RollbarDotNet/Blacklisters/ConfigurationBlacklister.cs +++ b/RollbarDotNet/Blacklisters/ConfigurationBlacklister.cs @@ -16,19 +16,19 @@ public class ConfigurationBlacklister : IBlacklister public ConfigurationBlacklister(IOptions config) { - this.Configuration = config?.Value?.Blacklist; - this.RegexChecks = new List(); - this.StringChecks = new List(); - if (this.Configuration != null) + Configuration = config?.Value?.Blacklist; + RegexChecks = new List(); + StringChecks = new List(); + if (Configuration != null) { - this.Configuration.Regex?.ForEach(r => this.RegexChecks.Add(new Regex(r))); - this.Configuration.Text?.ForEach(t => this.StringChecks.Add(t)); + Configuration.Regex?.ForEach(r => RegexChecks.Add(new Regex(r))); + Configuration.Text?.ForEach(t => StringChecks.Add(t)); } } public bool Check(string name) { - return this.RegexChecks.Any(c => c.IsMatch(name)) || this.StringChecks.Any(c => c == name); + return RegexChecks.Any(c => c.IsMatch(name)) || StringChecks.Any(c => c == name); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Blacklisters/IBlacklister.cs b/RollbarDotNet/Blacklisters/IBlacklister.cs similarity index 100% rename from src/RollbarDotNet/Blacklisters/IBlacklister.cs rename to RollbarDotNet/Blacklisters/IBlacklister.cs diff --git a/src/RollbarDotNet/Builder/ConfigurationBuilder.cs b/RollbarDotNet/Builder/ConfigurationBuilder.cs similarity index 84% rename from src/RollbarDotNet/Builder/ConfigurationBuilder.cs rename to RollbarDotNet/Builder/ConfigurationBuilder.cs index 8c3defa..9968f76 100644 --- a/src/RollbarDotNet/Builder/ConfigurationBuilder.cs +++ b/RollbarDotNet/Builder/ConfigurationBuilder.cs @@ -11,13 +11,13 @@ public class ConfigurationBuilder : IBuilder public ConfigurationBuilder(IOptions configuration) { - this.Configuration = configuration.Value; + Configuration = configuration.Value; } public void Execute(Payload payload) { - payload.AccessToken = this.Configuration.AccessToken; - payload.Data.Environment = this.Configuration.Environment; + payload.AccessToken = Configuration.AccessToken; + payload.Data.Environment = Configuration.Environment; if (string.IsNullOrEmpty(payload.AccessToken)) { diff --git a/src/RollbarDotNet/Builder/EnvironmentBuilder.cs b/RollbarDotNet/Builder/EnvironmentBuilder.cs similarity index 77% rename from src/RollbarDotNet/Builder/EnvironmentBuilder.cs rename to RollbarDotNet/Builder/EnvironmentBuilder.cs index 1660e02..27379fe 100644 --- a/src/RollbarDotNet/Builder/EnvironmentBuilder.cs +++ b/RollbarDotNet/Builder/EnvironmentBuilder.cs @@ -10,18 +10,18 @@ public class EnvironmentBuilder : IBuilder public EnvironmentBuilder(IDateTime datetime) { - this.DateTime = datetime; + DateTime = datetime; } protected static long ConvertToUnixTime(DateTime datetime) { var sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - return (long) (datetime - sTime).TotalSeconds; + return (long)(datetime - sTime).TotalSeconds; } public void Execute(Payload payload) { - payload.Data.Timestamp = ConvertToUnixTime(this.DateTime.UtcNow); + payload.Data.Timestamp = ConvertToUnixTime(DateTime.UtcNow); payload.Data.Language = "C#"; payload.Data.Platform = ".NET Core"; } diff --git a/src/RollbarDotNet/Builder/ExceptionBuilder.cs b/RollbarDotNet/Builder/ExceptionBuilder.cs similarity index 83% rename from src/RollbarDotNet/Builder/ExceptionBuilder.cs rename to RollbarDotNet/Builder/ExceptionBuilder.cs index 9ca3fed..568465d 100644 --- a/src/RollbarDotNet/Builder/ExceptionBuilder.cs +++ b/RollbarDotNet/Builder/ExceptionBuilder.cs @@ -21,7 +21,7 @@ public void Execute(Payload payload, Exception exception) } var traceChain = new List(); - this.BuildTraceList(exception, traceChain); + BuildTraceList(exception, traceChain); if (traceChain.Count > 0) { payload.Data.Body.TraceChain = traceChain; @@ -32,13 +32,13 @@ protected void BuildTraceList(Exception exception, List traceList) { var trace = new Trace { - Exception = this.BuildException(exception), - Frames = this.BuildFrames(exception) + Exception = BuildException(exception), + Frames = BuildFrames(exception) }; traceList.Add(trace); if (exception.InnerException != null) { - this.BuildTraceList(exception.InnerException, traceList); + BuildTraceList(exception.InnerException, traceList); } } @@ -74,7 +74,7 @@ protected List BuildFrames(Exception exception) if (exception.InnerException != null) { - frames.AddRange(this.BuildFrames(exception.InnerException)); + frames.AddRange(BuildFrames(exception.InnerException)); } return frames; @@ -82,9 +82,11 @@ protected List BuildFrames(Exception exception) protected Payloads.Exception BuildException(Exception exception) { - var payloadException = new Payloads.Exception(); - payloadException.Class = exception.GetType().Name; - payloadException.Message = exception.Message; + var payloadException = new Payloads.Exception + { + Class = exception.GetType().Name, + Message = exception.Message + }; return payloadException; } } diff --git a/src/RollbarDotNet/Builder/IBuilder.cs b/RollbarDotNet/Builder/IBuilder.cs similarity index 100% rename from src/RollbarDotNet/Builder/IBuilder.cs rename to RollbarDotNet/Builder/IBuilder.cs diff --git a/src/RollbarDotNet/Builder/IExceptionBuilder.cs b/RollbarDotNet/Builder/IExceptionBuilder.cs similarity index 100% rename from src/RollbarDotNet/Builder/IExceptionBuilder.cs rename to RollbarDotNet/Builder/IExceptionBuilder.cs diff --git a/src/RollbarDotNet/Builder/NotifierBuilder.cs b/RollbarDotNet/Builder/NotifierBuilder.cs similarity index 78% rename from src/RollbarDotNet/Builder/NotifierBuilder.cs rename to RollbarDotNet/Builder/NotifierBuilder.cs index 4d9be06..567cd8d 100644 --- a/src/RollbarDotNet/Builder/NotifierBuilder.cs +++ b/RollbarDotNet/Builder/NotifierBuilder.cs @@ -8,8 +8,10 @@ public class NotifierBuilder : IBuilder { public void Execute(Payload payload) { - payload.Data.Notifier = new Notifier(); - payload.Data.Notifier.Name = "RollbarDotNet"; + payload.Data.Notifier = new Notifier + { + Name = "RollbarDotNet" + }; var version = FileVersionInfo.GetVersionInfo(typeof(Rollbar).GetTypeInfo().Assembly.Location) .ProductVersion; payload.Data.Notifier.Version = version; diff --git a/src/RollbarDotNet/Builder/PersonBuilder.cs b/RollbarDotNet/Builder/PersonBuilder.cs similarity index 83% rename from src/RollbarDotNet/Builder/PersonBuilder.cs rename to RollbarDotNet/Builder/PersonBuilder.cs index a760f50..f123cd1 100644 --- a/src/RollbarDotNet/Builder/PersonBuilder.cs +++ b/RollbarDotNet/Builder/PersonBuilder.cs @@ -10,18 +10,18 @@ public class PersonBuilder : IBuilder public PersonBuilder(IHttpContextAccessor contextAccessor) { - this.ContextAccessor = contextAccessor; + ContextAccessor = contextAccessor; } public void Execute(Payload payload) { payload.Data.Person = new Person(); - this.BuildPerson(payload.Data.Person); + BuildPerson(payload.Data.Person); } private void BuildPerson(Person person) { - var principal = this.ContextAccessor.HttpContext?.User; + var principal = ContextAccessor.HttpContext?.User; if (principal == null) { return; diff --git a/src/RollbarDotNet/Builder/RequestBuilder.cs b/RollbarDotNet/Builder/RequestBuilder.cs similarity index 76% rename from src/RollbarDotNet/Builder/RequestBuilder.cs rename to RollbarDotNet/Builder/RequestBuilder.cs index bd4e66a..89276e1 100644 --- a/src/RollbarDotNet/Builder/RequestBuilder.cs +++ b/RollbarDotNet/Builder/RequestBuilder.cs @@ -16,19 +16,19 @@ public RequestBuilder( IBlacklistCollection blacklistCollection, IHttpContextAccessor contextAccessor) { - this.BlacklistCollection = blacklistCollection; - this.ContextAccessor = contextAccessor; + BlacklistCollection = blacklistCollection; + ContextAccessor = contextAccessor; } public void Execute(Payload payload) { payload.Data.Request = new Request(); - this.BuildRequest(payload.Data.Request); + BuildRequest(payload.Data.Request); } protected void BuildRequest(Request request) { - var context = this.ContextAccessor.HttpContext; + var context = ContextAccessor.HttpContext; if (context == null) { return; @@ -36,23 +36,23 @@ protected void BuildRequest(Request request) request.Url = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}"; request.Method = context.Request.Method.ToUpper(); - request.Headers = this.HeadersToDictionary(context.Request.Headers); + request.Headers = HeadersToDictionary(context.Request.Headers); request.UserIp = context.Features.Get().RemoteIpAddress.ToString(); - request.Cookies = this.CookiesToDictionary(context.Request.Cookies); + request.Cookies = CookiesToDictionary(context.Request.Cookies); if (context.Request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase)) { - request.Get = this.QueryToDictionary(context.Request.Query); + request.Get = QueryToDictionary(context.Request.Query); } else if (context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) && context.Request.HasFormContentType) { - request.Post = this.FormToDictionary(context.Request.Form); + request.Post = FormToDictionary(context.Request.Form); } if (context.Request.QueryString.HasValue) { - request.QueryString = this.QueryStringBreakdown(context.Request.QueryString.Value); + request.QueryString = QueryStringBreakdown(context.Request.QueryString.Value); } } @@ -80,7 +80,7 @@ protected string QueryStringBreakdown(string queryString) } var tempString = keyValue[0] + "="; - tempString += this.BlacklistCollection.Check(keyValue[0]) ? "**********" : keyValue[1]; + tempString += BlacklistCollection.Check(keyValue[0]) ? "**********" : keyValue[1]; parameters[i] = tempString; } @@ -93,7 +93,7 @@ protected Dictionary CookiesToDictionary(IRequestCookieCollectio var dictionary = new Dictionary(); foreach (var cookie in cookieCollection) { - dictionary.Add(cookie.Key, this.BlacklistCollection.Check(cookie.Key) ? "**********" : cookie.Value); + dictionary.Add(cookie.Key, BlacklistCollection.Check(cookie.Key) ? "**********" : cookie.Value); } return dictionary.Count == 0 ? null : dictionary; @@ -104,7 +104,7 @@ protected Dictionary FormToDictionary(IFormCollection formCollec var dictionary = new Dictionary(); foreach (var form in formCollection) { - dictionary.Add(form.Key, this.BlacklistCollection.Check(form.Key) ? "**********" : (string) form.Value); + dictionary.Add(form.Key, BlacklistCollection.Check(form.Key) ? "**********" : (string)form.Value); } return dictionary.Count == 0 ? null : dictionary; @@ -116,7 +116,7 @@ protected Dictionary QueryToDictionary(IQueryCollection queryCol foreach (var query in queryCollection) { dictionary.Add(query.Key, - this.BlacklistCollection.Check(query.Key) ? "**********" : (string) query.Value); + BlacklistCollection.Check(query.Key) ? "**********" : (string)query.Value); } return dictionary.Count == 0 ? null : dictionary; @@ -128,7 +128,7 @@ protected Dictionary HeadersToDictionary(IHeaderDictionary heade foreach (var header in headerDictionary) { dictionary.Add(header.Key, - this.BlacklistCollection.Check(header.Key) ? "**********" : (string) header.Value); + BlacklistCollection.Check(header.Key) ? "**********" : (string)header.Value); } return dictionary.Count == 0 ? null : dictionary; diff --git a/src/RollbarDotNet/Builder/ServerBuilder.cs b/RollbarDotNet/Builder/ServerBuilder.cs similarity index 69% rename from src/RollbarDotNet/Builder/ServerBuilder.cs rename to RollbarDotNet/Builder/ServerBuilder.cs index b8be74e..ff4cda4 100644 --- a/src/RollbarDotNet/Builder/ServerBuilder.cs +++ b/RollbarDotNet/Builder/ServerBuilder.cs @@ -14,20 +14,20 @@ public ServerBuilder( IEnvironment environment, IHostingEnvironment hostingEnvironment) { - this.Environment = environment; - this.HostingEnvironment = hostingEnvironment; + Environment = environment; + HostingEnvironment = hostingEnvironment; } public void Execute(Payload payload) { payload.Data.Server = new Server(); - this.BuildServer(payload.Data.Server); + BuildServer(payload.Data.Server); } private void BuildServer(Server server) { - server.Host = this.Environment.MachineName; - server.Root = this.HostingEnvironment.WebRootPath; + server.Host = Environment.MachineName; + server.Root = HostingEnvironment.WebRootPath; } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Configuration/BlacklistConfiguration.cs b/RollbarDotNet/Configuration/BlacklistConfiguration.cs similarity index 100% rename from src/RollbarDotNet/Configuration/BlacklistConfiguration.cs rename to RollbarDotNet/Configuration/BlacklistConfiguration.cs diff --git a/src/RollbarDotNet/Configuration/Configuration.cs b/RollbarDotNet/Configuration/Configuration.cs similarity index 100% rename from src/RollbarDotNet/Configuration/Configuration.cs rename to RollbarDotNet/Configuration/Configuration.cs diff --git a/src/RollbarDotNet/Configuration/RollbarOptions.cs b/RollbarDotNet/Configuration/RollbarOptions.cs similarity index 100% rename from src/RollbarDotNet/Configuration/RollbarOptions.cs rename to RollbarDotNet/Configuration/RollbarOptions.cs diff --git a/src/RollbarDotNet/Core/ExceptionHandlerExtensions.cs b/RollbarDotNet/Core/ExceptionHandlerExtensions.cs similarity index 100% rename from src/RollbarDotNet/Core/ExceptionHandlerExtensions.cs rename to RollbarDotNet/Core/ExceptionHandlerExtensions.cs diff --git a/src/RollbarDotNet/Core/ExceptionHandlerMiddleware.cs b/RollbarDotNet/Core/ExceptionHandlerMiddleware.cs similarity index 93% rename from src/RollbarDotNet/Core/ExceptionHandlerMiddleware.cs rename to RollbarDotNet/Core/ExceptionHandlerMiddleware.cs index 5f46d78..045168c 100644 --- a/src/RollbarDotNet/Core/ExceptionHandlerMiddleware.cs +++ b/RollbarDotNet/Core/ExceptionHandlerMiddleware.cs @@ -11,14 +11,14 @@ public class ExceptionHandlerMiddleware public ExceptionHandlerMiddleware( RequestDelegate next) { - this.Next = next; + Next = next; } public async Task Invoke(HttpContext context, Rollbar rollbar) { try { - await this.Next(context); + await Next(context); } catch (Exception exception) { diff --git a/src/RollbarDotNet/Core/IRollbarResponseFeature.cs b/RollbarDotNet/Core/IRollbarResponseFeature.cs similarity index 100% rename from src/RollbarDotNet/Core/IRollbarResponseFeature.cs rename to RollbarDotNet/Core/IRollbarResponseFeature.cs diff --git a/src/RollbarDotNet/Core/RollbarResponseFeature.cs b/RollbarDotNet/Core/RollbarResponseFeature.cs similarity index 100% rename from src/RollbarDotNet/Core/RollbarResponseFeature.cs rename to RollbarDotNet/Core/RollbarResponseFeature.cs diff --git a/src/RollbarDotNet/Core/ServiceExtensions.cs b/RollbarDotNet/Core/ServiceExtensions.cs similarity index 87% rename from src/RollbarDotNet/Core/ServiceExtensions.cs rename to RollbarDotNet/Core/ServiceExtensions.cs index 4912dd7..c36ef94 100644 --- a/src/RollbarDotNet/Core/ServiceExtensions.cs +++ b/RollbarDotNet/Core/ServiceExtensions.cs @@ -12,6 +12,7 @@ public static class ServiceExtensions public static IServiceCollection AddRollbar(this IServiceCollection services) { return services + .AddHttpClient() .AddSingleton() .AddSingleton() .AddSingleton() @@ -21,7 +22,7 @@ public static IServiceCollection AddRollbar(this IServiceCollection services) .AddSingleton() .AddSingleton() .AddSingleton() - .AddScoped(); + .AddSingleton(); } public static IServiceCollection AddRollbarWeb(this IServiceCollection services) @@ -29,8 +30,8 @@ public static IServiceCollection AddRollbarWeb(this IServiceCollection services) services.TryAddSingleton(); return services.AddRollbar() .AddSingleton() - .AddScoped() - .AddScoped(); + .AddSingleton() + .AddSingleton(); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/IBlacklistCollection.cs b/RollbarDotNet/IBlacklistCollection.cs similarity index 100% rename from src/RollbarDotNet/IBlacklistCollection.cs rename to RollbarDotNet/IBlacklistCollection.cs diff --git a/src/RollbarDotNet/Logger/RollbarDotNetLogger.cs b/RollbarDotNet/Logger/RollbarDotNetLogger.cs similarity index 84% rename from src/RollbarDotNet/Logger/RollbarDotNetLogger.cs rename to RollbarDotNet/Logger/RollbarDotNetLogger.cs index c9f37ae..b85d986 100644 --- a/src/RollbarDotNet/Logger/RollbarDotNetLogger.cs +++ b/RollbarDotNet/Logger/RollbarDotNetLogger.cs @@ -10,23 +10,23 @@ public class RollbarDotNetLogger : ILogger public RollbarDotNetLogger(Rollbar rollbar) { - this.Rollbar = rollbar; + Rollbar = rollbar; } public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { - if(logLevel == LogLevel.None) + if (logLevel == LogLevel.None) return; var rollbarLogLevel = MapLogLevel(logLevel); if (exception != null) { - this.Rollbar.SendException(rollbarLogLevel, exception).Wait(); + Rollbar.SendException(rollbarLogLevel, exception, formatter(state, exception)).Wait(); return; } - this.Rollbar.SendMessage(rollbarLogLevel, formatter(state, null)).Wait(); + Rollbar.SendMessage(rollbarLogLevel, formatter(state, null)).Wait(); } public bool IsEnabled(LogLevel logLevel) @@ -41,7 +41,7 @@ public IDisposable BeginScope(TState state) private RollbarLevel MapLogLevel(LogLevel logLevel) { - switch(logLevel) + switch (logLevel) { case LogLevel.Debug: return RollbarLevel.Debug; diff --git a/src/RollbarDotNet/Logger/RollbarDotNetLoggerExtensions.cs b/RollbarDotNet/Logger/RollbarDotNetLoggerExtensions.cs similarity index 100% rename from src/RollbarDotNet/Logger/RollbarDotNetLoggerExtensions.cs rename to RollbarDotNet/Logger/RollbarDotNetLoggerExtensions.cs diff --git a/src/RollbarDotNet/Logger/RollbarDotNetLoggerProvider.cs b/RollbarDotNet/Logger/RollbarDotNetLoggerProvider.cs similarity index 60% rename from src/RollbarDotNet/Logger/RollbarDotNetLoggerProvider.cs rename to RollbarDotNet/Logger/RollbarDotNetLoggerProvider.cs index beb443b..bfd9830 100644 --- a/src/RollbarDotNet/Logger/RollbarDotNetLoggerProvider.cs +++ b/RollbarDotNet/Logger/RollbarDotNetLoggerProvider.cs @@ -2,10 +2,8 @@ { using System; using System.Collections.Concurrent; - using Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; public class RollbarDotNetLoggerProvider : ILoggerProvider { @@ -15,19 +13,19 @@ public class RollbarDotNetLoggerProvider : ILoggerProvider public RollbarDotNetLoggerProvider(IServiceProvider serviceProvider) { - this.Loggers = new ConcurrentDictionary(); - this.ServiceProvider = serviceProvider; + Loggers = new ConcurrentDictionary(); + ServiceProvider = serviceProvider; } public void Dispose() { - this.Loggers.Clear(); + Loggers.Clear(); } public ILogger CreateLogger(string categoryName) { - var rollbar = this.ServiceProvider.GetRequiredService(); - return this.Loggers.GetOrAdd(categoryName, name => new RollbarDotNetLogger(rollbar)); + var rollbar = ServiceProvider.GetRequiredService(); + return Loggers.GetOrAdd(categoryName, name => new RollbarDotNetLogger(rollbar)); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Payloads/Body.cs b/RollbarDotNet/Payloads/Body.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Body.cs rename to RollbarDotNet/Payloads/Body.cs diff --git a/src/RollbarDotNet/Payloads/Client.cs b/RollbarDotNet/Payloads/Client.cs similarity index 68% rename from src/RollbarDotNet/Payloads/Client.cs rename to RollbarDotNet/Payloads/Client.cs index 55b5c56..e5c6164 100644 --- a/src/RollbarDotNet/Payloads/Client.cs +++ b/RollbarDotNet/Payloads/Client.cs @@ -7,11 +7,11 @@ public class Client { [JsonProperty("keys")] - private Dictionary Keys { get; set; } + public Dictionary Keys { get; set; } public Client() { - this.Keys = new Dictionary(); + Keys = new Dictionary(); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Payloads/CrashReport.cs b/RollbarDotNet/Payloads/CrashReport.cs similarity index 100% rename from src/RollbarDotNet/Payloads/CrashReport.cs rename to RollbarDotNet/Payloads/CrashReport.cs diff --git a/src/RollbarDotNet/Payloads/Data.cs b/RollbarDotNet/Payloads/Data.cs similarity index 97% rename from src/RollbarDotNet/Payloads/Data.cs rename to RollbarDotNet/Payloads/Data.cs index b372afe..6dcdabc 100644 --- a/src/RollbarDotNet/Payloads/Data.cs +++ b/RollbarDotNet/Payloads/Data.cs @@ -62,7 +62,7 @@ public class Data public Data() { - this.Body = new Body(); + Body = new Body(); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Payloads/Exception.cs b/RollbarDotNet/Payloads/Exception.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Exception.cs rename to RollbarDotNet/Payloads/Exception.cs diff --git a/src/RollbarDotNet/Payloads/Frame.cs b/RollbarDotNet/Payloads/Frame.cs similarity index 90% rename from src/RollbarDotNet/Payloads/Frame.cs rename to RollbarDotNet/Payloads/Frame.cs index 284cd3a..1ef4257 100644 --- a/src/RollbarDotNet/Payloads/Frame.cs +++ b/RollbarDotNet/Payloads/Frame.cs @@ -38,8 +38,8 @@ public class Frame public Frame() { - this.Context = new TraceContext(); - this.Locals = new Dictionary(); + Context = new TraceContext(); + Locals = new Dictionary(); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Payloads/JsonHttpContentSerializer.cs b/RollbarDotNet/Payloads/JsonHttpContentSerializer.cs similarity index 77% rename from src/RollbarDotNet/Payloads/JsonHttpContentSerializer.cs rename to RollbarDotNet/Payloads/JsonHttpContentSerializer.cs index 8713bc0..993b88b 100644 --- a/src/RollbarDotNet/Payloads/JsonHttpContentSerializer.cs +++ b/RollbarDotNet/Payloads/JsonHttpContentSerializer.cs @@ -12,17 +12,17 @@ public class JsonHttpContentSerializer : HttpContent public JsonHttpContentSerializer(string json) { - this.Payload = Encoding.UTF8.GetBytes(json); + Payload = Encoding.UTF8.GetBytes(json); } protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { - await stream.WriteAsync(this.Payload, 0, this.Payload.Length); + await stream.WriteAsync(Payload, 0, Payload.Length); } protected override bool TryComputeLength(out long length) { - length = this.Payload.Length; + length = Payload.Length; return true; } } diff --git a/src/RollbarDotNet/Payloads/Message.cs b/RollbarDotNet/Payloads/Message.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Message.cs rename to RollbarDotNet/Payloads/Message.cs diff --git a/src/RollbarDotNet/Payloads/Notifier.cs b/RollbarDotNet/Payloads/Notifier.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Notifier.cs rename to RollbarDotNet/Payloads/Notifier.cs diff --git a/src/RollbarDotNet/Payloads/Payload.cs b/RollbarDotNet/Payloads/Payload.cs similarity index 90% rename from src/RollbarDotNet/Payloads/Payload.cs rename to RollbarDotNet/Payloads/Payload.cs index 992690d..a85e151 100644 --- a/src/RollbarDotNet/Payloads/Payload.cs +++ b/RollbarDotNet/Payloads/Payload.cs @@ -13,7 +13,7 @@ public class Payload public Payload() { - this.Data = new Data(); + Data = new Data(); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Payloads/Person.cs b/RollbarDotNet/Payloads/Person.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Person.cs rename to RollbarDotNet/Payloads/Person.cs diff --git a/src/RollbarDotNet/Payloads/Request.cs b/RollbarDotNet/Payloads/Request.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Request.cs rename to RollbarDotNet/Payloads/Request.cs diff --git a/src/RollbarDotNet/Payloads/Response.cs b/RollbarDotNet/Payloads/Response.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Response.cs rename to RollbarDotNet/Payloads/Response.cs diff --git a/src/RollbarDotNet/Payloads/Result.cs b/RollbarDotNet/Payloads/Result.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Result.cs rename to RollbarDotNet/Payloads/Result.cs diff --git a/src/RollbarDotNet/Payloads/Server.cs b/RollbarDotNet/Payloads/Server.cs similarity index 100% rename from src/RollbarDotNet/Payloads/Server.cs rename to RollbarDotNet/Payloads/Server.cs diff --git a/src/RollbarDotNet/Payloads/Trace.cs b/RollbarDotNet/Payloads/Trace.cs similarity index 81% rename from src/RollbarDotNet/Payloads/Trace.cs rename to RollbarDotNet/Payloads/Trace.cs index 00423e8..58efe26 100644 --- a/src/RollbarDotNet/Payloads/Trace.cs +++ b/RollbarDotNet/Payloads/Trace.cs @@ -14,8 +14,8 @@ public class Trace public Trace() { - this.Frames = new List(); - this.Exception = new Exception(); + Frames = new List(); + Exception = new Exception(); } } } \ No newline at end of file diff --git a/src/RollbarDotNet/Payloads/TraceContext.cs b/RollbarDotNet/Payloads/TraceContext.cs similarity index 100% rename from src/RollbarDotNet/Payloads/TraceContext.cs rename to RollbarDotNet/Payloads/TraceContext.cs diff --git a/src/RollbarDotNet/Properties/AssemblyInfo.cs b/RollbarDotNet/Properties/AssemblyInfo.cs similarity index 100% rename from src/RollbarDotNet/Properties/AssemblyInfo.cs rename to RollbarDotNet/Properties/AssemblyInfo.cs diff --git a/RollbarDotNet/Rollbar.cs b/RollbarDotNet/Rollbar.cs new file mode 100644 index 0000000..40bc6ab --- /dev/null +++ b/RollbarDotNet/Rollbar.cs @@ -0,0 +1,95 @@ +namespace RollbarDotNet +{ + using System.Collections.Generic; + using System.Threading.Tasks; + using Builder; + using DotNext.Runtime.Caching; + using Payloads; + using Exception = System.Exception; + +#nullable enable + + public class Rollbar + { + protected IEnumerable Builders { get; } + + protected IEnumerable ExceptionBuilders { get; } + + protected RollbarClient RollbarClient { get; } + + protected ConcurrentCache SentExceptions { get; } = new ConcurrentCache(100, CacheEvictionPolicy.LRU); + + public Rollbar(IEnumerable builders, + IEnumerable exceptionBuilders, + RollbarClient rollbarClient) + { + Builders = builders; + ExceptionBuilders = exceptionBuilders; + RollbarClient = rollbarClient; + } + + public virtual Task SendException(Exception exception) => SendException(exception, null); + + public virtual async Task SendException(Exception exception, string? message) + { + return await SendException(RollbarLevel.Error, exception, message); + } + + public virtual Task SendException(RollbarLevel level, Exception exception) => SendException(level, exception, null); + + public virtual async Task SendException(RollbarLevel level, Exception exception, string? message) + { + if (SentExceptions.TryGetValue(exception, out var cached)) + { + return cached; + } + + var payload = SetupPayload(level); + foreach (var exceptionBuilder in ExceptionBuilders) + { + exceptionBuilder.Execute(payload, exception); + } + + payload.Data.Title = message; + var response = await RollbarClient.Send(payload); + SentExceptions[exception] = response; + return response; + } + + public virtual async Task SendMessage(string message) + { + return await SendMessage(RollbarLevel.Info, message); + } + + public virtual async Task SendMessage(RollbarLevel level, string message) + { + var payload = SetupPayload(level); + payload.Data.Body.Message = new Message + { + Body = message + }; + return await RollbarClient.Send(payload); + } + + protected Payload SetupPayload(RollbarLevel level) + { + var payload = new Payload(); + payload.Data.Level = LevelToString(level); + ExecuteBuilders(payload); + return payload; + } + + protected void ExecuteBuilders(Payload payload) + { + foreach (var builder in Builders) + { + builder.Execute(payload); + } + } + + protected static string LevelToString(RollbarLevel level) + { + return level.ToString().ToLower(); + } + } +} diff --git a/src/RollbarDotNet/RollbarClient.cs b/RollbarDotNet/RollbarClient.cs similarity index 67% rename from src/RollbarDotNet/RollbarClient.cs rename to RollbarDotNet/RollbarClient.cs index 33b504a..108238b 100644 --- a/src/RollbarDotNet/RollbarClient.cs +++ b/RollbarDotNet/RollbarClient.cs @@ -17,15 +17,18 @@ public class RollbarClient protected Uri RollbarUri => new Uri("https://api.rollbar.com/api/1/item/"); - public RollbarClient(IOptions rollbarOptions) + protected IHttpClientFactory HttpClientFactory { get; } + + public RollbarClient(IOptions rollbarOptions, IHttpClientFactory httpClientFactory) { - this.Configuration = new Configuration.Configuration(); - this.RollbarOptions = rollbarOptions.Value; + Configuration = new Configuration.Configuration(); + RollbarOptions = rollbarOptions.Value; + HttpClientFactory = httpClientFactory; } - public async Task Send(Payload payload) + public virtual async Task Send(Payload payload) { - if (this.RollbarOptions.Disabled) + if (RollbarOptions.Disabled) { return new Response { @@ -36,12 +39,12 @@ public async Task Send(Payload payload) }; } - var json = this.Serialize(payload); - using (var httpClient = new HttpClient()) + var json = Serialize(payload); + using (var httpClient = HttpClientFactory.CreateClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - var response = await httpClient.PostAsync(this.RollbarUri, new JsonHttpContentSerializer(json)); + var response = await httpClient.PostAsync(RollbarUri, new JsonHttpContentSerializer(json)); if (!response.IsSuccessStatusCode) { throw new HttpRequestException(response.ToString()); @@ -54,7 +57,7 @@ public async Task Send(Payload payload) protected string Serialize(Payload payload) { - return JsonConvert.SerializeObject(payload, this.Configuration.JsonSettings); + return JsonConvert.SerializeObject(payload, Configuration.JsonSettings); } } } \ No newline at end of file diff --git a/RollbarDotNet/RollbarDotNet.csproj b/RollbarDotNet/RollbarDotNet.csproj new file mode 100644 index 0000000..eb88365 --- /dev/null +++ b/RollbarDotNet/RollbarDotNet.csproj @@ -0,0 +1,38 @@ + + + + Rollbar Integration for .NET Core + William Roush 2016-2020 + RollbarDotNet + 0.8.0 + William Roush + RollbarDotNet + RollbarDotNet + Rollbar;dotnet;Core;Error + https://github.com/RoushTech/RollbarDotNet + MIT + false + false + false + net7.0 + enable + + + + + + + + + + + + + + + + + + + + diff --git a/src/RollbarDotNet/RollbarLevel.cs b/RollbarDotNet/RollbarLevel.cs similarity index 100% rename from src/RollbarDotNet/RollbarLevel.cs rename to RollbarDotNet/RollbarLevel.cs diff --git a/src/RollbarDotNet/Rollbar.cs b/src/RollbarDotNet/Rollbar.cs deleted file mode 100644 index 68d2cf4..0000000 --- a/src/RollbarDotNet/Rollbar.cs +++ /dev/null @@ -1,77 +0,0 @@ -namespace RollbarDotNet -{ - using System.Collections.Generic; - using System.Threading.Tasks; - using Builder; - using Payloads; - using Exception = System.Exception; - - public class Rollbar - { - protected IEnumerable Builders { get; } - - protected IEnumerable ExceptionBuilders { get; } - - protected RollbarClient RollbarClient { get; } - - public Rollbar(IEnumerable builders, - IEnumerable exceptionBuilders, - RollbarClient rollbarClient) - { - this.Builders = builders; - this.ExceptionBuilders = exceptionBuilders; - this.RollbarClient = rollbarClient; - } - - - public virtual async Task SendException(Exception exception) - { - return await this.SendException(RollbarLevel.Error, exception); - } - - public virtual async Task SendException(RollbarLevel level, Exception exception) - { - var payload = this.SetupPayload(level); - foreach (var exceptionBuilder in this.ExceptionBuilders) - { - exceptionBuilder.Execute(payload, exception); - } - - return await this.RollbarClient.Send(payload); - } - - public virtual async Task SendMessage(string message) - { - return await this.SendMessage(RollbarLevel.Info, message); - } - - public virtual async Task SendMessage(RollbarLevel level, string message) - { - var payload = this.SetupPayload(level); - payload.Data.Body.Message = new Message(); - payload.Data.Body.Message.Body = message; - return await this.RollbarClient.Send(payload); - } - - protected Payload SetupPayload(RollbarLevel level) - { - var payload = new Payload(); - payload.Data.Level = this.LevelToString(level); - this.ExecuteBuilders(payload); - return payload; - } - - protected void ExecuteBuilders(Payload payload) - { - foreach (var builder in this.Builders) - { - builder.Execute(payload); - } - } - - protected string LevelToString(RollbarLevel level) - { - return level.ToString().ToLower(); - } - } -} \ No newline at end of file diff --git a/src/RollbarDotNet/RollbarDotNet.csproj b/src/RollbarDotNet/RollbarDotNet.csproj deleted file mode 100644 index 4f9e499..0000000 --- a/src/RollbarDotNet/RollbarDotNet.csproj +++ /dev/null @@ -1,53 +0,0 @@ - - - - Rollbar Integration for .NET Core - William Roush 2016-2018 - RollbarDotNet - 0.7.0 - William Roush - RollbarDotNet - RollbarDotNet - Rollbar;dotnet;Core;Error - https://github.com/RoushTech/RollbarDotNet - https://github.com/RoushTech/RollbarDotNet/blob/master/LICENSE.txt - false - false - false - netstandard1.5;netstandard2.0 - - - - - - - - - - - - - $(DefineConstants);NETSTANDARD2 - - - - - - - - - - - - - - - - - - - - - - -