Get CPU Usage of a Process using C#
Posted by Kelly's Chronicles in Uncategorized on November 5, 2012
This was a fun assignment. I was asked to write a piece of code that when a particular process id was passed to it it would return its CPU usage. WMI is fun. Have a great night….
public static decimal GetUssage(string pid)
{
//get the process
ManagementObjectSearcher searcher = new ManagementObjectSearcher(“SELECT * FROM Win32_Process WHERE ProcessID = ” + pid);
decimal PercentProcessorTime = 0;
foreach (ManagementObject queryObj in searcher.Get())
{
DateTime firstSample, secondSample;
//populate the process info
firstSample = DateTime.Now;
queryObj.Get();
//get cpu usage
ulong u_oldCPU = (ulong)queryObj.Properties["UserModeTime"].Value
+ (ulong)queryObj.Properties["KernelModeTime"].Value;
//sleep to create interval
System.Threading.Thread.Sleep(1000);
//refresh object
secondSample = DateTime.Now;
queryObj.Get();
//get new usage
ulong u_newCPU = (ulong)queryObj.Properties["UserModeTime"].Value
+ (ulong)queryObj.Properties["KernelModeTime"].Value;
decimal msPassed = (decimal)(secondSample – firstSample).TotalMilliseconds;
//formula to get CPU ussage
if (u_newCPU > u_oldCPU)
PercentProcessorTime = (decimal)((u_newCPU – u_oldCPU)
/ (msPassed * 100 * Environment.ProcessorCount));
Console.WriteLine(“processor time ” + PercentProcessorTime);
}
return PercentProcessorTime;
}
How to make Linq and IList sort Dynamically using C#
Posted by Kelly's Chronicles in Uncategorized on October 26, 2012
I apologize that it has been a while. I have been extremely busy and in the time that I have been away I went through treatment for a medical issue. Needless to say I had other issues to deal with other than this blog. But I will try to publish more frequently. Today’s topic was a question from another developer which was to have have a Linq and IList sort dynamically. So long as you don’t force execution by using ToList, you can keep tacking on to your query until you are ready to actually run it. This is because much of LINQ uses “deferred execution”. For example, you could do something similar to:
var query = apps.AsQueryable()
.Select
(Application => new
{
ID = Application.ApplicationId,
Force = Application.Force.Description,
Function = Application.BusinessFunction.Description,
Category = Application.Category.Description,
SubCategory = Application.SubCategory.Description,
Name = Application.ApplicationName,
Description = Application.ApplicationDescription
}
).Take(10);
switch (sortType)
{
case “ID”:
query = query.Orderby(Application => Application.ApplicationId);
break;
case “Force”:
query = query.Orderby(Application => Application.Force);
break;
}
IList tempList = query.ToList();
As always it has been great getting your all feedback while I was gone. Thank You! ![]()
My Baked Chicken Recipe
Posted by Kelly's Chronicles in Cooking on June 10, 2012
If you know me at all you know one of my favorite foods is baked chicken (especially broasted chicken if done right). With some experimentation I came up with this recipe that is excellent at least to my liking. So I thought I would share it with you.
First thaw your chicken in a container you can immerse it in with water and a can of Bud Light Lime.
Then remove the neck and gizzard.
With these ingredients…
1/2 cup flour
1 teaspoon garlic salt
1 teaspoon paprika
1/4 teaspoon sage
1/4 teaspoon ground black pepper
1/2 cup butter
1/4 can of Bud Light Lime
1/2 cup crushed Tostitos with a Hint of Jalapeño Tortilla Chips
Mix the dry ingredients well in a plastic bag, then coat the cut up chicken parts with the mixture.Melt the butter. Place the chicken parts in the pan. Bake the chicken at 350 degrees for 1 1/2 to 2 hours or until done. Or if you are like me and have a NuWave Oven cut that time by about 25 percent.
It is delicious. ![]()
Databind ComboBox with WPF and C#
Posted by Kelly's Chronicles in .NET, C#, WPF, XAML on April 21, 2012
Its been a while my apologies. I have been extremely busy.
This topic came up because in existing applications data binding at design time was heavily used. I personally avoid such data binding as much as possible because well in all honesty it causes me a lot of problems later on. I realize many of you live and die with it. So don’t take it personally.
So I am converting one of these apps to XAML and WPF. They insisted I maintain a ComboBox databind. As many of you know data binding has changed a bit in WPF from your standard application. I created a property to bind the ComboBox to. I set the DataContext of the page to itself, which I like to do. It lets me expose various properties and quickly bind to them. Have a great weekend!
XAML
—-
<ComboBox
Height=”23″
HorizontalAlignment=”Left”
Margin=”10,10,0,0″
Name=”comboBox1″
VerticalAlignment=”Top”
Width=”120″
ItemsSource=”{Binding MyDataColumns}”
DisplayMemberPath=”ColumnName”
/>
CODE BEHIND
—-
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
LoadData();
DataContext = this;
}
private DataTable _dataTable = null;
private void LoadData()
{
SqlConnection cn = null;
SqlCommand cmd = null;
SqlDataAdapter adapter = null;
DataSet dataSet = null;
try
{
cn = new SqlConnection(“Data Source=MyMachine;Initial Catalog=MyDb;Integrated Security=True”);
cmd = new SqlCommand(“select top 1 * from MyTable”, cn);
adapter = new SqlDataAdapter(cmd);
dataSet = new DataSet();
adapter.Fill(dataSet);
_dataTable = dataSet.Tables[0];
}
finally
{
if (cmd != null)
cmd.Dispose();
if (adapter != null)
adapter.Dispose();
if (dataSet != null)
dataSet.Dispose();
if (cn != null)
cn.Dispose();
}
}
public IEnumerable MyDataColumns
{
get
{
return (IEnumerable)_dataTable.Columns;
}
}
}
Convert Visio Pages to Images in vb.net
Posted by Kelly's Chronicles in .NET, C#, vb.net on January 22, 2012
I have been fooling around with Visio automation since attempting to help a friend with a project that did so. In the course of this I did this code snippet to convert the Visio page to an image. The code loops through and takes each page and converts it to an image. Pretty basic. I have not posted in a while and my apologies to those of you who were wondering…. ![]()
Here is the code….
Sub SaveAsImage()
‘ creates an invisible Visio instance, opens a document, then
‘ saves all pages in the document as jpg images using
‘ page name and page number as file name
Dim vsoApp As Visio.Application
Dim vsoDoc As Visio.Document
Dim PathName As String, jpgName As String
Dim pg As Visio.Page
Set vsoApp = CreateObject(“Visio.InvisibleApp”)
‘ SET PATH/FILENAME BELOW TO VSD ON YOUR SYSTEM
Set vsoDoc = vsoApp.Documents.Open(“c:\TEST\test.vsd”)
PathName = vsoApp.Documents(1).Path ‘ Set pathname to that of first document
For Each pg In vsoApp.ActiveDocument.Pages
jpgName = PathName & Format(pg.Index, “0#”) & ” ” & pg.Name & “.jpg”
pg.Export jpgName
Next
vsoDoc.Close
vsoApp.Quit
Set vsoDoc = Nothing
Set vsoApp = Nothing
End Sub
Recent Comments