I need to remove items from a list - c#

I am making a program that takes user input and populates that into a list. That part is working great. However the user needs the ability to edit or delete his/her input. I cannot figure out how to remove an item from the list. Here is the code for populating the list:
[Serializable]
class Recipient
{
public string Fname { get; set; }
public string MInit { get; set; }
public string Lname { get; set; }
public string Suffix { get; set; }
public string Amount { get; set; }
public string Message { get; set; }
public string Custom { get; set; }
public string CardType { get; set; }
} protected void btnToCart_Click(object sender, EventArgs e)
{
if (ValidateInput("Card Information"))
{ SetUI("Your Shopping Cart"); }
else
{
return;
}
Recipient recipients = new Recipient();
List<string> FName = (List<string>)ViewState["recipientList"];
List<string> MInit = (List<string>)ViewState["recipientList"];
List<string> LName = (List<string>)ViewState["recipientList"];
List<string> Suffix = (List<string>)ViewState["recipientList"];
List<string> Amount = (List<string>)ViewState["recipientList"];
List<string> Message = (List<string>)ViewState["recipientList"];
List<string> Custom = (List<string>)ViewState["recipientList"];
List<string> CardType = (List<string>)ViewState["recipientList"];
if (FName == null && MInit == null && LName == null && Suffix == null && Amount == null &&
Message == null && Custom == null && CardType == null)
{
FName = new List<string>();
MInit = new List<string>();
LName = new List<string>();
Suffix = new List<string>();
Amount = new List<string>();
Message = new List<string>();
Custom = new List<string>();
CardType = new List<string>();
}
recipients.Fname = txtFName.Text;
recipients.MInit = txtMInit.Text;
recipients.Lname = txtLName.Text;
recipients.Suffix = ddlSuffix1.SelectedItem.ToString();
recipients.Amount = txtAmount.Text;
recipients.Message = ddlMessage.SelectedItem.ToString();
recipients.Custom = txtCustom.Text;
recipients.CardType = lblImage.Text;
FName.Add(recipients.Fname);
MInit.Add(recipients.MInit);
LName.Add(recipients.Lname);
Suffix.Add(recipients.Suffix);
Amount.Add(recipients.Amount);
Message.Add(recipients.Message);
Custom.Add(recipients.Custom);
CardType.Add(recipients.CardType);
ViewState["recipientList"] = FName;
ViewState["recipientList"] = MInit;
ViewState["recipientList"] = LName;
ViewState["recipientList"] = Suffix;
ViewState["recipientList"] = Amount;
ViewState["recipientList"] = Message;
ViewState["recipientList"] = Custom;
ViewState["recipientList"] = CardType;
if (FName.Count == 1 && MInit.Count == 1 && LName.Count == 1 && Suffix.Count == 1)
{
lblCartName.Text = FName[0] + " " + MInit[0] + " " + LName[0] + " " + Suffix[0];
lnkEdit1.Visible = true;
}
if (Amount.Count == 1 && Message.Count == 1 && Custom.Count == 1)
{
lblCartAmount.Text = "$" + Amount[0] + ".00";
if (txtCustom.Text == string.Empty)
{
lblCartMessage.Text = Message[0];
}
else
{
lblCartMessage.Text = Custom[0];
}
}
Yes there is more to it but anyways, once the user clicks the next button then a summary is displayed to the user with all input information. There is also two linkbuttons on the form that gives the user the choice of editing or deleting. I have tried variations of:
FName.Remove(recipients.fname); and FName.RemoveAt(0);for example and none of these have worked. So that is my problem, any help would be greatly appreciated. Thanks

Like #rich.okelly wrote you overwrite your ViewState:
Use something like this:
List<string> FName = (List<string>)ViewState["recipientListFName"];
List<string> MInit = (List<string>)ViewState["recipientListMInit"];
List<string> LName = (List<string>)ViewState["recipientListLName"];
List<string> Suffix = (List<string>)ViewState["recipientListSuffix"];
List<string> Amount = (List<string>)ViewState["recipientListAmount"];
List<string> Message = (List<string>)ViewState["recipientListMessage"];
List<string> Custom = (List<string>)ViewState["recipientListCustom"];
List<string> CardType = (List<string>)ViewState["recipientListCardType"];

Related

Can't build the filter for AD users

I'm looking for events from changing AD on the fly. There is a single example AFAICC that everybody using. It's ok for a separated OU containing users only, but when I've set it for the entire domain, too many events occuring, so I need to filter user's only changes. Currently I have an (objectClass=*) filter for the SearchRequest method and it works fine. But when I change it to (&(objectCategory=person)(objectClass=user)) or (sAMAccountType=805306368) or anything else, I've got a runtime DirectoryOperationalException. Why?
I have try to change syntax, after that I've copy-pasted some examples I have found in the Net directly into my code, but alas.
string searchFilter = "(sAMAccountType=805306368)";
SearchRequest request = new SearchRequest(
dn, //root the search here
searchFilter, //"(objectClass=*)", // very inclusive
scope, //any scope works
null //we are interested in all attributes
);
I am using this .. This code finds the persons details by first name, middle Initial, Last name. Not sure if you are looking for this.
https://lastloop.blogspot.com/2019/07/list-of-all-active-directory-properties.html
public List<Person> FindPersonDetails(Person objPerson)
{
string lname = string.Empty, fname = string.Empty, mname = string.Empty, MSID = string.Empty;
fname = objPerson.FirstName;
lname = objPerson.LastName;
mname = objPerson.MiddleName;
MSID = objPerson.MSID;
DataTable dt = new DataTable();
dt.Columns.Add("DisplayName", typeof(string));
dt.Columns.Add("GivenName", typeof(string));
dt.Columns.Add("SurName", typeof(string));
dt.Columns.Add("MSID", typeof(string));
dt.Columns.Add("Email", typeof(string));
dt.Columns.Add("employeeid", typeof(string));
//DirectoryEntry _objDirectoryEntry;
DirectorySearcher searcher = new DirectorySearcher();
if (lname != null && lname != "")
{
if (mname != null && mname != "")
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenName={0}*)(DisplayName={1}*)(middlename={2}*))", fname, lname, mname);
else
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenName={0}*)(DisplayName={1}*))", fname, lname);
}
else if (MSID != null && MSID != "")
{
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(cn={0}))", MSID);
}
else
{
if (mname != null && mname != "")
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenName={0}*)(middlename={1}*))", fname, mname);
else
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenName={0}*))", fname);
}
SearchResultCollection allResults;
//searcher.SizeLimit = 100;
searcher.Asynchronous = true;
//searcher.ClientTimeout = TimeSpan.FromSeconds(7);
allResults = searcher.FindAll();
try
{
if (allResults.Count >= 0)
{
for (int i = 0; i < allResults.Count; i++)
{
DirectoryEntry deMembershipUser = allResults[i].GetDirectoryEntry();
deMembershipUser.RefreshCache();
dt.Rows.Add(
(string)deMembershipUser.Properties["displayname"].Value ?? "Not Available",
(string)deMembershipUser.Properties["givenName"].Value ?? "Not Available",
(string)deMembershipUser.Properties["sn"].Value ?? "Not Available",
(string)deMembershipUser.Properties["cn"].Value ?? "Not Available",
(string)deMembershipUser.Properties["mail"].Value ?? "Not Available",
(string)deMembershipUser.Properties["employeeid"].Value ?? "Not Available"
);
}
}
}
catch ()
{
}
dt.DefaultView.Sort = "DisplayName ASC";
dt = dt.DefaultView.ToTable();
List<Person> objPersonList = new List<Person>();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
Person obj = new Person();
obj.DisplayName = dr["displayname"].ToString();
//obj.GivenName = dr["givenName"].ToString();
//obj.SurName = dr["SurName"].ToString();
obj.Email = dr["Email"].ToString();
obj.MSID = dr["MSID"].ToString();
//obj.employeeid = dr["employeeid"].ToString();
objPersonList.Add(obj);
}
}
return objPersonList;
}
public class Person
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string MSID { get; set; }
public string DisplayName { get; set; }
public string Email { get; set; }
//public string employeeid { get; set; }
}

datarow filtering array with dataset c# asp net

I have this page of operators that has two tables with data from database, one table with existing operators and one table with existing users. If a user is already an operator, I want that row to be hidden in the table. Here is my code:
C#:
var userDetailsList = new List<ContactPartial>();
TellusAPI.TellusUserDetails userDetails;
var operators = _administrationSystem.GetOperatorsInformation(userId); //DataSet
var getUser = webSearch.DoSearchForNameAndNumber(userId, txtSearchForOperator.Text, false, "", "", false, false, out userDetails); //Array
if (getUser == null)
{
userDetailsList.Add(new ContactPartial(userDetails));
rptAdd.DataSource = null;
}
else
{
userDetailsList = getUser.Select(x => new ContactPartial(x)).ToList();
var dv = new DataView(operators.Tables[0]);
foreach (var Operator in userDetailsList)
{
if (!userDetailsList.Contains(Operator)) continue;
dv.RowFilter = "ID = " + Operator.Id;
}
rptAdd.DataSource = userDetailsList; //Repeater
}
Class:
/// <summary>
/// Class for converting.
/// </summary>
public class ContactPartial
{
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
public ContactPartial(TellusUserDetails tud)
{
if (tud == null)
{
return;
}
Id = tud.UserID;
FirstName = tud.FirstName;
LastName = tud.LastName;
CompanyName = tud.Organisation.Description;
Email = tud.Email;
}
public ContactPartial(TellusSearchUserInfo tsi)
{
if (tsi == null)
{
return;
}
Id = tsi.ID;
FirstName = tsi.FirstName;
LastName = tsi.LastName;
CompanyName = tsi.CompanyName;
Email = tsi.Email;
}
}
So I now compare these two and filter the rows with ID, but it still reads all rows.
foreach (var Operator in userDetailsList) ******
{
if (!userDetailsList.Contains(Operator)) continue;
dv.RowFilter = "ID = " + Operator.Id;
}
I see some problem with naming convention .. You should corretly notify what is operator and what is user details object. Don't mix them up.
foreach (var user in userDetailsList)
{
// Since dv is the one which contain operator details
if (dv.Select("ID= '" + user.Id + "'").Count > 0)
{
dv.RowFilter = "ID = " + user.Id;
}
}

How to save more values in XML

I have a textfield where user can fill in strings under each other. But how to save now the different strings. Because now it is one long string. And not seperated strings
This is the class for Serialize and Deserialize:
public class PreConditionSettings
{
[Display(Name = "PreConditionResidentsOnly", ResourceType = typeof(Resources.Entity.Product))]
public bool ResidentsOnly { get; set; }
[Display(Name = "PreConditionMinimumAge", ResourceType = typeof(Resources.Entity.Product))]
public int MinimumAge { get; set; }
[SfsHelpers.PreConditionRedirectValidation(ErrorMessageResourceType = typeof(Resources.Entity.Product), ErrorMessageResourceName="PreConditionRedirectUrlValidation")]
[Display(Name = "PreConditionRedirectUrl", ResourceType = typeof(Resources.Entity.Product))]
public string RedirectUrl { get; set; }
[Display(Name = "PreConditionIpAddress", ResourceType = typeof(Resources.Entity.Product))]
public string IpAddress { get; set; }
public PreConditionSettings() {
this.ResidentsOnly = false;
this.MinimumAge = 0;
this.RedirectUrl = null;
this.IpAddress = null;
}
internal string Serialize(EditProductModel model) {
if (this.ResidentsOnly == false && this.MinimumAge == 0)
return model.Product.AuthenticationSettings;
XElement settings = XElement.Parse(model.Product.AuthenticationSettings ?? "<settings/>");
if (settings == null || settings.Attribute("authenticationrequired") == null || settings.Attribute("authenticationrequired").Value != "true")
return model.Product.AuthenticationSettings;
settings.Add(
new XElement("preconditions",
new XElement("residentsonly", this.ResidentsOnly ? "1" : "0"),
new XElement("minimumage", this.MinimumAge),
new XElement("redirecturl", this.RedirectUrl),
new XElement("ipaddress", this.IpAddress)
)
);
return settings.ToString();
}
internal void Deserialize(EditProductModel model) {
Deserialize(model.Product);
}
internal void Deserialize(Product product) {
XElement settings = XElement.Parse(product.AuthenticationSettings ?? "<settings/>");
if (settings == null || settings.Attribute("authenticationrequired") == null || settings.Attribute("authenticationrequired").Value != "true")
return;
XElement conditions = settings.Element("preconditions");
if (conditions == null)
return;
XElement condition = conditions.Element("residentsonly");
if (condition!= null)
this.ResidentsOnly = (condition.Value == "1");
condition = conditions.Element("minimumage");
if (condition != null) {
int age = 0;
if (Int32.TryParse(condition.Value, out age))
this.MinimumAge = age;
}
condition = conditions.Element("redirecturl");
if (condition != null) {
this.RedirectUrl = condition.Value;
}
condition = conditions.Element("ipaddress");
if (condition != null) {
this.IpAddress = condition.Value;
}
}
And it is about the propertie: IpAddress. The output of this is:
<settings authenticationrequired="true">
<accesslevel>level10</accesslevel>
<profile>test</profile>
<preconditions>
<residentsonly>1</residentsonly>
<minimumage>55</minimumage>
<redirecturl>/page/newpage</redirecturl>
<ipaddress>88888888
999999999</ipaddress>
</preconditions>
</settings>
But you see that it is one string, and not two strings: 88888888 and 999999999.
Thank you
I try it like this:
condition = conditions.Element("ipaddress");
if (condition != null) {
string[] lines = IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
this.IpAddress = condition.Value;
}
I try it something like this:
condition = conditions.Element("ipaddress");
if (condition != null) {
string[] lines = IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string lines = string.Join("\n",condition.Value);
//this.IpAddress = condition.Value;
}
If I try this:
condition = conditions.Element("ipaddress");
if (condition != null) {
string[] lines = IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++) {
lines[i] = condition.Value.ToString();
//lines = string.Join("\n", condition.Value.ToArray());
}
//lines = string.Join("\n",condition.Value);
//this.IpAddress = condition.Value;
}
I get this error:
Object reference not set to an instance of an object.
on this line:
string[] lines = IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
You should split your string IpAddress by \n or Environment.NewLine and save as array of strings.
After your edits :
condition = conditions.Element("ipaddress");
if (condition != null) {
string[] lines = condition.Value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
this.IpAddress = new XElement("ipaddresses", lines.Select(o=> new XElement("item", o))).ToString();
}
I would recommend you to either change the property to an ICollection or create a custom type IpAddresses, implementing ICollection and custom serialization/business logic.
This would bring the following change to your xml file:
<ipaddresses>
<item>88888888</item>
<item>99999999</item>
</ipaddresses>

How to concatenate values in to a comma seperated values in c#

I am reading text file where I would like to get values based on condition. First I will take FREQ where CELLID = 639 and ISMAINBCCH=YES,that I have done now next task is I have to concatenate FREQ values in a comma separated way where CELLID=639 and ISMAINBCCH=NO, so the output I want is 24,28,67. How to achieve that?
lines are
ADD GCELL:CELLID=639, CELLNAME="NR_0702_07021_G1_A", MCC="424", MNC="02", LAC=6112, CI=7021, NCC=6, BCC=0, EXTTP=Normal_cell, IUOTP=Concentric_cell, ENIUO=ON, DBFREQBCCHIUO=Extra, FLEXMAIO=OFF, CSVSP=3, CSDSP=5, PSHPSP=4, PSLPSVP=6, BSPBCCHBLKS=1, BSPAGBLKSRES=4, BSPRACHBLKS=1, TYPE=GSM900_DCS1800,
......................
.............
ADD GTRX:TRXID=0, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-0", FREQ=81, TRXNO=0, CELLID=639, IDTYPE=BYID, ISMAINBCCH=YES, ISTMPTRX=NO, GTRXGROUPID=2556;
ADD GTRX:TRXID=1, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-1", FREQ=24, TRXNO=1, CELLID=639, IDTYPE=BYID, ISMAINBCCH=NO, ISTMPTRX=NO, GTRXGROUPID=2556;
ADD GTRX:TRXID=5, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-2", FREQ=28, TRXNO=2, CELLID=639, IDTYPE=BYID, ISMAINBCCH=NO, ISTMPTRX=NO, GTRXGROUPID=2556;
ADD GTRX:TRXID=6, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-3", FREQ=67, TRXNO=3, CELLID=639, IDTYPE=BYID, ISMAINBCCH=NO, ISTMPTRX=NO, GTRXGROUPID=2556;
Update
I am getting values like shown below
using (StreamReader sr = File.OpenText(filename))
{
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("ADD GCELL:"))
{
var gtrx = new Gtrx
{
CellId = int.Parse(PullValue(s, "CELLID")),
Freq = int.Parse(PullValue(s, "FREQ")),
TrxNo = int.Parse(PullValue(s, "TRXNO")),
IsMainBcch = PullValue(s, "ISMAINBCCH").ToUpper() == "YES",
TrxName = PullValue(s, "TRXNAME"),
};
}
}
UPDATE
I used facade concept, but now it is taking lot of time. I am not sure whether I am using any bad logic two times I am iterating text file one for getting regular values and other for getting concatenated values
private class Gtrx
{
public int Freq { get; set; }
public int TrxNo { get; set; }
public string TrxName { get; set; }
public int CellId { get; set; }
public bool IsMainBcch { get; set; }
}
private class Gcell
{
public int CellId { get; set; }
public string CellName { get; set; }
public string Mcc { get; set; }
public int Lac { get; set; }
public int Ci { get; set; }
}
private class GcellGtrx
{
public Gcell Gcell { get; set; }
public Gtrx Gtrx { get; set; }
}
using (var sr = new StringReader(data))
{
string line = sr.ReadLine();
while (line != null)
{
line = line.Trim();
if (line.StartsWith("ADD GCELL:"))
{
var gcell = new Gcell
{
CellId = int.Parse(PullValue(line, "CELLID")),
CellName = PullValue(line, "CELLNAME"),
Ci = int.Parse(PullValue(line, "CI")),
Lac = int.Parse(PullValue(line, "LAC")),
Mcc = PullValue(line, "MCC")
};
var gcellGtrx = new GcellGtrx();
gcellGtrx.Gcell = gcell;
_dictionary.Add(gcell.CellId, gcellGtrx);
}
if (line.StartsWith("ADD GTRX:"))
{
var gtrx = new Gtrx
{
CellId = int.Parse(PullValue(line, "CELLID")),
Freq = int.Parse(PullValue(line, "FREQ")),
TrxNo = int.Parse(PullValue(line, "TRXNO")),
IsMainBcch = PullValue(line, "ISMAINBCCH").ToUpper() == "YES",
DEFINED_TCH_FRQ = null,
TrxName = PullValue(line, "TRXNAME")
};
if (!intarr.Contains(gtrx.CellId))
{
if (!_dictionary.ContainsKey(gtrx.CellId))
{
// No GCell record for this id. Do something!
continue;
}
intarr.Add(gtrx.CellId);
string results = string.Empty;
var result = String.Join(",",
from ss in File.ReadLines(filename)
where ss.Contains("ADD GTRX:")
where int.Parse(PullValue(ss, "CELLID")) == gtrx.CellId
where PullValue(ss, "ISMAINBCCH").ToUpper() != "YES"
select int.Parse(PullValue(ss, "FREQ")));
results = result;
var gtrxnew = new Gtrx
{
DEFINED_TCH_FRQ = results
};
_dictionary[gtrx.CellId].Gtrx = gtrx;
}
line = sr.ReadLine();
}
}
UPDATE
Finally I did it like first I saved lines starting with ADD GTRX in to an array by using File. Readalllines and then used only that array to get concatenated string instead of storing entire text file and got some performance improvement.
If I convert my Text files that contain hundreds of thousands of lines each into xml and then retrieve data from xml file rather from text file, will it make any performance improvement? If I use datatable and dataset rather than classes here will be a performance improvement?
Create gtrxs collection to store Gtrx objects and read data from file in to gtrxs. Then you can use LINQ (ming need to add using System.Linq;) to find Gtrx objects that are matching your requirements and call Select to get list of Freq values. Once you have a list, you can simply use String.Join(",", freqValues) to build up CSV string.
var gtrxs = new List<Gtrx>();
using (StreamReader sr = File.OpenText(filename))
{
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("ADD GCELL:"))
{
var gtrx = new Gtrx
{
CellId = int.Parse(PullValue(s, "CELLID")),
Freq = int.Parse(PullValue(s, "FREQ")),
TrxNo = int.Parse(PullValue(s, "TRXNO")),
IsMainBcch = PullValue(s, "ISMAINBCCH").ToUpper() == "YES",
TrxName = PullValue(s, "TRXNAME"),
};
gtrxs.Add(gtrx);
}
}
}
IEnumerable<int> freqValues = gtrxs.Where(x => x.CellId == 639 && x.IsMainBcch == false).Select(x => x.Freq);
string result = String.Join(",", freqValues);
Does this work for you?
var result = String.Join(",",
from s in File.ReadAllLines(filename)
where s.Contains("ADD GCELL:")
where int.Parse(PullValue(s, "CELLID")) == 639
where PullValue(s, "ISMAINBCCH").ToUpper() != "YES"
select int.Parse(PullValue(s, "FREQ")));

Remove/Replace comma from CSV file when using entity framework?

I have come across this issue and I can't solve it and it's driving me insane. I've created an C# app that reads a csv file, then inserts the information into MSSQL. When I do this though, I'm getting some skewed inserts. Everything inserts fine until there is a comma within double quotes.. for example, if the Bank Name is "Capital One,Inc" it will insert 'Inc' into the next column. I have tried removing the comma's, but I'm getting the same results. I am using the entity framework to do this.. this is how my dataclass is set up.
namespace CIT
{
class RawData
{
public string Branch { get; set; }
public string Pfx { get; set; }
public string AcctNo { get; set; }
public string CustName { get; set; }
public string CtrlNo { get; set; }
public string RefNo { get; set; }
public string Days { get; set; }
public string DealNoCat { get; set; }
public string BankNameFiCat { get; set; }
public string FinMgrName { get; set; }
public string Desc { get; set; }
public string DealDateCat { get; set; }
public string SchedNo { get; set; }
public string SchedTypeDv { get; set; }
public string SchedRemarks { get; set; }
public string Amt { get; set; }
public string Src { get; set; }
public string SysDateCat { get; set; }
public string JrnlDateDv { get; set; }
public string DateY4 { get; set; }
public string DaysOut { get; set; }
public RawData(string csvString)
{
string[] citData = csvString.Replace(", ", " ").Replace(".", " ").Split(',');
try
{
Branch = citData[0].Replace("\"", "");
Pfx = citData[1].Replace("\"", "");
AcctNo = citData[2].Replace("\"", "");
CustName = citData[3].Replace("\"", "");
CtrlNo = citData[4].Replace("\"", "");
RefNo = citData[5].Replace("\"", "");
Days = citData[6].Replace("\"", "");
DealNoCat = citData[7].Replace("\"", "");
BankNameFiCat = citData[8].Replace("\"", "");
FinMgrName = citData[9].Replace("\"", "");
Desc = citData[10].Replace("\"", "");
DealDateCat = citData[11].Replace("\"", "");
SchedNo = citData[12].Replace("\"", "");
SchedTypeDv = citData[13].Replace("\"", "");
SchedRemarks = citData[14].Replace("\"", "");
Amt = citData[15].Replace("\"", "");
Src = citData[16].Replace("\"", "");
SysDateCat = citData[17].Replace("\"", "");
JrnlDateDv = citData[18].Replace("\"", "");
DateY4 = citData[19].Replace("\"", "");
DaysOut = null;
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong. " + ex.ToString());
}
}
}
}
I have also tried
BankNameFiCat = citData[8].Replace(",", " ").Replace("\"", "");
but I have no had any luck with that. I think the problem is that the comma has no spaces before or after it. It is like "Capital One,Inc" and it's like that with other bank names as well.
This is how I'm uploading the file to the list then writing it to the db..
string text = File.ReadAllText(lblFileName.Text);
string[] lines = text.Split('\n');
int total = 0, reduced = 0;
foreach (string line in lines)
{
RawData temp = new RawData(line);
total++;
if (!(temp.Branch.Length == 0 || temp.Branch == "Branch"))
{
reduced++;
data.Add(temp);
}
}
Linq/Entity
foreach (RawData rData in data)
{
tFIManager fimanag;
tBank bank;
tCustomer cust;
fimanag = (context.tFIManagers.Any(fimanager => fimanager.FIName == rData.FinMgrName) ? context.tFIManagers.Where(fimanager => fimanager.FIName == rData.FinMgrName).FirstOrDefault() : context.tFIManagers.Add(new tFIManager { FIName = rData.FinMgrName }));
bank = (context.tBanks.Any(banks => banks.BankName == rData.BankNameFiCat) ? context.tBanks.Where(banks => banks.BankName == rData.BankNameFiCat).FirstOrDefault() : context.tBanks.Add(new tBank { BankName = rData.BankNameFiCat }));
cust = (context.tCustomers.Any(custs => custs.CustomerName == rData.CustName) ? context.tCustomers.Where(custs => custs.CustomerName == rData.CustName).FirstOrDefault() : context.tCustomers.Add(new tCustomer { CustomerName = rData.CustName }));
DateTime DateY4, DealDate, SysDate, JrnlDate;
bool hasDate = DateTime.TryParse(rData.DateY4, out DateY4);
bool hasDeal = DateTime.TryParse(rData.DealDateCat, out DealDate);
bool hasSys = DateTime.TryParse(rData.SysDateCat, out SysDate);
bool hasJrnl = DateTime.TryParse(rData.JrnlDateDv, out JrnlDate);
decimal amt;
bool hasAmt = Decimal.TryParse(rData.Amt, out amt);
tContractsInTransit cit = new tContractsInTransit
{
Branch = rData.Branch,
Pfx = rData.Pfx,
AcctNo = rData.AcctNo,
CustomerID = cust.CustomerID,
CtrlNo = rData.CtrlNo,
RefNo = rData.RefNo,
Days = rData.Days,
DealNoCat = rData.DealNoCat,
BankID = bank.BankID,
FIManagerID = fimanag.FIManagerID,
Desc = rData.Desc,
DealDateCat = null,
SchedNo = rData.SchedNo,
SchedTypeDv = rData.SchedTypeDv,
SchedRemarks = rData.SchedRemarks,
Amt = hasAmt ? amt : 0,
Src = rData.Src,
SysDateCat = null,
JrnlDateDv = null,
DateY4 = null
};
if (hasDeal)
{
cit.DealDateCat = DealDate;
}
if (hasSys)
{
cit.SysDateCat = SysDate;
}
if (hasJrnl)
{
cit.JrnlDateDv = JrnlDate;
}
if (hasDate)
{
cit.DateY4 = DateY4;
}
context.tContractsInTransits.Add(cit);
context.SaveChanges();
}
context.Dispose();
I'm not sure what else to try.. I probably am just tired of looking at it at this point. Thanks in advance!
Just find commas in quotes and replace them prior to doing anything else. You could probably use the code from one of the answers in this question.
Use Microsoft.ACE.OLEDB.12.0 to read Excel file. This should solve your problem.
public static DataSet ReadFile(string file)
{
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties='text;HDR=YES;FMT=Delimited';";
string sql = "select * from " + name;
DataSet ds = null;
Using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strSql, connstring))
{
ds = new DataSet();
myCommand.Fill(ds, "table1");
}
}
return ds;
}

Categories

Resources