Application Insights - Unit testing, Azure - c#

I have a MVC project which uses the application insight and it is working fine and it is capturing all the telemetric details in azure under the proper dashboard.
I am trying to test this functionality through the unit test project, from the unit test project i am calling the class file which is present in the MVC project.,
It is working and executing the the Funciton1() but these values are not diaplaying under the dashboard...
Any suggestions..
Application 1 -> Testproject C# Class project
[TestMethod]
Method1()
{
MVCAppinsightCls a = new MVCAppinsightCls();
a.Function1();
}
MVC WebApplication
Class MVCAppinsightCls
{
Funciton1()
{
TelemetryClient o = new TelemetryClient();
o.trackEvent("someName");
}
}

When you run the method like this from your Test project, then your Test project is your host so what you need is to add all the configurations related to your App Insights in your Test Peoject too (Instumentation Key settings and all other stuff) so that it sends the logs to App Insights.
You need the ApplicationInsights.config file and also you need to add the nuget packages related to App Insights to your Unit Test project.

Related

Core WCF - Visual Studio for Mac Proxy Settings

Running Visual Studio for Mac 17.4.2 (build 17)
I have a unit test that uses core WCF to call a web service at: https://www.dataaccess.com/webservicesserver/NumberConversion.wso
This works fine when I run the test if I have the ProxyMan app running. However, without ProxyMan I get a timeout after one minute.
In order to generate the wcf proxy class, I ran the following against my unit test project:
dotnet tool install --global dotnet-svcutil
dotnet-svcutil --roll-forward LatestMajor https://www.dataaccess.com/webservicesserver/NumberConversion.wso?WSDL
This generated a large reference.cs file - which I've copied here
My unit test that calls into this can be seen below:
[Fact]
public async Task CanConvertNumber()
{
var client = new NumberConversionSoapTypeClient(NumberConversionSoapTypeClient.EndpointConfiguration.NumberConversionSoap,
"https://www.dataaccess.com/webservicesserver/NumberConversion.wso");
var response = await client.NumberToWordsAsync(46);
Trace.WriteLine($"The response is: {response.Body.NumberToWordsResult}");
response.Body.Should().Equals("Forty Six");
}
I have now created a simple console app to reproduce what I have in the unit test. The code for this can be found at: https://github.com/RobBowman/core-wcf-client
Any ideas why it could be dependent on proxyman? It seems as if core wcf code is routing to localhost for some reason.
Thanks,
Rob.

Does NltkNet the NLTK wrapper class support .NET core web applications or only console applications?

When I try to Initialize the NltkNet object in my dotnet core web application I receive an error saying an assembly is not found or has a different manifest definition than its assembly reference.
The code is fairly simple, it does nothing at all except initialize an NltkNet object when a button is clicked.
public IActionResult Upload()
{
Nltk.Init(new List<string>()
{
#"C:\IronPython27\Lib",
#"C:\IronPython27\Lib\site-packages",
});
return View();
}
I was able to get the exact same code to work in my console application without issue.
Is this a configuration issue on my end or is ASP.NET core MVC web application support not available for NltkNet?
I have discovered that NltkNet does not support dotnet core.

ASP.NET Core 3.1 Host Sub application within main application

Let's say the main web app is: https:\mywebapp.com
Let's say I have separate Web API project and it has multiple services (api\service1, api\service2, )
For this I created 2 projects
ASP.NET Core MVC Project for Main App - https:\mywebapp.com
ASP.NET Core Web API project (Service 1, Service 2)
How should I set up my project and publish profile in Azure so that I have the following
Main App (https:\mywebapp.com) - This is good I have publish profile and this gets published correctly in Azure
Service 1 URL (https:\mywebapp.com\api\service1)
Service 2 URL (https:\mywebapp.com\api\service2)
How do I achieve pt 2 and pt3 and have my web API project as a sub-app in my main web application? and share the same URL\api ?
You could create virtual directory on same azure web app.
When you first create Core MVC Project in azure webapp, go to Configuration > Path mappings and config the Virtual directory site/api.
When we publish the Core api to the Azure, we need to include the virtual directory path in the Site Name and Destination URL sections on the Connection tab.
Because Core 3.1 web api consists of one or more controller classes that derive from ControllerBase. The web API project template provides a starter controller:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
So, we can visit it just with controllerName. And as it is sub directory, so the Url path is api\controllerName. Here is output:

Testing a Windows 8 Store App with NUnit

I'm currently working on a Windows Store Application (Windows 8) for a class and I'm having problems getting my NUnit tests to run.
My Solution/Project setup looks like the following:
TheMetroApp.sln
SQLite-net.csproj - Class Library (Windows Store Apps). Files are pulled from NuGet.
DataModel.csproj - Class Library (Windows Store Apps)
UnitTests.csproj - Unit Test Library (Windows Store Apps). NUnit framework is pulled from NuGet.
TheMetroApp.csproj - A project file which was pulled from one of the Windows SDK examples.
Misc. Dependencies and Utilities
Windows 8 Pro RTM/Visual Studio 2012 RTM
ReSharper 7
NUnit 2.6.1
SQLite (Set up per the instructions here)
UnitTests is dependent upon and references DataModel. DataModel is dependent upon and references SQLite-net. The only thing I have added to the UnitTests project is a single class containing some stub NUnit unit tests. As far as I can tell, these are set up correctly:
[TestFixture]
public class TaskSourceTests
{
#region Private Class Members
private ITaskSource _taskSource;
private String _dbPath;
#endregion
#region Testing Infrastructure
[SetUp]
public void SetUp()
{
// This part makes NUnit/ReSharper have problems.
_dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "UnitTestDatabase.sqlite");
}
#endregion
#region Misc. CRUD stuff
[Test]
public void CreateTaskTest()
{
// Save the task.
Task task = new Task( "Some Task", "lol.", DateTime.Now, false );
_taskSource.Save( task );
// Confirm that it is in the task db.
using( SQLiteConnection db = new SQLiteConnection( _dbPath ) )
{
const String query = "SELECT * FROM Task WHERE Id = ?";
IList<Task> results = db.Query<Task>( query, task.Id );
Assert.True( results.Contains( task ) );
}
}
// ...and so on [but with stubs that are basically Assert.Fail( "" )].
#endregion
}
TheMetroApp is one of the Windows 8 SDK sample projects, but with some custom XAML forms thrown in. I'm not having any problems with this project.
My issue is that none of the Unit Test runners that I have tried to use are working.
When I try to use the official NUnit x86 Test runner (version 2.6.1), my tests fail due to certificate related issues (see here):
UnitTests.TaskSourceTests.CreateTaskTest:
SetUp : System.InvalidOperationException : The process has no package identity. (Exception from HRESULT: 0x80073D54)
ReSharper's NUnit test runner fails for the exact same reason. Unfortunately, it doesn't look like there is currently a workaround for that.
I have also tried using the test runner built into Visual Studio 2012 (through the NUnit Visual Studio Test Adapter). When I try to run my tests using "Run All", I get the following output:
------ Run test started ------
Updating the layout...
Checking whether required frameworks are installed...
Registering the application to run from layout...
Deployment complete. Full package name: "GibberishAndStuff"
No test is available in C:\Projects\project-name\ProjectName\UnitTests\bin\Debug\UnitTests.dll. Make sure that installed test discoverers & executors, platform & framework version settings are appropriate and try again.
========== Run test finished: 0 run (0:00:09.4873768) ==========
Something strange I have noticed is that if I select a specific test in the Test Explorer and tell it to run, I get a slightly different error message:
Could not find test executor with URI 'executor://nunittestexecutor/'. Make sure that the test executor is installed and supports .net runtime version 4.0.30319.18010.
This is kind of perplexing because I have the NUnit Test Adapter installed. I'm not seeing anything similar to my issue on the launchpad page for the test adapter.
I'm not really sure where I should proceed from here. If this doesn't work I don't mind reworking my project to use xUnit.net, Microsoft's unit testing framework or something else. It would be pretty awesome if I could get NUnit working though.
Thanks!
I have a Windows 7 Phone app which had the same issue that you have. My solution was to create a separate "linked" project which compiles the code using the standard .net libraries. The linked project will have no issues with unit test / NUnit.
See the following for more information:
http://msdn.microsoft.com/en-us/library/ff921109(v=pandp.40).aspx
http://visualstudiogallery.msdn.microsoft.com/5e730577-d11c-4f2e-8e2b-cbb87f76c044/
I've ported the app to Windows 8 and have no problems running my test cases.
I've just hit the same error message while creating unit tests for an Universal App (W81 + WP81). The only solution here was to stop using NUnit and use MSTest only.

Why can't i access the RoleEnvironment in Application_Start when using a RoleEntryPoint?

I have a Azure WebRole which I'm trying to configure logging for using the DiagnosticMonitor.
According to the documentation at windowsazure.com the logging should be implemented in OnStart:
Note: The code in the following steps is typically added to the OnStart method of the role.
https://www.windowsazure.com/en-us/develop/net/common-tasks/diagnostics/
In order to access the OnStart method I have to define a RoleEntryPoint. But once it is defined I can't access the RoleEnvironment in web applications Application_Start.
How can I make the RoleEnvironment available to the application while still being able to use the DiagnosticMonitor?
I store the applications connection-strings in the service configuration.
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
// config
var config = DiagnosticMonitor.GetDefaultInitialConfiguration();
LocalResource localResource = RoleEnvironment.GetLocalResource("MyCustomLogs");
DirectoryConfiguration dirConfig = new DirectoryConfiguration();
dirConfig.Container = "wad-mycustomlogs-container";
dirConfig.DirectoryQuotaInMB = localResource.MaximumSizeInMegabytes;
dirConfig.Path = localResource.RootPath;
DiagnosticMonitorConfiguration diagMonitorConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
diagMonitorConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
diagMonitorConfig.Directories.DataSources.Add(dirConfig);
DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config);
return base.OnStart();
}
I've solved it.
After cleaning my solution, rebuilding, restarting IIS, shutting down the azure emulators and restarting Visual Studio it suddenly started working.
I changed no code at all.
(I even did all of those things before posting as well but it only worked when I did it all at the same time)
This is defintely the right example set of code. You need to set all of this in the Role though NOT in your web application.
NOTE: since Azure now has full IIS the context is different between the RoleEntryPoint On_start and the Web application, which is running in it's own worker pool within IIS.
Just a quick sanity checklist:
The code you're writing is in your class that inherits from RoleEntryPoint (typically WebRole.cs NOT in the Global.asax)?
You're running the project in the Azure Emulator (not inadvertently starting a web project directly?)
If you're running the application in the Azure emulator or deployed to Azure itself RoleEnvironment is available from within your IIS application as long as you have the relevant DLLs reference. If you can build with RoleEnvironment.IsAvailable in your code, then the libraries are included. The only thing I can think is that you're running the web site directly, not within the Azure emulator.
Set the Cloud project to be your startup in Visual Studio and you should be golden.

Categories

Resources