Getting values in XML parsing - c#

I am parsing a XML file and I want to insert the parsed values into the database,I parsed a set of values and placed in a variable "data". Now I want to pick each values from the variable.Can any one help me,I am a newbie?
The code
XDocument xdoc = XDocument.Parse(e.Result);
var data = from query in xdoc.Descendants("returnData")
select new fieldvalue
{
Authenticated = (String)query.Element("authenticated"),
Repphoto = (String)query.Element("rep_photo"),
Repuname = (String)query.Element("rep_uname"),
Repemail = (String)query.Element("rep_email"),
Repphone = (String)query.Element("rep_phone"),
Repwebsite = (String)query.Element("rep_website"),
Userimgsize = (String)query.Element("user_img_size"),
Usersigsize = (String)query.Element("user_sig_size")
};
The class file
public class fieldvalue
{
String authenticated, rep_photo, rep_uname, rep_email, rep_phone, rep_website, user_img_size, user_sig_size;
public String Authenticated
{
get { return authenticated; }
set { authenticated = value; }
}
public String Repphoto
{
get { return rep_photo; }
set { rep_photo = value; }
}
public String Repuname
{
get { return rep_uname; }
set { rep_uname = value; }
}
public String Repemail
{
get { return rep_email; }
set { rep_email = value; }
}
public String Repphone
{
get { return rep_phone; }
set { rep_phone = value; }
}
public String Repwebsite
{
get { return rep_website; }
set { rep_website = value; }
}
public String Userimgsize
{
get { return user_img_size; }
set { user_img_size = value; }
}
public String Usersigsize
{
get { return user_sig_size; }
set { user_sig_size = value; }
}
}
}

Now I want to pick each values from the variable.
Cast IEnumerable<fieldvalue> result to ToList<> and use index to access each element.
var data = (from query in xdoc.Descendants("returnData")
select new fieldvalue
{
Authenticated = (String)query.Element("authenticated"),
Repphoto = (String)query.Element("rep_photo"),
Repuname = (String)query.Element("rep_uname"),
Repemail = (String)query.Element("rep_email"),
Repphone = (String)query.Element("rep_phone"),
Repwebsite = (String)query.Element("rep_website"),
Userimgsize = (String)query.Element("user_img_size"),
Usersigsize = (String)query.Element("user_sig_size")
}).ToList();
Something like:
var name=data[0].Repuname;

Related

Given list of classes, how to make list\array from specific property of class?

I have a class:
public class MyField
{
private string fieldName;
public string FieldName
{
get { return fieldName; }
set { fieldName = value; }
}
private string fieldValue;
public string FieldValue
{
get { return fieldValue; }
set { fieldValue = value; }
}
private string fieldValidation;
public string FieldValidation
{
get { return fieldValidation; }
set { fieldValidation = value; }
}
private bool fieldValid;
public bool FieldValid
{
get { return fieldValid; }
set { fieldValid = value; }
}
}
and then I have a list made of them:
private IList<MyField> myFields;
myFields = new List<SpectraNameField>()
{
new SpectraNameField{FieldName = "FirstField", FieldValue="", FieldValid = false, FieldValidation="" },
new SpectraNameField{FieldName = "SecondField", FieldValue="", FieldValid = false, FieldValidation="" }
};
I then populate FieldValue for each member of the list through my XAML, but let's say as an example I just say:
myFields[0].FieldValue = "Value0";
myFields[1].FieldValue = "Value1";
At the end I need to get all the values of FieldValue for each MyField joined using "_" (i.e. I need to get string "Value0_Value1")
How do I get list or array of all the FieldValue of my list of MyField?
Use .Selectto get the values
var fieldValues = myFields.Select(f => f.FieldValue);
Use string.Join to combine multiple strings
var joinedString = string.join("_", fieldValues);

Check whether username is already in database

I am creating a help desk where one can create a new account. If the username is already in the database, you should get a message that tells you to take another username.
If the username is correct, the password must be provided with a hash before the data is entered in the database.
I have already searched for an answer via the internet but I don't find anything that works in my program.
//Declaratie private variabelen
private int _klantnummer;
private string _gebruikersnaam, _voornaam, _achternaam, _straatEnNummer, _postcode, _gemeente, _telefoonnummer, _email, _wachtwoord;
private bool _admin;
//Publieke eigenschappen
private int Klantnummer
{
get { return _klantnummer; }
set { _klantnummer = value; }
}
public string Gebruikersnaam
{
get { return _gebruikersnaam; }
set { _gebruikersnaam = value; }
}
public string Voornaam
{
get { return _voornaam; }
set { _voornaam = value; }
}
public string Achternaam
{
get { return _achternaam; }
set { _achternaam = value; }
}
public string StraatEnNummer
{
get { return _straatEnNummer; }
set { _straatEnNummer = value; }
}
public string Postcode
{
get { return _postcode; }
set { _postcode = value; }
}
public string Gemeente
{
get { return _gemeente; }
set { _gemeente = value; }
}
public string Telefoonnummer
{
get { return _telefoonnummer; }
set { _telefoonnummer = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string Wachtwoord
{
get { return _wachtwoord; }
set { _wachtwoord = value; }
}
public bool Admin
{
get { return _admin; }
set { _admin = value; }
}
//Default Constructor
public Klant()
{
Klantnummer = 0;
Gebruikersnaam = "";
Voornaam = "";
Achternaam = "";
StraatEnNummer = "";
Postcode = "";
Gemeente = "";
Telefoonnummer = "";
Email = "";
Wachtwoord = "";
Admin = false;
}
//Constructor met parameters
public Klant (string pGebruikersnaam, string pVoornaam, string pAchternaam, string pStraatEnNummer,
string pPostcode, string pGemeente, string pTelefoonnummer, string pEmail, string pWachtwoord,
bool pAdmin)
{
this.Gebruikersnaam = pGebruikersnaam;
this.Voornaam = pVoornaam;
this.Achternaam = pAchternaam;
this.StraatEnNummer = pStraatEnNummer;
this.Postcode = pPostcode;
this.Gemeente = pGemeente;
this.Telefoonnummer = pTelefoonnummer;
this.Email = pEmail;
this.Wachtwoord = pWachtwoord;
this.Admin = pAdmin;
}
//Constructor met parameters met klantnummer
public Klant(int pKlantnummer, string pGebruikersnaam, string pVoornaam, string pAchternaam, string pStraatEnNummer,
string pPostcode, string pGemeente, string pTelefoonnummer, string pEmail, string pWachtwoord,
bool pAdmin)
{
this.Klantnummer = pKlantnummer;
this.Gebruikersnaam = pGebruikersnaam;
this.Voornaam = pVoornaam;
this.Achternaam = pAchternaam;
this.StraatEnNummer = pStraatEnNummer;
this.Postcode = pPostcode;
this.Gemeente = pGemeente;
this.Telefoonnummer = pTelefoonnummer;
this.Email = pEmail;
this.Wachtwoord = pWachtwoord;
this.Admin = pAdmin;
}
What I usually do is make the username field unique in the database then use a try...catch on the call to the database. If it fails for a unique validation error I know the username was already used and respond to the user.

Why Query returns some null values to my list Object using dapper

I have this functional query where I only used fictive tables names for security concerns :
SELECT
h.CENID,
h.BMHFMC,
h.BMHDONEMIDASSTEP1,
h.BMHDONEMIDASSTEP2,
h.LMIID,
h.BMHHOLD,
h.BMHBATCHMIDAS,
h.BMHFMCVALUEDATE AS HeaderValueDate,
h.SUNID,
h.BRAID,
d.BMHID,
d.BMDRUBRIQUE,
d.BMDCLIENT,
d.BMDSEQUENCE,
d.BMDDATE,
d.BMDDEVISE,
d.BMDMONTANT,
d.BMDTYPE,
d.BMDNOTE,
d.BMDENTRYNBRE,
v.DEVDECIMAL ,
NVL(t.TYPVERIFCOMPTEMIDAS, 0) AS TYPVERIFCOMPTEMIDAS
FROM dbo.TableOne h
INNER JOIN dbo.Tabletwoo d
ON h.BMHID = d.BMHID
INNER JOIN dbo.tableThree v
ON d.BMDDEVISE = v.DEVID
LEFT JOIN dbo.TableFour t
ON t.TYPID=h.BMHFMC
WHERE d.BMDMONTANT != 0
AND h.BMHDONEMIDASSTEP1 = 0
AND h.BMHDONEMIDASSTEP2 = 0
AND h.LMIID = 0
AND h.BMHHOLD = 0
And I made a class in order to bind every fields
public class Batch :BaseRepository ,IList<Batch>
{
public Batch()
{
}
private string cendid;
private string bmhfmc;
private double bmhdonemidasstep1;
private double bmhdonemidasstep2;
private double lmiid;
private double bmhhold;
private double bmhbatchmidas;
private DateTime headervaluedateordinal;
private double sunid; //
private string bradid; //
private double bmhid;
private string bmdrubirique; //
private string bmdclient;
private string bmdsequence;
private DateTime bmddate;
private string bmddevise;
private double bmdmontant;
private string bmdtype;
private string bmdnote;
private string bmdentrynbre; //
private double devdecimalordinal;
private double typverifcomptemidasordinal;
public Batch(string cendid, string bmhfmc, double bmhdonemidasstep1, double bmhdonemidasstep2, double lmiid, double bmhhold, double bmhbatchmidas, DateTime headervaluedateordinal, double sunid, string bradid, double bmhid, string bmdrubirique, string bmdclient, string bmdsequence, DateTime bmddate, string bmddevise, double bmdmontant, string bmdtype, string bmdnote, string bmdentrynbre, double devdecimalordinal, double typverifcomptemidasordinal)
{
this.cendid = cendid;
this.bmhfmc = bmhfmc;
this.bmhdonemidasstep1 = bmhdonemidasstep1;
this.bmhdonemidasstep2 = bmhdonemidasstep2;
this.lmiid = lmiid;
this.bmhhold = bmhhold;
this.bmhbatchmidas = bmhbatchmidas;
this.headervaluedateordinal = headervaluedateordinal;
this.sunid = sunid;
this.bradid = bradid;
this.bmhid = bmhid;
this.bmdrubirique = bmdrubirique;
this.bmdclient = bmdclient;
this.bmdsequence = bmdsequence;
this.bmddate = bmddate;
this.bmddevise = bmddevise;
this.bmdmontant = bmdmontant;
this.bmdtype = bmdtype;
this.bmdnote = bmdnote;
this.bmdentrynbre = bmdentrynbre;
this.devdecimalordinal = devdecimalordinal;
this.typverifcomptemidasordinal = typverifcomptemidasordinal;
}
public string Cendid
{
get { return cendid; }
set { cendid = value; }
}
public string Bmhfmc
{
get { return bmhfmc; }
set { bmhfmc = value; }
}
public double Bmhdonemidasstep1
{
get { return bmhdonemidasstep1; }
set { bmhdonemidasstep1 = value; }
}
public double Bmhdonemidasstep2
{
get { return bmhdonemidasstep2; }
set { bmhdonemidasstep2 = value; }
}
public double Lmiid
{
get { return lmiid; }
set { lmiid = value; }
}
public double Bmhhold
{
get { return bmhhold; }
set { bmhhold = value; }
}
public double Bmhbatchmidas
{
get { return bmhbatchmidas; }
set { bmhbatchmidas = value; }
}
public DateTime Headervaluedateordinal
{
get { return headervaluedateordinal; }
set { headervaluedateordinal = value; }
}
public double Sunid
{
get { return sunid; }
set { sunid = value; }
}
public string Bradid
{
get { return bradid; }
set { bradid = value; }
}
public double Bmhid
{
get { return bmhid; }
set { bmhid = value; }
}
public string Bmdrubirique
{
get { return bmdrubirique; }
set { bmdrubirique = value; }
}
public string Bmdclient
{
get { return bmdclient; }
set { bmdclient = value; }
}
public string Bmdsequence
{
get { return bmdsequence; }
set { bmdsequence = value; }
}
public DateTime Bmddate
{
get { return bmddate; }
set { bmddate = value; }
}
public string Bmddevise
{
get { return bmddevise; }
set { bmddevise = value; }
}
public double Bmdmontant
{
get { return bmdmontant; }
set { bmdmontant = value; }
}
public string Bmdtype
{
get { return bmdtype; }
set { bmdtype = value; }
}
public string Bmdnote
{
get { return bmdnote; }
set { bmdnote = value; }
}
public string Bmdentrynbre
{
get { return bmdentrynbre; }
set { bmdentrynbre = value; }
}
public double Devdecimalordinal
{
get { return devdecimalordinal; }
set { devdecimalordinal = value; }
}
public double Typverifcomptemidasordinal
{
get { return typverifcomptemidasordinal; }
set { typverifcomptemidasordinal = value; }
}
Now when I execute the query into a list using dapper
Connection conn = new Connection();
OracleConnection connection = conn.GetDBConnection();
myList= connection.Query<Batch>(querySql).ToList();
Now,while debugging, all fields returns the expected values .But, I noticed those fields below are null in myList not empty but really null , but the problem is they aren't null in the database
Bmdrubirique , Sunid, Bmdentrynbre, Bradid ,Cenid
In oracle database those fields are like the following :
CENID is VARCHAR2(3 BYTE)`
Bmhid is VARCHAR2(3 BYTE)
Sunid is NUMBER(38,0)
Bradid is VARCHAR2(3 BYTE)
I don't get it , where did it go wrong? why other fields are properly loaded while those returns null value ?
My default assumption would be that there is a typo in the real code and the constructor is assigning a value from a field to itself. However, frankly: since you have a public Batch() {} constructor, I'm not sure what the benefit of the second one is - it just adds risk of errors. Likewise with the fields and manual properties.
So if this as me, where you currently have (simplified to two properties):
public class Batch
{
private string cendid;
private string bmhfmc;
public Batch() {}
public Batch(string cendid, string bmhfmc)
{
this.cendid = cendid;
this.bmhfmc = bmhfmc;
}
public string Cendid
{
get { return cendid; }
set { cendid = value; }
}
public string Bmhfmc
{
get { return bmhfmc; }
set { bmhfmc = value; }
}
}
I would have literally just:
public class Batch
{
public string Cendid {get;set;}
public string Bmhfmc {get;set;}
}
All of the rest of the code is just opportunities to make coding errors.
Now: the reason that Cendid is null is because: the column is CENID - only one d. This means that dapper isn't even using your custom constructor, because it isn't a perfect match between the constructor and the columns. Ditto the other fields like BRAID vs BRADID.
So the next thing to do is to fix the typos.

Enterprise Library Mappings

Is there a way to map database fields to OOP complex type fields with Enterprise Library. I am calling stored procedures that retrieves all data that I would like to store into custom class.
Here I retrieve data from sp:
IEnumerable<WorkHistoryGrid> data = new List<WorkHistoryGrid>();
return db.ExecuteSprocAccessor<WorkHistoryGrid>("PensionPDF_RetrieveParticipantWorkHistoryForFund", pensionId, fund);
And here is my class
public class WorkHistoryGrid : BindableBase
{
private string _rateType;
private string _fundType;
private string _employer;
private string _employerName;
private string _local;
private string _dateBalanced;
private string _plan;
private string _fund;
private WorkHistoryGridMergeData _mergeData;
#region Properties
public WorkHistoryGridMergeData MergeData
{
get { return _mergeData; }
set { SetProperty(ref _mergeData, value); }
}
public string RateType
{
get { return _rateType; }
set { SetProperty(ref _rateType, value); }
}
public string FundType
{
get { return _fundType; }
set { SetProperty(ref _fundType, value); }
}
public string Employer
{
get { return _employer; }
set { SetProperty(ref _employer, value); }
}
public string EmployerName
{
get { return _employerName; }
set { SetProperty(ref _employerName, value); }
}
public string Local
{
get { return _local; }
set { SetProperty(ref _local, value); }
}
public string DateBalanced
{
get { return _dateBalanced; }
set { SetProperty(ref _dateBalanced, value); }
}
public string Plan
{
get { return _plan; }
set { SetProperty(ref _plan, value); }
}
public string Fund
{
get { return _fund; }
set { SetProperty(ref _fund, value); }
}
}
}
}
It works fine if I would create one class with all database fields, but I would like to have more control over it by mapping database fields to custom complex type properties.
Here is the answer in my case, in case someone would look for similar solution:
var workHistoryGridSetMapper = new WorkHistoryGridSetMapper();
db.ExecuteSprocAccessor<WorkHistoryGrid>("PensionPDF_RetrieveParticipantWorkHistory", workHistoryGridSetMapper, pensionId);
IResultSetMapper
public class WorkHistoryGridSetMapper : IResultSetMapper<WorkHistoryGrid>
{
public IEnumerable<WorkHistoryGrid> MapSet(IDataReader reader)
{
List<WorkHistoryGrid> workHistoryLst = new List<WorkHistoryGrid>();
using (reader) // Dispose the reader when we're done
{
while (reader.Read())
{
WorkHistoryGrid workHist = new WorkHistoryGrid();
workHist.Amount = reader.GetValue(reader.GetOrdinal("Amount")).ToString();
workHist.DateBalanced = reader.GetValue(reader.GetOrdinal("DateBalanced")).ToString();
workHist.Employer = reader.GetValue(reader.GetOrdinal("Employer")).ToString();
workHist.EmployerName = reader.GetValue(reader.GetOrdinal("EmployerName")).ToString();
workHist.Fund = reader.GetValue(reader.GetOrdinal("Fund")).ToString();
workHist.FundType = reader.GetValue(reader.GetOrdinal("FundType")).ToString();
workHist.Hours = reader.GetValue(reader.GetOrdinal("Hours")).ToString();
workHist.Local = reader.GetValue(reader.GetOrdinal("Local")).ToString();
workHist.Period = reader.GetValue(reader.GetOrdinal("Period")).ToString();
workHist.Plan = reader.GetValue(reader.GetOrdinal("Plan")).ToString();
workHist.RateAmount = reader.GetValue(reader.GetOrdinal("RateAmount")).ToString();
workHist.RateType = reader.GetValue(reader.GetOrdinal("RateType")).ToString();
workHist.Status = reader.GetValue(reader.GetOrdinal("Status")).ToString();
workHist.WorkMonth = reader.GetValue(reader.GetOrdinal("WorkMonth")).ToString();
workHist.MergeData = new WorkHistoryGridMergeData
{
MergeDateMerged = reader.GetValue(reader.GetOrdinal("MergeDateMerged")).ToString(),
MergeLastUpdated = reader.GetValue(reader.GetOrdinal("MergeLastUpdated")).ToString(),
MergeLastUpdatedUserId = reader.GetValue(reader.GetOrdinal("MergeLastUpdatedUserId")).ToString(),
MergeLastUpdatedUserType = reader.GetValue(reader.GetOrdinal("MergeLastUpdatedUserType")).ToString(),
MergeNewSsn = reader.GetValue(reader.GetOrdinal("MergeNewSsn")).ToString(),
MergeNotes = reader.GetValue(reader.GetOrdinal("MergeNotes")).ToString(),
MergeOldSsn = reader.GetValue(reader.GetOrdinal("MergeOldSsn")).ToString(),
MergeTrustId = reader.GetValue(reader.GetOrdinal("MergeTrustId")).ToString(),
MergeUserName = reader.GetValue(reader.GetOrdinal("MergeUserName")).ToString()
};
workHistoryLst.Add(workHist);
};
}
return workHistoryLst;
}
}

Serialize two nodes with the same name but different child nodes

I need to be able to define two nodes with the same name but completely different subnode structures. I didn't design this XML schema but for the time being I'm forced to use it as is. I realize it's a terrible abuse of everything that is XML but there you have it.
What I need it to look like:
<order>
<ItemType type="Clubs">
<Club num="1">
<ClubName>Some Name</ClubName>
<ClubChoice>Something Else</ClubChoice>
</Club>
</ItemType>
<ItemType type="Gift" val="MailGreeting">
<GiftName>MailGreeting</GiftName>
<GiftDescription></GiftDescription>
<GiftQuanity>1</GiftQuanity>
</ItemType
</order>
Of course it's far more complicated than but you get the gist.
I'm using XmlSerializer and would really like to avoid using XDocument but if that's what I need to do then so be it.
If your order contains properties and not a list you can tell the serializer to name the elements like this:
[XmlRoot("order")]
public class Order
{
private Whatever whateverInstance;
[XmlElement("ItemType")]
public Whatever WhateverInstance
{
get { return whateverInstance; }
set { whateverInstance = value; }
}
private Something somethingInstance;
[XmlElement("ItemType")]
public Something SomethingInstance
{
get { return somethingInstance; }
set { somethingInstance = value; }
}
}
If it's a list of things you could get to have a identical element name as well but you will get a redundant xsi:Type attribute:
[XmlRoot("order")]
public class Order
{
private ItemType[] itemTypes;
[XmlElement("ItemType")]
public ItemType[] ItemTypes
{
get { return itemTypes; }
set { itemTypes = value; }
}
}
[XmlInclude(typeof(Clubs))]
[XmlInclude(typeof(Gift))]
public abstract class ItemType
{
private string type = "None";
[XmlAttribute]
public string Type
{
get { return type; }
set { type = value; }
}
}
public class Clubs : ItemType
{
public Clubs()
{
Type = "Clubs";
}
private Club[] clubsArray;
[XmlElement("Club")]
public Club[] ClubsArray
{
get { return clubsArray; }
set { clubsArray = value; }
}
}
public class Club
{
private int num = 0;
[XmlAttribute("num")]
public int Num
{
get { return num; }
set { num = value; }
}
private string clubName = "";
public string ClubName
{
get { return clubName; }
set { clubName = value; }
}
private string clubChoice = "";
public string ClubChoice
{
get { return clubChoice; }
set { clubChoice = value; }
}
}
public class Gift : ItemType
{
public Gift()
{
Type = "Gift";
}
private string val = "";
[XmlAttribute("val")]
public string Val
{
get { return val; }
set { val = value; }
}
private string giftName = "";
public string GiftName
{
get { return giftName; }
set { giftName = value; }
}
private string giftDescription = "";
public string GiftDescription
{
get { return giftDescription; }
set { giftDescription = value; }
}
private int giftQuanity = 0;
public int GiftQuanity
{
get { return giftQuanity; }
set { giftQuanity = value; }
}
}
Test:
List<ItemType> list = new List<ItemType>();
list.Add(new Clubs() { ClubsArray = new Club[] { new Club() { Num = 0, ClubName = "Some Name", ClubChoice = "Something Else" } } });
list.Add(new Gift() { Val = "MailGreeting", GiftName = "MailGreeting", GiftDescription = "GiftDescription", GiftQuanity = 1});
Order order = new Order();
rder.ItemTypes = list.ToArray();
XmlSerializer serializer = new XmlSerializer(typeof(Order));
StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Stuff.xml");
serializer.Serialize(sw, order);
sw.Close();
Output:
<order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ItemType xsi:type="Clubs" Type="Clubs">
<Club num="0">
<ClubName>Some Name</ClubName>
<ClubChoice>Something Else</ClubChoice>
</Club>
</ItemType>
<ItemType xsi:type="Gift" Type="Gift" val="MailGreeting">
<GiftName>MailGreeting</GiftName>
<GiftDescription>GiftDescription</GiftDescription>
<GiftQuanity>1</GiftQuanity>
</ItemType>
</order>

Categories

Resources