I'm attempting to loop through a switch in C# for a simple console application that returns data based on user input. I am new to coding. I know that the Switch works as I tested it before trying to implement my loop. But when I add the code for loop to my program I cannot get it to provide the data.
I tried taking the switch out completely and using independent If statements for each "case" but this was not working either. I'd really like to see the switch work in the loop if it's possible.
static void Main(string[] args)
{
var repeat = true;
while(repeat)
{
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string instruments = Console.ReadLine();
var action = Console.ReadLine();
if (action == instruments)
{
switch (instruments)
{
case "Jazzmaster":
string jazzmasterMake = "Fender";
string jazzmasterModel = "Jazzmaster";
string jazzmasterType = "guitar";
string jazzmasterCountry = "Japan";
int jazzmasterYear = 1997;
string jazzmasterSerial = "A019459";
string jazzmasterColor = "Sunburst";
{
Console.WriteLine("Your " + jazzmasterMake + " " + jazzmasterModel + " is a " + jazzmasterType + " made in " + jazzmasterCountry
+ " in " + jazzmasterYear + " in a " + jazzmasterColor + " color and with a serial number of " + jazzmasterSerial + ".");
}
break;
case "Jaguar":
string jaguarMake = "Fender";
string jaguarModel = "Jaguar";
string jaguarType = "guitar";
string jaguarCountry = "Japan";
int jaguarYear = 1997;
string jaguarSerial = "A035931";
string jaguarColor = "White";
{
Console.WriteLine("Your " + jaguarMake + " " + jaguarModel + " is a " + jaguarType + " made in " + jaguarCountry
+ " in " + jaguarYear + " in a " + jaguarColor + " color and with a serial number of " + jaguarSerial + ".");
}
break;
case "Stratocaster":
string stratocasterMake = "Fender";
string stratocasterModel = "Stratocaster";
string stratocasterType = "guitar";
string stratocasterCounty = "USA";
int stratocasterYear = 2018;
string stratocasterSerial = "US18004688";
string stratocasterColor = "Black";
{
Console.WriteLine("Your " + stratocasterMake + " " + stratocasterModel + " is a " + stratocasterType + " made in " + stratocasterCounty
+ " in " + stratocasterYear + " in a " + stratocasterColor + " color and with a serial number of " + stratocasterSerial + ".");
}
break;
default:
Console.WriteLine("That instrument is not in your collection.");
break;
}
}
else if (action == "Quit")
{
repeat = false;
}
}
}
}
}
Here's an alternative way of implementing your code. I post it not as a direct answer to your question, but as a way of showing an alternative to help your learning.
static void Main(string[] args)
{
Dictionary<string, Instrument> instruments = new Dictionary<string, Instrument>()
{
{ "Jazzmaster", new Instrument() { Make = "Fender", Model = "Jazzmaster", Type = "guitar", Country = "Japan", Year = 1997, Serial = "A019459", Color = "Sunburst", } },
{ "Jaguar", new Instrument() { Make = "Fender", Model = "Jaguar", Type = "guitar", Country = "Japan", Year = 1997, Serial = "A035931", Color = "White", } },
{ "Stratocaster", new Instrument() { Make = "Fender", Model = "Stratocaster", Type = "guitar", Country = "USA", Year = 2018, Serial = "US18004688", Color = "Black", } },
};
while (true)
{
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string input = Console.ReadLine();
if (input.ToLowerInvariant() == "quit")
{
break;
}
else if(instruments.ContainsKey(input))
{
Instrument instrument = instruments[input];
Console.WriteLine($"Your {instrument.Make} {instrument.Model} is a {instrument.Type} made in {instrument.Country} in {instrument.Year} in a {instrument.Color} color and with a serial number of {instrument.Serial}.");
}
else
{
Console.WriteLine("That instrument is not in your collection.");
}
}
}
public class Instrument
{
public string Make { get; init; }
public string Model { get; init; }
public string Type { get; init; }
public string Country { get; init; }
public int Year { get; init; }
public string Serial { get; init; }
public string Color { get; init; }
}
I would just remove action and instruments and the if else and just call the input you get choice, because it's what the user wants. I'm not going to recreate your whole code here, but:
static void Main(string[] args)
{
var repeat = true;
while(repeat)
{
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string choice = Console.ReadLine();
switch (choice)
{
case "Jazzmaster":
// Jazzmaster stuff
break;
case "Jaguar":
// Jaguar stuff
break;
case "Stratocaster":
// Stratocaster stuff
break;
case "Quit"
repeat = false;
break;
default:
Console.WriteLine("That instrument is not in your collection.");
break;
}
}
}
This seems much easier to understand what's going on. There are other tricks you can play to clean up your code, like creating an abstract Instrument class that overrides ToString(), to print whatever attributes you want, but that's beyond the scope of the question you've asked.
Ultimately the problem is that you're trying to get TWO inputs from your existing code.
For the code you shared, you have to to type in instrument twice to get a review. Problem is caused here:
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string instruments = Console.ReadLine();
var action = Console.ReadLine();
if (action == instruments)
Notice Console.ReadLine() is executed twice. In order to enter the if, you have to have have the two input strings that match.
Related
I am trying to print a bill of sale, it works fine for me. But I have a problem, I don't know how to make the product description appear aligned, under the cut I make to print the rest of the description on a new line.
The full description is: "Aloe Vera Coco 12 x 1500 ml"
I leave the image and the code that prints the detail.
Someone who knows iText well and tell me how to solve this detail.
Thank you all
private void SetDetalles()
{
// 1 2 3 4 5
// 12345678901234567890123456789012345678901234567890
// "Cant Descripcion 000000000 000000000"
// --------------------------------------------------
SetLineaDivisora();
string linea = "Cant Descripcion Precio Total";
SetTextoNormal(linea);
SetLineaDivisora();
int maxLenLine = 25;
string descpart = "";
foreach (DetallesPDF det in detalles)
{
string descripcion = det.Descripcion;
if (maxLenLine > descripcion.Length)
{
descpart = descripcion.PadRight(25);
descripcion = "";
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
SetTextoNormal(linea);
}
else
{
bool lflag = true;
descpart = descripcion.Substring(0, maxLenLine);
do
{
if (lflag)
{
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
descripcion = descripcion.Substring(maxLenLine);
lflag = false;
}
else
{
descpart = descripcion.Substring(0);
linea = $" {descpart}"; // --> Add 5 blanks so it will be aligned, but the line break shows it on the left side.
descripcion = descripcion.Replace(descpart, "");
}
SetTextoNormal(linea);
}
while (descripcion.Trim().Length > 0);
}
}
SetLineaDivisora();
}
Function that generates the sale detail item
private void SetTextoNormal(string linea, float separacion = 0.2f, bool centrado = false)
{
Paragraph header = new Paragraph(linea)
//.SetTextAlignment(TextAlignment.LEFT)
.SetMultipliedLeading(separacion)
.SetFontSize(7)
.SetFont(currierNew);
if (centrado)
header.SetTextAlignment(TextAlignment.CENTER);
miDocumento.Add(header);
}
I have an API that loops through addresses and cleanses them. I am testing it with about 40k addresses, and it takes several hours to loop through thousands of them. Sometimes it throws an error and closes out the application and I have to start it over. Is there a way that I can write in error handling into the catch, that if there is an error, it will just log it, but continue running the app?
I am using VS 2019, C#, Windows Forms.
public class Elements
{
public string streetaddress1 { get; set; }
public string streetaddress2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public string country { get; set; }
}
void Output(string strDebugText)
{
try
{
System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
txtResponse.SelectionStart = txtResponse.TextLength;
txtResponse.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
private void btnMultiple_Click(object sender, EventArgs e)
{
//Loads address that need to be cleansed
string filePath = #"C:data.csv";
List<Elements> addresses = new List<Elements>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split(',');
Elements newElement = new Elements();
newElement.streetaddress1 = entries[0];
newElement.streetaddress2 = entries[1];
newElement.city = entries[2];
newElement.state = entries[3];
newElement.zip = entries[4];
addresses.Add(newElement);
}
foreach (var Element in addresses)
{
Output($"{ Element.streetaddress1 } { Element.city} { Element.state } { Element.zip } " +
$"{ Element.country }");
var venvMulti = new AreaLookup.VertexEnvelope();
var clientMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqMulti = new AreaLookup.TaxAreaRequestType();
var reqresMulti = new AreaLookup.TaxAreaResultType();
var resMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLMulti;
string outputXMLMulti;
var TALMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateMulti = new DateTime();
var resTypeMulti = new AreaLookup.TaxAreaLookupResultType();
var postalMulti = new AreaLookup.PostalAddressType();
string StrNoteMulti = "";
int i, y;
var x = default(int);
postalMulti.MainDivision = Element.state;
postalMulti.City = Element.city;
postalMulti.PostalCode = Element.zip;
postalMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateMulti = Conversions.ToDate("2020-12-11");
TALMulti.asOfDate = TALasofDateMulti;
TALMulti.Item = postalMulti;
reqMulti.TaxAreaLookup = TALMulti;
var LITMulti = new AreaLookup.LoginType();
venvMulti.Login = new AreaLookup.LoginType();
venvMulti.Login.UserName = "****";
venvMulti.Login.Password = "****";
venvMulti.Item = reqMulti;
inputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(inputXMLMulti);
try
{
clientMulti.LookupTaxAreas90(ref venvMulti);
resMulti = (AreaLookup.TaxAreaResponseType)venvMulti.Item;
outputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(outputXMLMulti);
var loopTo = resMulti.TaxAreaResult.Length - 1;
}
catch (NullReferenceException)
{
Console.WriteLine("Null");
}
reqMulti = default;
reqresMulti = default;
resMulti = default;
void debugOutputCleansedMulti(string strDebugTextCleansedMulti)
{
try
{
System.Diagnostics.Debug.Write(strDebugTextCleansedMulti + Environment.NewLine);
txtCleansed.Text = txtCleansed.Text + strDebugTextCleansedMulti + Environment.NewLine;
txtCleansed.SelectionStart = txtCleansed.TextLength;
txtCleansed.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
debugOutputCleansedMulti("Address Cleanse Started: ");
var venvCleansedMulti = new AreaLookup.VertexEnvelope();
var clientCleansedMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqCleansedMulti = new AreaLookup.TaxAreaRequestType();
var reqresCleansedMulti = new AreaLookup.TaxAreaResultType();
var resCleansedMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLCleansedMulti;
string outputXMLCleansedMulti;
var TALCleansedMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateCleansedMulti = new DateTime();
var resTypeCleansedMulti = new AreaLookup.TaxAreaLookupResultType();
var postalCleansedMulti = new AreaLookup.PostalAddressType();
string StrNoteCleansedMulti = "";
int a, b;
var c = default(int);
postalCleansedMulti.MainDivision = Element.state;
postalCleansedMulti.City = Element.city;
postalCleansedMulti.PostalCode = Element.zip;
postalCleansedMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateCleansedMulti = Conversions.ToDate("2020-12-11");
TALCleansedMulti.asOfDate = TALasofDateCleansedMulti;
TALCleansedMulti.Item = postalCleansedMulti;
reqCleansedMulti.TaxAreaLookup = TALCleansedMulti;
var LITCleansedMulti = new AreaLookup.LoginType();
venvCleansedMulti.Login = new AreaLookup.LoginType();
venvCleansedMulti.Login.UserName = "****";
venvCleansedMulti.Login.Password = "****";
venvCleansedMulti.Item = reqCleansedMulti;
int j = 1;
//inputXMLCleansed = resCleansed.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " - " + resCleansed.TaxAreaResult[0].PostalAddress[0].PostalCode + " - " + resCleansed.TaxAreaResult[0].confidenceIndicator;
//debugOutputCleansed(inputXMLCleansed);
try
{
clientCleansedMulti.LookupTaxAreas90(ref venvCleansedMulti);
resCleansedMulti = (AreaLookup.TaxAreaResponseType)venvCleansedMulti.Item;
debugOutputCleansedMulti(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " | Street Address 1" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + " | Street Address 2" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + " | County" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + " | City" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + " | Zip Code" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + " | State" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator + " | Confidence Indicator");
string pathCleansed = #"C:\dev\data\data.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].Country + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + "," +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
txtCounter.Text = j.ToString();
j++;
var loopTo = resCleansedMulti.TaxAreaResult.Length - 1;
for (b = 0; b <= loopTo; b++)
{
if (c == 0)
{
StrNoteCleansedMulti = resCleansedMulti.TaxAreaResult[b].PostalAddress[0].StreetAddress1 + " - " + resCleansedMulti.TaxAreaResult[b].confidenceIndicator; c = 1;
}
else
{
StrNoteCleansedMulti += ", " + resCleansedMulti.TaxAreaResult[b].taxAreaId + " - " + resMulti.TaxAreaResult[b].confidenceIndicator;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
reqCleansedMulti = default;
reqresCleansedMulti = default;
resCleansedMulti = default;
}
}
Essentially you need a way to save your work in progress. One pattern would be to load the file and store it in a database, then as you process each line you mark off which item you have processed. If you did this I would split the code into different modules, importing file, processing file, and exporting results.
Another simpler approach might be to write the results out as you process them, and record the line number from the input file. Then if you have to restart, find the last line you output and use that to skip reprocessing the items in your input file
So I hava a page where the user gives data for the app to send it to a database.
When the user clicks on next the app navigates to the next page. But when the user goes back and edits the data the app still saves the old data from the first input to the database.
For example:
Name : Jon Do
The user made a mistake and goes to the previous pageL
Name : John Doe
The user clicks next and the data gets saved to the database. But except of saving the new data "John Doe" it sends the old data, "Jon Do". This, ofcourse, should not happen. I have no clue why this happens.
Here is my C# code of the page where the user should give his/her data
private void btnNext_Click(object sender, RoutedEventArgs e)
{
if (ckbGegevens.IsChecked == false)
{
try
{
dt.saveData = true;
dt.bedrijfsNaam = txxBvName.Text;
dt.contactPersoon = txxContPersn.Text;
dt.telNummer = Convert.ToInt32(txxTelNr.Text);
dt.eMail = txxEMail.Text;
dt.land = txxLand.Text;
dt.plaats = txxPlaats.Text;
dt.postcode = txxPostCode.Text;
postToJson.post("bvg");
this.NavigationService.Navigate(new Doelen());
}
catch (Exception)
{
MessageBox.Show("Er ontbreken gegevens!\nOf u heeft ongeldige gegevens ingevuld!");
}
}
else
{
try {
dt.bedrijfsNaam = txxBvName.Text;
dt.contactPersoon = txxContPersn.Text;
dt.telNummer = Convert.ToInt32(txxTelNr.Text);
dt.eMail = txxEMail.Text;
dt.land = txxLand.Text;
dt.plaats = txxPlaats.Text;
dt.postcode = txxPostCode.Text;
dt.saveData = false;
MessageBox.Show("Uw gegevens worden niet opgeslagen.\nVink voor optimaal gebruik deze functie aan.");
this.NavigationService.Navigate(new Doelen());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
This is how I save it to the database:
static string bedrijfsNaam = dt.bedrijfsNaam;
static string ContPers = dt.contactPersoon;
static int TelNum = dt.telNummer;
static string email = dt.eMail;
static string Land = dt.land;
static string Plaats = dt.plaats;
static string PostCode = dt.postcode;
static string json;
static string b64encode;
public postToJson(string reqCat)
{
}
public static void post(string reqCat)
{
if (reqCat == "bvg")
{
json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
"\"ContPers\":\"" + ContPers + "\"," +
"\"TelNum\":\"" + TelNum + "\"," +
"\"email\":\"" + email + "\"," +
"\"Land\":\"" + Land + "\"," +
"\"Plaats\":\"" + Plaats + "\"," +
"\"PostCode\":\"" + PostCode + "\"}";
var b64bytes = System.Text.Encoding.UTF8.GetBytes(json);
b64encode = System.Convert.ToBase64String(b64bytes);
var data = new NameValueCollection();
data["b64string"] = b64encode;
data["filename"] = dt.bedrijfsNaam;
using (WebClient client = new WebClient())
{
var sendB64 = client.UploadValues("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST", data);
}
}
}
The problem isn't in the PHP script so I don't have to post that script. I know this because I printed out the result of the JSON. Which always has the data from the first input.
Can someone please tell me what is going on here?
The assignments seem to be done in the declaration of the static class, thereby they will only happen once and you don't know when. Therefore you should put these in a separate method:
static string bedrijfsNaam = dt.bedrijfsNaam;
static string ContPers = dt.contactPersoon;
static int TelNum = dt.telNummer;
static string email = dt.eMail;
static string Land = dt.land;
static string Plaats = dt.plaats;
static string PostCode = dt.postcode;
And then call that method in the post method.
E.g.
private static void updateData() {
bedrijfsNaam = dt.bedrijfsNaam;
ContPers = dt.contactPersoon;
TelNum = dt.telNummer;
email = dt.eMail;
Land = dt.land;
Plaats = dt.plaats;
PostCode = dt.postcode;
}
So I am trying to validate a string I received from a MySQL database but for some reason cannot access. I am sure this is a dumb question but can anyone help me out? I feel like it might be related to the public vs private and the static but after playing around with every combination I can think of to pass through the variables, it still keeps giving me errors. Any ideas?
string failReason = "";
int valid = 0;
public static void getNewRow()
{
try
{
string getNewRow = "SELECT * FROM appointments WHERE valid IS NULL";
DbConnection mysqlDB = new DbConnection();
MySqlCommand mysqlCommand = new MySqlCommand(getNewRow, mysqlDB.GetLocalMySQLConnection());
MySqlDataReader reader = mysqlCommand.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("id");
string accountID = reader.GetString("accountID");
string appDate = reader.GetString("appDate");
string appTime = reader.GetString("apptime");
string patientName = reader.GetString("patientName");
string appPhone = reader.GetString("appPhone");
string appPhone2 = reader.GetString("appPhone2");
string smsPhone = reader.GetString("smsPhone");
string special = reader.GetString("special");
string email = reader.GetString("email");
string provider = reader.GetString("provider");
string location = reader.GetString("location");
string other = reader.GetString("other");
Console.WriteLine("ID: " + id);
Console.WriteLine("AccountID: " + accountID);
Console.WriteLine("Appointment Date: " + appDate);
Console.WriteLine("Appointment Time: " + appTime);
Console.WriteLine("Patient Name: " + patientName);
Console.WriteLine("Phone 1: " + appPhone);
Console.WriteLine("Phone 2: " + appPhone2);
Console.WriteLine("SMS Phone: " + smsPhone);
Console.WriteLine("Special: " + special);
Console.WriteLine("Email: " + email);
Console.WriteLine("Provider: " + provider);
Console.WriteLine("Location: " + location);
Console.WriteLine("Other: " + other);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
private bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
private bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
patientName exists only within the scope of getNewRow. You need to make that a class-scoped variable (like you did with failReason if you want to use them anywhere outside of getNewRow. You can also pass them as parameters, but I don't see that your methods have parameters to begin with.
string patientName = reader.GetString("patientName");
is local to
public static void getNewRow()
make it as such:
static string failReason = "";
static int valid = 0;
static string patientName = string.Empty;
public static void getNewRow()
{
try
{
string getNewRow = "SELECT * FROM appointments WHERE valid IS NULL";
DbConnection mysqlDB = new DbConnection();
MySqlCommand mysqlCommand = new MySqlCommand(getNewRow, mysqlDB.GetLocalMySQLConnection());
MySqlDataReader reader = mysqlCommand.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("id");
string accountID = reader.GetString("accountID");
string appDate = reader.GetString("appDate");
string appTime = reader.GetString("apptime");
patientName = reader.GetString("patientName");
string appPhone = reader.GetString("appPhone");
string appPhone2 = reader.GetString("appPhone2");
string smsPhone = reader.GetString("smsPhone");
string special = reader.GetString("special");
string email = reader.GetString("email");
string provider = reader.GetString("provider");
string location = reader.GetString("location");
string other = reader.GetString("other");
Console.WriteLine("ID: " + id);
Console.WriteLine("AccountID: " + accountID);
Console.WriteLine("Appointment Date: " + appDate);
Console.WriteLine("Appointment Time: " + appTime);
Console.WriteLine("Patient Name: " + patientName);
Console.WriteLine("Phone 1: " + appPhone);
Console.WriteLine("Phone 2: " + appPhone2);
Console.WriteLine("SMS Phone: " + smsPhone);
Console.WriteLine("Special: " + special);
Console.WriteLine("Email: " + email);
Console.WriteLine("Provider: " + provider);
Console.WriteLine("Location: " + location);
Console.WriteLine("Other: " + other);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
private static bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
private static bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
You should decide to make all your methods static or not. You cannot call a non static method from a static method.
-- 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 ;)