• No results found

Appendix A – Programkod ProgramForm.cs

N/A
N/A
Protected

Academic year: 2021

Share "Appendix A – Programkod ProgramForm.cs"

Copied!
8
0
0

Loading.... (view fulltext now)

Full text

(1)

Appendix A – Programkod

ProgramForm.cs

using System; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Collections; namespace ProcessManager {

public partial class ProgramWindow : Form {

string NewLine = System.Environment.NewLine; ProcessGroup[] MyGroup = new ProcessGroup[25]; string configuration = "";

bool groupassigned;

Hashtable cache = new Hashtable(); public ProgramWindow()

{

InitializeComponent(); }

private void Form1_Load(object sender, EventArgs e) {

//displayHelp();

cache.Add("processmanager", "This is me!"+NewLine+"Process Manager is made by Johan Svensson."+NewLine+"For feedback mail: processmanagersurvey@gmail.com");

configParser(); }

private void ProcessBox_SelectedIndexChanged(object sender, EventArgs e) {

getInfo(); }

private void scanbutton_Click(object sender, EventArgs e) {

updateConfig(); configParser(); }

private void savebutton_Click(object sender, EventArgs e) {

//Write the configuration string to a TXT-file.

SaveFileDialog SaveFile = new SaveFileDialog();

SaveFile.Filter = "PM text configuration file(*.cfg)|*.cfg"; if (SaveFile.ShowDialog() == DialogResult.OK)

{

//WriteAllText writes then closes the file.

updateConfig();

File.WriteAllText(SaveFile.FileName,configuration); }

}

(2)

{

//Read a configuration from TXT-file into string configuration.

OpenFileDialog OpenFile = new OpenFileDialog();

OpenFile.Filter = "PM text configuration file(*.cfg)|*.cfg"; if (OpenFile.ShowDialog() == DialogResult.OK)

{

//ReadAllText Opens,reads then closes the file

configuration = File.ReadAllText(OpenFile.FileName); }

//destroy previous configuration

int i = 1;

while (MyGroup[i] != null) { MyGroup[i] = null; i++; } configParser(); }

private void referencesbutton_Click(object sender, EventArgs e) {

string references = null;

references = string.Join(NewLine,

MyGroup[MyGroupBox.SelectedIndex].getRefProcessesInGroup().ToArray());

InfoBox.Text = "Group "+MyGroup[MyGroupBox.SelectedIndex].getName()+" contains"+NewLine+"the following process references: "+NewLine+references;

}

private void groupbutton_Click(object sender, EventArgs e) {

InputForm MyInputForm = new InputForm();

DialogResult dr = MyInputForm.ShowDialog(this); if (dr == DialogResult.OK)

{

groupassigned = false; int i = 0;

//Find unassigned slot in MyGroup, create new object with name from InputForm.

while (!groupassigned) {

if (MyGroup[i] == null) {

MyGroup[i] = new ProcessGroup();

MyGroup[i].setName("#"+MyInputForm.GroupName); groupassigned = true; } i++; } updateConfig(); configParser(); } }

private void MyGroupBox_SelectedIndexChanged(object sender, EventArgs e) {

//Display the processes in selected group.

MyProcessBox.DataSource =

MyGroup[MyGroupBox.SelectedIndex].getLiveProcessesInGroup(); processlabel.Text = "Processes in group: " + MyGroup[MyGroupBox.SelectedIndex].getLiveNumberofprocesses(); }

(3)

//getInfo

getInfo();

//Initiate dragdrop-event.

int indexOfItem = MyProcessBox.IndexFromPoint(e.X, e.Y);

if (indexOfItem >= 0 && indexOfItem < MyProcessBox.Items.Count) //check we clicked down on a string

{

MyProcessBox.DoDragDrop(MyProcessBox.Items[indexOfItem], DragDropEffects.Copy);

} }

private void MyGroupBox_DragEnter(object sender, DragEventArgs e) {

//Allow moving Strings, not pics and so and set appropriate effect.

if (e.Data.GetDataPresent(DataFormats.StringFormat) && (e.AllowedEffect == DragDropEffects.Copy || e.AllowedEffect == DragDropEffects.Move))

e.Effect = DragDropEffects.Copy; else

e.Effect = DragDropEffects.Move; //eller None?

}

private void MyGroupBox_DragDrop(object sender, DragEventArgs e) {

//Determine where process will be dropped.

int indexOfItemUnderMouseToDrop =

MyGroupBox.IndexFromPoint(MyGroupBox.PointToClient(new Point(e.X, e.Y)));

//Do not allow process to be dropped outside any groups or the ungrouped group(0).

if (indexOfItemUnderMouseToDrop > 0 && indexOfItemUnderMouseToDrop < MyGroupBox.Items.Count)

{

if (e.Data.GetDataPresent(DataFormats.StringFormat)) // Confirm that dropped item is still a string.

{

string name = Regex.Replace(e.Data.GetData(DataFormats.Text).ToString(),

@"\t\((.*)\)", string.Empty); MyGroup[MyGroupBox.SelectedIndex].removeRefProcess(name); MyGroup[indexOfItemUnderMouseToDrop].addRefProcess(name); updateConfig(); configParser(); } } }

private void deletebutton_Click(object sender, EventArgs e) {

//destroy group.

int i = 0;

if (MyGroupBox.SelectedIndex != 0) {

while (MyGroup[MyGroupBox.SelectedIndex + i + 1] != null) { MyGroup[MyGroupBox.SelectedIndex + i] = MyGroup[MyGroupBox.SelectedIndex + i + 1]; i++; } MyGroup[MyGroupBox.SelectedIndex + i] = null; updateConfig(); configParser(); }

(4)

private void helpbutton_Click(object sender, EventArgs e) {

displayHelp(); }

private void configParser() {

//Parse file, create groups and add predefined processes (references) to their respective processlist.

Regex _confparse = new Regex(@"^#\w*"); //MySystemProcesses.scanForProcesses();

Process[] processlist = Process.GetProcesses(); List<string> list = new List<string>();

foreach (Process theprocess in processlist) {

list.Add(theprocess.ProcessName); }

//Create default processes group for processlisting.

MyGroup[0] = new ProcessGroup();

MyGroup[0].setName("Ungrouped Processes");

MyGroup[0].setRefProcess("\'Ungrouped Processes\' never contains any references.");

string[] array = Regex.Split(configuration, NewLine); int i = 1;

foreach (string name in array) {

Match match = _confparse.Match(name); if (match.Success)

{

MyGroup[i] = new ProcessGroup(); MyGroup[i].setName(name); i++; } else { MyGroup[i - 1].addRefProcess(name); while (list.Contains(name)) {

foreach (Process theprocess in processlist) { if (theprocess.ProcessName == name) { MyGroup[i - 1].addLiveProcess(theprocess.ProcessName + "\t(" + theprocess.Id + ")"); list.Remove(name); } } } } }

foreach (string name in list) {

MyGroup[0].addLiveProcess(name); }

//Group objects and reference processlists created. The process with Id has been set for all LiveProcesses.

//Iterates over MyGroup's and create a list for MyGroupBox datasource.

(5)

for (int listitem = 0; listitem < i; listitem++) { grouplist.Add(MyGroup[listitem].getName()); } //Set DataSource. MyGroupBox.DataSource = grouplist; }

private void updateConfig() {

configuration = ""; int i = 1;

while (MyGroup[i] != null) {

configuration += MyGroup[i].getName() + NewLine; configuration += string.Join(NewLine, MyGroup[i].getRefProcessesInGroup().ToArray()); configuration += NewLine; i++; } configuration = configuration.Trim(); }

private void getInfo() {

//Format processname, removing ID and converting to lowercase.

string formatedname = Regex.Replace(MyProcessBox.SelectedItem.ToString().ToLower(), @"\t\((.*)\)", string.Empty); //Check Hash. if (cache.ContainsKey(formatedname)) { InfoBox.Text = cache[formatedname].ToString(); } else {

//Code for fetching webpage to string

string url = "http://www.processlibrary.com/directory/files/" + formatedname;

string result = null;

WebResponse response = null; StreamReader reader = null; try

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET";

response = request.GetResponse();

reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd();

//Format result with class for HTML-tags removal. It is optimized for speed.

//Then removes junk i.e. whitespaces and useless information. Run through precompiled regexp.

result = HtmlRemoval.StripTagsCharArray(result); result = HtmlRemoval.StripJunkRegexCompiled(result);

//result = Regex.Match(result, @"(?=Process name).*(?=Make sure you always use an updated antivirus and run a full scan)").Value;

}

catch (Exception ex) {

// Show error message

(6)

+ ex.Message; } finally { if (reader != null) reader.Close(); if (response != null) response.Close(); } cache.Add(formatedname, result); InfoBox.Text = result; } }

private void displayHelp() {

InfoBox.Text = "Welcome to the Process Manager!" + NewLine + "\'save/load configuration\' saves the current configuration to a file or loads a file of predefined groupings as the current configuration." + NewLine + "Press 'Scan for new processes' to update the list of currently running processes." + NewLine + "\'References for group\' displays the predefined processes for the selected group." + NewLine + NewLine + "Drag and drop processes from the process list onto a group to group your processes.";

} } }

ProcessGroup.cs

using System.Collections.Generic; namespace ProcessManager { class ProcessGroup {

//Members, groupname is used for groupBox display create list for storing processes.

string groupname;

public List<string> MyRefProcessList = new List<string>(); public List<string> MyLiveProcessList = new List<string>();

public void setName(string name) {

groupname = name; }

public string getName() {

return groupname; }

//Set all processes for group, may be used when instantiated.

public void setRefProcesses(List<string> list){ MyRefProcessList = list;

}

//Add single process to reference processlist.

public void addRefProcess(string name) {

MyRefProcessList.Add(name); }

//Remove single process from reference processlist.

public void removeRefProcess(string name) {

(7)

//set reference processlist to single string.

public void setRefProcess(string name) {

MyRefProcessList.Clear(); MyRefProcessList.Add(name); }

//Add single process to running processes processlist.

public void addLiveProcess(string name) {

MyLiveProcessList.Add(name); }

//Returns the actual running processes for the group.

public List<string> getLiveProcessesInGroup() {

return MyLiveProcessList; }

//Returns the predefined processes for the group.

public List<string> getRefProcessesInGroup() {

return MyRefProcessList; }

//Get the number of processes actually running in the group.

public int getLiveNumberofprocesses() {

return MyLiveProcessList.Count; }

//Get the number of processes defined in the group.

public int getRefNumberofprocesses() { return MyRefProcessList.Count; } } }

HtmlRemoval.cs

using System.Text.RegularExpressions; namespace ProcessManager {

// Methods to remove HTML from strings.

public static class HtmlRemoval {

// Compiled regular expression for performance,

// strips junk from stripped webpage i.e. multiple whitespace and links.

static Regex _cutBeginning = new Regex(@"^(.|\s)*?(?=(Process name\:|Application))", RegexOptions.Compiled);

static Regex _cutJunk = new Regex(@"(Recommended\: Scan your system for registry errors|As most applications store data in your system.*registry to identify hidden errors now\.|Uninstalling applications can leave registry keys that bloat your registry\. We recommend you scan your registry for fragmented and obsolete entries\.|Check Windows .*now to identify removable processes that are slowing down your computer\.)+",

RegexOptions.Compiled);

static Regex _cutWhitespaces = new Regex(@"[\t,\r,\n]+", RegexOptions.Compiled); static Regex _cutEnd = new Regex(@"(Is.*CPU intensive\?(.|\s)*)",

RegexOptions.Compiled);

/// Remove HTML from string with compiled Regex.

(8)

{

source = _cutBeginning.Replace(source, string.Empty); source = _cutEnd.Replace(source, string.Empty); source = _cutJunk.Replace(source, string.Empty);

return source = _cutWhitespaces.Replace(source, System.Environment.NewLine); }

// Remove HTML tags from string using char array.

public static string StripTagsCharArray(string source) {

char[] array = new char[source.Length]; int arrayIndex = 0;

bool inside = false;

for (int i = 0; i < source.Length; i++) {

char let = source[i]; if (let == '<') { inside = true; continue; } if (let == '>') { inside = false; continue; } if (!inside) { array[arrayIndex] = let; arrayIndex++; } }

return new string(array, 0, arrayIndex); }

References

Related documents

Computational fluid dynamics simulations is applied on the subject specific aorta in order to calculate time resolved wall shear stress distribution at the entire aortic wall

Measurement methods and investigations by constructing models for identifying the effect of geometric or kinematic errors on motion accuracy of various types multi- axis machine

Insamlingen av inspirationsmaterial kan vara både aktiv och passiv, en designer kan aktivt vara på jakt efter en bild som skall förmedla en viss känsla eller idé, men det kan även

SYSTEM OVERVIEW .....

The gramtest program reads a grammar de nition le into an MTCgrammar ob- ject. The purpose is to debug a grammar de nition le. The output of gramtest is a dump of the grammar

This study extends diffusion of innovations theory (relative advantage, complexity and compatibility) inspired by the construct of perceived ease of use from

Also, this is by no means a substitute for the textbook, which is warmly recommended: Fourier Analysis and Its Applications, by Gerald B.. He was the first math teacher I had

One answer is to look inside the company to uncover the hidden innovation potential, and to learn from those who found it before the crisis.. Amazon Web Services and C3