C# Performance Counter Error - c#

I create a new performance counter and gave it three things, Processor time, Total and Processor Information. However It gives me an error:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.dll
Code:
PerformanceCounter CpuCounter = new PerformanceCounter("% Processor Time", "_Total", "Processor Information");
Any ideas?

Related

A proper way to handle WCF network related exceptions

In the application I"m working with, there is some communication with the remote service using WCF (basic http binding, no fancy stuff). Since the client is lightweigh, the details of the server are irrelevant, you may assume that there is just a method that always return true (like ping or something).
The proxy is generated using a Task option, the new client instance is created each time the operation is called. Something like this could be spinning inside the timer:
void Foo()
{
var client = new PingServiceClient();
try
{
bool result = client.PingAsync().GetAwaiter().GetResult();
}
catch
{
//log something
}
finally
{
client.Abort();
}
}
My question is, how should I correctly handle the cases when the network is down? Because the behavior is different. I either get an application crashing (I assume on a task finalizer, which is for some reason not handled neither in AppDomain.CurrentDomain.UnhandledException nor in TaskScheduler.UnobservedTaskException), or sometimes it just silently outputs tons of error messages, but not crashing anything. Messages like these:
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.AggregateException' in mscorlib.dll
I'm struggling to find a graceful way of handling these, so if anybody has some knowledge regarding this please share the approach.
Thanks in advance.
UPD:
I have tried to re-create the proxy with Begin/End pair and override the end method implementation in a partial class:
public partial class PingServiceClient : IPingServiceClient, PingService
{
public Task<bool> PingSync()
{
return Task.Factory.FromAsync(BeginPing(null, null), HandledEndPing);
}
private bool HandledEndPing(System.IAsyncResult result)
{
var res = false;
try
{
res = EndPing(result);
}
catch (Exception e)
{
;
}
return res;
}
}
Still the same barrage of messages in the output as before (the catch is working, though).

SpotFire Error : Attempt to get snapshot info of a node state of type 'DisposedDocumentNodeState'

We are having a winforms add-on as a visualization in SpotFire. In the program we manullay set Tags using the below code
Tagcolumn = table.Columns["tags"].As<TagsColumn>());
Tagcolumn.Tag("tag", rowSelection);
After the above code is performed and when the UI refreshes to show the new tag,SpotFire is throwing below unhandled exception randomly (i.e) it does not always happens, I get 2 out of 5 times this exception.
"System.InvalidOperationException was unhandled Message: An unhandled
exception of type 'System.InvalidOperationException' occurred in
Spotfire.Dxp.Application.dll Additional information: Attempt to get
snapshot info of a node state of type 'DisposedDocumentNodeState'.
Spotfire.Dxp.Application.Calculations.TableFilterSetCalculationDependency.CheckChange.AnonymousMethod__5()"
This error happens consistently If I have opened scatter plot with kmeans and line similarity applied on the plot.
Does anybody have idea why this happens and how to handle this error in the code.
Calling Set Tag functionality inside the ExecuteTransactions avoids the mentioned exception as below. Before SetTag was running in application UI thread which was causing the error, running SeTTag as part of document transactions as below has fixed the issue.
DataTable.Transactions.ExecuteTransactions(delegate
{
SetTag();
});

.NET SignalR client crashing

I have a self-hosted Katana OWIN service with windows authentication (no https), that publishes a SignalR hub. Everything is at latest NuGet level, net4.6.2. The hub is publishing log events from NLog.
I need to access this hub from a WPF client. Just to make sure, I have a simple javascript client also, which is getting the messages as needed. But the c# client "crashes".
At an unpredictable point in time I see this in output window:
Exception thrown: 'System.InvalidOperationException' in System.dll
Exception thrown: 'System.InvalidOperationException' in System.dll
Exception thrown: 'System.ObjectDisposedException' in System.dll
Exception thrown: 'System.ObjectDisposedException' in System.dll
Exception thrown: 'System.ObjectDisposedException' in mscorlib.dll
And from that point on the On event is not fired anymore, even if not a single message arrived before:
public static async Task<bool> ConnectAsync()
{
var settings = new Properties.Settings();
Connection = new HubConnection(settings.WebAPI);
Connection.Credentials = CredentialCache.DefaultNetworkCredentials;
HubProxy = Connection.CreateHubProxy("NLogHub");
HubProxy.On<DTO.WebApi.List.Log>("logEvent", (logEvent) => {
Debug.WriteLine(logEvent.TimeStamp);
//LogEventArrived?.Invoke(logEvent);
});
try
{
ServicePointManager.DefaultConnectionLimit = 10;
await Connection.Start(new LongPollingTransport());
Connection.EnsureReconnecting();
}
catch (HttpRequestException)
{
return false;
}
return true;
}
I have tried other transports too, but no luck. Does not matter what is in the On event - can be fully empty, this still happens.
Both client and server are running now on Windows 2016. but server will be Windows 2012, clients Windows 7 for now.
[Update 1]
The exception is thrown/not catched somewhere inside SignelR client code. Depending on transport this is what I can get:
LongPollingTransport
WebSocketTransport
After adding trace, I have some more details (WebSocketTransport), but still no idea how to handle:
13:48:04.9934736 - b3378218-e7f5-4ab4-89f6-08e6579bc70a - WS: OnMessage({})
13:48:10.1545908 - b3378218-e7f5-4ab4-89f6-08e6579bc70a - OnError(System.TimeoutException: Couldn't reconnect within the configured timeout of 00:00:30, disconnecting.)
13:48:10.1595862 - b3378218-e7f5-4ab4-89f6-08e6579bc70a - Disconnected
Exception thrown: 'System.Net.Sockets.SocketException' in mscorlib.dll
13:48:10.1675878 - b3378218-e7f5-4ab4-89f6-08e6579bc70a - Transport.Dispose(b3378218-e7f5-4ab4-89f6-08e6579bc70a)
Exception thrown: 'System.OperationCanceledException' in mscorlib.dll
13:48:10.2616468 - b3378218-e7f5-4ab4-89f6-08e6579bc70a - Closed
Exception thrown: 'System.OperationCanceledException' in mscorlib.dll
Exception thrown: 'System.OperationCanceledException' in mscorlib.dll
Exception thrown: 'System.OperationCanceledException' in System.dll
Exception thrown: 'System.OperationCanceledException' in mscorlib.dll
Exception thrown: 'System.OperationCanceledException' in mscorlib.dll
As I mentioned before: the JavaScript client is working like a charm.
[Update 2]
All transports complain about n ot being able to reconnect. But nothing points on a connection lost. How to debug that?
Any idea is appreciated...

UserManager.FindById is slow

I using this code (where context is OAuthGrantCustomExtensionContext):
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser appUser1 = await userManager.FindByIdAsync("My user id"); // 31 seconds to execute
ApplicationUser appUser2 = await userManager.FindByIdAsync("My user id"); // 1 milisecond to execute
The execution of the function FindByIdAsync takes 31 seconds on the first time. On the second execution it's takes only <1 MS. I also checked how fast is my DB by running a "SELECT... WHERE..." query - and it's really fast - <1 MS.
I also noticed in this output inside the "Output Window":
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll Exception thrown: 'System.Data.SqlClient.SqlException'
in System.Data.dll Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll Exception
thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll Exception thrown: 'System.Data.SqlClient.SqlException'
in System.Data.dll Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll Exception
thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll Exception thrown: 'System.Data.SqlClient.SqlException'
in System.Data.dll Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll Exception
thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll The
thread 0x1598 has exited with code 0 (0x0). Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll Exception
thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll Exception thrown: 'System.Data.SqlClient.SqlException'
in System.Data.dll Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll Exception
thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll Exception thrown: 'System.Data.SqlClient.SqlException'
in System.Data.dll Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll Exception
thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll Exception thrown: 'System.Data.SqlClient.SqlException'
in System.Data.dll Exception thrown:
'System.Data.Entity.Infrastructure.RetryLimitExceededException' in
EntityFramework.dll 'iisexpress.exe' (CLR v4.0.30319:
/LM/W3SVC/6/ROOT-1-131126169736320764): Loaded
'EntityFrameworkDynamicProxies-EntityFramework'. Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll Exception
thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in
System.Data.dll Exception thrown: 'System.Data.SqlClient.SqlException'
in System.Data.dll Exception thrown:
'System.Data.Entity.Core.EntityCommandExecutionException' in
EntityFramework.dll Exception thrown:
'System.Data.Entity.Core.EntityCommandExecutionException' in
EntityFramework.dll Exception thrown:
'System.Data.Entity.Core.EntityCommandExecutionException' in
EntityFramework.dll Exception thrown:
'System.Data.Entity.Core.EntityCommandExecutionException' in
EntityFramework.dll 'iisexpress.exe' (CLR v4.0.30319:
/LM/W3SVC/6/ROOT-1-131126169736320764): Loaded
'EntityFrameworkDynamicProxies-ObjectModelLayer'. 'iisexpress.exe'
(CLR v4.0.30319: /LM/W3SVC/6/ROOT-1-131126169736320764): Loaded
'EntityFrameworkDynamicProxies-Microsoft.AspNet.Identity.EntityFramework'.
The output above is collected from the time my machine executed this line:
ApplicationUser appUser1 = await userManager.FindByIdAsync("My user id");
In the other lines of code, the Output Window was empty. (which can explain why they was so fast).
As you can see, alot of SqlException are thrown while this code line. It's seems to me like a "retry" mechanism that try agian and agian to execute some logic but it failed. I woundering if this is the reason why this taking so long?
I looking for:
Way to see exectly what is this SqlException? maybe I'll fix this and this code will run faster.
How to fix the FindByIdAsync to make it work fast (<5 seconds) every time?
Thank you for support!
UPDATE
I found a useful way to catch first chance exceptions. With this code:
AppDomain.CurrentDomain.FirstChanceException +=
(object source, FirstChanceExceptionEventArgs e) =>
{
Console.WriteLine("FirstChanceException event raised in {0}: {1}", AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
};
So, I ran the code and collected the thrown exceptions. Got the following exception for 18 times:
The server principal "XXX" is not able to access the database "master"
under the current security context. Database 'master' on server
'XXX.net' is not currently available. Please retry the connection
later. If the problem persists, contact customer support, and provide
them the session tracing ID of 'XXXXXXX-68E9-4FDD-9E3D-92BE27438835'.
Login failed for user 'XXX'.
My user is really not allowed to access the "master" table. So, it's make sense. I change my DB connection string to another user with permission to access the "master" table - and now it's working fast! (less then 3 seconds).
After giving the right permissions, I still got this exception in the log (for 7 times):
Invalid object name 'dbo.EdmMetadata'.
Questions:
I don't understand why the function FindByIdAsync need to access the master table???
How to fix the error "Invalid object name 'dbo.EdmMetadata'."?
6 years later, I am still getting similar behavior with the latest libraries for Identity and Entity-Framework. The first call to userManager.Get[Something] takes about 5 seconds; subsequent calls are 3-10 milliseconds.
Could it be that Identity is trying to check/recreate the underlying database on the first call?

Why does this unrelated error happen when I try to setup Windows 8 settings?

I have a few lines of code that have worked fine for months, and now suddenly they do not work and I get a very strange error. Here is the function in question:
public void OnCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs eventArgs) {
UICommandInvokedHandler handler = new UICommandInvokedHandler(OnSettingsCommand);
SettingsCommand appSettings = new SettingsCommand("appSettings", "アプリ内設定", handler);
eventArgs.Request.ApplicationCommands.Add(appSettings);
}
Naturally, this gets called in response to the SettingsPane.GetForCurrentView().CommandsRequested event. The error happens on the second line and is as follows:
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
If I continue the app, then another exception comes:
A first chance exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: Object in an IPropertyValue is of type 'String', which cannot be converted to a 'Guid'.
What is going on here? As you can see I'm not using any GUID values anywhere.
Although the documentation lists no restrictions, and all samples use strings, the first parameter is listed as taking Object - it's possible this now is simply set to require a giud.
Interestingly, it looks like this has been reported to Microsoft as a bug in the OS. No idea what the resolution is going to be.

Categories