Linq try to using Include after groupBy - c#

I have an Api in .net with EF, and the frontEnd needs to get the json in a particular way.
Originally i tried with this code:
[HttpGet("getTrafos")]
public IEnumerable<object> GetTrafos(){
var resultado =_context.Transformadores.OrderBy(z=>z.Anio).ThenBy(z=>z.Mes).ThenBy(x=>x.Prioridad)
.Include(t => t.Etapa).ThenInclude(x=>x.IdColorNavigation)
.Include(f=>f.Etapa).ThenInclude(x=>x.EtapaEmpleado)
.ToList();
List<Object> array = new List<Object>();
foreach(var result in resultado){
result.Etapa=result.Etapa.OrderBy(m=>m.IdTipoEtapa).ToList();
var mes = AsignarMes(resultado[0].Mes);
var obj=new {group = $"{mes} de {resultado[0].Anio}"};
var ultimoAnio=resultado[0].Anio;
var ultimoMes=mes;
array.Add(obj);
foreach(var trafo in resultado)
{
mes=this.AsignarMes(trafo.Mes);
if(trafo.Anio!=ultimoAnio)
{
obj=new {group = $"{mes} de {resultado[0].Anio}"};
array.Add(obj);
array.Add(trafo);
}
else{
if(mes!=ultimoMes)
{
obj=new{group=$"{mes} de {trafo.Anio}"};
array.Add(obj);
}
array.Add(trafo);
}
ultimoAnio=trafo.Anio;
ultimoMes=mes;
}
}
return array;
}
AsignarMes Method:
private string AsignarMes(int? mes){
var map = new Dictionary<int, string>()
{
{1, "Enero"},
{2, "Febrero"},
{3, "Marzo"},
{4,"Abril"},
{5,"Mayo"},
{6,"Junio"},
{7,"Julio"},
{8,"Agosto"},
{9,"Septiembre"},
{10,"Octubre"},
{11,"Noviembre"},
{12,"Diciembre"}
};
string output;
return map.TryGetValue(mes.GetValueOrDefault(), out output) ? output : "";
}
but for performance reasons (it takes 13 seconds aprox to download the content to the frontend) i tried with another way:
var resultado =_context.Transformadores.OrderBy(z=>z.Anio).ThenBy(z=>z.Mes).ThenBy(x=>x.Prioridad)
.GroupBy(x=> new { x.Anio, x.Mes }, (key, group) => new
{
Anio = key.Anio,
Mes = key.Mes,
Trafos = group.ToList()
});
List<Object> array = new List<Object>();
foreach (var result in resultado) {
foreach (var trafo in result.Trafos)
{
trafo.Etapa = trafo.Etapa.OrderBy(m => m.IdTipoEtapa).ToList();
}
var mesEnLetras = this.AsignarMes(result.Mes);
var obj = new {group = $"{mesEnLetras} de {result.Anio}"};
array.Add(obj);
array.AddRange(result.Trafos);
}
return array;
The performance was better with this last code but the problem is that i canĀ“t Include Etapa, IdColorNavigation and EtapaEmpleado.
Is there another way to do this?
Theese are the Models:
using System;
using System.Collections.Generic;
namespace Foha.Models
{
public partial class Transformadores
{
public Transformadores()
{
Etapa = new HashSet<Etapa>();
}
public int IdTransfo { get; set; }
public string OPe { get; set; }
public int? OTe { get; set; }
public string Observaciones { get; set; }
public int RangoInicio { get; set; }
public int RangoFin { get; set; }
public int? IdCliente { get; set; }
public string NombreCli { get; set; }
public int Potencia { get; set; }
public int? IdTipoTransfo { get; set; }
public DateTime? FechaCreacion { get; set; }
public int? Mes { get; set; }
public int? Anio { get; set; }
public int? Prioridad { get; set; }
public virtual Cliente IdClienteNavigation { get; set; }
public virtual TipoTransfo IdTipoTransfoNavigation { get; set; }
public virtual ICollection<Etapa> Etapa { get; set; }
}
}
using System;
using System.Collections.Generic;
namespace Foha.Models
{
public partial class Etapa
{
public Etapa()
{
EtapaEmpleado = new HashSet<EtapaEmpleado>();
}
public int IdEtapa { get; set; }
public int? IdTipoEtapa { get; set; }
public DateTime? DateIni { get; set; }
public DateTime? DateFin { get; set; }
public bool? IsEnded { get; set; }
public string TiempoParc { get; set; }
public string TiempoFin { get; set; }
public int? IdTransfo { get; set; }
public string IdEmpleado { get; set; }
public string Hora { get; set; }
public DateTime? InicioProceso { get; set; }
public int? IdColor { get; set; }
public int? NumEtapa { get; set; }
public virtual Colores IdColorNavigation { get; set; }
public virtual TipoEtapa IdTipoEtapaNavigation { get; set; }
public virtual Transformadores IdTransfoNavigation { get; set; }
public virtual ICollection<EtapaEmpleado> EtapaEmpleado { get; set; }
}
}

Related

Creating Viewmodels and mapping to entities

I am creating ViewModels for my entities. The FirmViewModel contains two list collections called Addressess and Websites. I have also created viewmodels for Addresses and Websites. At the moment in the controller code, I am getting trouble assigning Addresses and Wesbite collections
of the Firm Entity to FirmViewModels Addresses and Websites collection. Its says cant cast it implicitly. This is the line in the controller that it complains Addresses = firm.Addresses; How do aassign
Systems.Collections.Generic.ICollection<Manager.Model.Address> to Systems.Collections.Generic.ICollection<Manager.WebUI.ViewModels.AddressViewModel>
NewFirmViewModel
public class NewFirmViewModel
{
public int FirmId { get; set; }
public string FirmName { get; set;}
public Nullable<DateTime> DateFounded { get; set; }
public ICollection<AddressViewModel> Addresses { get; set; }
public ICollection<WebsiteViewModel> Websites { get; set; }
public bool hasIntralinks { get; set; }
}
AddressViewModel
public class AddressViewModel
{
public int AddressId { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Phone { get; set; }
public bool IsHeadOffice { get; set; }
public int FirmId { get; set; }
}
WebsiteViewModel
public class WebsiteViewModel
{
private int FirmWebsiteId { get; set; }
private string WebsiteUrl { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int FirmId { get; set; }
}
Entities - Firm
public class FIRM: Entity,IHasAUMs<FIRM_AUM>
{
public FIRM()
{
//this.FIRM_PERSON = new HashSet<FIRM_PERSON>();
this.MANAGERSTRATEGies = new HashSet<MANAGERSTRATEGY>();
this.FIRM_ACTIVITY = new HashSet<FIRM_ACTIVITY>();
this.FIRM_AUMs = new HashSet<FIRM_AUM>();
this.FIRM_REGISTRATION = new HashSet<FIRM_REGISTRATION>();
//this.ACTIVITies = new HashSet<ACTIVITY>();
Addresses = new HashSet<ADDRESS>();
//People = new HashSet<PERSON>();
// Websites = new HashSet<FIRM_WEBSITE>();
}
//public decimal ID { get; set; }
//
//
//
//
public string NAME { get; set; }
public string SHORT_NAME { get; set; }
public string ALTERNATE_NAME { get; set; }
public string WEBSITE { get; set; }
public string WEBSITE_USERNAME { get; set; }
public string WEBSITE_PASSWORD { get; set; }
public bool? INTRALINKS_FIRM { get; set; }
public string NOTES_TEXT { get; set; }
public string NOTES_HTML { get; set; }
public string HISTORY_TEXT { get; set; }
public string HISTORY_HTML { get; set; }
public string HISTORY_SUM_TEXT { get; set; }
public string HISTORY_SUM_HTML { get; set; }
public Nullable<decimal> OLD_ORG_REF { get; set; }
public Nullable<decimal> SOURCE_ID { get; set; }
[DisplayFormat(DataFormatString = PermalConstants.DateFormat)]
public Nullable<DateTime> DATE_FOUNDED { get; set; }
public virtual ICollection<ADDRESS> Addresses { get; set; }
// public ICollection<FIRM_WEBSITE> Websites { get; set; }
// public ICollection<PERSON> People { get; set; }
//public SOURCE SOURCE { get; set; }
// public ICollection<FIRM_PERSON> FIRM_PERSON { get; set; }
public ICollection<MANAGERSTRATEGY> MANAGERSTRATEGies { get; set; }
public ICollection<FIRM_ACTIVITY> FIRM_ACTIVITY { get; set; }
public ICollection<FIRM_REGISTRATION> FIRM_REGISTRATION { get; set; }
//public ICollection<ACTIVITY> ACTIVITies { get; set; }
public ICollection<FIRM_WEBSITE> Websites { get; set; }
public Nullable<int> KEY_CONTACT_ID { get; set; }
[NotMapped]
public ICollection<FIRM_AUM> AUMs
{
get
{
return this.FIRM_AUMs;
}
}
public ICollection<FIRM_AUM> FIRM_AUMs { get; set; }
}
ADDRESS
public class ADDRESS : Entity
{
public ADDRESS()
{
// DATE_CREATED = DateTime.Now;
}
public string LINE1 { get; set; }
public string LINE2 { get; set; }
public string LINE3 { get; set; }
public int CITY_ID { get; set; }
public string POSTAL_CODE { get; set; }
public string SWITCHBOARD_INT { get; set; }
public string NOTES { get; set; }
public int? OLD_ADDRESS_REF { get; set; }
public int? SOURCE_ID { get; set; }
public int FIRM_ID { get; set; }
[ForeignKey("FIRM_ID")]
public FIRM FIRM { get; set; }
[ForeignKey("CITY_ID")]
public CITY City { get; set; }
public ICollection<PERSON> People { get; set; }
// public SOURCE SOURCE { get; set; }
public bool IS_HEAD_OFFICE { get; set; }
[NotMapped]
public string AddressBlurb
{
get
{
return string.Join(",", new[] { LINE1, LINE2, City != null ? City.NAME : "", City != null && City.Country != null ? City.Country.NAME : "" }.Where(x => !string.IsNullOrEmpty(x)));
}
}
}
FIRM_WEBSITE
public class FIRM_WEBSITE : Entity
{
public FIRM_WEBSITE()
{
}
private string _WEBSITE_URL;
public string WEBSITE_URL
{
get
{
if (string.IsNullOrEmpty(_WEBSITE_URL))
return _WEBSITE_URL;
try
{
var ubuilder = new System.UriBuilder(_WEBSITE_URL ?? "");
return ubuilder.Uri.AbsoluteUri;
}
catch (UriFormatException ex)
{
return _WEBSITE_URL;
}
}
set { _WEBSITE_URL = value; }
}
public string USERNAME { get; set; }
public string PASSWORD { get; set; }
public int FIRM_ID { get; set; }
[ForeignKey("FIRM_ID")]
public FIRM FIRM { get; set; }
}
FirmController
public class FirmController : ApiControllerBase
{
[HttpGet]
[Route("api/Firm/{id}")]
public IHttpActionResult Details(int id)
{
var viewModel = GetFirmViewModel(id);
return Ok(viewModel);
}
private NewFirmViewModel GetFirmViewModel(int id)
{
var firmSvc = GetService<FIRM>();
var firm = firmSvc.GetWithIncludes(id, f => f.Addresses, f => f.Websites);
var firmVm = new NewFirmViewModel()
{
FirmId = firm.ID,
FirmName = firm.NAME,
DateFounded = firm.DATE_FOUNDED,
Addresses = firm.Addresses;
};
}
public virtual T GetWithIncludes(int id, params Expression<Func<T, object>>[] paths)
{
try
{
using (new TimedLogger(_perfLogger, GetCompletedText("GetWithIncludes"), typeof(T).Name))
{
return Authorize(_repo.GetWithIncludes(id, paths), AuthAccessLevel.Read);
}
}
catch (Exception ex) { Log(ex); throw; }
}

Strip all values from C# objects using Reflection

I have the following method which is used to retrieve all values as strings from an object using reflection. The object can have IEnumerables within them and I also want to retrieve these values. A list of ignore fields also needs to be taken into account so that those field's values are not returned.
public static IEnumerable<string> StringContent(this object obj, IEnumerable<string> ignoreProperties = null)
{
Type t = obj.GetType();
foreach (var prop in t.GetProperties())
{
if (ignoreProperties != null && ignoreProperties.Contains(field.Name))
{
continue;
}
var value = prop.GetValue(obj);
if (value != null)
{
if (value is IEnumerable<object>)
{
foreach (var item in (IEnumerable<object>)value)
{
foreach (var subValue in item.StringContent())
{
yield return subValue.ToString();
}
}
}
else
{
yield return value.ToString();
}
}
}
}
This method does work perfectly and gives me the correct result. However, I need to speed it up as much as possible because this is performed a lot of times.
Does anybody have any suggestions?
Thanks in advance!
** EDIT **
Example Test Case:
[TestMethod]
public void StringContent()
{
Project project = projectA;
List<string> ignoreFields = new List<string>() { "SalesEngineer", "CreationDate" };
var result = project.StringContent(ignoreFields);
Assert.IsTrue(result.Count() == 26);
}
Project Object:
public class Project : IEntity
{
public Project()
{
Products = new List<ProjectProducts>();
}
public int Id { get; set; }
public DateTime CreationDate { get; set; }
public string SalesEngineer { get; set; }
public string SalesEngineerEmail { get; set; }
public int? TeamId { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Originator { get; set; }
public string ContactName { get; set; }
public string MainClient { get; set; }
public string Contractor { get; set; }
public string ContractorContactName { get; set; }
public string ContractorLocation { get; set; }
public string Wholesaler { get; set; }
public string WholesalerContactName { get; set; }
public string WholesalerLocation { get; set; }
public float EstimatedValue { get; set; }
public float CalculatedValue {
get { return EstimatedValue/Convert.ToSingle(Currency != null ? Currency.Rate : (decimal)1.0); }
}
public int Probability { get; set; }
public int SectorId { get; set; }
public int TypeId { get; set; }
public string StatusCode { get; set; }
public string LostTo { get; set; }
public int ReasonId { get; set; }
public string SecondaryEngineer { get; set; }
public float SplitPercentage { get; set; }
public DateTime ExpectedOrder { get; set; }
public DateTime? RequiredOnSiteBy { get; set; }
public bool LightingDesignRequired { get; set; }
public string ReasonForLightingDesign { get; set; }
public DateTime? DesignRequiredBy { get; set; }
public DateTime? FollowUp { get; set; }
public string Comments { get; set; }
public int CurrencyId { get; set; }
public bool Void { get; set; }
public string AttachmentFolder { get; set; }
public virtual Currency Currency { get; set; }
public virtual Reason Reason { get; set; }
public virtual ProjectStatus Status { get; set; }
public virtual ProjectType Type { get; set; }
public virtual Sector Sector { get; set; }
public virtual ICollection<ProjectProducts> Products { get; set; }
public virtual Team Team { get; set; }
public object Key
{
get { return Id; }
}
}
You can use stringify package.
It exists in Nuget.
You can Hide parameters with Hidden attribute.
You can print every object with a.stringify();

Reading from Xml FIle into existing dataTable C# ASP.NET Core

Here is the method where I have the problem:
[HttpPost]
public async Task<IActionResult> XmlPage(IFormFile xmlFile)
{
var uploads = hostingEnvironment.WebRootPath;
if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
{
try
{
using (var fileStream = new FileStream(Path.Combine(uploads, xmlFile.FileName), FileMode.Create))
{
await xmlFile.CopyToAsync(fileStream);
XDocument xDoc = XDocument.Load(fileStream);
List<DmgRegister> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg =>
new DmgRegister
{
Uwyear = dmgReg.Element("UWYear").Value,
ClaimNo = dmgReg.Element("ClaimNo").Value,
PolicyNo = dmgReg.Element("PolicyNo").Value,
PolicyName = dmgReg.Element("PolicyHolder").Value,
Address1 = dmgReg.Element("Address1").Value,
Address2 = dmgReg.Element("Addresstype").Value,
PostalLocation = dmgReg.Element("City").Value,
Country = dmgReg.Element("Country").Value,
PostalCode = dmgReg.Element("Postalzone").Value
}).ToList();
context.SaveXmlToDb(dmgRegistterList);
}
catch
{
//Here where i come when i try to upload and parse the data
ViewBag.Error = "Converting fail";
return View("Export");
}
}
else
{
ViewBag.Error = "Uploading fail";
return View("Index");
}
return View();
}
Im trying to upload an xml file and then parse into a SQL Table(Sql DataTable named DmgRegister), I'm a beginner with ASP.Net so exuse me if the code looks like an italian spaghetti.
// SaveXmlToDb method in context
foreach (var item in dmgRegistterList)
{
DmgRegister.Add(item);
}
SaveChanges();
}
Now the Model that I'm trying to bind data from XML and save it to DataTable
[Serializable]
[XmlRoot("Claims")]
public class Claim
{
[XmlElement("ClientName")]
public string ClientName { get; set; }
[XmlElement("UWYear")]
public string Uwyear { get; set; }
[XmlElement("AgreementNo")]
public string AgreementNo { get; set; }
[XmlElement("BusinessType")]
public string BusinessType { get; set; }
[XmlElement("PeriodStart")]
public DateTime? PeriodStart { get; set; }
[XmlElement("PeriodEnd")]
public DateTime? PeriodEnd { get; set; }
[XmlElement("PolicyNo")]
public string PolicyNo { get; set; }
[XmlElement("PolicyHolder")]
public string PolicyName { get; set; }
[XmlElement("DateOfLoss")]
public DateTime? DateOfLoss { get; set; }
[XmlElement("ClaimNo")]
public string ClaimNo { get; set; }
[XmlElement("ClaimantName")]
public string ClaimantName { get; set; }
[XmlElement("ClaimedInsured")]
public string ClaimedInsured { get; set; }
[XmlElement("ReportDate")]
public DateTime? ReportDate { get; set; }
[XmlElement("CountryOfRisk")]
public string CountryOfRisk { get; set; }
[XmlElement("CountryOfLoss")]
public string CountryOfLoss { get; set; }
[XmlElement("TypeOfLoss")]
public string TypeOfLoss { get; set; }
[XmlElement("InsuranceCoverage")]
public string InsuranceCoverage { get; set; }
[XmlElement("LineOfBuisnessNo")]
public int? LineOfBuisnessNo { get; set; }
[XmlElement("LineOfBuisnessName")]
public string LineOfBuisnessName { get; set; }
[XmlElement("ClassOfBuisnessNo")]
public int? ClassOfBuisnessNo { get; set; }
[XmlElement("ClassOfBuisnessName")]
public string ClassOfBuisnessName { get; set; }
[XmlElement("CaptiveShare")]
public int? CaptiveShare { get; set; }
[XmlElement("OriginalCurrency")]
public string OriginalCurrency { get; set; }
[XmlElement("PaymentCurrency")]
public string PaidInCurrency { get; set; }
[XmlElement("TotalIncurredCaptiveShare")]
public decimal? TotalIncurredCaptiveShare { get; set; }
[XmlElement("PaidThisPeriod")]
public decimal? PaidThisPeriod { get; set; }
[XmlElement("PeriodDate")]
public DateTime? PeriodDate { get; set; }
[XmlElement("PaymentDate")]
public DateTime? PaymentDate { get; set; }
[XmlElement("TotalPaidCaptiveShare")]
public decimal? TotalPaidCaptiveShare { get; set; }
[XmlElement("RemainingReserveCaptiveShare")]
public decimal? RemainingReserveCaptiveShare { get; set; }
[XmlElement("Deductible")]
public string Deductible { get; set; }
[XmlElement("Recovery")]
public string Recovery { get; set; }
[XmlElement("LocationAdress")]
public string LocationAdress { get; set; }
[XmlElement("Address1")]
public string Address1 { get; set; }
[XmlElement("Addresstype")]
public string Address2 { get; set; }
[XmlElement("Postalzone")]
public string PostalCode { get; set; }
[XmlElement("City")]
public string PostalLocation { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
[XmlElement("GeograficalDiversification")]
public string GeograficalDiversification { get; set; }
[XmlElement("Cause")]
public string Cause { get; set; }
[XmlElement("Status")]
public string Status { get; set; }
[XmlElement("CloseDate")]
public DateTime? CloseDate { get; set; }
[XmlElement("DevelopmentYear")]
public string DevelopmentYear { get; set; }
[XmlElement("TotalIncurredInsurerShare")]
public decimal? TotalIncurredInsurerShare { get; set; }
[XmlElement("TotalPaidInsurerShare")]
public decimal? TotalPaidInsurerShare { get; set; }
[XmlElement("RemainingReserveInsurerShare")]
public decimal? RemainingReserveInsurerShare { get; set; }
}
[Serializable()]
[XmlRoot("Claims")]
public class Claims
{
[XmlArray("Claims")]
[XmlArrayItem("Claim", typeof(Claim))]
public Claim[] Claim { get; set; }
}
Here is the Xml example that im try upload
<ns0:Claims>
<Claim>
<ClaimNo>LL0000110262</ClaimNo>
<PolicyNo>LP0000004481</PolicyNo>
<PolicyHolder>NCC Rakennus Oy</PolicyHolder>
<AddressId>1</AddressId>
<Address1>Example Street 1</Address1>
<Addresstype>LocationOfLoss</Addresstype>
<City>Helsinki</City>
<Country>FI</Country>
<Postalzone>12345</Postalzone>
<UWYear>2015</UWYear>
<PeriodStart>2015-01-01</PeriodStart>
<PeriodEnd>2015-12-31</PeriodEnd>
<DateOfLoss>2015-07-15</DateOfLoss>
<ReportDate/>
<StatusAsPer>2015-12-31</StatusAsPer>
<Coverage>?</Coverage>
<TypeOfLoss>Leakage</TypeOfLoss>
<OriginalCurrency>EUR</OriginalCurrency>
<PaymentCurrency>EUR</PaymentCurrency>
<TotalReservesOrigCurr>0.00</TotalReservesOrigCurr>
<TotalPaymentOrigCurr>0.00</TotalPaymentOrigCurr>
<DeductibleOrigCurr>85000.00</DeductibleOrigCurr>
<TotalAmountOfClaimOrigCurr>3680.00</TotalAmountOfClaimOrigCurr>
<Status>Active</Status>
</Claim>
</ns0:Claims>
I try it even to convert from XML to JSON, but it jumps to catch
public async Task<IActionResult> XmlPage(IFormFile xmlFile)
{
var uploads = hostingEnvironment.WebRootPath;
var filePath = Path.Combine(uploads, xmlFile.FileName);
if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
{
try
{
using (var xReader = XmlReader.Create(new StringReader(filePath)))
{
// This line skips the XML declaration, eg "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - you can skip this if you don't have declaration as in your case
xReader.MoveToContent();
// Gets the actual XMLElement, if any
xReader.Read();
// Convert the xReader to an XNode for the Json serializer
XNode node = XNode.ReadFrom(xReader);
// Json output
string jsonText = JsonConvert.SerializeXNode(node);
}
}
catch
{
ViewBag.Error = "Converting fail";
return View("Export");
}
}
else
{
ViewBag.Error = "Uploading fail";
return View();
}
return View("Index");
}
Thx a lot CountZero, really gratefull after my first question here, still had issues but now is everything working,
The method in controller
public async Task<IActionResult> XmlPage(IFormFile xmlFile)
{
var uploads = hostingEnvironment.WebRootPath;
var filePath = Path.Combine(uploads, xmlFile.FileName).ToString();
if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
{
try
{
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await xmlFile.CopyToAsync(fileStream);
fileStream.Dispose();
XDocument xDoc = XDocument.Load(filePath);
List<DmgRegisterVM> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg =>
new DmgRegisterVM
{
Uwyear = dmgReg.Element("UWYear").Value,
ClaimNo = dmgReg.Element("ClaimNo").Value,
PolicyNo = dmgReg.Element("PolicyNo").Value,
PolicyName = dmgReg.Element("PolicyHolder").Value,
Address1 = dmgReg.Element("Address1").Value,
Address2 = dmgReg.Element("Addresstype").Value,
PostalLocation = dmgReg.Element("City").Value,
Country = dmgReg.Element("Country").Value,
PostalCode = dmgReg.Element("Postalzone").Value
}).ToList();
context.SaveXmlToDb(dmgRegistterList);
}
}
catch(Exception e)
{
ViewBag.Error = "Converting fail";
}
}
else
{
ViewBag.Error = "Uploading fail";
}
return View("Index");
}
SaveXmlToDb method in context
public void SaveXmlToDb(List<DmgRegisterVM> dmgRegList)
{
//from list to database
foreach (var item in dmgRegList)
{
var model = Mapper.Map<DmgRegister>(item);
DmgRegister.Add(model);
SaveChanges();
}
}
And finally the Claim class (where i have XML elements)
[Serializable]
[XmlRoot("ns0:Claims")]
public class Claim
{
[XmlElement("ClientName")]
public string ClientName { get; set; }
[XmlElement("UWYear")]
public string Uwyear { get; set; }
[XmlElement("AgreementNo")]
public string AgreementNo { get; set; }
[XmlElement("BusinessType")]
public string BusinessType { get; set; }
[XmlElement("PeriodStart")]
public DateTime? PeriodStart { get; set; }
[XmlElement("PeriodEnd")]
public DateTime? PeriodEnd { get; set; }
[XmlElement("PolicyNo")]
public string PolicyNo { get; set; }
[XmlElement("PolicyHolder")]
public string PolicyName { get; set; }
[XmlElement("DateOfLoss")]
public DateTime? DateOfLoss { get; set; }
[XmlElement("ClaimNo")]
public string ClaimNo { get; set; }
[XmlElement("ClaimantName")]
public string ClaimantName { get; set; }
[XmlElement("ClaimedInsured")]
public string ClaimedInsured { get; set; }
[XmlElement("ReportDate")]
public DateTime? ReportDate { get; set; }
[XmlElement("CountryOfRisk")]
public string CountryOfRisk { get; set; }
[XmlElement("CountryOfLoss")]
public string CountryOfLoss { get; set; }
[XmlElement("TypeOfLoss")]
public string TypeOfLoss { get; set; }
[XmlElement("InsuranceCoverage")]
public string InsuranceCoverage { get; set; }
[XmlElement("LineOfBuisnessNo")]
public int? LineOfBuisnessNo { get; set; }
[XmlElement("LineOfBuisnessName")]
public string LineOfBuisnessName { get; set; }
[XmlElement("ClassOfBuisnessNo")]
public int? ClassOfBuisnessNo { get; set; }
[XmlElement("ClassOfBuisnessName")]
public string ClassOfBuisnessName { get; set; }
[XmlElement("CaptiveShare")]
public int? CaptiveShare { get; set; }
[XmlElement("OriginalCurrency")]
public string OriginalCurrency { get; set; }
[XmlElement("PaymentCurrency")]
public string PaidInCurrency { get; set; }
[XmlElement("TotalIncurredCaptiveShare")]
public decimal? TotalIncurredCaptiveShare { get; set; }
[XmlElement("PaidThisPeriod")]
public decimal? PaidThisPeriod { get; set; }
[XmlElement("PeriodDate")]
public DateTime? PeriodDate { get; set; }
[XmlElement("PaymentDate")]
public DateTime? PaymentDate { get; set; }
[XmlElement("TotalPaidCaptiveShare")]
public decimal? TotalPaidCaptiveShare { get; set; }
[XmlElement("RemainingReserveCaptiveShare")]
public decimal? RemainingReserveCaptiveShare { get; set; }
[XmlElement("Deductible")]
public string Deductible { get; set; }
[XmlElement("Recovery")]
public string Recovery { get; set; }
[XmlElement("LocationAdress")]
public string LocationAdress { get; set; }
[XmlElement("Address1")]
public string Address1 { get; set; }
[XmlElement("Addresstype")]
public string Address2 { get; set; }
[XmlElement("Postalzone")]
public string PostalCode { get; set; }
[XmlElement("City")]
public string PostalLocation { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
[XmlElement("GeograficalDiversification")]
public string GeograficalDiversification { get; set; }
[XmlElement("Cause")]
public string Cause { get; set; }
[XmlElement("Status")]
public string Status { get; set; }
[XmlElement("CloseDate")]
public DateTime? CloseDate { get; set; }
[XmlElement("DevelopmentYear")]
public string DevelopmentYear { get; set; }
[XmlElement("TotalIncurredInsurerShare")]
public decimal? TotalIncurredInsurerShare { get; set; }
[XmlElement("TotalPaidInsurerShare")]
public decimal? TotalPaidInsurerShare { get; set; }
[XmlElement("RemainingReserveInsurerShare")]
public decimal? RemainingReserveInsurerShare { get; set; }
}
//[ModelMetadataType(typeof(DmgRegisterMetaData))]
[Serializable()]
[XmlRoot("ns0:Claims")]
public class ClaimsCollection
{
[XmlArray("Claims")]
[XmlArrayItem("Claim", typeof(Claim))]
public Claim[] Claim { get; set; }
}
Given you are getting a "Root element is missing" this looks like an issue with your mapping.
[XmlRoot("Claims")] will not map onto <ns0:Claims>.
Try updating your XML so the roots element is set to <Claims></Claims> rather than
<ns0:Claims></ns0:Claims>.
If this fixes it then you can either change your XML or update your attribute in the class so it looks like this.
[XmlRoot("ns0:Claims")].

c# how to derive data from 3 tables in one object list

I'm struggeling with nested classes. What I'm trying to do is derive a dataset from 3 related tables.
Here are the classes:
public partial class Trades
{
public Trades()
{
this.Executions = new HashSet<Executions>();
}
public int TradeId { get; set; }
public DateTime CreationDate { get; set; }
public int MarketParticipantId { get; set; }
public Nullable<int> TraderId { get; set; }
public int OtherMarketParticipantId { get; set; }
public tradeType TradeType { get; set; }
public orderTypesType OrderType { get; set; }
public tradingCapacityType TradingCapacity { get; set; }
public organisedMarketPlaceIdentifier OrganisedMarketPlaceIdentifier { get; set; }
public actionTypesType ActionType { get; set; }
public string LinkedTransactionId { get; set; }
public virtual ICollection<Executions> Executions { get; set; }
public virtual MarketParticipants MarketParticipants { get; set; }
public virtual MarketParticipants MarketParticipants1 { get; set; }
}
public partial class Executions
{
public Executions()
{
this.ExecutionDetails = new HashSet<ExecutionDetails>();
}
public int ExecutionsId { get; set; }
public DateTime CreationDate { get; set; }
public string ContractId { get; set; }
public string ContractName { get; set; }
public contractTypeType ContractType { get; set; }
public buySellIndicatorType Side { get; set; }
public energyCommodityType Commodity { get; set; }
public settlementMethodType SettlementMethod { get; set; }
public DateTime ExecutionStartDate { get; set; }
public DateTime ExecutionEndDate { get; set; }
public DateTime TransactionTime { get; set; }
public int DeliveryPointsId { get; set; }
public int TradeId { get; set; }
public virtual DeliveryPoints DeliveryPoints { get; set; }
public virtual Trades Trades { get; set; }
public virtual ICollection<ExecutionDetails> ExecutionDetails { get; set; }
}
This piece of code give me back a data setin an IQueryable object.
public static IQueryable GedTrades(int mpId, DateTime startDate, DateTime endDate)
{
var context = new RemitEntities();
var myTrades = context.Trades
.Where(t => (t.MarketParticipantId == mpId))
.Select(
t =>
new
{
MarketParticipantId = t.MarketParticipantId,
TraderId = t.TraderId,
OtherMarketParticipantId = t.OtherMarketParticipantId,
TradeType = t.TradeType,
OrderType = t.OrderType,
TradingCapacity = t.TradingCapacity,
OrganisedMarketPlaceIdentifier = t.OrganisedMarketPlaceIdentifier,
ActionType = t.ActionType,
LinkedTransactionId = t.LinkedTransactionId,
Executions = context.Executions
.Where(ex =>
(((ex.TradeId == t.TradeId) && (ex.ExecutionStartDate >= startDate)) &&
(ex.ExecutionEndDate < endDate)
)
).Select(ex =>
new
{
ContractId = ex.ContractId,
ContractName = ex.ContractName,
ContractType = ex.ContractType,
Side = ex.Side,
Commodity = ex.Commodity,
SettlementMethod = ex.SettlementMethod,
ExecutionStartDate = ex.ExecutionStartDate,
ExecutionEndDate = ex.ExecutionEndDate,
TransactionTime = ex.TransactionTime,
DeliveryPointsId = ex.DeliveryPointsId,
ExecutionDetails = context.ExecutionDetails
.Where(ed => (ed.ExecutionsId == ex.ExecutionsId))
.Select(
ed =>
new
{
Uti = ed.Uti,
DeliveryStartTime = ed.DeliveryStartTime,
DeliveryEndTime = ed.DeliveryEndTime,
Price = ed.Price,
Currency = ed.Currency,
Quantity = ed.Quantity,
QuantityType = ed.QuantityType
}
)
}
)
}
);
return myTrades;
}
What I realy like to achieve is to parse the data set to another object by e.g. a list object like List.
How do I do that?

Adding multiple different types of records in some collection and sorting them

I want to send a collection of two different Collections as a Json but in a sorted format. I am not able to do it with Linq. Need little help.And also is there any better way. Thank you!
Here is my action.
public ActionResult GetAllJobPosts()
{
var Institutes = new List<Institute>()
{
new Institute(){InstituteId="ins1",InstituteName="name1",Location="Mumbai"},
new Institute(){InstituteId="ins2",InstituteName="name2",Location="Navi Mumbai"},
new Institute(){InstituteId="ins3",InstituteName="name3",Location="Thiruvananthpuram"}
};
var Companys = new List<Company>()
{
new Company(){CompanyId="com1",CompanyName="comName1",Location="Mumbai"},
new Company(){CompanyId="com2",CompanyName="comName2",Location="Navi Mumbai"},
new Company(){CompanyId="com3",CompanyName="comName3",Location="Mumbai"}
};
var Organizations = new List<Organization>()
{
new Organization(){OrganizationId="org1",OrganizationName="orgName1",Location="Navi Mumbai"},
new Organization(){OrganizationId="org2",OrganizationName="orgName2",Location="Navi Mumbai"},
new Organization(){OrganizationId="org3",OrganizationName="orgName3",Location="Mumbai"},
};
var CompanyJobPosts = new List<CompanyJobPost>()
{
new CompanyJobPost(){CompanyId="com1",CompanyJobPostId="com1jp1",CreatedOn=System.DateTime.Now.AddDays(-2),JobDiscription="Tester",KeySkils="Sylanium"},
new CompanyJobPost(){CompanyId="com1",CompanyJobPostId="com1jp2",CreatedOn=System.DateTime.Now.AddDays(-3),JobDiscription="Developer",KeySkils="C#"},
new CompanyJobPost(){CompanyId="com2",CompanyJobPostId="com2jp1",CreatedOn=System.DateTime.Now.AddDays(-5),JobDiscription="Tester",KeySkils="Sylanium"},
new CompanyJobPost(){CompanyId="com2",CompanyJobPostId="com2jp2",CreatedOn=System.DateTime.Now.AddDays(-6),JobDiscription="Developer",KeySkils="C#"},
new CompanyJobPost(){CompanyId="com3",CompanyJobPostId="com3jp1",CreatedOn=System.DateTime.Now.AddDays(-7),JobDiscription="Tester",KeySkils="Sylanium"},
new CompanyJobPost(){CompanyId="com3",CompanyJobPostId="com3jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils="C#"}
};
var InstituteJobPosts = new List<InstituteJobPost>()
{
new InstituteJobPost(){InstituteId="ins1",InstituteJobPostId="ins1jp1",CreatedOn=System.DateTime.Now.AddDays(-1),JobDiscription="Trainer",KeySkils="C#",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins1",InstituteJobPostId="ins1jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils="Java",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins2",InstituteJobPostId="ins2jp1",CreatedOn=System.DateTime.Now.AddDays(-1),JobDiscription="Trainer",KeySkils="Java",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins2",InstituteJobPostId="ins2jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils=".Net",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins3",InstituteJobPostId="ins3jp1",CreatedOn=System.DateTime.Now.AddDays(-1),JobDiscription="Trainer",KeySkils="C#",ExtraField="MDifferent"},
new InstituteJobPost(){InstituteId="ins3",InstituteJobPostId="ins3jp2",CreatedOn=System.DateTime.Now.AddDays(-8),JobDiscription="Developer",KeySkils="Java",ExtraField="MDifferent"}
};
var allJobPosts=new List<object>();
foreach (var item in CompanyJobPosts)
{
allJobPosts.Add(new { JType = "Company", JobPost = item });
}
foreach (var item in InstituteJobPosts)
{
allJobPosts.Add(new { JType = "Institute", JobPost = item });
}
//var allJobPostsOrderdByDate=??
return Json(allJobPosts, JsonRequestBehavior.AllowGet);
}
Here are My Models just to make it simple.
namespace WebApplication1.Models
{
public class Company
{
public string CompanyId { get; set; }
public string CompanyName { get; set; }
public string Location { get; set; }
}
public class Organization
{
public string OrganizationId { get; set; }
public string OrganizationName { get; set; }
public string Location { get; set; }
}
public class Institute
{
public string InstituteId { get; set; }
public string InstituteName { get; set; }
public string Location { get; set; }
}
public class CompanyJobPost
{
public string CompanyJobPostId { get; set; }
public string CompanyId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
}
public class OrganizationJobPost
{
public string OrganizationJobPostId { get; set; }
public string OrganizationId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField2 { get; set; }
}
public class InstituteJobPost
{
public string InstituteJobPostId { get; set; }
public string InstituteId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField { get; set; }
}
}
And finally my sweet view
<input name="GetAllJobPosts" id="GetAllJobPosts" type="submit" value="Search Jobs">
<ul id="JobPostList"></ul>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$("#GetAllJobPosts").click(function () {
var actionUrl = '#Url.Action("GetAllJobPosts", "Default")';
$.getJSON(actionUrl, displayDetailData);
});
function displayDetailData(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
$("#JobPostList").append("<li>" + response[i].JType + " " + (response[i].JobPost).CreatedOn + "</li>")
}
}
}
Thank You!
Based on your comments, I can only assume the following, so will do my best to point you in the correct direction:
You do not have a common object of inheritance between the two - that is, you wish to sort them on property x, but property x, is not defined to exist in both.
So, solution? Easy: add a common interface, class or abstract class between the two that has the property you wish to sort by, then sort by it:
public interface IJobPost
{
DateTime CreatedOn { get; set; }
}
Then modify your three existing objects:
public class CompanyJobPost : IJobPost
{
public string CompanyJobPostId { get; set; }
public string CompanyId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
}
public class OrganizationJobPost : IJobPost
{
public string OrganizationJobPostId { get; set; }
public string OrganizationId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField2 { get; set; }
}
public class InstituteJobPost : IJobPost
{
public string InstituteJobPostId { get; set; }
public string InstituteId { get; set; }
public string KeySkils { get; set; }
public string JobDiscription { get; set; }
public DateTime CreatedOn { get; set; }
public string ExtraField { get; set; }
}
Lastly, the action:
var allJobPosts=new List<IJobPost>();
// Add other posts to allJobPosts here.
var allJobPostsOrderdByDate = allJobPosts.OrderBy(x => x.CreatedOn).ToList();
Note: Code is untested. LINQ query may or may not work. Did this all from memory.
Edit: You can also share any other properties you wish to force between the three of them. That is what an interface or abstract class is for. That also means you can share Description or other properties.

Categories

Resources