It's free and it's on a relevant topic, so can't get much better than that!
Thursday, August 22, 2013
Wednesday, July 17, 2013
Get CPU Usage Across All Cores In C# Using WMI
There are (2) main ways I have seen to get the CPU usage in a .NET app: via a PerformanceCounter and via WMI. The PerformanceCounter code seemed ideal and is the most concise, but had a caveat for this particular (CPU) counter. The code to retrieve this value using this method is as follows:
Notice that stall for 1 second nested in that code above? As documented here: Retrieving Accurate CPU Usage In C# and as seen in almost all code examples, you must add in that stall in order to get an accurate reading. It appears the 1 second value was not arbitrary either and is required in order for the reading to refresh the value.
Well how many are using this statistic in a static manner that is only shown 1 time ever? Not anyone I'm guessing, which mean this code is a part of a page reload or top level refresh in your app that is occurring often. Then I see some code smell because I don't want to have to wait 1 second every time my main page/form/etc. loads. Thinking async? Might work in a WinForm/WPF situation where this could occur on a separate thread, but if this is a part of a web app say monitoring a server, you could incur this hit on every postback. Also, if the total of processing is still having to wait on this code and everything else is complete in less than 1 second, you will still be delayed in net time of 1 second. Point being, incorporate this code into a separate async process or deal with a 1 second delay for every time called.
I think the better solution here is just to use an alternative method in WMI. I also like this method because you get an array/list back with the reading from each core and then the total from all cores. The following WMI code snippet I found can be used to get the CPU core usage values:
The thing is I didn't really know what to do with this information at 1st until I dug into it. The List returned will contain the current CPU usage for each core on the processor (1..n) and the total average of all cores. This is the value I'm interested in, and is represented as the last item in the List returned with the name "_Total". Here is the remaining code to get the CPU usage as a single value:
If you want to verify the values, add up each core's value in the cpuTimes List and then divide by the total number of cores to get the "_Total" value.
//Getting the CPU usage via a PerformanceCounter
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000); // wait a second to get a valid reading
var usage = cpuCounter.NextValue();
Notice that stall for 1 second nested in that code above? As documented here: Retrieving Accurate CPU Usage In C# and as seen in almost all code examples, you must add in that stall in order to get an accurate reading. It appears the 1 second value was not arbitrary either and is required in order for the reading to refresh the value.
Well how many are using this statistic in a static manner that is only shown 1 time ever? Not anyone I'm guessing, which mean this code is a part of a page reload or top level refresh in your app that is occurring often. Then I see some code smell because I don't want to have to wait 1 second every time my main page/form/etc. loads. Thinking async? Might work in a WinForm/WPF situation where this could occur on a separate thread, but if this is a part of a web app say monitoring a server, you could incur this hit on every postback. Also, if the total of processing is still having to wait on this code and everything else is complete in less than 1 second, you will still be delayed in net time of 1 second. Point being, incorporate this code into a separate async process or deal with a 1 second delay for every time called.
I think the better solution here is just to use an alternative method in WMI. I also like this method because you get an array/list back with the reading from each core and then the total from all cores. The following WMI code snippet I found can be used to get the CPU core usage values:
//Get CPU usage values using a WMI query
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
var cpuTimes = searcher.Get()
.Cast<managementobject>()
.Select(mo => new
{
Name = mo["Name"],
Usage = mo["PercentProcessorTime"]
}
)
.ToList();
The thing is I didn't really know what to do with this information at 1st until I dug into it. The List returned will contain the current CPU usage for each core on the processor (1..n) and the total average of all cores. This is the value I'm interested in, and is represented as the last item in the List returned with the name "_Total". Here is the remaining code to get the CPU usage as a single value:
//The '_Total' value represents the average usage across all cores, //and is the best representation of overall CPU usage var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage); var cpuUsage = query.SingleOrDefault();
If you want to verify the values, add up each core's value in the cpuTimes List and then divide by the total number of cores to get the "_Total" value.
Tuesday, May 28, 2013
VS.NET 2012 Missing Setup and Deployment Project Type
Well it is difficult to keep up with all of the news going on in and surrounding .NET, but I missed the news (from a couple of years ago) that new versions of VS.NET would no longer have the deployment/installer package as a project type. I was a bit shocked when I was looking for a setup project for my Windows Service and the old 'Setup' project type was no longer listed in VS.NET 2012.
A more official source of this information can be found on this MSDN blog post by Buck Hodges:
Visual Studio setup projects (vdproj) will not ship with future versions of VS
As for a quick install of a Windows Service for developement scenarios, just use the 'installutil.exe' installer tool (this tool is automatically installed with Visual Studio and with the Windows SDK) using the following command:
>installutill.exe C:\MyWindowsService.exe
Alternatives? WiX and NSIS are good alternatives. WiX allows creation of .msi packages for silent deployments (if required or desired) and NSIS creates a .exe and offers a straight forward to use scripting language to build deployment packages. Both have a ton of documentation and support. I have used NSIS only briefly, but it offers a low level richness that will suffice for any size deployment needed. Here are some links to each product:
NSIS
WiX
A quick word if anyone is upset at Microsoft for this - don't be. We all have to yield to the massive open source communities with their maturing and robust products that just overall trump anything a little sector within the tools section of the VS.NET team can produce and support on an ongoing basis. It's better to become familiar with one of these well known and stable open source deployment products and begin using them anyway.
A more official source of this information can be found on this MSDN blog post by Buck Hodges:
Visual Studio setup projects (vdproj) will not ship with future versions of VS
As for a quick install of a Windows Service for developement scenarios, just use the 'installutil.exe' installer tool (this tool is automatically installed with Visual Studio and with the Windows SDK) using the following command:
>installutill.exe C:\MyWindowsService.exe
Alternatives? WiX and NSIS are good alternatives. WiX allows creation of .msi packages for silent deployments (if required or desired) and NSIS creates a .exe and offers a straight forward to use scripting language to build deployment packages. Both have a ton of documentation and support. I have used NSIS only briefly, but it offers a low level richness that will suffice for any size deployment needed. Here are some links to each product:
NSIS
WiX
A quick word if anyone is upset at Microsoft for this - don't be. We all have to yield to the massive open source communities with their maturing and robust products that just overall trump anything a little sector within the tools section of the VS.NET team can produce and support on an ongoing basis. It's better to become familiar with one of these well known and stable open source deployment products and begin using them anyway.
Wednesday, May 22, 2013
Download and Export NuGet Packages Without VS.NET
99.999% of the NuGet packages that I use are associated with a specific project in VS.NET and adding them with the Package Manager Console is trivial. Just copy and paste the command from the NuGet site, and your done.
Interestingly enough though I came across a couple of utilities I wanted to use that were hosted on NuGet that were not application specific; specifically 'OpenCover' and 'ReportGenerator'. These are used for unit testing code coverage metrics and reporting, so I thought they needed to be added to my unit test project. After seeing how they worked I realized they had nothing to do with any project and could be downloaded independently. I can still use VS.NET to download the packages and then move them, but why clutter my app with packages that are truly not required.
There is an easy enough way to download NuGet packages separate from VS.NET and export their contents to any given directory. One method I want to show you is a quick way to download a package from NuGet without any tooling at all, and just using the browser. Find the name of your package from NuGet and append it on to the end of this URL:
http://packages.nuget.org/api/v1/package/{package name}
and then add the package to make the complete download URL like this:
http://packages.nuget.org/api/v1/package/OpenCover
Which will immediately result in the download of the .nupkg NuGet package:
Now that's a quick and easy way to get the NuGet package without VS.NET. However there is a more inclusive tool named 'NuGet Package Explorer' available from CodePlex which allows us to download and export directly. This tool can be downloaded from the following link:
NuGet Package Explorer
It's a ClickOnce package and once installed there should be a desktop icon to launch the tool:
The easier way to download a package is to select 'Open a package from online feed' from the dialog presented upon opening the application. However if you already have the package downloaded you can select the 'Open a local package' link instead:
Search for the package you wish to download and extract:
Once you select the package you are looking for and press 'OK', the package's contents will be shown. Go to FILE -> Export where you can select the export location of the package:
Upon successful export of the NuGet package you should see the following message:
Lastly, navigate to the export location you selected and verify the contents of the NuGet package exist:
That's it! There is other functionality of the Package Explorer that includes making your own NuGet package as well. However it is possible to download and easily export the contents of a NuGet package without using VS.NET.
Interestingly enough though I came across a couple of utilities I wanted to use that were hosted on NuGet that were not application specific; specifically 'OpenCover' and 'ReportGenerator'. These are used for unit testing code coverage metrics and reporting, so I thought they needed to be added to my unit test project. After seeing how they worked I realized they had nothing to do with any project and could be downloaded independently. I can still use VS.NET to download the packages and then move them, but why clutter my app with packages that are truly not required.
There is an easy enough way to download NuGet packages separate from VS.NET and export their contents to any given directory. One method I want to show you is a quick way to download a package from NuGet without any tooling at all, and just using the browser. Find the name of your package from NuGet and append it on to the end of this URL:
http://packages.nuget.org/api/v1/package/{package name}
and then add the package to make the complete download URL like this:
http://packages.nuget.org/api/v1/package/OpenCover
Which will immediately result in the download of the .nupkg NuGet package:
Now that's a quick and easy way to get the NuGet package without VS.NET. However there is a more inclusive tool named 'NuGet Package Explorer' available from CodePlex which allows us to download and export directly. This tool can be downloaded from the following link:
NuGet Package Explorer
It's a ClickOnce package and once installed there should be a desktop icon to launch the tool:
The easier way to download a package is to select 'Open a package from online feed' from the dialog presented upon opening the application. However if you already have the package downloaded you can select the 'Open a local package' link instead:
Search for the package you wish to download and extract:
Once you select the package you are looking for and press 'OK', the package's contents will be shown. Go to FILE -> Export where you can select the export location of the package:
Upon successful export of the NuGet package you should see the following message:
Lastly, navigate to the export location you selected and verify the contents of the NuGet package exist:
That's it! There is other functionality of the Package Explorer that includes making your own NuGet package as well. However it is possible to download and easily export the contents of a NuGet package without using VS.NET.
Monday, May 20, 2013
Where are we Headed with .NET? It's Anyone's Guess
Now here is an interesting piece of information that over the years I have not been up on or too familiar with: 'Future Predictions of .NET and the Microsoft Stack'. The main reasons for this are many: new to development, not a part of the insiders industry, didn't understand why this important, etc..
Most of us have the tools we or our employer has set forth in front of us and just blindly use them. C# + Windows Forms, ASP.NET MVC + C#, VB.NET + WebForms, etc. It's just some combination that someone years before we got on the project decided, and one punches in daily and continues to use them. My interest being completely invested in this .NET community is to at least listen to the 'road map' of our tool set, even if the 'road map' is somewhat unofficial. My recommendation is to come out of the .NET cave and be aware of some of this too.
You might wonder, "why is this important to me?" Well that I can at least answer. You don't want to be the next guy/gal that is pleading to use the next 'Silverlight' for your mega company only to find it abandoned a few years later. None of us could have really know this (about the demise of Silverlight) a few years ago, but those of us that saw the writing on the wall early on and were not in the camp 'crossing our fingers and holding our breath' waiting for Silverlight 6, were ahead of the game. Being a little knowledgeable about this information can be helpful.
In the last year or so and especially with the advent of Windows 8 and WinRT, I've seen a LOT of buzz around "What's Microsoft doing?", "What's the future of .NET?", "What is the future of technology 'X' that our company has invested in so greatly?"
I can speak somewhat intelligently on the actual use of certain technologies and my thought on how viable they are today and in the future, but this information is based on my experience and purely speculative. I have no real ties into anyone 'in the know' at Microsoft. My information comes in the form of blog posts by the well known in our community (not being paid to promote so they can be more truthful) and in the form of conferences, events, magazine and online articles too. Therefore I find this information filling a void in some of my current knowledge.
It also seems to be more of a topic of interest in the last several weeks with a few articles on this very subject. At DotNetConf there was a session that Scott Hanselman hosted about .NET Open Source and it appeared there was a lot of unhappy folks in this community. I can't gauge well the sentiment as I am not a huge OS community contributor and therefore don't have much in the way of an opinion, but there are plenty that do.
I'm trying to immerse myself into this line of knowledge and discussion that has been going on and have a few interesting links to provide that are worth reading. From pissed off Silverlight and XNA developers, to talk of .NET being obsolete, I can't help but perk up my ears. So to let those that know better than I provide insight, please check out the following information on this topic:
A perspective: developers vs Microsoft
Where Is .NET Headed?
BUILD 2013, Windows 8.1, and Microsoft's Deep-Tech Team: Hopeful News for Devs
dotNetConf - .NET Open Source Panel
The Microsoft Transition and How It Will Affect You
Like the rest reading this, I'm curious to hear the word at the Build conference this year. Let's see...
Most of us have the tools we or our employer has set forth in front of us and just blindly use them. C# + Windows Forms, ASP.NET MVC + C#, VB.NET + WebForms, etc. It's just some combination that someone years before we got on the project decided, and one punches in daily and continues to use them. My interest being completely invested in this .NET community is to at least listen to the 'road map' of our tool set, even if the 'road map' is somewhat unofficial. My recommendation is to come out of the .NET cave and be aware of some of this too.
You might wonder, "why is this important to me?" Well that I can at least answer. You don't want to be the next guy/gal that is pleading to use the next 'Silverlight' for your mega company only to find it abandoned a few years later. None of us could have really know this (about the demise of Silverlight) a few years ago, but those of us that saw the writing on the wall early on and were not in the camp 'crossing our fingers and holding our breath' waiting for Silverlight 6, were ahead of the game. Being a little knowledgeable about this information can be helpful.
In the last year or so and especially with the advent of Windows 8 and WinRT, I've seen a LOT of buzz around "What's Microsoft doing?", "What's the future of .NET?", "What is the future of technology 'X' that our company has invested in so greatly?"
I can speak somewhat intelligently on the actual use of certain technologies and my thought on how viable they are today and in the future, but this information is based on my experience and purely speculative. I have no real ties into anyone 'in the know' at Microsoft. My information comes in the form of blog posts by the well known in our community (not being paid to promote so they can be more truthful) and in the form of conferences, events, magazine and online articles too. Therefore I find this information filling a void in some of my current knowledge.
It also seems to be more of a topic of interest in the last several weeks with a few articles on this very subject. At DotNetConf there was a session that Scott Hanselman hosted about .NET Open Source and it appeared there was a lot of unhappy folks in this community. I can't gauge well the sentiment as I am not a huge OS community contributor and therefore don't have much in the way of an opinion, but there are plenty that do.
I'm trying to immerse myself into this line of knowledge and discussion that has been going on and have a few interesting links to provide that are worth reading. From pissed off Silverlight and XNA developers, to talk of .NET being obsolete, I can't help but perk up my ears. So to let those that know better than I provide insight, please check out the following information on this topic:
A perspective: developers vs Microsoft
Where Is .NET Headed?
BUILD 2013, Windows 8.1, and Microsoft's Deep-Tech Team: Hopeful News for Devs
dotNetConf - .NET Open Source Panel
The Microsoft Transition and How It Will Affect You
Like the rest reading this, I'm curious to hear the word at the Build conference this year. Let's see...
Tuesday, May 14, 2013
Visual Studio Live! is Heading Back to Microsoft Campus this August!
Visual Studio Live! is heading back to Microsoft campus on August 19-23 in Redmond, WA. Surrounded by your fellow developers, Visual Studio Live! provides you with immediately usable education that will keep you relevant in the workforce.
SPECIAL OFFER: As a reader of my blog, I can extend $500 savings on the 5-day package. Register here: http://bit.ly/11oZIks and use code UGRD8.
Learn how you can Code like a Rockstar at Visual Studio Live! Redmond — bring the issues that keep you up at night and prepare to leave this event with the answers, guidance and training you need. Register now: http://bit.ly/11oZIks
Thursday, May 9, 2013
Using Postman for Google Chrome to call REST and OData Services
A tool I heard mentioned at the recent online DotNetConf virtual conference and have begun using recently is the 'Postman' developer tool for Google Chrome. You can find it on the Chrome Store at the following URL: Postman for Google Chrome This tool is another client utility to make HTTP calls to REST based services. Open a new tab in Google and you will see it as an option to open:
Interestingly, the side chat for DotNetConf contained a brief conversation about Fiddler vs. Postman. Most folks were fond of Postman and preferred it over Fiddler for basic HTTP calls because of its refined and smooth interface (in fact I think these were the paraphrased sentiments of Scott Hanselman in the conversation). While Postman is not by any means a replacement for the rich feature functionality of Fiddler, it certainly has a bit more polished UI and easier to use for constructing basic GET and POST calls. If you are not doing any special debugging, I would probably use Postman 1st and Fiddler in other scenarios.
The main features I like about Postman are the following:
Interestingly, the side chat for DotNetConf contained a brief conversation about Fiddler vs. Postman. Most folks were fond of Postman and preferred it over Fiddler for basic HTTP calls because of its refined and smooth interface (in fact I think these were the paraphrased sentiments of Scott Hanselman in the conversation). While Postman is not by any means a replacement for the rich feature functionality of Fiddler, it certainly has a bit more polished UI and easier to use for constructing basic GET and POST calls. If you are not doing any special debugging, I would probably use Postman 1st and Fiddler in other scenarios.
The main features I like about Postman are the following:
- History of calls down the left-hand pane for easy access to recall recent GET, POST, etc.
- Ability to add in Basic Authentication Headers in their raw form without having to Base64 encode them 1st (Postman will do this for you)
- Simplicity to add custom headers
- Ability to have the URL contain spaces instead of having to encode the query string with %20. This is key for creating OData calls using OData commands.
- Smooth, refined, easy to use interface
Below are the security option tabs across the top of the product. Often you will use 'Normal' or 'Basic Auth'. Normal would be used if you are not adding any authentication information to the headers.
Basic Auth is used when adding HTTP Basic Authentication information to the request headers. As you can see you can enter in the credentials directly without having to encode the information manually:
Once you press the 'Refresh headers' button, the encoded basic authentication information will be added for you! Saves a bit of time as opposed to having to do this through a site, test harness, or code.
You can also easily add custom headers by simply typing in he 'Header' and 'Value' text boxes and again pressing the 'Refresh headers' button. It's nice and organized and makes sure the headers are added properly to the request and reduces chances you might add the header values incorrectly.
As far as using OData command parameter, notice in my query string how I do not have to encode the 'spaces' in the URL. The tool will construct and encode the URL for me, making writing OData queries much easier. You can add the commands directly to the URL or type them in the 'URL Parameter Key' and 'Value' text boxes:
One other nicety to mention is if constructing a traditional query string parameter, you can add those parameters easily too, and Postman will make sure the query string is constructed properly.
This was just a brief introduction to Postman, but I highly recommend it's usage for OData service calls or any other REST based calls. It makes constructing OData queries easier, and its user friendly interface is a great choice for traditional REST based calls.
Subscribe to:
Posts (Atom)















