I have used some code a couple times in testing and it seems to work well. Now I am working on a helper app for a game and trying to apply the same code, but it is failing. I need to know if there is some error I am overlooking. I am trying to read from an xml file and populate text boxes and combo boxes in my winform. I pull the name correctly, but the remaining attributes do not populate. Here is an example of my code:
public bool LoadChar(string _filename) //Fetches character stats from xml file and loads to the textboxes
{
try
{
_name = tbName.Text;//hero
XmlDocument doc = new XmlDocument();//hero
doc.Load(_filename);//hero
XmlNode _currNode = doc.SelectSingleNode("/Characters/Char[#name='" + _name + "']");//hero
_currNode.Attributes["st"].Value = _st;
_currNode.Attributes["dx"].Value = _dx;
_currNode.Attributes["iq"].Value = _iq;
_currNode.Attributes["ma"].Value = _ma;
_currNode.Attributes["armor"].Value = _armor;
_currNode.Attributes["hits"].Value = _hits;
_currNode.Attributes["wounds"].Value = _wounds;
_currNode.Attributes["fatigue"].Value = _fatigue;
_currNode.Attributes["attack"].Value = _attack;
_currNode.Attributes["dmgdie"].Value = _dmgdie;
_currNode.Attributes["dmgmod"].Value = _dmgmod;
_currNode.Attributes["exp"].Value = _exp;
_currNode.Attributes["description"].Value = _description;
_currNode.Attributes["equipment_money"].Value = _equipmentmoney;
_currNode.Attributes["weapons_armor"].Value = _wpnarmor;
_currNode.Attributes["talents_spells"].Value = _talentspell;
_currNode.Attributes["gender"].Value = _gender;
_currNode.Attributes["race"].Value = _race;
_currNode.Attributes["type"].Value = _type;
_currNode.Attributes["job"].Value = _job;
tbName.Text = _name;
tbSt.Text = _st;
tbDx.Text = _dx;
tbIq.Text = _iq;
tbMa.Text = _ma;
tbArmor.Text = _armor;
tbHitStop.Text = _hits;
tbWounds.Text = _wounds;
tbFatigue.Text = _fatigue;
tbAttack.Text = _attack;
tbDmgDie.Text = _dmgdie;
tbDmgMod.Text = _dmgmod;
tbExp.Text = _exp;
tbDescription.Text = _description;
tbEquipmentMoney.Text = _equipmentmoney;
tbWeaponArmor.Text = _wpnarmor;
tbTalentSpell.Text = _talentspell;
cbGender.SelectedValue = _gender;
cbRace.SelectedValue = _race;
cbType.SelectedValue = _type;
cbJob.SelectedValue = _job;
return true;
}
catch
{
return false;
}
}
Here is the xml file I am attempting to get the data from:
<?xml version="1.0" encoding="UTF-8" ?>
- <Characters>
<Char name="Conan" st="15" dx="13" iq="8" ma="10" armor="Leather" hits="2" wounds="2"
fatigue="0" attack="Great Sword" dmgdie="3" dmgmod="+2" exp="69" description="Conan is a
big enthusiastic gentleman" equipment_money="Backpack, 4 gold coins."
weapons_armor="Great Sword, Longbow." talents_spells="Killing, Maiming, Strangling,
Boxing, Florist." gender="Male" race="Human" type="Barbarian" job="Unskilled" />
</Characters>
I created the xml file by writing the textboxes and comboboxes in my form to the xml, but now I want to load a character from the xml and it is not working in this example. I do have it working in another example and I have compared the two closely together, but can not find any real differences besides this example having more and different attributes.
Note: I placed a breakpoint and the _name value pulls "Conan" but all other values are null.
I intend to refine this later at some point--just bashing it out right now.
You are not loading data from XML. To read data you need to change places like this:
public bool LoadChar(string _filename) //Fetches character stats from xml file and loads to the textboxes
{
try
{
_name = tbName.Text;//hero
XmlDocument doc = new XmlDocument();//hero
doc.Load(_filename);//hero
XmlNode _currNode = doc.SelectSingleNode("/Characters/Char[#name='" + _name + "']");//hero
//reading attributes values
_st = _currNode.Attributes["st"].Value;
_dx = _currNode.Attributes["dx"].Value;
_iq = _currNode.Attributes["iq"].Value;
_ma = _currNode.Attributes["ma"].Value;
_armor = _currNode.Attributes["armor"].Value;
_hits = _currNode.Attributes["hits"].Value;
_wounds = _currNode.Attributes["wounds"].Value;
_fatigue = _currNode.Attributes["fatigue"].Value;
_attack = _currNode.Attributes["attack"].Value;
_dmgdie = _currNode.Attributes["dmgdie"].Value;
_dmgmod = _currNode.Attributes["dmgmod"].Value;
_exp = _currNode.Attributes["exp"].Value;
_description = _currNode.Attributes["description"].Value;
_equipmentmoney = _currNode.Attributes["equipment_money"].Value;
_wpnarmor = _currNode.Attributes["weapons_armor"].Value;
_talentspell = _currNode.Attributes["talents_spells"].Value;
_gender = _currNode.Attributes["gender"].Value;
_race = _currNode.Attributes["race"].Value;
_type = _currNode.Attributes["type"].Value;
_job = _currNode.Attributes["job"].Value;
tbName.Text = _name;
tbSt.Text = _st;
tbDx.Text = _dx;
tbIq.Text = _iq;
tbMa.Text = _ma;
tbArmor.Text = _armor;
tbHitStop.Text = _hits;
tbWounds.Text = _wounds;
tbFatigue.Text = _fatigue;
tbAttack.Text = _attack;
tbDmgDie.Text = _dmgdie;
tbDmgMod.Text = _dmgmod;
tbExp.Text = _exp;
tbDescription.Text = _description;
tbEquipmentMoney.Text = _equipmentmoney;
tbWeaponArmor.Text = _wpnarmor;
tbTalentSpell.Text = _talentspell;
cbGender.SelectedValue = _gender;
cbRace.SelectedValue = _race;
cbType.SelectedValue = _type;
cbJob.SelectedValue = _job;
return true;
}
catch
{
return false;
}
}
Related
I am consuming trade and quote data with BLPAPI in C#. When I process a LAST_TRADE_PRICE_TIME_TODAY_RT like this using //blp/mktdata service and processing the SUBCRIPTION_DATA event fine except for this message element:
{MarketDataEvents = {
RT_TIME_OF_TRADE = 2022-06-23
INDICATIVE_NEAR =
IMBALANCE_BUY =
IMBALANCE_SELL =
ORDER_IMB_BUY_VOLUME =
ORDER_IMB_SELL_VOLUME =
THEO_PRICE =
IMBALANCE_INDIC_RT =
PREV_CLOSE_VALUE_REALTIME = 11737.5
TRADING_DT_REALTIME = 2022-06-24
PREV_TRADING_DT_REALTIME = 2022-06-23
PX_ASK_LME_OFFICIAL_RT =
NUM_TRADES_RT = 0
PX_OFFICIAL_AUCTION_RT =
LAST_UPDATE_BID_RT = 2022-06-23
LAST_UPDATE_ASK_RT = 2022-06-23
OFFICIAL_AUCTION_VOLUME_RT =
IN_AUCTION_RT =
TURNOVER_TODAY_REALTIME =
OFFICIAL_OPEN_AUCTION_PRICE_RT =
OFFICIAL_OPEN_AUCTION_VOLUME_RT =
OFFICIAL_CLOSE_AUCTION_PRICE_RT =
OFFICIAL_CLOSE_AUCTION_VOLUME_RT =
AUCTION_EXTENSION_RT =
BLOCK_TRADE_ACCUM_VOLUME_RT =
TOTAL_MSG_SCRAPED_OFFERS_RT =
EVENT_TIME = 22:30:00.000
VOLUME_THEO =
OPEN_YLD_TDY_RT =
HIGH_YLD_TDY_RT =
LOW_YLD_TDY_RT =
LAST_YLD_TDY =
MID_TDY =
SIZE_LAST_TRADE_TDY =
RT_PX_CHG_NET_1D = 171.75
RT_PX_CHG_PCT_1D = 1.485
OPEN_TDY =
ASK_SIZE_TDY =
BID_SIZE_TDY =
VOLUME_TDY =
LAST_PRICE_TDY =
BID_TDY =
ASK_TDY =
HIGH_TDY =
LOW_TDY =
BID_YLD_TDY =
ASK_YLD_TDY =
TIME = 2022-06-23
LAST_UPDATE_ALL_SESSIONS_RT =
PX_OPEN_ALL_WITH_SWITCHOVER_RT =
BID_ALL_SESSION_TDY_RT =
ASK_ALL_SESSION_TDY_RT =
CONTINUOUS_TRAD_CLOS_BID_PX_RT =
CONTINUOUS_TRAD_CLOS_ASK_PX_RT =
POST_CLOSING_AUCTION_BID_PX_RT =
POST_CLOSING_AUCTION_ASK_PX_RT =
LAST_TRADE_RECEIVED_TIME_RT =
PRICE_CHANGE_ON_DAY_RT = 171.75
PRICE_LAST_ASK_RT =
PRICE_LAST_BID_RT =
PRICE_HIGH_RT =
PRICE_LOW_RT =
PRICE_OPEN_RT =
LAST_TRADE_PRICE_TODAY_RT =
PREVIOUS_TOTAL_VOLUME_RT = 622197
PREVIOUS_CLOSE_ADJ_BY_GR_DVD_RT =
TIME_AUCTION_CALL_CONCLUSION_RT =
PER_TRADE_VWAP_REALTIME =
PER_TRADE_VWAP_TURNOVER_RT =
PER_TRADE_VWAP_VOLUME_RT =
OPEN_HIGH_PRICE_REALTIME =
OPEN_LOW_PRICE_REALTIME =
CLOSE_HIGH_PRICE_REALTIME =
CLOSE_LOW_PRICE_REALTIME =
EXCHANGE_FOR_PHYSICAL_VOLUME_RT =
EXCHANGE_FOR_SWAP_VOLUME_RT =
LAST_BID_TIME_TODAY_REALTIME =
LAST_ASK_TIME_TODAY_REALTIME =
LAST_MID_TIME_TODAY_REALTIME =
LAST_PRICE_TIME_TODAY_REALTIME =
LAST_TRADE_PRICE_TIME_TODAY_RT =
MINIMUM_ORDER_LIMIT_PRICE_RT =
MAXIMUM_ORDER_LIMIT_PRICE_RT =
MIN_DYNAMIC_TRADING_LIMIT_PX_RT =
MAX_DYNAMIC_TRADING_LIMIT_PX_RT =
15_SECOND_PRICE_CHANGE_RT =
1_MINUTE_PRICE_CHANGE_RT =
5_MINUTE_PRICE_CHANGE_RT =
15_MINUTE_PRICE_CHANGE_RT =
1_HOUR_PRICE_CHANGE_RT =
CIRCUIT_BREAKER_TRIG_SIGNAL_RT =
LAST_CONTINUOUS_TRADE_PRICE_RT =
DYNAMIC_TRADING_LIMITS_REF_PX_RT =
LAST_OFF_BOOK_TRADE_PRICE_RT =
CB_TRIGGER_SIGNAL_START_TIME_RT =
CB_TRIGGER_SIGNAL_END_TIME_RT =
EFFECTIVE_DATE_RT =
OPEN_TRADE_PRICE_TODAY_RT =
HIGH_TRADE_PRICE_TODAY_RT =
LOW_TRADE_PRICE_TODAY_RT =
EXCHANGE_FOR_RISK_VOLUME_RT =
BLOOMBERG_CLOSE_PRICE_TODAY_RT =
PRICE_CLOSE_CC_TODAY_RT =
SUB_SEC_TM_AUCT_CALL_CNCLSN_RT =
THEORETICAL_TIME_TODAY_RT =
ON_EXCHANGE_VOLUME_TODAY_RT =
ON_BOOK_VOLUME_TODAY_RT =
LIT_BOOK_VOLUME_TODAY_RT =
CONTINUOUS_VOLUME_TODAY_RT =
AUCTION_VOLUME_TODAY_RT =
SCHEDULED_AUCT_VOLUME_TODAY_RT =
OPENING_AUCTION_VOLUME_RT =
CLOSING_AUCTION_VOLUME_RT =
INTRADAY_AUCTION_VOLUME_TODAY_RT =
UNSCHEDULED_AUCT_VOLUME_TODAY_RT =
TRADE_LAST_CLOSE_VOLUME_TODAY_RT =
PRE_POST_AUTO_EXECTN_VOL_TDY_RT =
DARK_BOOK_VOLUME_TODAY_RT =
ON_BK_NEG_BTF_OR_CC_VOL_TDY_RT =
ODD_LOT_BOOK_VOLUME_TODAY_RT =
OFF_BOOK_VOLUME_TODAY_RT =
NEGOTIATED_VOLUME_TODAY_RT =
OFF_BK_BLOCK_OR_CC_VOLUME_TDY_RT =
OFF_BOOK_ODD_LOT_VOLUME_TODAY_RT =
OTC_VOLUME_TODAY_RT =
SYSTEMATIC_INTERNAL_VOL_TDY_RT =
REPORTED_DARK_VOLUME_TODAY_RT =
PERCENT_CHANGE_ON_DAY_TODAY_RT =
NET_CHANGE_ON_DAY_TODAY_RT =
LAST_TRADE_AM_SESSION_TODAY_RT =
OPEN_PRICE_AM_SESSION_TODAY_RT =
HIGH_PRICE_AM_SESSION_TODAY_RT =
LOW_PRICE_AM_SESSION_TODAY_RT =
VOLUME_AM_SESSION_TODAY_RT =
LAST_TRADE_PM_SESSION_TODAY_RT =
OPEN_PRICE_PM_SESSION_TODAY_RT =
HIGH_PRICE_PM_SESSION_TODAY_RT =
LOW_PRICE_PM_SESSION_TODAY_RT =
VOLUME_PM_SESSION_TODAY_RT =
EXCHANGE_VWAP_TODAY_RT =
SETTLEMENT_PRESENT_VALUE_RT =
MATURITY_CALIBRATION_RATE_RT =
MATURITY_CALIBRATION_PV_RT =
CONTRIBUTED_RECOVERY_RATE_RT =
PAR_SPREAD_BID_RT =
PAR_SPREAD_ASK_RT =
LIQUIDITY_INDICATOR_RT =
PRICE_BID_CLOSE_TODAY_RT =
PRICE_ASK_CLOSE_TODAY_RT =
OFFICIAL_CLOSE_TODAY_RT =
PREVIOUS_BLOOMBERG_CLOSE_PX_RT = 11737.5
PREVIOUS_LAST_TRADE_PRICE_RT = 11688
BLOOMBERG_SEND_TIME_RT = 2022-06-23T21:31:23.469+00:00
10_MINUTE_PRICE_CHANGE_RT =
30_MINUTE_PRICE_CHANGE_RT =
BLOOMBERG_CLOSE_PX_AM_TODAY_RT =
PERIODIC_AUCT_ON_DMD_VOL_TDY_RT =
PERIODIC_AUCT_ON_DMD_THEO_PX_RT =
CHG_NET_REG_SES_PRV_RG_SES_CL_RT =
CHG_PCT_REG_SES_PRV_RG_SES_CL_RT =
ACTUAL_TRADED_PRICE_RT =
MIN_DYNMC_BID_ORDR_LIMT_PX_RT =
MAXMM_DYNMC_BID_ORDR_LIMT_PX_RT =
MIN_DYNMC_ASK_ORDR_LIMT_PX_RT =
MAXMM_DYNMC_ASK_ORDR_LIMT_PX_RT =
MKTDATA_EVENT_TYPE = SUMMARY
MKTDATA_EVENT_SUBTYPE = NEWDAY
DELTA_AVAT_30_DAY_INTERVAL =
DELTA_AVAT_1_DAY_INTERVAL =
DELTA_AVAT_5_DAY_INTERVAL =
DELTA_AVAT_10_DAY_INTERVAL =
DELTA_AVAT_20_DAY_INTERVAL =
DELTA_AVAT_100_DAY_INTERVAL =
DELTA_AVAT_180_DAY_INTERVAL =
DELTA_ATAT_1_DAY_INTERVAL =
DELTA_ATAT_5_DAY_INTERVAL =
DELTA_ATAT_10_DAY_INTERVAL =
DELTA_ATAT_20_DAY_INTERVAL =
DELTA_ATAT_30_DAY_INTERVAL =
DELTA_ATAT_100_DAY_INTERVAL =
DELTA_ATAT_180_DAY_INTERVAL =
REALTIME_15_SEC_PRICE_PCT_CHG =
REALTIME_ONE_MIN_PRICE_PCT_CHG =
REALTIME_FIVE_MIN_PRICE_PCT_CHG =
REALTIME_15_MIN_PRICE_PCT_CHG =
REALTIME_ONE_HOUR_PRICE_PCT_CHG =
REALTIME_VOLUME_5_DAY_INTERVAL =
CURRENT_SESSION_RT = 4
IMPLIED_BID_PRICE_RT =
IMPLIED_ASK_PRICE_RT =
IMPLIED_BID_SIZE_RT =
IMPLIED_ASK_SIZE_RT =
IS_DELAYED_STREAM = false
}
}
I use this to check the datetime and emit a trade event:
if (message.HasElement(LAST_TIME))
{
if (message.GetElementAsDatetime(LAST_TIME).IsValid())
{
DateTime time = message.GetElementAsDatetime(LAST_TIME).ToSystemDateTime();
if (message.HasElement(LAST) && message.HasElement(SIZE))
{
double last = message.GetElementAsFloat64(LAST);
int last_size = message.GetElementAsInt32(SIZE);
long volume = message.GetElementAsInt64(VOLUME); ...
I receive:
'Bloomberglp.Blpapi.NotFoundException: LAST_TRADE_PRICE_TIME_TODAY_RT has no value in MarketDataUpdate.'
I have tried converting to string first and checking if empty and checking null. Any ideas would be helpful...
I don't think checking the DataType is what you want. The
DataType is part of the schema. It should always be set even when there is no value. If it seems to be working, it is possibly because the element's data type is not DATETIME. For instance, if it is of type DATE, or TIME, GetAsDateTime would still work, but the DataType will never be DATETIME—meaning the code path will never get hit. What you want to check is if it has a value.
HasElement is saying that the schema contains such an element, but if the schema definition allows for there to be zero values (optional), it might not have a value. GetValueAsDatetime() is really GetValueAsDatetime(0), meaning the 0th value which may not exist. Note the same function can be used for array type items that have more than one value. I think the correct way to check this would be:
Element lastTime = message.GetElement(LAST_TIME);
if (lastTime.NumValues > 0) {
DateTime dt = lastTime.GetValueAsDatetime();
I suspect that
if (message.HasElement(LAST_TIME))
returns true because the field is there (but empty). However when you call:
if (message.GetElementAsDatetime(LAST_TIME).IsValid())
GetElementAsDatetime throws an exception because the value (which is empty) is not a valid datetime.
I think something like this may work:
Element lastTime = message.GetElement(LAST_TIME);
if (lastTime.Datatype() == Schema.Datatype.DATETIME) {
DateTime dt = lastTime.GetValueAsDatetime();
I have section in my class that looks like this:
public Details GetTicketById(string #ref)
{
var query = "SELECT * FROM support WHERE ref = #ref";
var args = new Dictionary<string, object>
{
{"#ref", #ref}
};
DataTable dt = ExecuteRead(query, args);
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
var details = new Details
{
#ref = Convert.ToString(dt.Rows[0]["ref"]),
subject = Convert.ToString(dt.Rows[0]["subject"]),
contact_name = Convert.ToString(dt.Rows[0]["contact_name"]),
company_name = Convert.ToString(dt.Rows[0]["company_name"]),
description = Convert.ToString(dt.Rows[0]["description"]),
business_impact = Convert.ToString(dt.Rows[0]["business_impact"]),
severity = Convert.ToString(dt.Rows[0]["severity"])
};
return details;
}
I know that there is a return value when I debug.
My button in my main form looks like this:
private void Button3_Click(object sender, EventArgs e)
{
var getTicket = new ticket();
getTicket.GetTicketById("1235");
ticket.Details td = new ticket.Details();
td.#ref = txtRef.Text;
td.subject = txtSubject.Text;
td.contact_name = txtContact_Name.Text;
td.company_name = txtCompany_Name.Text;
td.description = rtDescription.Text;
td.business_impact = rtBusiness_Impact.Text;
td.severity = txtSeverity.Text;
}
Unfortunately my text boxes do not show the values from my returned data table.
Can you see why?
Your method GetTicketById() return value like you and see with debug. But you don't take this value into variable. Do this:
var details = getTicket.GetTicketById("1235");
In order to set Text property to new value do this:
txtSubject.Text = details.subject
txtContact_Name.Text = details.contact_name
txtCompany_Name.Text = details.company_name
// and so on
This line need to delete
ticket.Details td = new ticket.Details();
I want to get my linq query result back as json format. I have been searching for hours.
Here is my code :
public IEnumerable<callersW> GetAllCallersF()
{
testCDREntities1 context = this.CurrentDataSource;
var query = (
from oneCaller in CurrentDataSource.TestTables
select new
{
Created = oneCaller.Created,
Answered = oneCaller.Answered,
Destroyed = oneCaller.Destroyed,
CallerID = oneCaller.CallerId,
CalledID = oneCaller.CalledId,
DisconnectionCode = oneCaller.DisconnectionCode,
RTP_Caller_G107MOS = oneCaller.RTP_Caller_G107MOS,
RTP_Caller_LostPackets = oneCaller.RTP_Caller_LostPackets,
RTP_Caller_MaxRfc3550Jitter = oneCaller.RTP_Caller_MaxRfc3550Jitter,
RTP_Caller_MeanRfc3550Jitter = oneCaller.RTP_Caller_MeanRfc3550Jitter,
RTP_Called_G107MOS = oneCaller.RTP_Called_G107MOS,
RTP_Called_LostPackets = oneCaller.RTP_Called_LostPackets,
RTP_Called_MaxRfc3550Jitter = oneCaller.RTP_Called_MaxRfc3550Jitter,
RTP_Called_MeanRfc3550Jitter = oneCaller.RTP_Called_MeanRfc3550Jitter,
}).ToList()
.Select(x => new callersW
{
Created = Convert.ToDateTime(x.Created),
Answered = Convert.ToDateTime(x.Answered),
Destroyed = Convert.ToDateTime(x.Destroyed),
CallerID = x.CallerID,
CalledID = x.CalledID,
DisconnectionCode = Convert.ToInt32(x.DisconnectionCode),
RTP_Caller_G107MOS = Convert.ToDouble(x.RTP_Caller_G107MOS),
RTP_Caller_LostPackets = Convert.ToDouble(x.RTP_Caller_LostPackets),
RTP_Caller_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MaxRfc3550Jitter),
RTP_Caller_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MeanRfc3550Jitter),
RTP_Called_G107MOS = Convert.ToDouble(x.RTP_Called_G107MOS),
RTP_Called_LostPackets = Convert.ToDouble(x.RTP_Called_LostPackets),
RTP_Called_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MaxRfc3550Jitter),
RTP_Called_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MeanRfc3550Jitter)
}).ToList();
return query;
}
Can somebody help me with this ?
Add to your project JSON.NET and serialize object eg:
string json = JsonConvert.SerializeObject(query);
More examples here.
I'm importing records from a text file into my DB. I have it setup to check the record that I to ensure there is not already a duplicate in the database. If there is already an entry in the database it skips that record.
Now the issue I need to address is when there is not a record in the text file but there is a record in the database. I need to remove the record from the database that does not match any records in the file.
public static void ParseComplaint(string location)
{
Console.WriteLine("Parsing.....");
List<AutoMakeNoEntity> am = DBCacheHelper.GetAllMakes().ToList<AutoMakeNoEntity>();
using (var reader = new StreamReader(location))
{
foreach (string line in File.ReadLines(location))
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
var tokens = line.Trim().Split(new char[] { '\t' });
if (am.Any(c => c.MakeName == tokens[3]))
{
using (RecallsContext context = new RecallsContext())
{
string tmp = tokens[0];
if (!context.complaints.Any(c => c.CMPLID == tmp))
{
var recalls = new Complaints();
recalls.CMPLID = tokens[0];
recalls.ODINO = tokens[1];
recalls.MFR_NAME = tokens[2];
recalls.MAKETXT = tokens[3];
recalls.MODELTXT = tokens[4];
recalls.YEARTXT = tokens[5];
recalls.CRASH = tokens[6];
recalls.FAILDATE = tokens[7];
recalls.FIRE = tokens[8];
recalls.INJURED = tokens[9];
recalls.DEATHS = tokens[10];
recalls.COMPDESC = tokens[11];
recalls.CITY = tokens[12];
recalls.STATE = tokens[13];
recalls.VIN = tokens[14];
recalls.DATEA = tokens[15];
recalls.LDATE = tokens[16];
recalls.MILES = tokens[17];
recalls.OCCURENCES = tokens[18];
recalls.CDESCR = tokens[19];
recalls.CMPL_TYPE = tokens[20];
recalls.POLICE_RPT_YN = tokens[21];
recalls.PURCH_DT = tokens[22];
recalls.ORIG_OWNER_YN = tokens[23];
recalls.ANTI_BRAKES_YN = tokens[24];
recalls.CRUISE_CONT_YN = tokens[25];
recalls.NUM_CYLS = tokens[26];
recalls.DRIVE_TRAIN = tokens[27];
recalls.FUEL_SYS = tokens[28];
recalls.FUEL_TYPE = tokens[29];
recalls.TRANS_TYPE = tokens[30];
recalls.VEH_SPEED = tokens[31];
recalls.DOT = tokens[32];
recalls.TIRE_SIZE = tokens[33];
recalls.LOC_OF_TIRE = tokens[34];
recalls.TIRE_FAIL_TYPE = tokens[35];
recalls.ORIG_EQUIP_YN = tokens[36];
recalls.MANUF_DT = tokens[37];
recalls.SEAT_TYPE = tokens[38];
recalls.RESTRAINT_TYPE = tokens[39];
recalls.DEALER_NAME = tokens[40];
recalls.DEALER_TEL = tokens[41];
recalls.DEALER_CITY = tokens[42];
recalls.DEALER_STATE = tokens[43];
recalls.DEALER_ZIP = tokens[44];
recalls.PROD_TYPE = tokens[45];
if (tokens.Length == 47)
{
recalls.REPAIRED_YN = tokens[46];
}
context.complaints.Add(recalls);
context.SaveChanges();
recalls.Dispose();
}
}
}
}
}
}
I need to remove the record from the database that does not match any records in the file.
If you want the database to match the contents of the text file, why don't you simply empty it first?
I have some code that is using the following xml file. Can someone tell me why my doc.Descendants is returning null?
Here is the XML File:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<EmployerTPASeparationResponseCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://uidataexchange.org/schemas SeparationResponse.xsd" xmlns="https://uidataexchange.org/schemas">
<EmployerTPASeparationResponse>
<StateRequestRecordGUID>94321098761987654321323456109883</StateRequestRecordGUID>
<BrokerRecordTransactionNumber>123456789</BrokerRecordTransactionNumber>
<SSN>999999999</SSN>
<ClaimEffectiveDate>2011-02-09</ClaimEffectiveDate>
<ClaimNumber>1234568010</ClaimNumber>
<StateEmployerAccountNbr>12345689</StateEmployerAccountNbr>
<ClaimantJobTitle>Assistant Manager</ClaimantJobTitle>
<EmployerReportedClaimantFirstDayofWork>2009-02-02</EmployerReportedClaimantFirstDayofWork>
<EmployerReportedClaimantLastDayofWork>2010-03-16</EmployerReportedClaimantLastDayofWork>
<TotalEarnedWagesNeededInd>2</TotalEarnedWagesNeededInd>
<TotalEarnedWages>15000.00</TotalEarnedWages>
<WagesEarnedAfterClaimEffectiveDate>20000.00</WagesEarnedAfterClaimEffectiveDate>
<NumberOfHoursWorkedAfterClaimEffectiveDate>80</NumberOfHoursWorkedAfterClaimEffectiveDate>
<AverageWeeklyWage>10.00</AverageWeeklyWage>
<EmployerSepReasonCode>2</EmployerSepReasonCode>
<EmployerSepReasonComments>Expected return date back to work is 4/25/11</EmployerSepReasonComments>
<PreparerTypeCode>T</PreparerTypeCode>
<PreparerCompanyName>Barnett Associates</PreparerCompanyName>
<PreparerTelephoneNumberPlusExt>5555555555</PreparerTelephoneNumberPlusExt>
<PreparerContactName>Diana Turkoane</PreparerContactName>
<PreparerTitle>CSR</PreparerTitle>
<PreparerFaxNbr>5555555555</PreparerFaxNbr>
<PreparerEmailAddress>asdf#asdf.com</PreparerEmailAddress>
</EmployerTPASeparationResponse>
<EmployerTPASeparationResponse>
<StateRequestRecordGUID>94321098761987654321323456109884</StateRequestRecordGUID>
<BrokerRecordTransactionNumber>123456789</BrokerRecordTransactionNumber>
<SSN>999999999</SSN>
<ClaimEffectiveDate>2011-02-10</ClaimEffectiveDate>
<ClaimNumber>1234568010</ClaimNumber>
<StateEmployerAccountNbr>12345689</StateEmployerAccountNbr>
<ClaimantJobTitle>Assistant Manager</ClaimantJobTitle>
<EmployerReportedClaimantFirstDayofWork>2009-02-03</EmployerReportedClaimantFirstDayofWork>
<EmployerReportedClaimantLastDayofWork>2010-03-17</EmployerReportedClaimantLastDayofWork>
<EmployerSepReasonCode>2</EmployerSepReasonCode>
<EmployerSepReasonComments>Expected return date back to work is 4/30/11</EmployerSepReasonComments>
<PreparerTypeCode>T</PreparerTypeCode>
<PreparerCompanyName>Barnett Associates</PreparerCompanyName>
<PreparerTelephoneNumberPlusExt>5555555555</PreparerTelephoneNumberPlusExt>
<PreparerContactName>Diana Turkoane</PreparerContactName>
<PreparerTitle>CSR</PreparerTitle>
<PreparerFaxNbr>5555555555</PreparerFaxNbr>
<PreparerEmailAddress>asdf#asdf.com</PreparerEmailAddress>
</EmployerTPASeparationResponse>
</EmployerTPASeparationResponseCollection>
Here is the code I am using. I first use some Linq to get the Anonymous values, then try to loop through each child node and populate with cmd.parameters.
Here is the code:
XDocument doc = XDocument.Load("XmlString.xml");
var EmployerTPASeparationResponse =
from node in doc.Descendants("EmployerTPASeparationResponse")
select new
{
param1 = node.Element("StateRequestRecordGUID").Value,
param2 = node.Element("BrokerRecordTransactionNumber").Value,
param3 = node.Element("SSN").Value,
param4 = node.Element("ClaimEffectiveDate").Value,
param5 = node.Element("ClaimNumber").Value,
param6 = node.Element("StateEmployerAccountNbr").Value,
param7 = node.Element("CorrectedEmployerName").Value,
param8 = node.Element("CorrectedStateEmployerAccountNbr").Value,
param9 = node.Element("CorrectedFEIN").Value,
param10 = node.Element("OtherSSN").Value,
param11 = node.Element("ClaimantNameWorkedAsForEmployers").Value,
param12 = node.Element("ClaimantJobTitle").Value,
param13 = node.Element("SeasonalEmploymentInd").Value,
param14 = node.Element("EmployerReportedClaimantFirstDayofWork").Value,
param15 = node.Element("EmployerReportedClaimantLastDayofWork").Value,
param16 = node.Element("EffectiveSeparationDate").Value,
param17 = node.Element("TotalEarnedWagesNeededInd").Value,
param18 = node.Element("TotalEarnedWages").Value,
param19 = node.Element("TotalWeeksWorkedNeededInd").Value,
param20 = node.Element("TotalWeeksWorked").Value,
param21 = node.Element("WagesEarnedAfterClaimEffectiveDate").Value,
param22 = node.Element("NumberOfHoursWorkedAfterClaimEffectiveDate").Value,
param23 = node.Element("AverageWeeklyWage").Value,
param24 = node.Element("EmployerSepReasonCode").Value,
param25 = node.Element("ReturnToWorkInd").Value,
param26 = node.Element("ReturnToWorkDate").Value,
param27 = node.Element("WorkingAllAvailableHoursInd").Value,
param28 = node.Element("NotWorkingAvailableHoursReason").Value,
param29 = node.Element("DischargeReasonCode").Value,
param30 = node.Element("FinalIncidentReason").Value,
param31 = node.Element("FinalIncidentDate").Value,
param32 = node.Element("ViolateCompanyPolicyInd").Value,
param33 = node.Element("DischargePolicyAwareInd").Value,
param34 = node.Element("DischargePolicyAwareExplanationCode").Value,
param35 = node.Element("WhoDischargedName").Value,
param36 = node.Element("WhoDischargedTitle").Value,
param37 = node.Element("DischargeReasonComments").Value,
param38 = node.Element("VoluntarySepReasonCode").Value,
param39 = node.Element("HiringAgreementChangesCode").Value,
param40 = node.Element("HiringAgreementChangeComments").Value,
param41 = node.Element("ClaimantActionstoAvoidQuitInd").Value,
param42 = node.Element("ActionTakenComments").Value,
param43 = node.Element("ContinuingWorkAvailableInd").Value,
param44 = node.Element("VoluntarySepReasonComments").Value,
param45 = node.Element("AmendedResponse").Value,
param46 = node.Element("AmendedResponseDescription").Value,
param47 = node.Element("EmployerSepReasonComments").Value,
param48 = node.Element("LaborDisputeTypeInd").Value,
param49 = node.Element("AttachmentID").Value,
param50 = node.Element("MandatoryRetirementInd").Value,
param51 = node.Element("PriorIncidentID").Value,
param52 = node.Element("PreparerTypeCode").Value,
param53 = node.Element("PreparerCompanyName").Value,
param54 = node.Element("PreparerTelephoneNumberPlusExt").Value,
param55 = node.Element("PreparerContactName").Value,
param56 = node.Element("PreparerTitle").Value,
param57 = node.Element("PreparerFaxNbr").Value,
param58 = node.Element("PreparerEmailAddress").Value,
};
foreach (var node in EmployerTPASeparationResponse)
{
cmd4.Parameters["StateRequestRecordGUID"].Value = node.param1;
cmd4.Parameters["BrokerRecordTransactionNumber"].Value = node.param2;
cmd4.Parameters["SSN"].Value = node.param3;
cmd4.Parameters["ClaimEffectiveDate"].Value = node.param4;
cmd4.Parameters["ClaimNumber"].Value = node.param5;
cmd4.Parameters["StateEmployerAccountNbr"].Value = node.param6;
cmd4.Parameters["CorrectedEmployerName"].Value = node.param7;
cmd4.Parameters["CorrectedStateEmployerAccountNbr"].Value = node.param8;
cmd4.Parameters["CorrectedFEIN"].Value = node.param9;
cmd4.Parameters["OtherSSN"].Value = node.param10;
cmd4.Parameters["ClaimantNameWorkedAsForEmployers"].Value = node.param11;
cmd4.Parameters["ClaimantJobTitle"].Value = node.param12;
cmd4.Parameters["SeasonalEmploymentInd"].Value = node.param13;
cmd4.Parameters["EmployerReportedClaimantFirstDayofWork"].Value = node.param14;
cmd4.Parameters["EmployerReportedClaimantLastDayofWork"].Value = node.param15;
cmd4.Parameters["EffectiveSeparationDate"].Value = node.param16;
cmd4.Parameters["TotalEarnedWagesNeededInd"].Value = node.param17;
cmd4.Parameters["TotalEarnedWages"].Value = node.param18;
cmd4.Parameters["TotalWeeksWorkedNeededInd"].Value = node.param19;
cmd4.Parameters["TotalWeeksWorked"].Value = node.param20;
cmd4.Parameters["WagesEarnedAfterClaimEffectiveDate"].Value = node.param21;
cmd4.Parameters["NumberOfHoursWorkedAfterClaimEffectiveDate"].Value = node.param22;
cmd4.Parameters["AverageWeeklyWage"].Value = node.param23;
cmd4.Parameters["EmployerSepReasonCode"].Value = node.param24;
cmd4.Parameters["ReturnToWorkInd"].Value = node.param25;
cmd4.Parameters["ReturnToWorkDate"].Value = node.param26;
cmd4.Parameters["WorkingAllAvailableHoursInd"].Value = node.param27;
cmd4.Parameters["NotWorkingAvailableHoursReason"].Value = node.param28;
cmd4.Parameters["DischargeReasonCode"].Value = node.param29;
cmd4.Parameters["FinalIncidentReason"].Value = node.param30;
cmd4.Parameters["FinalIncidentDate"].Value = node.param31;
cmd4.Parameters["ViolateCompanyPolicyInd"].Value = node.param32;
cmd4.Parameters["DischargePolicyAwareInd"].Value = node.param33;
cmd4.Parameters["DischargePolicyAwareExplanationCode"].Value = node.param34;
cmd4.Parameters["WhoDischargedName"].Value = node.param35;
cmd4.Parameters["WhoDischargedTitle"].Value = node.param36;
cmd4.Parameters["DischargeReasonComments"].Value = node.param37;
cmd4.Parameters["VoluntarySepReasonCode"].Value = node.param38;
cmd4.Parameters["HiringAgreementChangesCode"].Value = node.param39;
cmd4.Parameters["HiringAgreementChangeComments"].Value = node.param40;
cmd4.Parameters["ClaimantActionstoAvoidQuitInd"].Value = node.param41;
cmd4.Parameters["ActionTakenComments"].Value = node.param42;
cmd4.Parameters["ContinuingWorkAvailableInd"].Value = node.param43;
cmd4.Parameters["VoluntarySepReasonComments"].Value = node.param44;
cmd4.Parameters["AmendedResponse"].Value = node.param45;
cmd4.Parameters["AmendedResponseDescription"].Value = node.param46;
cmd4.Parameters["EmployerSepReasonComments"].Value = node.param47;
cmd4.Parameters["LaborDisputeTypeInd"].Value = node.param48;
cmd4.Parameters["AttachmentID"].Value = node.param49;
cmd4.Parameters["MandatoryRetirementInd"].Value = node.param50;
cmd4.Parameters["PriorIncidentID"].Value = node.param51;
cmd4.Parameters["PreparerTypeCode"].Value = node.param52;
cmd4.Parameters["PreparerCompanyName"].Value = node.param53;
cmd4.Parameters["PreparerTelephoneNumberPlusExt"].Value = node.param54;
cmd4.Parameters["PreparerContactName"].Value = node.param55;
cmd4.Parameters["PreparerTitle"].Value = node.param56;
cmd4.Parameters["PreparerFaxNbr"].Value = node.param57;
cmd4.Parameters["PreparerEmailAddress"].Value = node.param58;
cmd4.ExecuteNonQuery();
if (cmd4 != null)
{
cmd4 = null;
}
}
You need to include the namespace (xmlns) in all of the element names:
XNamespace ns = "https://uidataexchange.org/schemas";
doc.Descendants(ns + "EmployerTPASeparationResponse")
(And in all of the Element calls)
Note that your code can be made dramatically shorter by looping through the child elements and adding parameters with their names instead of using anonymous types.
For example:
var node = doc.Descendants(ns + "EmployerTPASeparationResponse").Single();
using (cmd4) {
foreach(var param in node.Elements()) {
cmd4.Parameters.AddWithValue(param.Name.LocalName, param.Value);
}
cmd4.ExecuteNonQuery();
}