Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 days ago.
The community is reviewing whether to reopen this question as of 3 days ago.
Improve this question
I went through the following tutorial to add AppInsights into a C# project
https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net
Using the manual method. All worked as expected.
I now want to add this same feature into a .Net Framework Class Library.
Following that tutorial I can't carry out steps 5 and 6 because they are explicitly used in an MVC project.
How could I add or what is the equivalent code for steps 5 and 6 from that link to add the same code into a .Net Framework Class Library?
Edit 1
So after implementing the manual method in an MVC app all looks good.
In my Class Library in the constructor i have added similar code as below
private TelemetryClient _telClient;
public class SomeClass(TelemetryClient telClient)
{
_telClient = new TelemetryClient();
}
public void SomeMethod()
{
_telClient.TrackException(new Exception("Hello World");
}
In my MVC app i have the below code
if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
{
//If customError is Off, then AI HTTPModule will report the exception
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
var ai = new TelemetryClient();
ai.TrackException(filterContext.Exception);
SomeClass sc = new SomeClass(ai);
}
}
For a .Net Framework Class library you should only expect a TelemetryClient (or a TelemetryConfiguration so you can create a TelemetryClient) to be passed to the constructor using a constructor argument or dependency injection.
Typically the reading the ApplicationInsights.config file and constructing a client is done by the code that calls your class library. You shouldn't do that in the class library itself.
Then, in your class library you can manually call the methods of the TelemetryClient like TrackEvent(..), TrackException(...), TrackDependency(...) etc.
Steps 5 and 6 take care of tracking unhandled exceptions on a controller level. You cannot do that in a class library unless you want to provide an exception handler to the calling code.
So, unless you want to manually send telemetry from within your class library you shouldn't bothered about Application Insights at all in your class library.
Related
This question already has answers here:
How to do integration testing for .NET 6 Web Api projects using WebApplicationFactory?
(1 answer)
Integration test and hosting ASP.NET Core 6.0 without Startup class
(1 answer)
Integration test for ASP.NET Core 6 web API throws System.InvalidOperationException
(2 answers)
How to use WebApplicationFactory in .net6 (without speakable entry point)
(3 answers)
Closed 1 year ago.
I need to write some unit tests for an ASP.Net 6 API and need to create a test server to verify authorization. However since the startup class has been removed, I don't know what I should use as the entry point for the test server creation.
This was the way of creating one in previous versions.
var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
The issue ended up being that by default Program.cs isn't discoverable, so I ended up adding this to the ASP.Net .csproj file.
<ItemGroup>
<InternalsVisibleToInclude="{Insert testing project name here}" />
</ItemGroup>
And adding
public partial class Program { }
To the bottom of the Program.cs file
You can use WebApplicationFactory (which, based on docs, is a wrapper around TestServer and exposes properties and methods to create and get it like CreateServer and Server) for your integration tests. To set up it with the new minimal hosting model you need to make you web project internals visible to the test one for example by adding next property to csproj:
<ItemGroup>
<InternalsVisibleTo Include ="YourTestProjectName"/>
</ItemGroup>
And then you can inherit your WebApplicationFactory from the generated Program class for the web app:
class MyWebApplication : WebApplicationFactory<Program>
{
protected override IHost CreateHost(IHostBuilder builder)
{
// shared extra set up goes here
return base.CreateHost(builder);
}
}
And then in the test:
var application = new MyTestApplication();
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");
Or use WebApplicationFactory<Program> from the test directly:
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder .ConfigureServices(services =>
{
// set up servises
});
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");
Code examples from migration guide.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Am just wondering how to solve this. I need to automate my company website. There I need to navigate more than one url for a multiple web pages. I have designed Hybrid framework along with Page object Model Design.
My Requirement is,
say I have 3 url's :
www.google.com
www.yahoo.com
Facebook
All the above url and its test data I will keep in an Excel sheet. I have created three different pages and three different test classes.
So my list of questions are:
How to pass url's one by one to [setup] method
how to call the test method deepening upon the url type
Execution Flow need to implement of Application:
You need to parametrize your test with TestCase attribute.
[TestCase("www.google.com")]
[TestCase("www.yahoo.com")]
[TestCase("www.facebook.com")]
public void WebPageTest(string site)
{
driver.Url(site);
//continue with the test.
}
See this article to learn more: https://github.com/nunit/docs/wiki/TestCase-Attribute
Storing URL in excel is not good idea,
You may store URL in app.config file and by using ConfigManager utility you may retrieve those URL from app.config file
As according to your test cases you can use URL where its needed and required
I would suggest you to use [category] attribute to categorise your test cases. For example
[Test]
[Category("GoogleTest")]
public void googletest1()
{
}
[Test]
[Category("FBTest")]
public void fbtest1()
{
}
Now in the [SetUp] method you can load url based on the category, something like
[SetUp]
public void testsetup()
{
#initialise driver
var category = TestContext.CurrentContext.Test.Properties.Keys;
if(category.Contains("GoogleTest"))
{
//category1 setup
}
else if(category.Contains("FBTest"))
{
//category2 setup
}
}
So using this method you can solve query # 2, i.e the url related to the test is already loaded for you, so you can continue with your tests after setup
I have an API written in Asp Net Core 2.1 (upgraded from 2.0) which build an entity from a DTO sent by a mobile app.
The DTO have a field "mobileId" (Guid format) to prevent the mobile to send the same object when it goes online (after connectivity issues for example).
But this solution does not seem to be efficient as presented below :
There are 4 lines whereas I actually wanted only 1 line :S I don't understand how it occurred because I specified in the Startup:
services.AddScoped<DbContext>(s =>
{
// code emitted for brevity
});
The code of the API itself is centralized in a Handler because our API follow a little piece of CQRS pattern and the "Dispatcher" is registered via Autofac :
public class DispatcherModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<Dispatcher>()
.As<IDispatcher>()
.InstancePerDependency();
}
}
The same applies for IUnitOfWork which use our scoped DbContext internally
At the beginning I check that an entity with the same 'mobileId' is not already present in database :
if (dto.MobileId != null)
{
Report existingMobileId = await UnitOfWork.Repository<Report>()
.GetFirstOrDefaultAsync(qr => qr.MobileId == dto.MobileId);
if (existingMobileId != null)
{
return new Result<object>(new Error(400, $"Report with '{dto.MobileId}' already exists in DB."));
}
}
What do you think I'm doing wrong ? Or maybe I should add something else ?
Thank you for your help guyz :)
Technical environment :
- ASP.NET Core 2.1
- Entity Framework Core
- Azure SQL Database
AddScoped means that new instance of service is created for each request, so, if you have several simultaneous requests, you may have some kind of race condition on repository level when each checks presence of a row before writing it to db. I would recommend putting this responsibility on the database level applying Unique constraint on mobileId column.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In my account controller I have something like this:
var result = await UserManager.CreateAsync(user, model.Password);
foreach (var error in result.Errors)
{
modelstateErrors.Add(error);
}
Every error string is localized in English language
What's the best practice in localizing ASP.NET Identity error messages?
Are there any libraries with localized errors, and how are they implemented?
Would it be good idea to switch on every ASP.NET Identity error and return your own localized string?
To localize ASP.Net Identity you need to install one of the following Nuget packages from the Nuget store => https://www.nuget.org/packages?q=Microsoft.AspNet.Identity.Core
You install the package that belong to your culture. So for French culture you should install Microsoft.AspNet.Identity.Core.fr
They all follow the pattern Microsoft.AspNet.Identity.Core.[Culture] where [Culture] is the code fo the culture.
Create e base controller and extend every controller from it
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
// verify which kind of exception it is and do somethig like logging
}
}
It is one of the best practice por handlling errors, but for the localizing itself do what #codeNotFound said.
I have an ASP.NET MVC application using StructureMap.
I have created a service called SecurityContext which has a static Current property. A simplified version looks like this:
public class SecurityContext : ISecurityContext
{
public bool MyProperty { get; private set; }
public static SecurityContext Current
{
get
{
return new SecurityContext() { MyProperty = true };
}
}
}
I've hooked this up in my StructureMap registry as follows:
For<ISecurityContext>().Use(() => SecurityContext.Current);
My understanding of this Linq expression overload of the Use method is that the returned concrete object is the same for the entire HTTP request scope.
However, I've set up a test case where my context interface is injected in two places, once in the controller's constructor and again using the SetterProperty attribute in the base class my view inherits from.
When debugging I observe the Current static method being hit twice so clearly my assumptions are wrong. Can anyone correct what I'm doing here? The reason I want this request-scoped is because I'm loading certain data into my context class from the database so I don't want this to happen multiple times for a given page load.
Thanks in advance.
The default lifecycle for a configuration is Transient, thus each request for an ISecurityContext will create a new instance of SecurityContext. What I think you want is to use the legacy HttpContext lifecycle.
Include the StructureMap.Web nuget package. Then change your configuration to the following:
For<ISecurityContext>()
.Use(() => SecurityContext.Current)
.LifeCycleIs<HttpContextLifecycle>();
More information on lifecyles can be found here.
The HttpContextLifecycle is obsolete, however I do not know if or when it will be removed. The StructureMap team does recommend against using this older ASP.Net lifecycle. They state in the documentation that most modern web frameworks use a nested container per request to accomplish the same scoping. Information about nested containers can be found here.
I don't know if the version of ASP.Net MVC you are using is considered a modern web framework. I doubt it is because ASP.Net Core 1.0 is the really the first in the ASP.Net line to fully embrace the use of DI. However, I will defer to #jeremydmiller on this one.