Issue with checking if ID in class has changed - c#

I have a class called Line that stores bunch of information including the ID of the Line(I have a list of lines). I am writing this information in a CSV file and I want to check if the first character of my ID has changed (hopefully to a greater number). This change signifies a new folder.
Here is what I have tried:
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = 0;
if (newID != oldID)
{
oldID = newID;
return true;
}
else
{
oldID = newID;
return false;
}
}
Here is my store to csv method:
public void csvWriter (Line ln, StreamWriter stream)//Writes List to CSV
{
//some code here
if (IsNewFile(ln))
{
//MAGICAL LINE
}
else
{
//NOT MAGICAL LINE
}
stream.WriteLine(printLine);
}
here is getID()
public string getID()
{
return id;
}
With the current code I print MAGICAL LINE every time! What am I doing wrong?

You're always checking if the newID is != 0 because you always initialize oldID to 0. You should store the oldID in your Line class because as of now, setting oldID = newID will do nothing as those variables will get destroyed when the function returns its boolean.
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = ln.getOldID()[0];
if (newID != oldID)
{
ln.oldID = newID;
return true;
}
else
{
ln.oldID = newID;
return false;
}
}

I'm not sure you are giving us enough information but oldID is always 0. You need to store oldID and compare it to newID somewhere.

Related

RowUpdating Not working showing me input string is not in correct format

protected void gv_card_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int result = 0;
CreditCard prod = new CreditCard();
GridViewRow row = gv_card.Rows[e.RowIndex];
string id = gv_card.DataKeys[e.RowIndex].Value.ToString();
string tid = ((TextBox)row.Cells[0].Controls[0]).Text;
string tnumber = ((TextBox)row.Cells[1].Controls[0]).Text;
string texpirydate = ((TextBox)row.Cells[2].Controls[0]).Text;
string tcvv = ((TextBox)row.Cells[3].Controls[0]).Text;
string tcardtype = ((TextBox)row.Cells[4].Controls[0]).Text;
string tholdername = ((TextBox)row.Cells[5].Controls[0]).Text;
result = prod.CardUpdate(int.Parse(tid), tholdername, tnumber,texpirydate, int.Parse(tcvv), tcardtype );
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
gv_card.EditIndex = -1;
bind();
}
}
Above is my Code but it just cant seem to update my gridview
That message is likely coming from your call to int.Parse(string), which expects the string to be a valid integer. To handle this, you can instead use int.TryParse(string, out int), which will return true or false if it is able to parse the string. If it's successful, the out parameter will contain the parsed integer value.
So you would first try to parse the integer fields. If that fails you could return an error message, and if it succeeds then you can use the integers directly in your call to CardUpdate:
int tidValue;
int tcvvValue;
if (!int.TryParse(tid, out tidValue))
{
Response.Write("<script>alert('The value specified for TID is not an integer.');</script>");
}
else if (!int.TryParse(tcvv, out tcvvValue))
{
Response.Write("<script>alert('The value specified for TCVV is not an integer.');</script>");
}
else
{
result = prod.CardUpdate(tidValue, tholdername, tnumber, texpirydate, tcvvValue, tcardtype);
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
}

Null Reference Exception when trying to store an array

So I'm trying to store fields from a text file into an array. But when I reach the line
data = record.Trim().Split('*');
I get an error saying "Object reference not set to an instance of an object."
public bool matchCustomer(string accountID, string record)
{
String[] data = new String[5];
data = null;
data = record.Trim().Split('*');
this.accountNumber = data[0];
if (accountID == this.accountNumber)
{
return true;
}
else
{
return false;
}
}
Here is where the method is called:
public bool findCustomer(string accountNumber)
{
string record = Global.currentFile.getNextRecord(ref endOfFile);
bool okay = Global.customer.matchCustomer(accountNumber, record);
return okay;
}
Here is getNextRecord:
public string getNextRecord(ref Boolean endOfFileFlag)
{
string nextRecord;
endOfFileFlag = false;
nextRecord = reader.ReadLine();
if (nextRecord == null)
{
endOfFileFlag = true;
}
else
{
recordReadCount += 1;
} // end if
return (nextRecord);
} // end getNextRecord
First, you can simplify your code by replacing:
String[] data = new String[5];
data = null;
data = record.Trim().Split('*');
with just a single line:
string[] data = record.Trim().Split('*');
This is a correct statement, because you don't know the max index (elements) of the string[] array returning by Split() function.
Second, make sure that record!=null, and also it has a string containing "*" characters used as delimiter in Split() function.
Let's look at this line of code
data = record.Trim().Split('*');
If a NullReferenceException occurred here, that means you must be calling a method on a null object. In this case, the only possible object is record.
Now we know what is null, but why is it null? Let's look at this method:
public bool findCustomer(string accountNumber)
{
string record = Global.currentFile.getNextRecord(ref endOfFile);
bool okay = Global.customer.matchCustomer(accountNumber, record);
return okay;
}
Apparently you are using the return value of getNextRecord to call matchCustomer. This means that getNextRecord must return be returning null! So let's find out why getNextRecord returns null:
public string getNextRecord(ref Boolean endOfFileFlag)
{
string nextRecord;
endOfFileFlag = false;
nextRecord = reader.ReadLine();
if (nextRecord == null)
{
endOfFileFlag = true;
}
else
{
recordReadCount += 1;
} // end if
return (nextRecord);
} // end getNextRecord
If the method return nextRecord, that means nextRecord is null. And how did you get nextRecord? reader.ReadLine!
So the ultimate reason why record is null is that reader.ReadLine is null.
To avoid this exception, you need to first check whether record is null, then call the method on it:
if (record != null) {
data = record.Trim().Split('*');
} else {
// do other stuff
}
In C# 6, this can be simplified to
data = record?.Trim().Split('*');
If record is null, data will be null too!
Also, note that this code is redundant:
String[] data = new String[5];
data = null;
You are creating a bunch of strings and then setting the array to null. What's the point? So you can just remove that, and change the next line to:
string[] data = record?.Trim().Split('*');

Show error message if string has no value

I am trying to add some validation on my code to show if there is any data or not in the database:
This is my code
public PartsRequestL SavModal(int Pk, string partNum)
{
M9Lib.Models.PartsRequest PR = new PartsRequest("new", string.Empty);
double price = 0.00;
string PartCode = PR.getAltPartCode(partNum, ref price);
PartsRequestL partListModel = _partsRequestLRepository.Get(c => c.Pk == Pk);
partListModel.PartNum = PartCode;
Save();
return partListModel;
}
getAltPartCode checks if the partNum is available in the database.
partListModel.PartNum = PartCode
"PartCode" is sometimes empty because it doesn't match the PartNum
I need a validation to show if partCode has any data then carry on as normal, if not show an error before submitting (save).
Try this:
string PartCode = PR.getAltPartCode(partNum, ref price);
if(String.IsNullOrEmpty(PartCode))
{
//do whatever needs to happen when no partcode is returned
}
if(PartCode != null)
{
PartsRequestL partListModel = _partsRequestLRepository.Get(c => c.Pk == Pk);
partListModel.PartNum = PartCode;
Save();
}

Keynotfound exception

Keynotfound exception
public int getLastUniqueID()
{
int lastID = 0;
IsolatedStorageSettings uc = IsolatedStorageSettings.ApplicationSettings;
List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];
foreach (sMedication temp in medicationList) {
lastID = temp.UniqueID;
}
return lastID;
}
It is happening on the following line:
List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];
As the error indicate that key was not found in the dictionary before accessing the value check if the key exists or not
if(uc.Contains("medicationList"))
{
// your code here
}
You're going to run into problems with that approach because, if the key "medicationList" isn't there in the retrieved Application Settings, then it'll throw an exception like you have witnessed.
Try the following:
uc.TryGetValue<List<sMedication>>("medicationList", out medicationList)
if (medicationList != null)
{
foreach(sMedication temp in medicationList)
{
lastID = temp.UniqueID;
return lastID;
}
}
else
{
// handle the key not being there
}

Reading a line from a streamreader without consuming?

Is there a way to read ahead one line to test if the next line contains specific tag data?
I'm dealing with a format that has a start tag but no end tag.
I would like to read a line add it to a structure then test the line below to make sure it not a new "node" and if it isn't keep adding if it is close off that struct and make a new one
the only solution i can think of is to have two stream readers going at the same time kinda suffling there way along lock step but that seems wastefull (if it will even work)
i need something like peek but peekline
The problem is the underlying stream may not even be seekable. If you take a look at the stream reader implementation it uses a buffer so it can implement TextReader.Peek() even if the stream is not seekable.
You could write a simple adapter that reads the next line and buffers it internally, something like this:
public class PeekableStreamReaderAdapter
{
private StreamReader Underlying;
private Queue<string> BufferedLines;
public PeekableStreamReaderAdapter(StreamReader underlying)
{
Underlying = underlying;
BufferedLines = new Queue<string>();
}
public string PeekLine()
{
string line = Underlying.ReadLine();
if (line == null)
return null;
BufferedLines.Enqueue(line);
return line;
}
public string ReadLine()
{
if (BufferedLines.Count > 0)
return BufferedLines.Dequeue();
return Underlying.ReadLine();
}
}
You could store the position accessing StreamReader.BaseStream.Position, then read the line next line, do your test, then seek to the position before you read the line:
// Peek at the next line
long peekPos = reader.BaseStream.Position;
string line = reader.ReadLine();
if (line.StartsWith("<tag start>"))
{
// This is a new tag, so we reset the position
reader.BaseStream.Seek(pos);
}
else
{
// This is part of the same node.
}
This is a lot of seeking and re-reading the same lines. Using some logic, you may be able to avoid this altogether - for instance, when you see a new tag start, close out the existing structure and start a new one - here's a basic algorithm:
SomeStructure myStructure = null;
while (!reader.EndOfStream)
{
string currentLine = reader.ReadLine();
if (currentLine.StartsWith("<tag start>"))
{
// Close out existing structure.
if (myStructure != null)
{
// Close out the existing structure.
}
// Create a new structure and add this line.
myStructure = new Structure();
// Append to myStructure.
}
else
{
// Add to the existing structure.
if (myStructure != null)
{
// Append to existing myStructure
}
else
{
// This means the first line was not part of a structure.
// Either handle this case, or throw an exception.
}
}
}
Why the difficulty? Return the next line, regardless. Check if it is a new node, if not, add it to the struct. If it is, create a new struct.
// Not exactly C# but close enough
Collection structs = new Collection();
Struct struct;
while ((line = readline()) != null)) {
if (IsNode(line)) {
if (struct != null) structs.add(struct);
struct = new Struct();
continue;
}
// Whatever processing you need to do
struct.addLine(line);
}
structs.add(struct); // Add the last one to the collection
// Use your structures here
foreach s in structs {
}
Here is what i go so far. I went more of the split route than the streamreader line by line route.
I'm sure there are a few places that are dieing to be more elegant but for right now it seems to be working.
Please let me know what you think
struct INDI
{
public string ID;
public string Name;
public string Sex;
public string BirthDay;
public bool Dead;
}
struct FAM
{
public string FamID;
public string type;
public string IndiID;
}
List<INDI> Individuals = new List<INDI>();
List<FAM> Family = new List<FAM>();
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\mostrecent.ged";
ParseGedcom(path);
}
private void ParseGedcom(string path)
{
//Open path to GED file
StreamReader SR = new StreamReader(path);
//Read entire block and then plit on 0 # for individuals and familys (no other info is needed for this instance)
string[] Holder = SR.ReadToEnd().Replace("0 #", "\u0646").Split('\u0646');
//For each new cell in the holder array look for Individuals and familys
foreach (string Node in Holder)
{
//Sub Split the string on the returns to get a true block of info
string[] SubNode = Node.Replace("\r\n", "\r").Split('\r');
//If a individual is found
if (SubNode[0].Contains("INDI"))
{
//Create new Structure
INDI I = new INDI();
//Add the ID number and remove extra formating
I.ID = SubNode[0].Replace("#", "").Replace(" INDI", "").Trim();
//Find the name remove extra formating for last name
I.Name = SubNode[FindIndexinArray(SubNode, "NAME")].Replace("1 NAME", "").Replace("/", "").Trim();
//Find Sex and remove extra formating
I.Sex = SubNode[FindIndexinArray(SubNode, "SEX")].Replace("1 SEX ", "").Trim();
//Deterine if there is a brithday -1 means no
if (FindIndexinArray(SubNode, "1 BIRT ") != -1)
{
// add birthday to Struct
I.BirthDay = SubNode[FindIndexinArray(SubNode, "1 BIRT ") + 1].Replace("2 DATE ", "").Trim();
}
// deterimin if there is a death tag will return -1 if not found
if (FindIndexinArray(SubNode, "1 DEAT ") != -1)
{
//convert Y or N to true or false ( defaults to False so no need to change unless Y is found.
if (SubNode[FindIndexinArray(SubNode, "1 DEAT ")].Replace("1 DEAT ", "").Trim() == "Y")
{
//set death
I.Dead = true;
}
}
//add the Struct to the list for later use
Individuals.Add(I);
}
// Start Family section
else if (SubNode[0].Contains("FAM"))
{
//grab Fam id from node early on to keep from doing it over and over
string FamID = SubNode[0].Replace("# FAM", "");
// Multiple children can exist for each family so this section had to be a bit more dynaimic
// Look at each line of node
foreach (string Line in SubNode)
{
// If node is HUSB
if (Line.Contains("1 HUSB "))
{
FAM F = new FAM();
F.FamID = FamID;
F.type = "PAR";
F.IndiID = Line.Replace("1 HUSB ", "").Replace("#","").Trim();
Family.Add(F);
}
//If node for Wife
else if (Line.Contains("1 WIFE "))
{
FAM F = new FAM();
F.FamID = FamID;
F.type = "PAR";
F.IndiID = Line.Replace("1 WIFE ", "").Replace("#", "").Trim();
Family.Add(F);
}
//if node for multi children
else if (Line.Contains("1 CHIL "))
{
FAM F = new FAM();
F.FamID = FamID;
F.type = "CHIL";
F.IndiID = Line.Replace("1 CHIL ", "").Replace("#", "");
Family.Add(F);
}
}
}
}
}
private int FindIndexinArray(string[] Arr, string search)
{
int Val = -1;
for (int i = 0; i < Arr.Length; i++)
{
if (Arr[i].Contains(search))
{
Val = i;
}
}
return Val;
}

Categories

Resources