Performance counter throws SecurityException - performancecounter

This is the code:
private static void CreateCounter()
{
if (PerformanceCounterCategory.Exists("DemoCategory"))
PerformanceCounterCategory.Delete("DemoCategory");
CounterCreationDataCollection ccdArray = new CounterCreationDataCollection();
CounterCreationData ccd = new CounterCreationData();
ccd.CounterName = "RequestsPerSecond";
ccd.CounterType = PerformanceCounterType.NumberOfItems32;
ccd.CounterHelp = "Requests per second";
ccdArray.Add(ccd);
PerformanceCounterCategory.Create("DemoCategory", "Demo category",
PerformanceCounterCategoryType.SingleInstance, ccdArray);
Console.WriteLine("Press any key, to start use the counter");
}
Obviously:
PerformanceCounterCategory.Create("DemoCategory", "Demo category",
PerformanceCounterCategoryType.SingleInstance, ccdArray);
is the line where the exception was thrown.
I have read about PerformanceCounterPermission, what should I do exactly?

Your application's process does not have the appropriate privilege level. That's what the security exception is telling you.
The simple fix is to request that permission when your application starts. You can do this by modifying your application's manifest such that the requestedExecutionLevel is set to requireAdministrator.
The complete section added to your application's manifest will look something like this:
<!-- Identify the application security requirements. -->
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
There are potentially better alternatives if your application does not otherwise require administrative privileges, because you should always run at the lowest privilege level that is absolutely necessary or required. You can investigate these alternatives using Google; it's going to involve spinning off a separate process that requests UAC elevation and runs the performance counter when requested explicitly by the user.

Related

ApplicationInsights dotnet core custom initializer

I'm unable to figure out how to configure AI for aspnetcore project. I've done the following:
services.AddSingleton<ITelemetryInitializer, AppInsightsInitializer>();
services.AddApplicationInsightsTelemetry(Configuration);
Where I need the loggedin user and the servicename so I've got this initializer:
public class AppInsightsInitializer : ITelemetryInitializer
{
private IHttpContextAccessor _httpContextAccessor;
public AppInsightsInitializer(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException("httpContextAccessor");
}
public void Initialize(ITelemetry telemetry)
{
var httpContext = _httpContextAccessor.HttpContext;
telemetry.Context.Properties["appname"] = "MyCoolService";
if (httpContext != null && httpContext.User.Identity.IsAuthenticated == true && httpContext.User.Identity.Name != null)
{
telemetry.Context.User.AuthenticatedUserId = httpContext.User.Identity.Name;
}
}
}
I've got no applicationinights.config file (I understand they are not needed)
Problem: I got 4 entries of each log (same id). The data is correct. I also got the following errror in the logs:
AI: Error collecting 9 of the configured performance counters. Please check the configuration. Counter \Process(??APP_WIN32_PROC??)\% Processor Time: Failed to perform the first read for performance counter. Please make sure it exists.
Category: Process, counter: % Processor Time, instance Counter \Memory\Available Bytes: Failed to register performance counter.
Category: Memory, counter: Available Bytes, instance: .
Counter \ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec: Failed to perform the first read for performance counter. Please make sure it exists.
Category: ASP.NET Applications, counter: Requests/Sec, instance MyCoolv3.Api.exe Counter \.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec: Failed to perform the first read for performance counter. Please make sure it exists.
Category: .NET CLR Exceptions, counter: # of Exceps Thrown / sec, instance Counter \ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time: Failed to perform the first read for performance counter. Please make sure it exists.
Category: ASP.NET Applications, counter: Request Execution Time, instance MyCoolv3.Api.exe Counter \Process(??APP_WIN32_PROC??)\Private Bytes: Failed to perform the first read for performance counter. Please make sure it exists. Category: Process, counter: Private Bytes, instance Counter \Process(??APP_WIN32_PROC??)\IO Data Bytes/sec: Failed to perform the first read for performance counter. Please make sure it exists.
Category: Process, counter: IO Data Bytes/sec, instance Counter \ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue: Failed to perform the first read for performance counter. Please make sure it exists. Category: ASP.NET Applications, counter: Requests In Application Queue, instance MyCoolv3.Api.exe
Counter \Processor(_Total)\% Processor Time: Failed to register performance counter. Category: Processor, counter: % Processor Time, instance: _Total.
I'm using:
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.1.0-beta1" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
services.AddApplicationInsightsTelemetry(Configuration);
isn't needed anymore (hypothetically, you should even be getting deprecation warnings on that line?)
if you create a asp.net core new project in VS2017, AI will already be there in package references (though the 2.0 version, not that 2.1 beta version), and all of the wireup would already be done in program.cs and in some other files.
If you're porting an existing one, then instead of the above AddApplicationInsights... line, instead you'd have
.UseApplicationInsights()
in your program.cs startup of your app instead. for more details, there's some info about this in the 2.1 beta release notes on github
We're also working on updating the "configure application insights" tools in VS2017 to properly "migrate" apps like this in a future update.
I'm not sure why you'd get multiple instances of any events unless you're explicitly logging them, or if you possibly have multiple calls to startup (which also shouldn't affect anything). Where are are you seeing multiple instances? in VS's appinsights tools? in the portal?

Spring Integration: How to use an "error gateway" with Splitter Aggregator when Exception thrown

I've seen more than a few posts about this topic, but can't seem to find a solution to my specific problem, which I think is a pretty typical one, namely: how to keep processing messages when an error occurs (Exception thrown) using a Splitter / Aggregator.
The best explanation that I have come upon is here. But there's no explanation of exactly what/how the filters/transformers work. And in the end, the author posts "That worked!" but without posting an updated SI.config.xml.
From what I understand, the idea is to use an "error gateway", which is downstream from the original calling gateway and after the Splitter. This Gateway's job would be if there is an Exception thrown, to deal with it, but to make sure (via a transformer or a filter) that all Messages make it to the Aggregator.
My very simplified SI.config.xml if more or less like this:
<int:gateway id="myGateway" ... /> // incoming gateway
<int:chain ... input-channel="in" output-channel="out">
<int:splitter ... />
<int:service-activator />
<int:aggregator />
</int:chain>
So my question is, where exactly to stick this other gateway? And how to configure filters/transformers that (from what I gather) would grab the Message which launched an Exception and put it back on the correct channel (after logging it or whatever ...) so all Messages make it to the Aggregator.
I have looked at the SI samples, on SO, and the 2 SI books (SI in Acton and Pro SI) and can't find an example of this.
The solution looks like:
<int:chain ... input-channel="in" output-channel="out">
<int:splitter ... />
<int:gateway request-channel="processChannel" errorChannel="processError"/>
<int:aggregator />
</int:chain>
<int:chain input-channel="processChannel">
<int:service-activator />
</int:chain>
The error handler on the processError channel should consult incoming ErrorMessage and returns some compensation which will be sent to the aggregator.
The ErrorMessage typically contains MessagingException with a failedMessage where error has caused. That failedMessage contains all useful headers to go ahead with a compensation. Some of them are replyChannel and errorChannel, but for your aggregator case you need all those correlationId, sequenceNumber, sequenceSize etc. In other words when you build compensation message to be sent forward to the downstream for the aggregator, you should copy all the headers from that failedMessage.
For more info: http://docs.spring.io/spring-integration/docs/4.3.5.RELEASE/reference/html/configuration.html#namespace-errorhandler

Spring integration Error handling - How do I access original faulty message's history?

We have a spring-integration application where we would like to deal with the messages on the error channel.At a minimum we would like to extract the history and log it so we can visualise where exactly it failed etc
Here is a brief markup of just this bit
<int:poller id="defaultPoller" default="true" fixed-delay="5000" />
<int:channel id="MyCustomErrorChannel">
<int:queue capacity="10"/>
</int:channel>
<int:header-enricher id="errorMsg.HeaderEnricher"
input-channel="errorChannel"
output-channel="MyCustomErrorChannel">
<int:header name="history" expression="payload.failedMessage.headers" />
</int:header-enricher>
<int:service-activator input-channel="MyCustomErrorChannel" ref="errorLogger" method="logError"/>
<bean id="errorLogger" class="com.dataprep.util.ErrorLogger" />
The idea is to define our custom error channel MyCustomErrorChannel. Any error that ends up in the default errorChannel gets its header's enriched before being put out on MyCustomErrorChannel
Lastly we have a logger that reads the messages from MyCustomErrorChannel and logs the payload which is the underlying exception and also the history.
I notice that the history in my logger is always 3 steps
errorChannel,errorMsg.HeaderEnricher,pbSwiftRouterErrorChannel i.e nothing prior to this message landing on the errorChannel is obtainable in the history.
How do I get hold of the original message's history (i.e the history of the faulty message which somehow landed on the default error channel as a new Error Message)
Could you please take a look at my header enricher and let me know how to access the headers on the failed message and stuff it to the error message?
Is it doable at all ?
To replace existing headers you should use overwrite="true", because the history is built for the ErrorChannel, too.
You should override exactly with history header, not the whole headers. Therefore your expression must be like this:
<int:header name="history"
expression="payload.failedMessage.headers.history"
overwrite="true"/>

Access is denied in BackgroundTaskBuilder.Register

var builder=new BackgroundTaskBuilder();
builder.Name=name;
builder.TaskEntryPoint=taskEntryPoint;
builder.SetTrigger(trigger);
if(condition!=null)
builder.AddCondition(condition);
builder.Register(); // in this step I get exception System.UnauthorizedAccessException. Additional information: Access is denied.
This exception is throwed in Windows 8 release preview.
In consumer preview I did not get this exception.
I use SystemTrigger (SystemtriggerType.UserPresent) and SystemCondition(SystemConditionType.InternetAvailable)
In Package.appxmanifest file I set System event checkbox to true and input Entry point value.
Also in Package.appxmanifest code I removed 'Executable' attribute.
Maybe someone know how I can fix it?
Thank you in advance!
Some SystemTriggers,however do need the app to be on the lock screen:
SessionConnected ,UserPresent,UserAway and ControlChannelReset If you use these triggers without beging on the lock screen ,the BackgroundTaskBuilder.Register() call will fail with "acess denied"

Maximum number of messages sent to a Queue in OpenMQ?

I am currently using Glassfish v2.1 and I have set up a queue to send and receive messages from with Sesion beans and MDBs respectively. However, I have noticed that I can send only a maximum of 1000 messages to the queue. Is there any reason why I cannot send more than 1000 messages to the queue? I do have a "developer" profile setup for the glassfish domain. Could that be the reason? Or is there some resource configuration setting that I need to modify?
I have setup the sun-resources.xml configuration properties as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>
<admin-object-resource
enabled="true"
jndi-name="jms/UpdateQueue"
object-type="user"
res-adapter="jmsra"
res-type="javax.jms.Queue">
<description/>
<property name="Name" value="UpdatePhysicalQueue"/>
</admin-object-resource>
<connector-resource
enabled="true" jndi-name="jms/UpdateQueueFactory"
object-type="user"
pool-name="jms/UpdateQueueFactoryPool">
<description/>
</connector-resource>
<connector-connection-pool
associate-with-thread="false"
connection-creation-retry-attempts="0"
connection-creation-retry-interval-in-seconds="10"
connection-definition-name="javax.jms.QueueConnectionFactory"
connection-leak-reclaim="false"
connection-leak-timeout-in-seconds="0"
fail-all-connections="false"
idle-timeout-in-seconds="300"
is-connection-validation-required="false"
lazy-connection-association="false"
lazy-connection-enlistment="false"
match-connections="true"
max-connection-usage-count="0"
max-pool-size="32"
max-wait-time-in-millis="60000"
name="jms/UpdateFactoryPool"
pool-resize-quantity="2"
resource-adapter-name="jmsra"
steady-pool-size="8"
validate-atmost-once-period-in-seconds="0"/>
</resources>
Hmm .. further investigation revealed the following in the imq logs:
[17/Nov/2009:10:27:57 CST] ERROR sendMessage: Sending message failed. Connection ID: 427038234214377984:
com.sun.messaging.jmq.jmsserver.util.BrokerException: transaction failed: [B4303]: The maximum number of messages [1,000] that the producer can process in a single transaction (TID=427038234364096768) has been exceeded. Please either limit the # of messages per transaction or increase the imq.transaction.producer.maxNumMsgs property.
So what would I do if I needed to send more than 5000 messages at a time?
What I am trying to do is to read all the records in a table and update a particular field of each record based on the corresponding value of that record in a legacy table to which I have only read only access. This table has more than 10k records in it. As of now, I am sequentially going through each record in a for loop, getting the corresponding record from the legacy table, comparing the field values, updating the record if necessary and adding corresponding new records in other tables.
However, I was hoping to improve performance by processing all the records asynchronously. To do that I was thinking of sending each record info as a separate message and hence requiring so many messages.
To configure OpenMQ and set artitrary broker properties, have a look at this blog post.
But actually, I wouldn't advice to increase the imq.transaction.producer.maxNumMsgs property, at least not above the value recommended in the documentation:
The maximum number of messages that a producer can process in a single transaction. It is recommended that the value be less than 5000 to prevent the exhausting of resources.
If you need to send more messages, consider doing it in several transactions.