Implement User Log in a Centralized Way - c#

I'm currently working on finding a way to Log UserActions/Requests. I'm inclined towards logging the details to a text file. The LOG details are organized in a tree-like (hierarchical) structure so that it is readable and shows method names in a step-by-step manner. (if a request went through several methods)
I have a sample app which works fine but it is not the way how it should be. Consider the following classes.
Node class which is the template to make a tree-like (hierarchical) structure. It has attributes such as name (method name), Time and a List type para named Children.
public class Node
{
public string Name; // method name
public DateTime Time; // time when accessed
public List<Node> Children;
public static void PrintTree(Node tree)
{
string temp = "";
List<Node> firstStack = new List<Node>();
firstStack.Add(tree);
List<List<Node>> childListStack = new List<List<Node>>();
childListStack.Add(firstStack);
while (childListStack.Count > 0)
{
List<Node> childStack = childListStack[childListStack.Count - 1];
if (childStack.Count == 0)
{
childListStack.RemoveAt(childListStack.Count - 1);
}
else
{
tree = childStack[0];
childStack.RemoveAt(0);
string indent = "";
for (int i = 0; i < childListStack.Count - 1; i++)
{
indent += (childListStack[i].Count > 0) ? "| " : " ";
}
temp = indent + "+- " + tree.Name + " (" + tree.Time + ")";
Console.WriteLine(indent + "+- " + tree.Name + " (" + tree.Time + ")");
File.AppendAllText(#"C:\Users\aimalkhan\Desktop\Log Work\Log.txt", temp + Environment.NewLine);
if (tree.Children != null)
{
if (tree.Children.Count > 0)
{
childListStack.Add(new List<Node>(tree.Children));
}
}
}
}
File.AppendAllText(#"C:\Users\aimalkhan\Desktop\Log Work\Log.txt", Environment.NewLine + "*************************************************************" + Environment.NewLine);
}
}
My sample Employee class with a sample method SetEmployeeName() having AN EXTRA parameter of NODE type for Logging purposes.
public class Employee
{
private string FirstName { get; set; }
private string LastName { get; set; }
public string SetEmployeeName(string firstName, string lastName, Node node)
{
node.Name = "Class Name: " +this.GetType().Name + ", Calling method Name: setEmployeeName()";
node.Time = DateTime.Now;
this.FirstName = firstName;
this.LastName = lastName;
return this.FirstName + " " + this.LastName;
}
public void CompleteTask(string empName, string taskName)
{
Console.WriteLine("Employee: " + empName + " is completing the task: " + taskName);
}
}
and finally this is how i'm using the aforementioned sample of Codes.
Node root = new Node();
root.Name = "ClassName: Main";
root.Time = DateTime.Now;
root.Children = new List<Node>();
Node child = new Node();
Employee emp = new Employee();
emp.SetEmployeeName("John", "D", child);
root.Children.Add(child);
Node.PrintTree(root);
This is how the output looks
Now my question is that it would really be a headache for me to pass a NODE type para every time i need a child info log. Could this be some how made centralized in any possible way? Is there a better way than this one? A little guidance would really be appreciated.

Related

Efficient method to increase "code" by 1 - HtmlAgilityPack

I'm working on an app that extracts content from a game page (example), displays it to the user in a textbox and if the user wishes to do so, he/she can save it as a .txt file or .xsl (excel spreadsheet format).
But the main problem I'm facing right now is that you have to manually change the code to "extract" data about another in-game unit.
If you open the link you'll see that I'm currently extracting the "Weapons", "Used", "Survived" and "Casualties" from the Defender side (as for now), but only 1 type of unit (more like only 1 row of that table) is being "extracted", I'm looking for a way to search "tr[1]/td[2]/span[1]" through "tr[45]/td[2]/span[1]" (even if the example page only goes until tr[16]), or maybe a way to automate it to search until it finds no data (nothing) then it would stop.
Sorry for any text mistakes, I'm not a native speaker
private void btnStart_Click(object sender, RoutedEventArgs e)
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
HtmlNodeCollection nodes = brPage.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/table[2]");
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
brContentSaver cL = new brContentSaver();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = item.SelectSingleNode("tr[16]/td[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = item.SelectSingleNode("tr[16]/td[2]/span[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Survived = item.SelectSingleNode("tr[16]/td[3]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (cL.Survived == "0")
{
cL.Casualties = cL.Used;
} else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = item.SelectSingleNode("tr[16]/td[4]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
}
ContentList.Add(cL);
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
brContent.Text = result;
}
Sorry if this sounds silly, but I'm new to programming, especially in C#.
Edit 1: I noticed that "if (cL.Survived == "0")", I was just testing stuff some stuff way earlier and I forgot to change it, but hey, it works
Edit 2: If you are wondering I'm also using this:
public class brContentSaver
{
public string Weapons
{
get;
set;
}
public string Used
{
get;
set;
}
public string Survived
{
get;
set;
}
public string Casualties
{
get;
set;
}
}
I don't have much time to write this but hope it will help if you still need. I find Linq is more handy:
private static void Run()
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
var nodes = brPage.DocumentNode.Descendants("table").Where(_ => _.Attributes["class"] != null && _.Attributes["class"].Value != null && _.Attributes["class"].Value.Contains("battleReport"));
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
if (item.Descendants("th").Any(_ => _.InnerText.Equals("Weapons")))
{
//get all tr nodes except first one (header)
var trNodes = item.Descendants("tr").Skip(1);
foreach (var node in trNodes)
{
brContentSaver cL = new brContentSaver();
var tds = node.Descendants("td").ToArray();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = tds[0].InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = tds[1].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Used))
{
cL.Used = tds[1].InnerText;
}
cL.Survived = tds[2].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Survived))
{
cL.Casualties = cL.Used;
}
else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = tds[3].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Casualties))
{
cL.Casualties = tds[3].InnerText;
}
}
ContentList.Add(cL);
}
}
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
var text = result;
}

I cannot figure out how to fix an unhandled Format Excpetion

I am trying to write a C# program using Visual Studio that reads data from a file and allow me perform various sorts on the data. I am a beginner so it took much research to figure out how to write this code: Now I get a:
Format Exception was unhandled. Input string was not in a correct
format
I am not sure where I went wrong. This is happening for the following line of code:
Candidate newrec = new Candidate(str[0], str[1], str [2], str[3], str[4], str[5], str[6], Convert.ToInt32(str[7]), str[8], str[9], str[10], str[11]);
The entire code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace Unit4IP
{
//used to sort in asceding and descending order
public struct Candidate:IComparable
{
public char[] _FirstName;
public char[] _LastName;
public char[] _Company;
public char[] _Address;
public char[] _City;
public char[] _Country;
public char[] _State;
public char[] _Phone;
public char[] _Fax;
public char[] _Email;
public char[] _Web;
public int _zip;
//for comparing objects
public int CompareTo(object obj)
{
Candidate Candidate2 = (Candidate)obj;
return _LastName.ToString().CompareTo(Candidate2._LastName.ToString());
}
//implements sorting based on assignments such as zip, lastname, etc.
public int CompareTo(Candidate Candidate2,
CandidateComparer.ComparisonType comptype)
{
if(comptype==CandidateComparer.ComparisonType.Lastname)
{
String _LName = new String(_LastName);
String LName = new String(Candidate2._LastName);
return _LName.CompareTo(LName);// Convert Character Array to String because CompareTo Works efficiently with Strings
}
else
{
return Candidate2._zip.CompareTo(_zip); // compareto values that are interchanged in descending order
}
}
//Constructor of Candidate Structure
public Candidate(string FirstName, string LastName, string Company, string Address, string City, string Country, string State, int zip, string Phone, string Fax, string Email, string Web)
{
_FirstName = new char[12];
_LastName = new char[16];
_Company = new char[32];
_Address = new char[32];
_City = new char[24];
_Country = new char[24];
_State = new char[2];
_Phone = new char[12];
_Fax = new char[12];
_Email = new char[32];
_Web = new char[42];
_FirstName = FirstName.ToCharArray();
_LastName = LastName.ToCharArray();
_Company = Company.ToCharArray();
_Address = Address.ToCharArray();
_City = City.ToCharArray();
_Country = Country.ToCharArray();
_State = State.ToCharArray();
_zip = zip;
_Phone = Phone.ToCharArray();
_Fax = Fax.ToCharArray();
_Email = Email.ToCharArray();
_Web = Web.ToCharArray();
}
//Implement IComparer Interface as nested structure
public struct CandidateComparer : IComparer
{
public enum ComparisonType
{ Lastname = 1, zip = 2 }
private ComparisonType _comparisonType;
public ComparisonType comptype
{
get { return _comparisonType; }
set { _comparisonType = value; }
}
public int Compare(object x, object y)
{
Candidate Candidate1 = (Candidate)x;
Candidate Candidate2 = (Candidate)y;
return Candidate1.CompareTo(Candidate2, _comparisonType);
}
}
}
class Program
{
static void Main(string[] args)
{
ArrayList ArrayTest = new ArrayList();
//Loading of File 'ITCO321_U4_sample_data.csv' into ArraList. File only holds values, no heading i.e. remove headings
StreamReader stream1 = File.OpenText("c:\\Users\\Cdhss\\Documents\\ITCO321_U4IP_sample_data-2.csv");
string recdata = null;
while ((recdata = stream1.ReadLine()) != null)
{
string[] str = recdata.Split(',');
Candidate newrec = new Candidate(str[0], str[1], str [2], str[3], str[4], str[5], str[6], Convert.ToInt32(str[7]), str[8], str[9], str[10], str[11]);
ArrayTest.Add(newrec);//add struct object into ArrayList
}
//Traversing of Records
Console.WriteLine("Traversing Records");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname=new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
string address=new String(Candidate1._Address);
string city=new String(Candidate1._City);
string country = new String(Candidate1._Country);
string phone = new String(Candidate1._Phone);
string fax = new String(Candidate1._Fax);
string email=new String(Candidate1._Email);
string web = new String(Candidate1._Web);
Console.WriteLine( fname + "," + lname + "," + company + "," + address + "," + city + "," + country + "," + Candidate1._zip + "," + phone + "," + fax + "," + email + "," + web);
}
Candidate.CandidateComparer comparer = new Candidate.CandidateComparer();
//Sort by Lastname in ascending order
comparer.comptype = Candidate.CandidateComparer.ComparisonType.Lastname;
ArrayTest.Sort(comparer);
Console.WriteLine("Sorting of Elements by LastName");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname = new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
Console.WriteLine("\t" + fname + "," + lname + "," + company);
}
// Data sorted in desending order of ZIP field
comparer.comptype = Candidate.CandidateComparer.ComparisonType.zip;
ArrayTest.Sort(comparer);
Console.WriteLine("Sorting of Elements by Zip");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname = new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
Console.WriteLine("\t" + fname + "," + lname + "," + company + "," + Candidate1._zip);
}
//Display Records of 'NY' State
Console.WriteLine("Display Records of NY State");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname = new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
string address = new String(Candidate1._Address);
string city = new String(Candidate1._City);
string country = new String(Candidate1._Country);
string phone = new String(Candidate1._Phone);
string fax = new String(Candidate1._Fax);
string email = new String(Candidate1._Email);
string web = new String(Candidate1._Web);
if (new String(Candidate1._State).Contains("NY"))
Console.WriteLine(fname + "," + lname + "," + company + "," + address + "," + city + "," + country + "," + Candidate1._zip + "," + phone + "," + fax + "," + email + "," + web);
}
Console.Read();
}
}
}
Your problem is in your call to Convert.ToInt32. Whatever string you are passing can't be parsed as an int.
A good solution here might be to use the some structured exception handling, either with try catch blocks or Int32.TryParse(string) for example you could do this
int intValue;
if (Int32.TryParse(str[7], out intValue))
{
//Do some thing with the int value
}
else
{
throw new Exception("Some informative error message, probably using string.Format to include the string you tried to parse");
}
TryParse returns true if the parse is successfull, false if it is not, and puts the parsed integer value in the second out parameter.
A few other comments on you code to help you out.
No one uses ArrayLists in C# anymore. Generics were introduced a long time ago, and it is almost always better, from a standpoint of both type safety and speed to use a List (Look up C# generics if you don't know what they are).
You don't need to copy the candidate properties in your foreach loop into new variables.
Give more informative variable names. Readability is the single most important quality in good code. fname should be firstName, recdata should be recievedData. Key strokes are cheap in a world with tab completion.

Pass multiple data from one function to label in C#

I have a function that retrieves multiple lines of data and I want to display them in a label. My function is as shown below.
public static string GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
}
return res;
}
So far I can only return a string which is the last line of the retrieved data. How can I retrieve all the records? I tries arraylist, but it seems that the AWS web application doesn't allow me to use arraylist. Can anyone please help me to solve this??
Return it as as a Enumberable,
List<String> Results ;
Your method would be
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = null;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
Results = new List<String>();
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}

Showing an updated list in a form

I'm designing a database to hold a list of employees which is reading from a text file.
I have two forms, the first one (frmManager) acts as a view to go through the list, which i have next and previous buttons which i scroll through the employees in the list. The other form(frmAdd), can add new employees to the List. My problem is, when i update the List<>, how can i update it in frmManager? when i add a new employee, theiir attributes get written to the text file but I have to rebuild the project to show the updated list.
file that adds employees:
public class EmployeeDB
{
public List<Employee> employees;
public static EmployeeDB instance;
public static EmployeeDB Instance
{
get
{
if (instance == null)
{
instance = new EmployeeDB();
instance.populate();
}
return instance;
}
}
public EmployeeDB()
{
employees = new List<Employee>();
}
public void populate()
{
string[] parts;
foreach (string line in File.ReadAllLines("StaffList.txt"))
{
parts = line.Split(',');
employees.Add(new Employee(parts[0], parts[1], parts[2], parts[3], int.Parse(parts[4]), int.Parse(parts[5])));
}
}
}
The employee class contains just a constructor to add their details.
the form to add new employees
public partial class frmAdd : Form
{
EmployeeDB employee;
int grade;
public frmAddEmployee()
{
employee = EmployeeDB.Instance;
InitializeComponent();
}
private void btnCreate_Click(object sender, EventArgs e)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("StaffList.txt", true);
foreach (Employee em in employee.employees) //To avoid username clashes
{
if (em.username == txtUsername.Text)
{
file.WriteLine(txtFName.Text + "," + txtLName.Text + "," + txtUsername.Text + employee.employees.Count()
+ "," + txtPassword.Text + "," + checkedButton().ToString() + ","
+ 0.ToString(), Environment.NewLine);
}
else
{
file.WriteLine(txtFName.Text + "," + txtLName.Text + "," + txtUsername.Text
+ "," + txtPassword.Text + "," + checkedButton().ToString() + ","
+ 0.ToString(), Environment.NewLine);
}
file.Close();
MessageBox.Show("Employee successfully added");
return;
}
I have tried recalling the EmployeeDB file hoping it would repopulate to no avail. Any help will be much appreciated.
You are not adding the new Employee to the list anywhere. From the code you included, you are only populating the list via populate().
I would add the new Employee to the EmployeeDB on button click. This will cause the list to be up-to-date. Then I would add a method to your EmployeeDB class that writes the file.
private void btnCreate_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
int i = employee.employees.Count();
while (employee.AsEnumerable().Select(r => r.username == username).Count() > 0)
{
username = txtUserName.Text + i++; //Makes sure you have no common usernames
}
employee.employees.Add(new Employee(){...});
employee.SaveFile(); //New method
}
I am assuming you have a string in the class Employee called username hence the r => r.username above

Display multiple content to textbox depending on which option was selected from combobox

-- EDIT --
Worth to point out. While having a problem with different homework problem I see than I am able to use separate objects as an entry (which I probably should do). This would make working on my final problem much easier. This is a problem that might be usefull for me.
I am trying to display data to text box using foreach loop. The data should be displayed coresponding to the selection of combo box. For example if I want to display PC I should see only UserName and Password and if I add another entry for example WebSite I should see previous entry in it's format and new entry with fields URL, Username, and Password. I have tried IF-statement in my previous question but didn't seem to work properly.
StringBuilder sb = new StringBuilder();
foreach (AddEntry list in addedEntry)
{
sb.AppendLine();
sb.AppendLine("URL: " + list.URL);
sb.AppendLine("Software Name: " + list.SoftwareName);
sb.AppendLine("Serial Code: " + list.SerialCode);
sb.AppendLine("User Name: " + list.UserName);
sb.AppendLine("Password: " + list.Password);
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
Regards.
StringBuilder sb = new StringBuilder();
foreach (AddEntry list in addedEntry)
{
sb.AppendLine();
if (!string.IsNullOrEmpty(list.URL))
sb.AppendLine("URL: " + list.URL);
if (!string.IsNullOrEmpty(list.SoftwareName))
sb.AppendLine("Software Name: " + list.SoftwareName);
if (!string.IsNullOrEmpty(list.SerialCode))
sb.AppendLine("Serial Code: " + list.SerialCode);
if (!string.IsNullOrEmpty(list.UserName))
sb.AppendLine("User Name: " + list.UserName);
if (!string.IsNullOrEmpty(list.Password))
sb.AppendLine("Password: " + list.Password);
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
2nd Option
Add following method to AddEntry class
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
if (!string.IsNullOrEmpty(this.URL))
sb.AppendLine("URL: " + list.URL);
if (!string.IsNullOrEmpty(this.SoftwareName))
sb.AppendLine("Software Name: " + this.SoftwareName);
if (!string.IsNullOrEmpty(this.SerialCode))
sb.AppendLine("Serial Code: " + this.SerialCode);
if (!string.IsNullOrEmpty(this.UserName))
sb.AppendLine("User Name: " + this.UserName);
if (!string.IsNullOrEmpty(this.Password))
sb.AppendLine("Password: " + this.Password);
sb.AppendLine();
return sb.ToString();
}
then you can show all the added Entry as below
StringBuilder sb = new StringBuilder();
foreach (AddEntry entry in addedEntry)
{
sb.Append(entry.ToString());
}
mainWindow.ChangeTextBox = sb.ToString();
StringBuilder sb = new StringBuilder();
foreach (AddEntry list in addedEntry)
{
sb.AppendLine();
if (!string.IsNullOrEmpty(list.URL))
sb.AppendLine("URL: " + list.URL);
if (!string.IsNullOrEmpty(list.SoftwareName))
sb.AppendLine("Software Name: " + list.SoftwareName);
if (!string.IsNullOrEmpty(list.SerialCode))
sb.AppendLine("Serial Code: " + list.SerialCode);
if (!string.IsNullOrEmpty(list.UserName))
sb.AppendLine("User Name: " + list.UserName);
if (!string.IsNullOrEmpty(list.Password))
sb.AppendLine("Password: " + list.Password);
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
Edit: I have used UnhandledException's version as it is much more legible than my solution was (and the conditional operator is generally frowned upon in most cases).
I also want to point out that your AddEntry class could be easier written using auto properties (assuming you're using .NET 3.0+).
See:
namespace Store_Passwords_and_Serial_Codes
{
class AddEntry
{
// Auto properties make this class a lot easier to read.
public string type { get; set; }
public string url { get; set; }
public string softwareName { get; set; }
public string serialCode { get; set; }
public string userName { get; set; }
public string password { get; set; }
// Non-default constructor.
public AddEntry(string type, string url, string softwareName, string serialCode, string userName, string password)
{
this.type = type;
this.url = url;
this.softwareName = softwareName;
this.serialCode = serialCode;
this.userName = userName;
this.password = password;
}
}
}
And lastly, as you have said, it's important that you don't save information for one entry type that would belong in another (for instance, you shouldn't save URL into a PC entry type, as it makes no sense to). This entire solution would probably be better off using stronger typed objects (i.e. WebPassword, PCPassword, SoftwareSerialCode, etc). These could all inherit from a base class (Entry or something to that effect) to make it easier to strongly type the list, as well.
For instance:
class Entry { }
class PCPassword : Entry
{
string userName { get; set; }
string password { get; set; }
public PCPassword(string uName, string pass)
{
this.userName = uName;
this.password = pass;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("User Name: " + this.userName);
sb.AppendLine("Password: " + this.password);
sb.AppendLine();
return sb.ToString();
}
}
You would then refer to it in your code as such:
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Making sure that type is selected.
if (cmbType.SelectedIndex != -1)
{
if (cmbType.SelectedIndex == 0)
{
if(textUserName.Text == String.Empty || textPassword.Text == String.Empty)
MessageBox.Show("Please fill all the fields!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
addedEntry.Add(new PCPassword(textUserName.Text, textPassword.Text));
MessageBox.Show("Entry was successfully added!", "Entry Added!", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearFields();
}
}
// etc, etc
// Print our items
StringBuilder sb = new StringBuilder();
foreach (Entry item in addedEntry)
{
sb.Append(item.ToString());
}
mainWindow.ChangeTextBox = sb.ToString();
}
}
Just thought I'd throw that out there ;)

Categories

Resources