NullReferenceException being thrown - c#

I am a beginner in C#.NET and we were tasked to create an online banking system in which transactions and login data are stored in an array of class. Although I am slowly getting a grasp of the whole array-of-class concept, it seems that I am stuck in saving the login data to an array of class. Here is my program:
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 BankTransaction;
namespace LabExam1
{
public partial class Registration : Form
{
Transactions trans = new Transactions();
int number = 10000;
int x = 0;
const int size = 100;
Transactions[] loginData = new Transactions[size];
public void saveLoginData()
{
loginData[x].Username = trans.createUserName(txtFname.Text, txtLname.Text, txtMi.Text);
loginData[x].Password = txtPass.Text;
x++;
}
public Registration()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cboType.SelectedIndex = 0;
}
private void btnRegister_Click(object sender, EventArgs e)
{
if (txtFname.Text == "" || txtLname.Text == ""|| txtMi.Text == "" || txtPass.Text == "")
{
MessageBox.Show("Please fill up all required fields!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
if (cboType.SelectedIndex == 0)
{
number++;
loginData[x] = new Transactions();
saveLoginData();
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");
this.Hide();
Transaction tr = new Transaction();
tr.ShowDialog();
}
if (cboType.SelectedIndex == 1)
{
if (nudDeposit.Value < 2500.00m)
{
MessageBox.Show("The initial deposit for your account type is insufficient", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
number++;
loginData[x] = new Transactions();
saveLoginData();
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");
this.Hide();
Transaction tr = new Transaction();
tr.ShowDialog();
}
}
if (cboType.SelectedIndex == 2)
{
if (nudDeposit.Value < 3000.00m)
{
MessageBox.Show("The initial deposit for your account type is insufficient", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
number++;
loginData[x] = new Transactions();
saveLoginData();
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");
this.Hide();
Transaction tr = new Transaction();
tr.ShowDialog();
}
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
I am getting an error on this part which throws the nullReferenceException:
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");
Here is my class definition:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankTransaction
{
public class Transactions
{
String username, password;
#region forArrayOfClassLogin
public String Password
{
get { return password; }
set { password = value; }
}
public String Username
{
get { return username; }
set { username = value; }
}
#endregion
public String createUserName(String fname, String lname, String mi)
{
String firstString = fname[0].ToString();
String secondString = mi[0].ToString();
String thirdString = lname[0].ToString();
String uname = firstString + secondString + thirdString;
return uname;
}
public void setBalance(String type, decimal initialBalance)
{
}
public String getUserName()
{
return username;
}
public String setPassword(String pass)
{
return password = pass;
}
public String getPassword()
{
return password;
}
}
}
Any help would be greatly appreciated. Thanks in advance.

You need to use loginData[x -1] as you have increment the value of x in saveLoginData()
MessageBox.Show("Generated Username: " + loginData[x -1].Username + number + "\n" + "Please do not share this Information to anyone!");

The issue seems to be in line "x++;" in the function saveLoginData().
You are declaring the X as member level variable, with X=0.
And as you increment the value of x in "saveLoginData()" function it becomes X=1, then while trying to access the array in parent function, the value of X is 1 now, but your array does not has any value stored for that index, which results in the exception.

In saveLoginData you're doing x++ at the end,
When you refer to loginData[x].Username in your message, x is not the same as it was when you setup loginData[x] = new Transactions(); and so loginData[x] will be null at that moment.

String firstString = fname[0].ToString();
String secondString = mi[0].ToString();
String thirdString = lname[0].ToString();
insted of above line try doing
String firstString = fname;
String secondString = mi;
String thirdString = lname;
Please refer below link for more details.
http://msdn.microsoft.com/en-us/library/ms228362.aspx

loginData[x] = new Transactions();
saveLoginData();
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");
The problem here is that the call to saveLoginData() increments the value of x, so when you show the MessageBox, the you're pointing to the next element in loginData, which is uninitialized.
This is a good illustration as to why you should be wary of using global variables. It's not obvious saveLoginData would modify x, which is probably why you made the mistake in the first place.
Also, if this weren't an exercise, I would recommend using List<Transactions> instead of an array, because it makes adding elements easier; you don't have to keep track of the number of elements yourself.
Finally, this fragment appears several times in your code:
number++;
loginData[x] = new Transactions();
saveLoginData();
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");
this.Hide();
Transaction tr = new Transaction();
tr.ShowDialog();
It would be better to turn this into a method which you would then call several times.

The Think is whenever we getting null reference .. it mean that it has not memory for that ..
so debug each and every line you can find the solution for that .. otherwise before using the properties put null check condition

Related

C# page keeps sending old data

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

What is different between DCOM Identity “The interactive user” and “This user” if the username is the same (Administrator)?

I’m working on an ASP webpage that uses a Minitab DCOM object. My problem is that this DCOM object stops responding (hangs) if the Identity is set as “This User” under Component Services (DCONCNFG) but if I log into windows with the user that I used under “This User” and set the Identity as “Interactive user” everything works fine.
My question is what is different between DCOM Identity “The interactive user” and “This user” if the username is the same (Administrator)?
Mainly this webpage uses Minitab to generate graphs. Before it hangs it does generate graphs but only 5 or 6 graphs then it stops responding.
Here is the C# code incase you are wondering where it hangs:
using System;
using System.Web;
using System.Web.UI.WebControls;
using Mtb; // Minitab Library (Mtb 16.0 Type Library)
using System.IO;
using System.Data;
using System.Runtime.InteropServices;
using System.Threading;
namespace TRWebApp.TestDetails
{
public partial class TestDetails : System.Web.UI.Page
{
// MiniTab Stuff
Mtb.IApplication g_MtbApp;
Mtb.IProject g_MtbProj;
Mtb.IUserInterface g_MtbUI;
Mtb.IWorksheets g_MtbWkShts;
Mtb.ICommands g_MtbCommands;
Mtb.IOutputs g_MtbOutputs;
Mtb.IGraph g_MtbGraph;
Mtb.IOutputs g_MtbOutputs2;
Mtb.IGraph g_MtbGraph2;
int g_GraphIdx = 1;
int g_Loop = 1;
// Tests Table
enum testsTable { TestIdx, TestSeq, ParamName, LSL, USL, Units };
Tools tools = new Tools();
string g_SessionID = "";
Mtb_DataSetTableAdapters.XBarTableAdapter xbarTA = new Mtb_DataSetTableAdapters.XBarTableAdapter();
protected void Page_Init(object sender, EventArgs e)
{
g_MtbApp = new Application();
g_MtbProj = g_MtbApp.ActiveProject;
g_MtbUI = g_MtbApp.UserInterface;
g_MtbWkShts = g_MtbProj.Worksheets;
g_MtbCommands = g_MtbProj.Commands;
g_MtbUI.DisplayAlerts = false;
g_MtbUI.Interactive = false;
g_MtbUI.UserControl = false;
lblProductDesc.Text = ""; // Start with a clear variable
g_SessionID = HttpContext.Current.Session.SessionID;
string imgFolder = "Images/Mtb/";
string mtbSessionPath = Server.MapPath(ResolveUrl("~/" + imgFolder)) + g_SessionID;
Directory.CreateDirectory(mtbSessionPath);
Array.ForEach(Directory.GetFiles(mtbSessionPath), File.Delete); // Delete all the files from the directory
Session["MtbSessionPath"] = mtbSessionPath; // Store the Session Path so we can later delete it
// Add the two image columns to the grid view
GridView1.AutoGenerateColumns = false;
ImageField imgColumn = new ImageField();
imgColumn.HeaderText = "Scatterplot";
imgColumn.DataImageUrlField = "TestIdx";
imgColumn.DataImageUrlFormatString = "~\\Images\\Mtb\\" + g_SessionID + "\\{0}.GIF";
imgColumn.ControlStyle.CssClass = "MtbImgDetail";
GridView1.Columns.Add(imgColumn);
ImageField img2Column = new ImageField();
img2Column.HeaderText = "Histogram";
img2Column.DataImageUrlField = "TestIdx";
img2Column.DataImageUrlFormatString = "~\\Images\\Mtb\\" + g_SessionID + "\\H{0}.GIF";
img2Column.ControlStyle.CssClass = "MtbImgDetail";
GridView1.Columns.Add(img2Column);
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
lblErrMsg.Text = "";
// Fill dates if they are empty
if (String.IsNullOrEmpty(tbxFromDate.Text))
tbxFromDate.Text = String.Format("{0:MM/01/yy}", DateTime.Today, null, DateTime.Today);
if (String.IsNullOrEmpty(tbxToDate.Text))
tbxToDate.Text = String.Format("{0:MM/dd/yy}", DateTime.Today);
}
catch (Exception ex)
{
lblErrMsg.Text = ex.Message;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// Get the data for the parameter name
DataTable dt = xbarTA.GetXBarData(lbxProduct.SelectedValue, Convert.ToDateTime(tbxFromDate.Text), Convert.ToDateTime(tbxToDate.Text), e.Row.Cells[(int)testsTable.ParamName].Text);
// Pass the data to an object array so we can pass it to minitab
object[] data = new object[dt.Rows.Count];
object[] time = new object[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
if (tools.IsNumeric(dr["ParamValue"]))
{
data[i] = Convert.ToDouble(dr["ParamValue"]);
time[i] = i;
}
i++;
}
if (dt.Rows.Count > 1) // Do graphs with at least two measurements
{
// Only pass it to minitab if we have numeric data
if (!ReferenceEquals(data[0], null)) // if it is not null it means it has a numeric value
{
g_MtbWkShts.Item(1).Columns.Add().SetData(data);
g_MtbWkShts.Item(1).Columns.Add().SetData(time);
g_MtbWkShts.Item(1).Columns.Item(1).Name = e.Row.Cells[(int)testsTable.ParamName].Text + " (" + e.Row.Cells[(int)testsTable.Units].Text + ")";
g_MtbWkShts.Item(1).Columns.Item(2).Name = "Time";
//// H E R E
////
//// FOLLOWING LINE HANGS AFTER GENERATING 6 GRAPHS WHEN THE IDENTITY "THIS USER" IS SET
////
g_MtbProj.ExecuteCommand("Plot C1*C2;\nSymbol;\nConnect.", g_MtbWkShts.Item(1));
// Convert LSL and USL to Decimal
if (tools.IsNumeric(e.Row.Cells[(int)testsTable.LSL].Text.Trim()) && tools.IsNumeric(e.Row.Cells[(int)testsTable.USL].Text.Trim()))
{
if (Convert.ToDouble(e.Row.Cells[(int)testsTable.LSL].Text) < Convert.ToDouble(e.Row.Cells[(int)testsTable.USL].Text))
{
g_MtbProj.ExecuteCommand("Capa C1 " + dt.Rows.Count.ToString() + ";\nLspec " + e.Row.Cells[(int)testsTable.LSL].Text + ";\nUspec " + e.Row.Cells[(int)testsTable.USL].Text + ";\nPooled;\nAMR;\nUnBiased;\nOBiased;\nToler 6;\nWithin;\nOverall;\nCStat.", g_MtbWkShts.Item(1));
}
else
{
g_MtbProj.ExecuteCommand("Histogram C1;\nBar;\nDistribution;\nNormal.", g_MtbWkShts.Item(1));
}
}
else
{
g_MtbProj.ExecuteCommand("Histogram C1;\nBar;\nDistribution;\nNormal.", g_MtbWkShts.Item(1));
}
try
{
g_MtbOutputs = g_MtbCommands.Item(g_GraphIdx).Outputs;
g_GraphIdx++;
g_MtbOutputs2 = g_MtbCommands.Item(g_GraphIdx).Outputs;
g_GraphIdx++;
string graphPath = "";
if (g_MtbOutputs.Count > 0)
{
g_MtbGraph = g_MtbOutputs.Item(1).Graph;
graphPath = Server.MapPath(ResolveUrl("~/Images/Mtb/")) + g_SessionID + Path.DirectorySeparatorChar + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif";
g_MtbGraph.SaveAs(graphPath, true, MtbGraphFileTypes.GFGIF, 600, 400, 96);
}
if (g_MtbOutputs2.Count > 0)
{
g_MtbGraph2 = g_MtbOutputs2.Item(1).Graph;
graphPath = Server.MapPath(ResolveUrl("~/Images/Mtb/")) + g_SessionID + Path.DirectorySeparatorChar + "H" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif";
g_MtbGraph2.SaveAs(graphPath, true, MtbGraphFileTypes.GFGIF, 600, 400, 96);
}
}
catch (Exception ex)
{
lblErrMsg.Text = "Test Idx: " + e.Row.Cells[(int)testsTable.TestIdx].Text + " seems to have problems.<BR />Error: " + ex.Message;
}
g_MtbWkShts.Item(1).Columns.Delete(); // Delete all the columns (This line of code is needed otherwise the Mtb.exe will still running on the server side task manager
}
else
{
// Copy the No numeric image as a graph
File.Copy(Server.MapPath("~\\Images\\Mtb\\NaN.gif"), Server.MapPath("~\\Images\\Mtb\\" + g_SessionID + "\\" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif"));
File.Copy(Server.MapPath("~\\Images\\Mtb\\NaN.gif"), Server.MapPath("~\\Images\\Mtb\\" + g_SessionID + "\\H" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif"));
}
}
}
}
protected void GridView1_Unload(object sender, EventArgs e)
{
// All these lines of code are needed otherwise the Mtb.exe will not be close on the task manager (server side)
GC.Collect();
GC.WaitForPendingFinalizers();
if (g_MtbGraph != null)
Marshal.ReleaseComObject(g_MtbGraph); g_MtbGraph = null;
if (g_MtbOutputs != null)
Marshal.ReleaseComObject(g_MtbOutputs); g_MtbOutputs = null;
if (g_MtbGraph2 != null)
Marshal.ReleaseComObject(g_MtbGraph2); g_MtbGraph2 = null;
if (g_MtbOutputs2 != null)
Marshal.ReleaseComObject(g_MtbOutputs2); g_MtbOutputs2 = null;
if (g_MtbCommands != null)
Marshal.ReleaseComObject(g_MtbCommands); g_MtbCommands = null;
if (g_MtbWkShts != null)
Marshal.ReleaseComObject(g_MtbWkShts); g_MtbWkShts = null;
if (g_MtbUI != null)
Marshal.ReleaseComObject(g_MtbUI); g_MtbUI = null;
if (g_MtbProj != null)
Marshal.ReleaseComObject(g_MtbProj); g_MtbProj = null;
if (g_MtbApp != null)
{
g_MtbApp.Quit();
Marshal.ReleaseComObject(g_MtbApp); g_MtbApp = null;
}
}
}
}
I'm using:
Windows Server 2008 R2 Standard (SP 1)
IIS 7.5.7600.16385
Framework 4.0.30319
Visual Studio 2010 Version 10.0.30319.1
Minitab 16.1.0
Thank you,
Pablo
Just a guess, based on something that happened to me ages ago:
For some reason, Minitab is displaying a modal error dialog of some kind. When you configure DCOM to launch as some user (not the interactive user), the process gets its own "windows station" which is not actually visible to you as the logged in user. So there is a dialog popped up somewhere invisible, waiting for input forever, hence the hang. Why the dialog is displaying is a different matter, likely a permissions issue. Sometimes, certain parts of the registry are available or not available in different activation contexts, for example.
Thanks Jlew for the link. It helped me to solve the problem by changing a register value from “Shared Section=1024,20480,768” to “Shared Section=1024,20480,2304” (3 times bigger) on this register key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems\Windows
This value specifies a memory heap size when the user is not logged on. I guess it was not enough to handle all the MiniTab graphs.
Pablo

Reading File Records and Assigning to an Array

I'm creating a poker stats WinForm program to write player info and 8 weeks' worth of winnnings and a total winnings amount to a file and read that info to display in a form. I'm having issues reading the 8 weekly winnings amounts textboxes into my array. I receive an "Object reference not set to an instance of an object." error. I've noted in the code below where I think the error is coming from. I've included both the form code and my class code. Any ideas what I'm doing wrong? I hope I've provided enough background of the issue. Thanks in advance!!
My form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Text;
using System.Windows.Forms;
namespace PokerStats
{
public partial class FormPokerStats : Form // FormPokerStats inheriting from class Form
{
// declaring and assigning of variables needed for file read/write
const char DELIM = ',';
const string FILEPATH = #"C:\C# Project Output\";
const string FILENAME = "PokerPlayers.txt";
// declaring instances of Person, Location, and Winnings classes
Person myplayer = new Person();
Location mycasino = new Location();
Winnings mywinnings = new Winnings();
// constructing in/out FileStream/StreamReader/StreamWriter objects
static FileStream inFile = new FileStream(FILEPATH + FILENAME, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
StreamWriter writer = new StreamWriter(outFile);
static FileStream outFile = new FileStream(FILEPATH + FILENAME, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamReader reader = new StreamReader(inFile);
public FormPokerStats()
{
InitializeComponent();
}
// "Enter/Update Player" tab Enter Player button: read/assign user input, write to file, close file stream
private void buttonEnterPlayer_Click(object sender, EventArgs e)
{
// if directory does not exist, create it
if (!(Directory.Exists(FILEPATH)))
{
// create directory
Directory.CreateDirectory(FILEPATH);
}
try
{
// read user input and assign to variables; test for empty player inputs and reprompt for input, if necessary
// Player Information fields
// if any or all textboxes are left blank
if ((textBoxSSN.Text == String.Empty || textBoxFirstName.Text == String.Empty || textBoxLastName.Text == String.Empty
|| textBoxCasinoName.Text == String.Empty || textBoxCasinoState.Text == String.Empty) ||
(textBoxSSN.Text == String.Empty && textBoxFirstName.Text == String.Empty && textBoxLastName.Text == String.Empty
&& textBoxCasinoName.Text == String.Empty && textBoxCasinoState.Text == String.Empty))
{
MessageBox.Show("Please complete all player information fields.", "Input Error!");
}
else
{
// if all textboxes are completed, assign to variables
myplayer.SocialSecurityNumber = textBoxSSN.Text;
myplayer.FirstName = textBoxFirstName.Text;
myplayer.LastName = textBoxLastName.Text;
mycasino.CasinoName = textBoxCasinoName.Text;
mycasino.CasinoState = textBoxCasinoState.Text;
// writing record to text file
writer.WriteLine(myplayer.ToString() + mycasino.ToString());
// if record is successfully written, display messagebox
MessageBox.Show("Wrote " + myplayer.FirstName.ToString() + ' ' + myplayer.LastName.ToString() + " to file with winnings totaling " + mywinnings.TotalWinnings.ToString("C2") + ".", "File Written");
}
***************************ERROR HERE***************************
// read weekly winnings input and assign to appropriate array position; test for empty inputs and assign default value of 0 if empty
// Week1
if (textBoxWeek1Winnings.Text == String.Empty)
{
mywinnings.ReadWinningsIntoArray("0", 0);
}
else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 0);
//// Week2
//if (textBoxWeek2Winnings.Text == String.Empty)
//{
// mywinnings.ReadWinningsIntoArray("0", 1);
//}
//else mywinnings.ReadWinningsIntoArray(textBoxWeek2Winnings.Text, 1);
//// Week3
//if (textBoxWeek3Winnings.Text == String.Empty)
//{
// mywinnings.ReadWinningsIntoArray("0", 2);
//}
//else mywinnings.ReadWinningsIntoArray(textBoxWeek3Winnings.Text, 2);
//// Week4
//if (textBoxWeek2Winnings.Text == String.Empty)
//{
// mywinnings.ReadWinningsIntoArray("0", 3);
//}
//else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 3);
//// Week5
//if (textBoxWeek2Winnings.Text == String.Empty)
//{
// mywinnings.ReadWinningsIntoArray("0", 4);
//}
//else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 4);
//// Week6
//if (textBoxWeek2Winnings.Text == String.Empty)
//{
// mywinnings.ReadWinningsIntoArray("0", 5);
//}
//else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 5);
//// Week7
//if (textBoxWeek2Winnings.Text == String.Empty)
//{
// mywinnings.ReadWinningsIntoArray("0", 6);
//}
//else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 6);
//// Week8
//if (textBoxWeek2Winnings.Text == String.Empty)
//{
// mywinnings.ReadWinningsIntoArray("0", 7);
//}
//else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 7);
//// calculate total winnings by summing WeeklyWinnings array values and assigning to TotalWinnings
//mywinnings.TotalWinnings = mywinnings.WeeklyWinnings.Sum();
}
catch (FormatException)
{
// if format exception is thrown in try, display messagebox with message
MessageBox.Show("Winnings must be entered at xx.xx (e.g. 34.56).", "Input Error!");
}
catch (Exception f)
{
// if exception is thrown in try, display messagebox with message
MessageBox.Show(f.Message, "Error!");
}
// clear form textboxes
ClearTextBoxes();
writer.Close();
}
// "Enter/Update Player" tab Exit button: closes file streams and quits the application
private void buttonExit_Click(object sender, EventArgs e)
{
// closing file streams
reader.Close();
inFile.Close();
writer.Close();
outFile.Close();
// close application
Application.Exit();
}
// "Player List" tab View Player Winnings button: read file records, display records sorted by total winnings descending
private void buttonRead_Click(object sender, EventArgs e)
{
// if file exists
if (!(File.Exists(FILEPATH + FILENAME)))
{
// if file does not exist, display messagebox
MessageBox.Show("File does not exist.", "File Does Not Exist!");
}
else
{
string[] fields;
// read first record in file
string recordIn = reader.ReadLine();
listBoxOutputRecords.Items.Add("First Name\tLast Name\tCasino Name\tCasino State\tTotal Winnings\t");
while (recordIn != null)
{
// split record into array and assign
fields = recordIn.Split(DELIM);
myplayer.SocialSecurityNumber = fields[0];
myplayer.FirstName = fields[1];
myplayer.LastName = fields[2];
mycasino.CasinoName = fields[3];
mycasino.CasinoState = fields[4];
// output record to listbox
listBoxOutputRecords.Items.Add(myplayer.FirstName + "\t\t" + myplayer.LastName + "\t\t" + mycasino.CasinoName + "\t\t" + mycasino.CasinoState + "\t\t");
// read next record in file
recordIn = reader.ReadLine();
}
}
// return file position to 0
inFile.Seek(0, SeekOrigin.Begin);
}
// "Player List" tab Exit button: call buttonExit_Click method
private void buttonExit2_Click(object sender, EventArgs e)
{
// call buttonExit_Click method
buttonExit_Click(sender, e);
}
// method to clear listbox items when "Player List" tab is left
private void tabPagePlayerList_Leave(object sender, EventArgs e)
{
// clear listbox items
listBoxOutputRecords.Items.Clear();
}
// method to clear textbox controls
private void ClearTextBoxes()
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
}
}
My class code:
class Person
{
// SocialSecurityNumber, FirstName, LastName properties
public string SocialSecurityNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// overridden ToString() method to return string output
public override string ToString()
{
return (SocialSecurityNumber + ',' + FirstName + ',' + LastName + ',');
}
}
// Location class
class Location
{
// CasinoName and CasinoState properties
public string CasinoName { get; set; }
public string CasinoState { get; set; }
// overridden ToString() method to return string output
public override string ToString()
{
return (CasinoName + ',' + CasinoState + ',');
}
}
// Winnings class
class Winnings
{
double[] weeklyWinnings = new double[8];
// WeeklyWinnings and TotalWinnings properties
public double[] WeeklyWinnings { get; set; }
public double TotalWinnings { get; set; }
// overridden ToString() method to return string output
public override string ToString()
{
return ( WeeklyWinnings[0].ToString("C2") + ','
+ WeeklyWinnings[1].ToString("C2") + ','
+ WeeklyWinnings[2].ToString("C2") + ','
+ WeeklyWinnings[3].ToString("C2") + ','
+ WeeklyWinnings[4].ToString("C2") + ','
+ WeeklyWinnings[5].ToString("C2") + ','
+ WeeklyWinnings[6].ToString("C2") + ','
+ WeeklyWinnings[7].ToString("C2") + ','
+ TotalWinnings.ToString("C2"));
}
// method to read textbox winnings inputs into the array
public void ReadWinningsIntoArray(string textBoxText, int position)
{
double value;
if (double.TryParse(textBoxText, out value))
WeeklyWinnings[position] = Convert.ToDouble(value);
}
}
Is textBoxWeek1Winnings properly defined in a designer file? If not, the null is because this variable isn't defined anywhere and that is the problem.
I would think in the design view of the form you should be able to see the name of the textboxes for the winnings and this is what you haven't set correctly. In declaring a new textbox
Dotnetperls has an example that may be useful to consider for how you are coding this as I think you're missing something relatively simple here.
You can greatly simplify your code by making use of the File.ReadAllLines() and File.WriteAllLines() methods.

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

C# and Metadata File Errors

I've created my own little c# compiler using the tutorial on MSDN, and it's not working properly. I get a few errors, then I fix them, then I get new, different errors, then I fix them, etc etc.
The latest error is really confusing me.
---------------------------
---------------------------
Line number: 0, Error number: CS0006, 'Metadata file 'System.Linq.dll' could not be found;
---------------------------
OK
---------------------------
I do not know what this means.
Can somebody please explain what's going on here?
Here is my code.
MY SAMPLE C# COMPILER CODE:
using System;
namespace JTM
{
public class CSCompiler
{
protected string ot,
rt,
ss, es;
protected bool rg, cg;
public string Compile(String se, String fe, String[] rdas, String[] fs, Boolean rn)
{
System.CodeDom.Compiler.CodeDomProvider CODEPROV = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
ot =
fe;
System.CodeDom.Compiler.CompilerParameters PARAMS = new System.CodeDom.Compiler.CompilerParameters();
// Ensure the compiler generates an EXE file, not a DLL.
PARAMS.GenerateExecutable = true;
PARAMS.OutputAssembly = ot;
foreach (String ay in rdas)
{
if (ay.Contains(".dll"))
PARAMS.ReferencedAssemblies.Add(ay);
else
{
string refd = ay;
refd = refd + ".dll";
PARAMS.ReferencedAssemblies.Add(refd);
}
}
System.CodeDom.Compiler.CompilerResults rs = CODEPROV.CompileAssemblyFromFile(PARAMS, fs);
if (rs.Errors.Count > 0)
{
foreach (System.CodeDom.Compiler.CompilerError COMERR in rs.Errors)
{
es = es +
"Line number: " + COMERR.Line +
", Error number: " + COMERR.ErrorNumber +
", '" + COMERR.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
// Compilation succeeded.
es = "Compilation Succeeded.";
if (rn) System.Diagnostics.Process.Start(ot);
}
return es;
}
}
}
... And here is the app that passes the code to the above class:
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] f = { "Form1.cs", "Form1.Designer.cs", "Program.cs" };
string[] ra = { "System.dll", "System.Windows.Forms.dll", "System.Data.dll", "System.Drawing.dll", "System.Deployment.dll", "System.Xml.dll", "System.Linq.dll" };
JTS.CSCompiler CSC = new JTS.CSCompiler();
MessageBox.Show(CSC.Compile(
textBox1.Text, #"Test Application.exe", ra, f, false));
}
}
}
So, as you can see, all the using directives are there. I don't know what this error means. Any help at all is much appreciated.
Thank you
Solution:
Add this:
PARAMS.ReferencedAssemblies.Add(typeof(System.Xml.Linq.Extensions).Assembly.Location);
So the code now looks like this:
namespace JTM
{
public class CSCompiler
{
protected string ot,
rt,
ss, es;
protected bool rg, cg;
public string Compile(String se, String fe, String[] rdas, String[] fs, Boolean rn)
{
System.CodeDom.Compiler.CodeDomProvider CODEPROV = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
ot =
fe;
System.CodeDom.Compiler.CompilerParameters PARAMS = new System.CodeDom.Compiler.CompilerParameters();
// Ensure the compiler generates an EXE file, not a DLL.
PARAMS.GenerateExecutable = true;
PARAMS.OutputAssembly = ot;
PARAMS.ReferencedAssemblies.Add(typeof(System.Xml.Linq.Extensions).Assembly.Location);
foreach (String ay in rdas)
{
if (ay.Contains(".dll"))
PARAMS.ReferencedAssemblies.Add(ay);
else
{
string refd = ay;
refd = refd + ".dll";
PARAMS.ReferencedAssemblies.Add(refd);
}
}
System.CodeDom.Compiler.CompilerResults rs = CODEPROV.CompileAssemblyFromFile(PARAMS, fs);
if (rs.Errors.Count > 0)
{
foreach (System.CodeDom.Compiler.CompilerError COMERR in rs.Errors)
{
es = es +
"Line number: " + COMERR.Line +
", Error number: " + COMERR.ErrorNumber +
", '" + COMERR.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
// Compilation succeeded.
es = "Compilation Succeeded.";
if (rn) System.Diagnostics.Process.Start(ot);
}
return es;
}
}
}

Categories

Resources