XML reading - Deserialize vs XElement.Load - c#

my question is fairly simple, which method should I use and why for parsing XML files?
Right now I have function for that:
return new EdiFile
{
SPPLR_MAILBOX = xmlDoc.Element("SPPLR_MAILBOX").Value,
MESSAGE_ID = xmlDoc.Element("MESSAGE_ID").Value,
ATTRIBUTE05 = xmlDoc.Element("ATTRIBUTE05").Value,
Levels0 = (from a in xmlDoc.Element("LEVELS0").Elements("LEVEL0")
select new Level0
{
PLT_NUM = a.Element("PLT_NUM").Value,
PLT_LABEL_ID = a.Element("PLT_LABEL_ID").Value,
BOX_QTY = a.Element("BOX_QTY").Value,
PLT_WEIGHT = a.Element("PLT_WEIGTH").Value,
PLT_DIMENSION = a.Element("PLT_DIMENSION").Value,
PLT_CHEM = a.Element("PLT_CHEM").Value,
PLT_NOT_STACK = a.Element("PLT_NOT_STACK").Value,
PLT_NOTE = a.Element("PLT_NOTE").Value,
ATTRIBUTE01 = a.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = a.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = a.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = a.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = a.Element("ATTRIBUTE05").Value,
Levels1 = (from b in a.Element("LEVELS1").Elements("LEVEL1")
select new Level1
{
BOX_NUM = b.Element("BOX_NUM").Value,
BOX_LABEL_ID = b.Element("BOX_LABEL_ID").Value,
Items = (from c in b.Element("ITEMS").Elements("ITEM")
select new Item
{
SPPLR_ITEM = c.Element("SPPLR_ITEM").Value,
CUST_ITEM = c.Element("CUST_ITEM").Value,
ATTRIBUTE01 = c.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = c.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = c.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = c.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = c.Element("ATTRIBUTE05").Value,
Lots = (from d in c.Element("LOTS").Elements("LOT")
select new Lot
{
LOT_NUM = d.Element("LOT_NUM").Value,
LOT_LABEL_ID = d.Element("LOT_LABEL_ID").Value,
LOT_NOTE = d.Element("LOT_NOTE").Value,
LOT_EXP_DATE = d.Element("LOT_EXP_DATE").Value,
QTY = d.Element("QTY").Value,
UOM = d.Element("UOM").Value,
ATTRIBUTE01 = d.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = d.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = d.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = d.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = d.Element("ATTRIBUTE05").Value
}).ToList()
}).ToList()
}).ToList()
}).ToList()
};
But should I use deserialize? I learnt about serialization yesterday.
I cant really find any source explaining my method, vs deserialization.
Can someone get me any insight please?

Your method is more performance and flexie, because you have control on processing xml file. Serialization is using reflection and it is less performance.

Related

SQL select query excluding a value in EF CORE

I have the LINQ query with the simple select statement which maps the columns from a table to the custom entity.
I have quite a few fields so I'm trying to select one by one and leave one field out. This way seems pretty silly to me. There was an option such as not select in SQL, it should have a counterpart in the entity framework.
I don't want to select the image area in this query. Do I have to write such a long code for this?
var result = from ch in _tenantDbContext.CariHesap
where ch.KartTipi == cariHesapKartTip
select new CariHesap
{
Id = ch.Id,
HesapKodu = ch.HesapKodu,
Unvan = ch.Unvan,
Ad = ch.Ad,
Soyad = ch.Soyad,
AktifPasif = ch.AktifPasif,
KartTipi = ch.KartTipi,
IslemTipi = ch.IslemTipi,
BakGostSekli = ch.BakGostSekli,
DvzTL = ch.DvzTL,
DovizCinsi = ch.DovizCinsi,
KrediLimiti = ch.KrediLimiti,
DvzKrediLimiti = ch.DvzKrediLimiti,
BolgeKod = ch.BolgeKod,
OzelKod = ch.OzelKod,
GrupKod = ch.GrupKod,
TipKod = ch.TipKod,
MhsKod = ch.MhsKod,
MasrafMerkezi = ch.MasrafMerkezi,
VergiDairesi = ch.VergiDairesi,
HesapNo = ch.HesapNo,
FaturaChk = ch.FaturaChk,
IskontoOran = ch.IskontoOran,
OpsiyonGunu = ch.OpsiyonGunu,
OdemeGunu = ch.OdemeGunu,
OdemePlani = ch.OdemePlani,
KulSatisFiyat = ch.KulSatisFiyat,
CHKodu = ch.CHKodu,
KDVTevfikatUygula = ch.KDVTevfikatUygula,
KDVMuaf = ch.KDVMuaf,
KDVMuafAck = ch.KDVMuafAck,
FormBaBsUnvan = ch.FormBaBsUnvan,
SirketEMail = ch.SirketEMail,
SirketWebAdres = ch.SirketWebAdres,
SatIslemEMail = ch.SatIslemEMail,
SatAlmaIslemEMail = ch.SatAlmaIslemEMail,
FinIslemEMail = ch.FinIslemEMail,
UnvanFaturadan = ch.UnvanFaturadan,
EFatSenaryo = ch.EFatSenaryo,
EIrsSenaryo = ch.EIrsSenaryo,
EMMSenaryo = ch.EMMSenaryo,
EFatEtiket = ch.EFatEtiket,
EIrsEtiket = ch.EIrsEtiket,
MusBrmSubeTanim = ch.MusBrmSubeTanim,
MusBrmSubeDeger = ch.MusBrmSubeDeger,
MusCHKoduTanim = ch.MusCHKoduTanim,
MusCHKoduDeger = ch.MusCHKoduDeger,
LegalEntityID = ch.LegalEntityID,
LegalEntityName = ch.LegalEntityName,
EArsivTeslimSekli = ch.EArsivTeslimSekli,
EArsivTeslimEMail1 = ch.EArsivTeslimEMail1,
EArsivTeslimEMail2 = ch.EArsivTeslimEMail2,
EArsivTeslimEMail3 = ch.EArsivTeslimEMail3,
FaturaXSLT = ch.FaturaXSLT,
IrsaliyeXSLT = ch.IrsaliyeXSLT,
SGKChk = ch.SGKChk,
SGKFaturaTipi = ch.SGKFaturaTipi,
KamuChk = ch.KamuChk,
Kod1 = ch.Kod1,
Kod2 = ch.Kod2,
Kod3 = ch.Kod3,
Kod4 = ch.Kod4,
Kod5 = ch.Kod5,
Kod6 = ch.Kod6,
Kod7 = ch.Kod7,
Kod8 = ch.Kod8,
Kod9 = ch.Kod9,
Kod10 = ch.Kod10,
Kod11 = ch.Kod11,
Kod12 = ch.Kod12,
Kod13 = ch.Kod13,
Kod14 = ch.Kod14,
Kod15 = ch.Kod15,
Nesne1 = ch.Nesne1,
Nesne2 = ch.Nesne2,
};

Return Entity Framework result as JSON

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.

read specific line this xml?

Is there anyway to read the specific line in this xml?
http://i.stack.imgur.com/hDPIg.jpg
var guide = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameTitle = (string)query.Element("Title"),
Gamedescription = (string)query.Element("Description"),
GameGuide = (string)query.Element("Guide")
};
GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameGuide.StartsWith("See 'Payne In The Ass'")).Take(1);
this will show all guides in the xml.
This Work:
var guide = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameTitle = (string)query.Element("Title"),
Gamedescription = (string)query.Element("Description"),
GameGuide = (string)query.Element("Guide")
};
//GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameGuide.StartsWith("See 'Payne In The Ass'")).Take(1);
GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameTitle.StartsWith("Serious"));
So start with whatever is the first child in the XML.
Just continue your statement with a where clause: (change the condition based on your needs)
var guides = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameGuide = (string)query.Element("Guide")
};
AchivementsListBox.ItemsSource = guides.Where( ngc => ngc.GameGuide.StartsWith("Chapter 4:"));

Is there a way to combine 2 LINQ2XML queries?

var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements()
}).SingleOrDefault();
var fields = from item in instructions.fields
select new
{
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
};
I think something like this should work. I added the Select method to return the anonymous class.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements().Select(item => new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
}
).SingleOrDefault();
If you don't want to use the Select Extension method, you can use LINQ syntax. Here is an example of this.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = from e in item.Element("fields").Elements()
select new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
} // End of inner select statement
} // End of outer select statement
).SingleOrDefault();

InvalidCastException when running linq 2 sql statement

C#, Linq2Sql, .NET 2.0, SQL 2005 Express
When I run the following code I get a
InvalidCastException unable to cast of type System.Byte[] to System.String
This does not occur on all rows in the table i.e. this code runs fine soemtimes.
I checked there are no columns in the table that linq declares as SYstem.Byte[]
The stack trace says the exception occurs on the linq statement and when I F11
into the code the GetProject is never called the exception occurs before this method
is called.
So I think it is Linq framework bug.
This has got me stumped? any ideas?
[code]
public Project GetProject(int id)
{
var project = (from row in _dbctx.Projects
where row.ProjectID == id
select row).SingleOrDefault();
Project proj = GetProject(project);
return proj;
}
private Project GetProject(TBRServices.Domain.TBR.DataContext.Project sqlproject)
{
Project project = new Project();
project.ProjectID = sqlproject.ProjectID;
project.ProjectName = sqlproject.ProjectName;
project.ProjectDescription = sqlproject.ProjectDescription;
project.ClientID = sqlproject.ClientID;
project.PurchaseOrderNumber = sqlproject.PurchaseOrderNumber;
project.ProjectTotalBillingEstimate = sqlproject.ProjectTotalBillingEstimate;
project.EmployeeID = sqlproject.EmployeeID;
project.ProjectBeginDate = sqlproject.ProjectBeginDate.ToString();
project.ProjectEndDate = sqlproject.ProjectEndDate.ToString();
project.Active = sqlproject.Active;
project.InclGST = sqlproject.InclGST;
project.ContractRate = sqlproject.ContractRate;
project.MarginRate = sqlproject.MarginRate;
project.Notes = sqlproject.Notes;
project.PayrollTax = sqlproject.PayrollTax;
project.EmployeeReference = sqlproject.EmployeeReference;
project.PayReference = sqlproject.PayReference;
project.ProjectLocation = sqlproject.ProjectLocation;
project.ContractTypeID = sqlproject.ContractTypeID;
project.DoNotCalcMarginOrGST = sqlproject.DoNotCalcMarginOrGST;
project.ConvertToInvoice = sqlproject.ConvertToInvoice;
project.AuthFirstname = sqlproject.AuthFirstname;
project.AuthLastname = sqlproject.AuthLastname;
project.AuthEmail = sqlproject.AuthEmail;
project.CapturedDocumentType = sqlproject.CapturedDocumentType;
project.TimesheetProcessingType = sqlproject.TimesheetProcessingType;
project.TimesheetFrequency = sqlproject.TimesheetFrequency;
project.AggregateTimesheet = sqlproject.AggregateTimesheet;
project.AggregateAutomatically = sqlproject.AggregateAutomatically;
project.BusProcEmpCut = sqlproject.BusProcEmpCut;
project.BusProcAgencyCut = sqlproject.BusProcAgencyCut;
project.SendCopyTimesheet = sqlproject.SendCopyTimesheet;
project.TimesheetRecipient1 = sqlproject.TimesheetRecipient1;
project.TimesheetRecipient2 = sqlproject.TimesheetRecipient2;
project.SendCopyInvoice = sqlproject.SendCopyInvoice;
project.PublishedOn = sqlproject.PublishedOn.ToString();
project.SendAggTimesheetsWhenReceived = sqlproject.SendAggTimesheetsWhenReceived;
project.AuthoriseInvoice = sqlproject.AuthoriseInvoice;
project.HourlyDailyMthly = sqlproject.HourlyDailyMthly;
project.EmployeeCategory = sqlproject.EmployeeCategory;
project.AgencyRate = sqlproject.AgencyRate;
project.ConsultantID = sqlproject.ConsultantID;
project.SendCopyInvoiceEmployee = sqlproject.SendCopyInvoiceEmployee;
project.UseClientDetailsForTimesheet = sqlproject.UseClientDetailsForTimesheet;
project.FaxedTimesheet = sqlproject.FaxedTimesheet;
project.TimesheetEditable = sqlproject.TimesheetEditable;
project.IncludeInReport = sqlproject.IncludeInReport;
project.SendLogonEmail = sqlproject.SendLogonEmail;
project.NoticePeriodID = sqlproject.NoticePeriodID;
project.ManagerCanViewPaidUnpaid = sqlproject.ManagerCanViewPaidUnpaid;
project.LesterSalesStaff = sqlproject.LesterSalesStaff;
project.IncludeSalesReport = sqlproject.IncludeSalesReport;
project.CurrencyAccount = sqlproject.CurrencyAccount;
project.LeaveMustBeAuthorisedTimesheet = sqlproject.LeaveMustBeAuthorisedTimesheet;
project.LeaveMustBeAuthorisedLeaveForm = sqlproject.LeaveMustBeAuthorisedLeaveForm;
project.DefaultHoursWorkedWeek = sqlproject.DefaultHoursWorkedWeek;
project.DefaultHoursWorkedDay = sqlproject.DefaultHoursWorkedDay;
project.AccruedLeaveStartDate = sqlproject.AccruedLeaveStartDate.ToString();
project.AllowLeaveMoreThanAccrued = sqlproject.AllowLeaveMoreThanAccrued;
project.IsPaidASalary = sqlproject.IsPaidASalary;
project.AgencyID = sqlproject.AgencyID;
project.SendEmailToManagerToOKLeave = sqlproject.SendEmailToManagerToOKLeave;
project.SpecialPayrollNotes = sqlproject.SpecialPayrollNotes;
project.SpecialInvoicingNotes = sqlproject.SpecialInvoicingNotes;
project.InvoiceTermsMessage = sqlproject.InvoiceTermsMessage;
project.AuthManagerPhone = sqlproject.AuthManagerPhone;
project.LMF = sqlproject.LMF;
project.LMFPercent = sqlproject.LMFPercent;
project.LMFInclInPayRate = sqlproject.LMFInclInPayRate;
project.LMFOnTop = sqlproject.LMFOnTop;
project.AgencyComm = sqlproject.AgencyComm;
project.AgencyCommPercent = sqlproject.AgencyCommPercent;
project.AgencyCommInclInPayRate = sqlproject.AgencyCommInclInPayRate;
project.AgencyCommOnTop = sqlproject.AgencyCommOnTop;
project.PayRateInclMargin = sqlproject.PayRateInclMargin;
project.MarginRatePercent = sqlproject.MarginRatePercent;
project.MarginRateGST = sqlproject.MarginRateGST;
project.MarginRateInclInPayRate = sqlproject.MarginRateInclInPayRate;
project.MarginRateOnTop = sqlproject.MarginRateOnTop;
project.PayRateInclSuper = sqlproject.PayRateInclSuper;
project.PayrollTaxAmount = sqlproject.PayrollTaxAmount;
project.PayrollTaxPercent = sqlproject.PayrollTaxPercent;
project.PayrollTaxInclInPayRate = sqlproject.PayrollTaxInclInPayRate;
project.PayrollTaxOnTop = sqlproject.PayrollTaxOnTop;
project.TypeOfArrangement = sqlproject.TypeOfArrangement;
project.ParameterRequired = sqlproject.ParameterRequired;
project.SpecialPayrollEnabled = sqlproject.SpecialPayrollEnabled;
project.ClientContactUsedReceiptOfInvoiceID = sqlproject.ClientContactUsedReceiptOfInvoiceID;
project.ExcludeEmpNameOnInvoice = sqlproject.ExcludeEmpNameOnInvoice;
project.BPForReporting = sqlproject.BPForReporting;
project.UseGemteqInvoiceFormat = sqlproject.UseGemteqInvoiceFormat;
project.TreatPayrollDetailsSameAsBP = sqlproject.TreatPayrollDetailsSameAsBP;
return project;
}
[/code]
Check the answer to a similar SO question. It will not be the exact answer but may help you find the problem in your query -
Problem with Linq to SQL
unable to cast of type System.Byte[] to System.String
Indicates that a property in sqlproject is stored as byte[] while the corresponding property in project is a string

Categories

Resources