How to control Adaptive Sampling in .NET Core application - azure

I'm trying to limit the amount of data sent to Application Insights in a .NET Core program. I'm attempting to follow the documention here which says I should use the UseAdaptiveSampling method. It has the rather cryptic instruction:
Use extension methods of TelemetryProcessorChainBuilder as shown below to customize sampling behavior.
However, it doesn't tell me where exactly this extension method lives. My code is as follows:
public AppInsightsStats(string appInsightsKey)
{
TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
configuration.InstrumentationKey = appInsightsKey;
telemetry = new TelemetryClient(configuration);
// Enable sampling since amount of logging is massive
var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5); // <-- Compiler error here
}
However, the code doesn't compile since UseAdaptiveSampling isn't found. I have the following using statements:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
The source code I can dig up that uses UseAdaptiveSampling all seems to be .NET Framework 4.5 code, so I'm wondering if this just isn't included with the .NET Core version. These instructions are for ASP.NET Core, but I'm wondering if they mean running that on the .NET Framework on Windows.

For console project, you should use this package Microsoft.ApplicationInsights.WorkerService. It's used for non-http application like console project.
I used your code with this package, everything is ok. Please give it a try, and let me know if you still have the issue.

Related

ASP.NET Core Application Insights adaptive sampling

TL;DR: Does ExcludedTypes in Microsoft.ApplicationInsights.AspNetCore SDK default to Exception and Trace?
I am running an ASP.NET Core 2.2 app with version 2.6.1 Microsoft.ApplicationInsights.AspNetCore SDK. I am reading: https://learn.microsoft.com/en-us/azure/azure-monitor/app/sampling#configuring-adaptive-sampling-for-aspnet-applications where they write that the default values for ExcludedTypes is Trace and Exception, which is just the way i like it, but I am wondering, since the default values is for ASP.NET (actually specified in the application insights config for the host), if these default values also apply for ASP.NET Core applications that doesnt have an application insights config file (all config is done through code).
I know that the SDK is open sourced, but I haven't been able to search through it and find the initial values: https://github.com/microsoft/ApplicationInsights-aspnetcore. Maybe I am just searching for the wrong things.
Update:
Yes, the default ExcludedTypes for asp.net core is Event. There'are 2 places mentionded that:
1.In this article, it says "In ASP.NET Core, exact same default behavior is enabled in code.":
2.In the source code, you can find it's defined here:
First, the default values for ExcludedTypes is not Trace and Exception, it is Event. There is a GitHub issue for that. And I also tested it myself, the default ExcludedType is Event indeed.
For asp.net core, the default ExcludedType should be same as asp.net, you can take a look at this section of the article you provided. I'll try to go through the code to find out what's in the code for asp.net core and will update you later.

Using an Objective C framework, which is inside a Swift framework, in a Xamarin iOS project

I have a Objective C framework. (This framework is working properly with a Swift project)
Then I have a Swift framework. This framework has used the previously mentioned Objective C framework. (This Swift framework also working in a Swift project)
Now I am trying to use that Swift framework inside a Xamarin iOS project.
I have created a Binding Library project in my Xamarin iOS project and under the Native Reference, I have added both those Swift framework and Objective C framework fat files.
I have updated the ApiDefinition file accordingly as well.
But when I run the application it launch in the phone and exit without giving any error. I'm glad if application crashed with an error. But it doesn't and I'm clueless now. Any thoughts?
Below is how I'm trying to access the methods in those frameworks inside my Xamarin iOS project
using BindingSwift;
// More codes here
public override void ViewDidLoad()
{
base.ViewDidLoad();
var myClass = new AroshaMathPerformer();
var result = myClass.DoTheMath;
Console.WriteLine("# Result = " + result);
}
But, if I add a breakpoint, it doesn't even hit at the run time before the application exits.
Assuming that everything you did is in the question, then it is expected not to work. Swift libraries are not officially supported on Xamarin.iOS. Some people made them work with these steps: https://medium.com/#Flash3001/binding-swift-libraries-xamarin-ios-ff32adbc7c76
In such a case, you can find the real reason by going to
Settings -> Privacy -> Analytics -> Analytics Data -> And find the log
file with your bundle ID and the crashed occur date/time.
The error show to me was related to #rpath/ but actually it solved after signing the bundle with a valid provisioning profile.
For those who are interesting, you can visit here to find out my experience of implementing this whole scenario mentioned in the title.

Azure Function gives error: System.Drawing is not supported on this platform

(If this question is poorly worded, could someone please help me clear it up?)
I have an Azure Function (2.0) which relies on some System.Drawing code. I've added a NuGet reference to System.Drawing.Common (4.5.0).
After publishing the app, however, when the function is called, it produces the error:
System.Private.CoreLib: Exception while executing function:
[MyFunctionName]. System.Drawing.Common: System.Drawing is not
supported on this platform.
As far as I'm aware, System.Drawing.Common is supported on .NET Core now, which I believe is the environment in which my Azure Function is running. The actual project is a .NET Standard 2.0 project, though.
I am confused as to how to resolve this. I've tried converting the project to a .NET Core 2.1 project but that led to bizarre errors related to "Metadata generation failed" and an inability to find System.Runtime.
My project references Microsoft.Azure.WebJobs.Extensions.EventGrid (2.0.0-beta2) if that's relevant.
It's not about the CLR, it's about the sandbox.
System.Drawing relies heavily on GDI/GDI+ to do its thing. Because of the somewhat risky nature of those APIs (large attack surface) they are restricted in the App Service sandbox.
Win32k.sys (User32/GDI32) Restrictions
For the sake of radical attack surface area reduction, the sandbox prevents almost all of the Win32k.sys APIs from being called, which practically means that most of User32/GDI32 system calls are blocked. For most applications this is not an issue since most Azure Web Apps do not require access to Windows UI functionality (they are web applications after all).
Try to find an different library that doesn't rely on System.Drawing/GDI, like ImageSharp.
A little update can help a lot of people.
Now you can switch your Azure Function to v3:
in Function app settings panel -> Runtime version ~3
With this setup, your code run in a sandbox that support Core 3, (you don't need to rebuild your dll to Core3, i run my .net core 2.1 dll without errors), and surprise... you don't get this exception anymore:
System.Drawing.Common: System.Drawing is not supported on this platform.
Because the CLI can found GDI/GDI+ that need in the subsystem.
Now i can convert html to pdf without go crazy.

Azure Function Structure

I'm trying to wrap my head around how we're supposed to build Azure functions.
I love the idea of building serverless, compact, single-function apps that respond to events.
Here are the problems I'm running into:
I have nice class libraries built in .NET Standard 2 that handle all my "backend needs" namely handling CRUD ops with Cosmos Db, Azure Table Storage, Azure SQL, Redis, Azure Storage. No matter what I did, I couldn't integrate these class libraries into an Azure Functions project. More details below.
Also, getting dependency injection in Azure Functions project has proven to be quite a task -- especially with my class libraries mentioned above.
At this point, the only option I'm seeing is to "copy and paste" code into a new Azure Functions project and use it without any DI.
This seems to go against "best practices". So what's the solution other than either to create monolithic code or wait till Azure Functions support .NET Core and DI.
I thought I could use my .NET Standard class libraries from a regular Azure Functions project targeting .NET Framework. After all, the idea of .NET Standard is to "standardize" things. I opened a couple of posts here on SO. I'm providing the links so that you can see the issues I've run into:
Using .NET Core 2.0 Libraries in WebJob Targeting .NET Framework 4.7
No parameterless constructor error in WebJobs with .NET Core and Ninject
P.S. My previous posts are referring to WebJobs. That was plan B approach because WebJobs seem half a step ahead of Azure Functions when it comes to supporting things like .NET Core and DI. Ultimately, I'd like to build a few Azure Functions that can use my class libraries built in .NET Standard 2.
Also, my previous posts mention that my class libraries target .NET Core 2.0. Since then I converted them to .NET Standard 2 which didn't really take much at all. I did this so that I truly conform to .NET Standard 2.
One issue is that Visual Studio has an outdated version of the Functions Core tools. Until this is resolved, you can work around in the following way:
Install the latest via npm by running npm install -g azure-functions-core-tools
In your Function App in VS, go to the Properties
Go to Debug, and click New... under Profile
Name the new Profile something like FunctionsNpm
Set the executable to (replace [YourUserName]): C:\Users\[YourUserName]\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\func.exe
Set the arguments to host start
Set the working directory to $(TargetDir)
In toolbar, look for the green triangle icon to change your current Profile to the one you just created:
Now when you run from VS, you'll be using the npm tools instead of the older one that come with the VS package.
.NET Standard 2 support is on its way, see this github issue.

Attempt by security transparent method X to access security critical method Y failed

I have a fairly stable server application version that's been deployed for nearly a year at dozens of customers.
One new customer recently setup the application and is getting the following error:
System.MethodAccessException: Attempt by security transparent method
[SomeMethod] to access security critical method [SomeOtherMethod]
failed.
Both SomeMethod and SomeOtherMethod are methods in assemblies that I wrote, that are built against .NET 4, and that are running inside a Windows Service. If it makes a difference, SomeOtherMethod does reference a type from a 3rd party assembly (EntLib 4.1) built against .NET 2.0. Looking at the code for EntLib 4.1, I do see that they use both SecurityTransparent and APTC attributes, but this has never caused issues at other clients.
These assemblies were upgraded from the .NET 2.0 CLR, but a long time ago. This exact code is running on other customers just fine, and I'm not explicitly using the APTC attribute nor am I using the SecurityCritical attribute anywhere.
This leads me to the conclusion that it's a configuration issue or perhaps .NET Framework patch issue. Has there been a patch released for .NET that would cause this breaking change? Is there a configuration setting some where that enforces this type of check which is off by default but that my customer may have enabled?
One last point. My service utilizes SSRS RDLCs to generate PDFs. Due to some changes in .NET 4, I must force the service to use the legacy security policy via the following config:
<runtime>
<NetFx40_LegacySecurityPolicy enabled="true" />
</runtime>
For more details on why I need to do this, see this stackoverflow post: Very High Memory Usage in .NET 4.0
The important point is that I do this at all my other customers as well. Only this one customer is having issues.
Sigh, the patterns and practices employed by the Microsoft Patterns And Practices team that's responsible for the Enterprise libraries are pretty deplorable. Well, the exception is accurate, you cannot call a method that's decorated as "I'll definitely check security" from code that's decorated with "Meh, I won't check security so don't bother burning the cpu cycles to check it". Which scales about as well as exception specifications as used in Java. CAS is incredibly useful, but diagnosing the exceptions is a major headache and often involves code that you don't own and can't fix. Big reason it got deprecated in .NET 4.
Editorial done. Taking a pot-shot at the problem, you need to find out why CAS is being enforced here. The simplest explanation for that is that the service doesn't run in full trust. The simplest explanation for that is that the client didn't install the service on the local hard drive. Or is generally running code in don't-trust-it mode even on local assemblies, a very paranoid admin could well prefer that. That needs to be configured with Caspol.exe, a tool whose command line options are as mysterious as CAS. Pot-shooting at the non-trusted location explanation, your client needs to run Caspol as shown in this blog post. Or just simply deploy the service locally so the default "I trust thee" applies.
Editing in the real reason as discovered by the OP: beware of the alternate data stream that gets added to a file when it is downloaded from an untrusted Internet or network location. The file will get a stream named "Zone.Identifier" that keeps track of where it came from with the "ZoneId" value. It is that value that overrides the trust derived from the storage location. Usually putting it in the Internet zone. Use Explorer, right-click the file and click "Unblock" to remove that stream. After you're sure you can trust the file :)
I was facing the similar issue while running the downloaded WCF sample from http://www.idesign.net/ while using their ServiceModelEx library.
I commented out the below line in AssemblyInfo.cs in ServiceModelEx project
//[assembly: AllowPartiallyTrustedCallers]
and it worked for me.
In case it helps others i post my solution for this issue:
1) On the AssemblyInfo.cs, removed/commented the [assembly: SecurityTransparent] line.
2) The Class and the Method that does the actual Job was marked as [SecuritySafeCritical], in my case establishing a Network Connection:
[SecuritySafeCritical]
public class NetworkConnection : IDisposable
{
[SecuritySafeCritical]
public NetworkConnection(string networkName, NetworkCredential credentials)
{
.............
}
}
3) The Caller Class and Method was market as [SecurityCritical]:
[SecurityCritical]
public class DBF_DAO : AbstractDAO
{
[SecurityCritical]
public bool DBF_EsAccesoExclusivo(string pTabla, ref ArrayList exepciones)
{
....
using (new NetworkConnection(DBF_PATH, readCredentials))
{
....
}
}
}
In my case it was an issue when I managed a NuGet packages in the solution some package overrides System.Web.Mvc assembly version binding in main web site project. Set back to 4.0.0.0 (I had 5.0 installed). I didn't change notice the change because Mvc v4.0 was installed and accessible via GAC. Set back

Resources