How to add more Attribute in XElement? - c#-4.0

I have a data structure as under
class BasketCondition
{
public List<Sku> SkuList { get; set; }
public string InnerBoolean { get; set; }
}
class Sku
{
public string SkuName { get; set; }
public int Quantity { get; set; }
public int PurchaseType { get; set; }
}
Now let us populate some value to it
var skuList = new List<Sku>();
skuList.Add(new Sku { SkuName = "TSBECE-AA", Quantity = 2, PurchaseType = 3 });
skuList.Add(new Sku { SkuName = "TSEECE-AA", Quantity = 5, PurchaseType = 3 });
BasketCondition bc = new BasketCondition();
bc.InnerBoolean = "OR";
bc.SkuList = skuList;
The desire output is
<BasketCondition>
<InnerBoolean Type="OR">
<SKUs Sku="TSBECE-AA" Quantity="2" PurchaseType="3"/>
<SKUs Sku="TSEECE-AA" Quantity="5" PurchaseType="3"/>
</InnerBoolean>
</BasketCondition>
My program so far is
XDocument doc =
new XDocument(
new XElement("BasketCondition",
new XElement("InnerBoolean", new XAttribute("Type", bc.InnerBoolean),
bc.SkuList.Select(x => new XElement("SKUs", new XAttribute("Sku", x.SkuName)))
)));
Which gives me the output as
<BasketCondition>
<InnerBoolean Type="OR">
<SKUs Sku="TSBECE-AA" />
<SKUs Sku="TSEECE-AA" />
</InnerBoolean>
</BasketCondition>
How can I add the rest of the attributes Quantity and PurchaseType to my program.
Please help

I found it
bc.SkuList.Select(x => new XElement("SKUs", new XAttribute("Sku", x.SkuName),
new XAttribute("Quantity", x.Quantity),
new XAttribute("PurchaseType", x.PurchaseType)
))

You can simply do this:
yourXElement.Add(new XAttribute("Quantity", "2"));
yourXElement.Add(new XAttribute("PurchaseType", "3"));

Related

How can I populate the datagrid cobmo box column in WPF?

I am having problems populating data grid combo box column with combo boxes, the data grid column is not showing any data. But, first things first. Here are my binding classes:
public class StartingEleven
{
public string name { get; set; }
public int shirt_number { get; set; }
public string position { get; set; }
public bool captain { get; set; }
}
public class DGObject
{
public string FifaID { get; set; }
public string Venue { get; set; }
public string Location { get; set; }
public DateTime Date { get; set; }
public int Goals { get; set; }
public int Penalties { get; set; }
public string AwayTeamCode { get; set; }
public int GuestGoals { get; set; }
public List<StartingEleven> HomeTeam11 { get; set; }
}
And my root object:
public class RootObject
{
public string venue { get; set; }
public string location { get; set; }
public string status { get; set; }
public string time { get; set; }
public string fifa_id { get; set; }
public Weather weather { get; set; }
public string attendance { get; set; }
public List<string> officials { get; set; }
public string stage_name { get; set; }
public string home_team_country { get; set; }
public string away_team_country { get; set; }
public DateTime datetime { get; set; }
public string winner { get; set; }
public string winner_code { get; set; }
public HomeTeam home_team { get; set; }
public AwayTeam away_team { get; set; }
public List<HomeTeamEvent> home_team_events { get; set; }
public List<AwayTeamEvent> away_team_events { get; set; }
public HomeTeamStatistics home_team_statistics { get; set; }
public AwayTeamStatistics away_team_statistics { get; set; }
public DateTime last_event_update_at { get; set; }
public DateTime last_score_update_at { get; set; }
}
There is a saying: a single picture is worth a thousand words... So, to be more accurate, first, here is my output that I am having problems with:
Here is my method that loads this datagrid:
public static void LoadAllEventsForHomeTeam(System.Windows.Controls.ComboBox cb, System.Windows.Controls.DataGrid dg)
{
var url = new Url("http://worldcup.sfg.io/matches/country?fifa_code=");
string urlEndpoint = GetItemFromComboBoxWpf(cb);
var request = url + urlEndpoint;
string cbItem = cb.SelectedItem.ToString();
System.Windows.Controls.DataGridTextColumn c1 = new System.Windows.Controls.DataGridTextColumn();
c1.Header = "Game ID";
c1.Binding = new System.Windows.Data.Binding("FifaID");
c1.Width = 120;
dg.Columns.Add(c1);
System.Windows.Controls.DataGridTextColumn c2 = new System.Windows.Controls.DataGridTextColumn();
c2.Header = "City";
c2.Binding = new System.Windows.Data.Binding("Venue");
c2.Width = 95;
dg.Columns.Add(c2);
System.Windows.Controls.DataGridTextColumn c3 = new System.Windows.Controls.DataGridTextColumn();
c3.Header = "Location";
c3.Binding = new System.Windows.Data.Binding("Location");
c3.Width = 150;
dg.Columns.Add(c3);
System.Windows.Controls.DataGridTextColumn c4 = new System.Windows.Controls.DataGridTextColumn();
c4.Header = "Date";
c4.Binding = new System.Windows.Data.Binding("Date");
c4.Width = 180;
dg.Columns.Add(c4);
System.Windows.Controls.DataGridTextColumn c5 = new System.Windows.Controls.DataGridTextColumn();
c5.Header = "Goals";
c5.Binding = new System.Windows.Data.Binding("Goals");
c5.Width = 75;
dg.Columns.Add(c5);
System.Windows.Controls.DataGridTextColumn c6 = new System.Windows.Controls.DataGridTextColumn();
c6.Header = "Penalties";
c6.Binding = new System.Windows.Data.Binding("Penalties");
c6.Width = 100;
dg.Columns.Add(c6);
System.Windows.Controls.DataGridTextColumn c7 = new System.Windows.Controls.DataGridTextColumn();
c7.Header = "Guest";
c7.Binding = new System.Windows.Data.Binding("AwayTeamCode");
c7.Width = 90;
dg.Columns.Add(c7);
System.Windows.Controls.DataGridTextColumn c8 = new System.Windows.Controls.DataGridTextColumn();
c8.Header = "Guest score";
c8.Binding = new System.Windows.Data.Binding("GuestGoals");
c8.Width = 110;
dg.Columns.Add(c8);
System.Windows.Controls.DataGridComboBoxColumn c9 = new System.Windows.Controls.DataGridComboBoxColumn();
c9.Header = "Team 11";
c9.TextBinding = new System.Windows.Data.Binding("HomeTeam11");
c9.Width = 110;
dg.Columns.Add(c9);
try
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(async () =>
// await Task.Run(async () =>
{
if (request != null)
{
List<Teams.RootObject> matches = await request.GetJsonAsync<List<Teams.RootObject>>();
foreach (var match in matches)
{
if (cbItem.Contains(match.home_team.code))
{
dg.Items.Add(new Teams.DGObject
{
FifaID = match.fifa_id,
Venue = match.venue,
Location = match.location,
Date = match.datetime.ToLocalTime(),
Goals = match.home_team.goals,
Penalties = match.home_team.penalties,
AwayTeamCode = match.away_team.code,
GuestGoals = match.away_team.goals,
HomeTeam11 = match.home_team_statistics.starting_eleven
});
}
}
}
}));
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
As you can see, this method loads datagrid with events which are soccer matches for selected team. By selecting an item from combo box, here named cb, a method forms an API call by completing an API call with selected combo box item as endpoint thus loading datagrid with matches that Germany played as a home team. Now, here is the problem: Last column, here named Team11 should contain combo boxes, and combo boxes should contain eleven players (starting eleven) that played that match. Selected team, in this case Germany, obviously, played four matches as home team. So, in column Team11 there should be four comboboxes, one for each game, placed in each row, and each combobox should contain eleven players that played that particular match, but there is no data in column Team11. Any ideas? Thank you.

Why this is not working with AutoMapper?

I'm new in AutoMapper and I'm trying to map list to list in this way:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
public class PersonMin
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<List<Person>, List<PersonMin>>();
});
IMapper iMapper = config.CreateMapper();
List<Person> source = new List<Person>
{
new Person { Id = 1, FirstName = "Bob", LastName = "Davis", Address = "Street1", Age = 40},
new Person { Id = 2, FirstName = "Rob", LastName = "Mavis", Address = "Street2", Age = 42}
};
List<PersonMin> destination = iMapper.Map<List<Person>, List<PersonMin>>(source);
foreach (var item in destination)
{
Console.WriteLine(item.Id + ", " + item.FirstName + ", " + item.LastName);
}
The destination is empty.
You don't need to care about the list.
Just simply map the models
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Person, PersonMin>();
});

ServiceStack 'ExcludePropertyReferences' dynamically if decorate with datamember attribute

I want to ignore some properties from my Object during run time. The properties are decorated with data member attribute (Without data member attribute excludepropertyreferencces is working fine). Can you please provide some insight? Thanks
Question : HOW TO EXCLUDE PROPERTIES AT RUN TIME, IF THEY ARE DECORATE WITH DATAMEMBER ATTRIBUTE ?
ServiceStack , ExcludePropertyReferences
var model = new Model {
FirstName = "First Name",
LastName = "Last Name",
Children = new List<ModelChild>{
new ModelChild { ChildFirstName = "ChildFirstName 1", ChildLastName = "ChildLastName 1" },
new ModelChild { ChildFirstName = "ChildFirstName 2", ChildLastName = "ChildLastName 2" }
}
};
var model1 = new Model1 {
FirstName = "First Name",
LastName = "Last Name",
Children = new List<Model1Child>{
new Model1Child { ChildFirstName = "ChildFirstName 1", ChildLastName = "ChildLastName 1" },
new Model1Child { ChildFirstName = "ChildFirstName 2", ChildLastName = "ChildLastName 2" }
}
};
Console.WriteLine("Properties won't get ignored because the Model is decorated with Serialization Attributes");
using(MemoryStream stream = new MemoryStream())
using (var jsConfig = JsConfig.BeginScope()) {
jsConfig.ExcludeTypeInfo = true;
jsConfig.ExcludePropertyReferences = new [] { "Model.LastName", "ModelChild.ChildLastName" }.ToArray();
JsonSerializer.SerializeToStream(model, model.GetType(), stream);
LINQPad.Extensions.Dump(System.Text.Encoding.Default.GetString(stream.ToArray()));
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Properties will get ignored because the Model is not decorated with Serialization Attributes");
using(MemoryStream stream = new MemoryStream())
using (var jsConfig = JsConfig.BeginScope()) {
jsConfig.ExcludeTypeInfo = true;
jsConfig.ExcludePropertyReferences = new [] { "Model1.LastName", "Model1Child.ChildLastName" }.ToArray();
JsonSerializer.SerializeToStream(model1, model1.GetType(), stream);
LINQPad.Extensions.Dump(System.Text.Encoding.Default.GetString(stream.ToArray()));
}
// Define other methods and classes here
[DataContract()]
public class Model {
[DataMember(Name = "first_name",EmitDefaultValue = false )]
public string FirstName { get; set; }
[DataMember(Name = "last_name")]
public string LastName { get; set; }
[DataMember(Name = "collections")]
public List<ModelChild> Children { get; set; }
}
[DataContract()]
public class ModelChild {
[DataMember(Name = "child_first_name")]
public string ChildFirstName { get; set; }
[DataMember(Name = "child_last_name")]
public string ChildLastName { get; set; }
}
public class Model1 {
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Model1Child> Children { get; set; }
}
public class Model1Child {
public string ChildFirstName { get; set; }
public string ChildLastName { get; set; }
}

EF is overriding properties that i have set

I'm using a EF 4.1 Code First setup, here are the entities.
public class Vendor
{
public int VendorId { get; set; }
public string Name { get; set; }
public virtual ICollection<VendorProduct> VendorProducts { get; set; }
}
public class VendorProduct
{
public int VendorProductId { get; set; }
public int ProductId { get; set; }
public int VendorId { get; set; }
public string VendorProductNumber { get; set; }
public int Quantity { get; set; }
public decimal SalesPrice { get; set; }
public Product Product { get; set; }
public Vendor Vendor { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Manufacturer { get; set; }
public string ManufacturerNumber { get; set; }
public string UPC { get; set; }
public decimal SalesPrice { get; set; }
public string Description { get; set; }
public virtual ICollection<VendorProduct> VendorProducts { get; set; }
}
Here are the configurations
public class VendorConfiguration : EntityTypeConfiguration<Vendor>
{
public VendorConfiguration()
{
Property(p => p.Name).IsOptional().HasMaxLength(128);
}
}
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
//HasKey(p => p.ProductId);
//HasMany(p => p.Images).WithOptional();
Property(p => p.Name).IsOptional().HasMaxLength(128);
Property(p => p.Manufacturer).IsOptional().HasMaxLength(64);
Property(p => p.ManufacturerNumber).IsOptional().HasMaxLength(32);
Property(p => p.UPC).IsOptional().HasMaxLength(32);
Property(p => p.SalesPrice).IsOptional();
}
}
public VendorProductConfiguration()
{
//HasKey(v => v.VendorProductId);
Property(o => o.Quantity).IsRequired();
Property(o => o.SalesPrice).IsRequired();
Property(o => o.VendorId).IsRequired();
Property(o => o.ProductId).IsRequired();
Property(o => o.VendorProductNumber).IsOptional().HasMaxLength(50);
HasRequired(o => o.Product).WithMany(p => p.VendorProducts).HasForeignKey(o => o.ProductId).WillCascadeOnDelete(false);
}
Here is the DbContext.
public class UbidContext : DbContext
{
public IDbSet<Product> Products { get; set; }
public IDbSet<Vendor> Vendors { get; set; }
public IDbSet<VendorProduct> VendorProducts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Add any configuration or mapping stuff here
modelBuilder.Configurations.Add(new VendorConfiguration());
modelBuilder.Configurations.Add(new VendorProductConfiguration());
modelBuilder.Configurations.Add(new ProductConfiguration());
}
public void Seed(UbidContext context)
{
//Create our indexes
context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_Name ON Products (Name)");
context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_Manufacturer ON Products (Manufacturer)");
context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_ManufacturerNumber ON Products (ManufacturerNumber)");
context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_UPC ON Products (UPC)");
//Add vendors to the database
AddVendors(context);
context.SaveChanges();
//Add products to the database
AddProducts(context);
context.SaveChanges();
//Add vendor products to the database
AddVendorProducts(context);
}
private static void AddVendors(UbidContext context)
{
new List<Vendor>
{
new Vendor()
{
Name = "TestVendor1",
},
new Vendor()
{
Name = "TestVendor2",
},
new Vendor()
{
Name = "TestVendor3",
}
}.ForEach(v => context.Vendors.Add(v));
}
private static void AddProducts(UbidContext context)
{
Image[] images = new Image[1];
images[0] = new Image
{
Url = "http://content.etilize.com/Thumbnail/10006997.jpg"
};
new List<Product>
{
new Product()
{
Manufacturer = "StarTech.com",
ManufacturerNumber = "SV211K",
Name = "StarTech.com SV211K KVM Switch - 2 x 1 - 2 x HD-15 Video",
UPC = "SV211K",
Images = images
},
new Product()
{
Manufacturer = "Targus Group International",
ManufacturerNumber = "CBT300",
Name = "Targus BlackTop Standard Notebook Case - Clamshell - Carrying Strap - 5 Pocket - Nylon - Black, Blue",
UPC = "CBT300"
},
new Product()
{
Manufacturer = "Lenovo Group Limited",
ManufacturerNumber = "31P8700",
Name = "Lenovo Optical ScrollPoint Pro Mouse - Optical - USB, PS/2",
UPC = "31P8700"
},
new Product()
{
Manufacturer = "Epson Corporation",
ManufacturerNumber = "C823071",
Name = "Epson Serial Interface Board with 32K Buffer - 1 x RS-232 Serial",
UPC = "C823071"
},
new Product()
{
Manufacturer = "Cisco Systems, Inc",
ManufacturerNumber = "WSX4013",
Name = "Cisco Catalyst 4000 Series Supervisor Engine II-Plus - 2 x GBIC, 1 x - Supervisor Engine",
UPC = "WSX4013"
}
}.ForEach(p => context.Products.Add(p));
}
private static void AddVendorProducts(UbidContext context)
{
Random random = new Random();
var vps = new List<VendorProduct>()
{
new VendorProduct()
{
ProductId = 1,
VendorId = 1,
Quantity = random.Next(3, 40),
SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)),
},
new VendorProduct()
{
ProductId = 2,
VendorId = 1,
Quantity = random.Next(3, 40),
SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)),
},
new VendorProduct()
{
ProductId = 3,
VendorId = 1,
Quantity = random.Next(3, 40),
SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)),
},
new VendorProduct()
{
ProductId = 4,
VendorId = 2,
Quantity = random.Next(3, 40),
SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)),
},
new VendorProduct()
{
ProductId = 4,
VendorId = 3,
Quantity = random.Next(3, 40),
SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)),
}
};
foreach (var vp in vps)
context.VendorProducts.Add(vp);
}
public class DropCreateIfChangeInitializer : DropCreateDatabaseIfModelChanges<UbidContext>
{
protected override void Seed(UbidContext context)
{
context.Seed(context);
base.Seed(context);
}
}
static UbidContext()
{
Database.SetInitializer<UbidContext>(new DropCreateIfChangeInitializer());
}
}
Now, what happens is that when it gets to the VendorProducts, the first one is added just fine, but the second one will not save because it looks like EF is not setting the Vendor object, the pattern that i see is that for each vendorproduct that is added if the vendorid and/or productid was used on a previous entity within the same context it will not populate the vendor or product so it sets it to null. As you can see from my code i am explicitly setting VendorId below, but when EF sends the data to the db, VendorId is null. If you need more info please let me know.
Thanks
I have copied and pasted your code into a console app with EF 4.1. When I run it I get this result in the database (SQL Server 2008 R2 Express):
I only have removed the stuff with the image and the Converter.ConvertObjToDecimal (didn't compile, I have directly used random.Next).
This is what one would expect from your code, I think. Do you get another result?

AutoMapper failing to map a simple list

I have used automapper for mapping lists in the past, for for some reason it won't work in this case.
public class MyType1 {
public int Id { get; set; }
public string Description { get; set; }
}
public class MyType2 {
public int Id { get; set; }
public string Description { get; set; }
}
public void DoTheMap() {
Mapper.CreateMap<MyType2, MyType1>();
Mapper.AssertConfigurationIsValid();
var theDto1 = new MyType2() { Id = 1, Description = "desc" };
var theDto2 = new MyType2() { Id = 2, Description = "desc2" };
List<MyType2> type2List = new List<MyType2> { theDto1, theDto2 };
List<MyType1> type1List = Mapper.DynamicMap<List<MyType1>>(type2List);
//FAILURE. NO EXCEPTION, BUT ZERO VALUES
List<MyType1> type1List2 =type2List.Select(Mapper.DynamicMap<MyType1>).ToList();
//SUCCESS, WITH LINQ SELECT
}
Change this:
Mapper.DynamicMap<List<MyType1>>(type2List)
To this:
Mapper.Map<List<MyType1>, List<MyType2>>(type2List);
DynamicMap is only if you don't know the type at compile time - for things like anonymous types.

Resources