Get CPU Usage of a Process using C#

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;
}

, , , ,

Leave a comment

How to make Linq and IList sort Dynamically using C#

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! Smile

, , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

My Baked Chicken Recipe

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. Smile

, , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Class Set as DataContext in XAML without Code Behind

In dealing with a problem at work and I am probably as guilty as anyone of relying on code behind to do basic functions without soley using XAML. Why? Because that’s the way I have always done it. But it’s a new day and time to learn new ways to do things. So here we go….

This example shows a class set as datacontext – the code behind file is completely empty.

Have a great week….

 

<Window x:Class=”cSharpTest.MainWindow”
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
        xmlns:vm=”clr-namespace:cSharpTest”
        Title=”MainWindow” Height=”350″ Width=”525″>
    <Window.Resources>
        <vm:MyData x:Key=”ViewModel”/>
    </Window.Resources>
    <Grid DataContext=”{StaticResource ViewModel}”>
        <ListBox Name=”MyListBox” ItemsSource=”{Binding Primes}”/>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cSharpTest
{
    class MyData
    {
        public MyData()
        {
            _primes = new int[5] { 1, 3, 5, 7, 11 };
        }
        private int[] _primes;
        public  int[] Primes
        {
            get { return this._primes; }
         }
    }
}

, , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

C# Application linked to SharePoint List Web Service

This weekend found myself knee deep in a crisis that my friend who had migrated from SharePoint 2003 to 2007 (there were reasons he couldn’t go to 2010). Simply put the migration from SharePoint 2003 to 2007 had broken his application (tracking program that submitted data to a 2003 SharePoint List) because in SharePoint 2007  you can’t do this while not on the actual server if you have “Web Page Security Validation” enabled. So for the code below you have to have SPWeb.AllowUnsafeUpdates = true; . Obviously not the ideal solution for my friend but we didn’t have time to screw around. Here is what I did….

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml;
using System.ServiceModel;
using System.Net;
 
namespace Trigger_Tracker
{
    public partial class Form1 : Form
    {//form move on click and drag
        bool FormMoving;
        Point initialPoint;
        TriggerTrackerPictureBox frmPicture;
 
        public Form1()
        {//form move on click and drag
            InitializeComponent();
            comboBox1.SelectedIndex = 0;
            FormMoving = false;
 
            frmPicture = new TriggerTrackerPictureBox();
            frmPicture.localForm = this;
            frmPicture.Owner = this;
            frmPicture.Show();
            frmPicture.Width = 68;
            frmPicture.Height = 65;
            SetPositionOfPictureForm();
        }
 
        private void SetPositionOfPictureForm()
        {
            frmPicture.Top = this.Top + 26;
            frmPicture.Left = this.Left + 87;
        }
 
       
 
        private void TrackerButton(object sender, EventArgs e)
        {
            string listGUID = “A93E1A7E-67D0-4D7D-A4ED-803D7DFE684B”;
            string viewGUID = “6B2F3EF2-4B0C-41E1-B87E-0C3185B587DD”;
            //string viewGUID2 = “6B2F3EF2-4B0C-41E1-B87E-0C3185B587DD”;
 
            int ItemCounter = 1;
            ServiceList.Lists listService = new ServiceList.Lists();
           // RetentionLists.ListsSoapClient listService = new RetentionLists.ListsSoapClient();
 
            //////
           listService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
           //listService.ChannelFactory.Credentials.Windows.ClientCredential   = System.Net.CredentialCache.DefaultNetworkCredentials;
 
            XmlNode activeItemData = listService.GetListItems(listGUID, viewGUID, null, null, “100″, null);
            XmlDocument xDoc = new XmlDocument();
            string tmpString = activeItemData.InnerXml.Replace(“\r\r”, “”);
            xDoc.LoadXml(tmpString);
            XmlNamespaceManager nsManager = new XmlNamespaceManager(xDoc.NameTable);
            nsManager.AddNamespace(“z”, “#RowsetSchema”);
            nsManager.AddNamespace(“rs”, “urn:schemas-microsoft-com:rowset”);
 
            XmlNodeList xNode = xDoc.SelectNodes(“/rs:data/z:row”, nsManager);
 
            foreach (XmlNode tmpNode in xNode)
                ItemCounter++;
 
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append(“<Method ID=’” + ItemCounter + “‘ Cmd=’New’>”);
            strBuilder.Append(“<Field Name=’Attachments’>” + “0″ + “</Field>”);
            strBuilder.Append(“<Field Name=’Title’>” + PolicyNumber.Text + “</Field>”);
            strBuilder.Append(“<Field Name=’Reason’>” + comboBox1.Text + “</Field>”);
            strBuilder.Append(“</Method>”);
 
            string strBatch = strBuilder.ToString();
 
            XmlDocument newDoc = new XmlDocument();
            XmlElement newElement = newDoc.CreateElement(“Batch”);
            newElement.SetAttribute(“OnError”, “Continue”);
            newElement.SetAttribute(“ViewName”, viewGUID);
            newElement.InnerXml = strBatch;
           
            XmlNode returnNode = listService.UpdateListItems(listGUID, newElement);
 
            this.comboBox1.Text = “Please Select….”;
            this.PolicyNumber.Text = “”;
            this.PolicyNumber.Mask = “0000000000″;
 
            comboBox1.Focus();
        }
 
       
 
 
        public void Form1_MouseUp(object sender, MouseEventArgs e)
        {//form move on click and drag
            FormMoving = false;
        }
 
        public void Form1_MouseMove(object sender, MouseEventArgs e)
        {//form move on click and drag
            if (FormMoving)
            {
                if ((Left + e.X – initialPoint.X) <= 0)
                    Left = 0;
                else if ((Right + e.X – initialPoint.X) >= Screen.PrimaryScreen.Bounds.Right)
                    Left = Screen.PrimaryScreen.Bounds.Right – Width;
                else
                    Left = Left + e.X – initialPoint.X;
                if ((Top + e.Y – initialPoint.Y) <= 0)
                    Top = 0;
                else if ((Bottom + e.Y – initialPoint.Y) >= Screen.PrimaryScreen.Bounds.Bottom)
                    Top = Screen.PrimaryScreen.Bounds.Bottom – Height;
                else
                    Top = Top + e.Y – initialPoint.Y;
            }
            SetPositionOfPictureForm();
        }
 
        public void Form1_MouseDown(object sender, MouseEventArgs e)
        {//form move on click and drag
            FormMoving = true;
            initialPoint = new Point(e.X, e.Y);
        }
 
        public void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {//form move on click and drag
            FormMoving = true;
            initialPoint = new Point(e.X, e.Y);
        }
 
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
        }
 
        private void pictureBox1_MouseHover(object sender, EventArgs e)
        {
        }
 
        public void label1_MouseHover(object sender, EventArgs e)
        {
            FormMoving = false;
        }
 
        public void label1_MouseUp(object sender, MouseEventArgs e)
        {
            FormMoving = false;
        }
 
       
 
        public void Form1_MouseHover(object sender, EventArgs e)
        {
            this.Opacity = 1;
        }
 
        public void Form1_MouseLeave(object sender, EventArgs e)
        {
            if(!PolicyNumber.Focused)
                this.Opacity = .25;
        }
 
        public void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            this.Opacity = 1;
        }
 
        public void pictureBox1_MouseHover_1(object sender, EventArgs e)
        {
            this.Opacity = 1;
        }
 
        public void Form1_Click(object sender, EventArgs e)
        {
            comboBox1.Focus();
        }
    }
}

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Databind ComboBox with WPF and C#

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;
        }
    }
}

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Convert Visio Pages to Images in vb.net

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…. Smile

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

, , , , , , , , , , , , , , , , , , , , , , , ,

2 Comments

Follow

Get every new post delivered to your Inbox.