I have a class like so:
[System.Serializable]
public class UIColor
{
public UIColor()
{
}
public UIColor(double red, double green, double blue, double alpha)
{
r = (float)red;
g = (float)green;
b = (float)blue;
a = (float)alpha;
}
public UIColor(double white, double alpha)
{
r = (float)white;
g = (float)white;
b = (float)white;
a = (float)alpha;
}
[System.Xml.Serialization.XmlElement("r", typeof(float))]
public float r
{
get;
set;
}
[System.Xml.Serialization.XmlElement("g", typeof(float))]
public float g
{
get;
set;
}
[System.Xml.Serialization.XmlElement("b", typeof(float))]
public float b
{
get;
set;
}
[System.Xml.Serialization.XmlElement("alpha", typeof(float))]
public float a
{
get;
set;
}
}
And many instances of it in a class like so:
class Colors
{
[XmlElement("Col1")]
UIColor Col1;
[XmlElement("Col2")]
UIColor Col2;
//etc etc
}
What I'd like to do is serialize out the class Colors into xml in the following format:
<Color name="Col1" r="1" g="1" b="1" alpha="1"/>
<Color name="Col2" r="2" g="2" b="2" alpha="2"/>
Currently the way it serializes out is like:
<Col1>
<r>1</r>
//etc etc
Your original class should look like:
[System.Serializable]
[System.Xml.Serialization.XmlRoot("Color")]
public class UIColor
{
public UIColor()
{
name = "Col1"
}
public UIColor(double red, double green, double blue, double alpha)
{
r = (float)red;
g = (float)green;
b = (float)blue;
a = (float)alpha;
name = "Col1";
}
public UIColor(double white, double alpha)
{
r = (float)white;
g = (float)white;
b = (float)white;
a = (float)alpha;
name = "Col1";
}
[System.Xml.Serialization.XmlAttribute]
public string name
{
get;
set;
}
[System.Xml.Serialization.XmlAttribute]
public float r
{
get;
set;
}
[System.Xml.Serialization.XmlAttribute]
public float g
{
get;
set;
}
[System.Xml.Serialization.XmlAttribute]
public float b
{
get;
set;
}
[System.Xml.Serialization.XmlAttribute("alpha")]
public float a
{
get;
set;
}
}
And the serialization code:
using (System.IO.TextWriter writer = new System.IO.StreamWriter(#"C:\temp\test.xml"))
{
System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(UIColor));
System.Xml.Serialization.XmlSerializerNamespaces namspace = new XmlSerializerNamespaces();
namespace.Add("", "");
xml.Serialize(writer, new UIColor(), namespace);
}
And the out XML will produce:
<?xml version="1.0" encoding="utf-8"?>
<Color name="Col1" r="0" g="0" b="0" alpha="0" />
Related
I was trying to do XML Serialization. Which have multiple different classes which is Header & Item. I create class TransferOrder to combine Header & Item. Header is doing well, but Item is showing twice.
Below here are my Program.cs
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Collections.Generic;
namespace XML_Serialization
{
class Program
{
public static void Main(string[] args)
{
Program p = new Program();
p.Final("item.xml");
}
public void Final(string filename)
{
XmlSerializer s = new XmlSerializer(typeof(TransferOrder));
TextWriter writer = new StreamWriter(filename);
TransferOrder c = new TransferOrder();
Header head = new Header();
head.DocNo = 0000000044;
head.MoveType = 311;
head.SourceStrType = 010;
head.SourceStrBin = "IQA";
head.DestStrType = 921;
head.DestStrBin = "TRANSFER";
head.Werks = 3006;
c.Header = head;
//Item Serialization
Item item1 = new Item();
item1.MaterialNo = 000000000010001251;
item1.Sloc = "KM22";
item1.Quantity = 5.000;
item1.UOM = "M2";
item1.PlantID = 3006;
item1.LineItem = 1;
Item item2 = new Item();
item2.MaterialNo = 000000000010001251;
item2.Sloc = "KM22";
item2.Quantity = 5.000;
item2.UOM = "M2";
item2.PlantID = 3006;
item2.LineItem = 2;
Item item3 = new Item();
item3.MaterialNo = 000000000010001251;
item3.Sloc = "KM22";
item3.Quantity = 5.000;
item3.UOM = "M2";
item3.PlantID = 3006;
item3.LineItem = 3;
Item[] ig = { item1, item2, item3 };
c.Item = ig;
s.Serialize(writer, c);
writer.Close();
}
}
public class TransferOrder
{
public Header Header { get; set; }
public Item []Item { get; set; }
}
public class Header
{
public int DocNo { get; set; }
public int MoveType { get; set; }
public int SourceStrType { get; set; }
public string SourceStrBin { get; set; }
public int DestStrType { get; set; }
public string DestStrBin { get; set; }
public int Werks { get; set; }
}
public class Item
{
public int MaterialNo { get; set; }
public string Sloc { get; set; }
public double Quantity { get; set; }
public string UOM { get; set; }
public int PlantID { get; set; }
public int LineItem { get; set; }
}
The result I wanna get is like this
<?xml version="1.0" encoding="utf-8"?><dtl:TransferOrder xmlns:dtl="http://FS.BizTalk.App.RFID.CommonTODetail.Schemas.DetailTO/2021/03">
<Header>
<DocNo>0000000044</DocNo>
<MoveType>311</MoveType>
<SourceStrType>010</SourceStrType>
<SourceStrBin>IQA</SourceStrBin>
<DestStrType>921</DestStrType>
<DestStrBin>TRANSFER</DestStrBin>
<Werks>3006</Werks>
</Header>
<Item>
<MaterialNo>000000000010001251</MaterialNo>
<SLoc>KM22</SLoc>
<Quantity>5.000</Quantity>
<UOM>M2</UOM>
<PlantId>3006</PlantId>
<LineItem>1</LineItem>
</Item>
<Item>
<MaterialNo>000000000010001251</MaterialNo>
<SLoc>KM22</SLoc>
<Quantity>5.000</Quantity>
<UOM>M2</UOM>
<PlantId>3006</PlantId>
<LineItem>2</LineItem>
</Item>
<Item>
<MaterialNo>000000000010001251</MaterialNo>
<SLoc>KM22</SLoc>
<Quantity>5.000</Quantity>
<UOM>M2</UOM>
<PlantId>3006</PlantId>
<LineItem>3</LineItem>
</Item>
</dtl:TransferOrder>
However, if you run my code, the output of my code have 2 Item Element . Which is different with the one I want.
Could anyone help me to solve this ?
Add [XmlElement]:
public class TransferOrder
{
public Header Header { get; set; }
[XmlElement]
public Item []Item { get; set; }
}
(the default behaviour is to add a wrapper layer on lists/arrays; [XmlElement] tells it to omit that and go direct to the child data)
I have Collection:
public class Test
{
public double Index { set; get; }
public double A { set; get; }
public double B { set; get; }
public double C { set; get; }
}
List<Test> test = new List<Test>();
I filled A and B with some random numbers. After that, I want add items C in collection. For example, what I trying:
foreach (Test t in test)
{
c = t.A + t.B;
test.Add(new Test {C = c }); <------
}
How can I add element C on same position like A and B? (Sorry for my english)
If you want C to be the sum of A and B it might be better to use a computed field:
public class Test
{
public double Index { set; get; }
public double A { set; get; }
public double B { set; get; }
public double C
{
get
{
return A + B;
}
}
}
So
Test test = new Test()
{
A = 1;
B = 2;
};
test.C == 3; //true
the advantage of the above is that C is always the sum of the other values and you don't need to recompute it every time. So if I take above and do:
test.B = 3; //instead of the original 2
Then C stays in sync:
test.C == 3; //false
test.C == 4; //now true
To do this with your original method (or the other answer) means re-looping the result set.
Or in C# 6.0 you can use an expression-bodied property
public class Test
{
public double Index { set; get; }
public double A { set; get; }
public double B { set; get; }
public double C => A + B;
}
foreach (Test t in test)
{
t.C = t.A + t.B;
}
just set the property to the equation
I am wondering how to convert string to a colour I have already set in c#? I have a class which sets a colour from a list and the colour variable name is set as a string. I have objects set as the colour but I am wondering how to set the colours using a colour converter for other objects, I realise this description is poor so hopefully my image will help explain more. Also hopefully someone can help me :)
Image 1 is my current output
Image 1
I want the colours under the "Zone legend" to be the same as the "Sequence Stratigraphy"
My Code for the colour setting of the sequence straigraphy is below along with my code for the zone legend
Sequence Stratigraphy Colours
internal static class ZoneColorizer
{
public static void Colorize(ZoneDto[] zones)
{
Color[] colorsToChooseFrom = new Color[] { Colors.DarkSlateGray, Colors.DarkBlue, Colors.DarkRed, Colors.DarkCyan, Colors.DarkGoldenrod, Colors.DarkGreen, Colors.DarkMagenta };
byte colorIndex = 0;
foreach (var zone in zones)
{
var color = colorsToChooseFrom[colorIndex];
var zoneColor = Color.FromArgb(128, color.R, color.G, color.B);
zone.ColourCode = zoneColor.ToString();
colorIndex++;
byte subzoneNumber = 50;
byte totalSubZones = (byte)zone.Subzones.LongLength;
byte multipler = (byte)(200 / totalSubZones);
foreach (var subzone in zone.Subzones)
{
var subZoneColor = Color.FromArgb(subzoneNumber, color.R, color.G, color.B);
subzone.ColourCode = subZoneColor.ToString();
subzoneNumber+= multipler;
}
}
}
}
Zone Legend code
private List<Color> colours;
public ObservableCollection<string> Zones { get; set; }
public LegendControl()
{
colours = new List<Color>() { Colors.DarkSlateGray, Colors.DarkBlue, Colors.DarkRed, Colors.DarkCyan, Colors.DarkGoldenrod, Colors.DarkGreen, Colors.DarkMagenta };
InitializeComponent();
Zones = new ObservableCollection<string>();
DataContext = Zones;
}
public void Bind(ZoneDto[] zones)
{
int zoneNumber = 0;
int rowNumber = 0;
byte subzoneNumber = 0;
byte totalsubZones = 0;
Zones.Clear();
foreach (var zone in zones)
{
Color zoneColor = GetColour(zoneNumber);
var zonerectangle = CreateZoneRectangle(zone, rowNumber, zoneColor);
Grid1.Children.Add(zonerectangle);
var zoneName = CreateZoneName(zone, rowNumber);
Grid1.Children.Add(zoneName);
zoneNumber++;
foreach (var subzone in zone.Subzones)
{
totalsubZones++;
Grid1.RowDefinitions.Add(new RowDefinition());
Color subzoneColor = GetGradeColour(subzoneNumber, totalsubZones, zoneColor);
var subzoneRectangle = CreateSubZoneRectangle(subzone, rowNumber, subzoneColor);
Grid1.Children.Add(subzoneRectangle);
var subzoneName = CreateSubZoneName(subzone, rowNumber);
Grid1.Children.Add(subzoneName);
subzoneNumber++;
rowNumber++;
}
}
}
private Rectangle CreateZoneRectangle(ZoneDto zone, int rowNumber, Color zoneColour)
{
var rectangle = new Rectangle
{
Fill = new SolidColorBrush(zoneColour),
Margin = new Thickness(2)
};
int rowSpan = 0;
foreach (var subzone in zone.Subzones)
{
rowSpan++;
}
rectangle.SetValue(Grid.RowProperty, rowNumber);
rectangle.SetValue(Grid.ColumnProperty, 0);
rectangle.SetValue(Grid.RowSpanProperty, rowSpan);
return rectangle;
}
private TextBlock CreateZoneName(ZoneDto zone, int rowNumber)
{
Zones.Clear();
var textblock = new TextBlock
{
Text = zone.Name,
RenderTransformOrigin = new Point(0.5, 0.5),
LayoutTransform = new RotateTransform(270),
VerticalAlignment = System.Windows.VerticalAlignment.Center,
HorizontalAlignment = System.Windows.HorizontalAlignment.Center
};
int rowSpan = 0;
foreach (var subzon in zone.Subzones)
{
rowSpan++;
}
textblock.SetValue(Grid.RowProperty, rowNumber);
textblock.SetValue(Grid.ColumnProperty, 0);
textblock.SetValue(Grid.RowSpanProperty, rowSpan);
return textblock;
}
private Rectangle CreateSubZoneRectangle(ZoneDto subzone, int rowNumber, Color subzoneColor)
{
var rectangle = new Rectangle
{
Fill = new SolidColorBrush(subzoneColor),
Margin = new Thickness(2)
};
rectangle.SetValue(Grid.RowProperty, rowNumber);
rectangle.SetValue(Grid.ColumnProperty, 1);
return rectangle;
}
private TextBlock CreateSubZoneName(ZoneDto subzone, int rowNumber)
{
var textblock = new TextBlock
{
Text = subzone.Name,
VerticalAlignment = System.Windows.VerticalAlignment.Center,
HorizontalAlignment = System.Windows.HorizontalAlignment.Center
};
textblock.SetValue(Grid.RowProperty, rowNumber);
textblock.SetValue(Grid.ColumnProperty, 1);
return textblock;
}
private Color GetColour(int zoneNumber)
{
var numOfColours = colours.Count;
if (zoneNumber >= numOfColours)
{
return colours[zoneNumber % numOfColours];
}
return colours[zoneNumber];
}
private Color GetGradeColour(byte subzoneNumber, byte totalsubZones, Color zoneColour)
{
byte multipler = (byte)(200 / totalsubZones);
byte a = (byte)((subzoneNumber + 1) * multipler);
return Color.FromArgb(a, zoneColour.R, zoneColour.G, zoneColour.B);
}
the code for the ZoneDto
public class GridDataDto
{
public WellDto[] Wells { get; set; }
public ZoneDto[] Zones { get; set; }
public string[] Facies { get; set; }
public CellDto MinLimits { get; set; }
public CellDto MaxLimits { get; set; }
}
public class ZoneDto
{
public string Name { get; set; }
public ZoneDto[] Subzones { get; set; }
public int MinK { get; set; }
public int MaxK { get; set; }
public string ColourCode { get; set; }
}
public class WellDto
{
public string Name { get; set; }
public double X { get; set; }
public double Y { get; set; }
}
public class CellDto
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public int I { get; set; }
public int J { get; set; }
public int K { get; set; }
}
EDIT: Seems there is already a built in method for this ColorConverter.ConvertFromString https://msdn.microsoft.com/en-us/library/system.windows.media.colorconverter.convertfromstring(v=vs.110).aspx
Here's the old code anyway -
The System.Windows.Media.Color ToString() method returns a hex string of the aRGB values that looks like this: #80C8DCF0 you can just split the bytes out and create a new color:
static Color FromString(string colorString)
{
byte a = Convert.ToByte(colorString.Substring(1, 2), 16);
byte r = Convert.ToByte(colorString.Substring(3, 2), 16);
byte g = Convert.ToByte(colorString.Substring(5, 2), 16);
byte b = Convert.ToByte(colorString.Substring(7, 2), 16);
return Color.FromArgb(a, r, g, b);
}
I could be reading your question wrong but if you just want the legend to share the same colours as the "Sequence Stratigraphy" could you not just use the ZoneColorizer's Colorize method on the ZoneDto[] object in your zone legend code's Bind method?
public class Placement
{
public Point3D Location { get; set; }
public Point3D Axis { get; set; }
public Point3D Direction { get; set; }
}
public class Attribute1
{
public string Key { get; set; }
public Type Type { get; set; }
public Object Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
Attribute1 a = new Attribute1();
a.Key = "test";
var p = new Placement();
p.Axis = new Point3D(12.0, 22.09, 0);
p.Location = new Point3D(12.0, 22.09, 0);
p.Direction = new Point3D(12.0, 22.09, 0);
a.Value = p;
var serializer = new XmlSerializer(typeof(Attribute1));
var path = "E:\\details.xml";
using (TextWriter writer = new StreamWriter(path))
{
serializer.Serialize(writer, a);
}
Console.Read();
}
}
I am trying to serialize Point3D using XmlSerializer.
I am using XmlSerializer for serializing other properties of the class which contain Attribute1
But I get error while serializing.
Please let me know how to achieve this or point me to relevant resources. Thanks!
You have told it that you want to serialize Attribute1 but not Placement. Just change this one line:
var serializer = new XmlSerializer(typeof(Attribute1), new Type[] { typeof(Placement) });
I need to get data as per this json format.
series: [{
name: 'Marriage',
data: [1, 2, 3] // Sample Data
}, {
name: 'Chess',
data: [2, 2, 3]
}, {
name: 'Ludo',
data: [3, 4, 4]
}]
I need to create chart as here in http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/bar-stacked/
What I have tried is using group by from device id and and using for loop to get the result. But I am quite stuck here getting required output.
Here is what I have tried so far.
void Main()
{
DateTime currentDate = DateTime.UtcNow.Date.AddDays(-30);
var currentMonthData = Device_GameDevices.Where(x => x.CreatedDate >= currentDate).ToList();
// Get total game list
var gamesList = currentMonthData.Select(x => x.GameName).Distinct();
// Group the data as per the device id
var groupedData = from gameData in currentMonthData
group gameData by gameData.DeviceID
into egroup
select new {
Game = egroup.Key,
Data = from bug in egroup
group bug by bug.GameName into g2
select new { Name = g2.Key, HoursPlayed = g2.Sum(x => (x.EndTime - x.StartTime).TotalMinutes/60) }
};
Console.Write(groupedData);
List<DashboardVM.ChartData> chartDatas = new List<DashboardVM.ChartData>();
List<double> hourResultList = new List<double>();
foreach(var item in groupedData)
{
var chart = new DashboardVM.ChartData();
foreach(var gameItem in gamesList)
{
chart.GameNameResult = gameItem;
foreach(var groupedDataItem in item.Data)
{
if(gameItem == groupedDataItem.Name)
{
hourResultList.Add(groupedDataItem.HoursPlayed);
}
else
{
hourResultList.Add(0.0);
}
}
chart.HoursPlayed = hourResultList;
}
chartDatas.Add(chart);
}
Console.Write(chartDatas);
}
public class DashboardVM{
public class ChartData{
public string GameNameResult{get;set;}
public List<double> HoursPlayed{get;set;}
}
}
public class Chart
{
public string type { get; set; }
}
public class Title
{
public string text { get; set; }
}
public class XAxis
{
public List<string> categories { get; set; }
}
public class Title2
{
public string text { get; set; }
}
public class YAxis
{
public int min { get; set; }
public Title2 title { get; set; }
}
public class Legend
{
public bool reversed { get; set; }
}
public class Series
{
public string stacking { get; set; }
}
public class PlotOptions
{
public Series series { get; set; }
}
public class Series2
{
public string name { get; set; }
public List<double> data { get; set; }
}
public class RootObject
{
public Chart chart { get; set; }
public Title title { get; set; }
public XAxis xAxis { get; set; }
public YAxis yAxis { get; set; }
public Legend legend { get; set; }
public PlotOptions plotOptions { get; set; }
public List<Series2> series { get; set; }
}
void Main()
{
var Device_GameDevices = new[] {
new {ID=1,CreatedDate=DateTime.Parse("8/23/2017 06:07:30"),DeviceID="Desktop12",EndTime=DateTime.Parse("8/23/2017 06:06:30"),GameName="CyberGunner",StartTime=DateTime.Parse("8/23/2017 06:03:45")},
new {ID=2,CreatedDate=DateTime.Parse("8/23/2017 07:14:01"),DeviceID="A12" ,EndTime=DateTime.Parse("8/23/2017 11:14:01"),GameName="Marriage" ,StartTime=DateTime.Parse("8/23/2017 07:14:01")},
new {ID=3,CreatedDate=DateTime.Parse("8/23/2017 07:14:02"),DeviceID="A12" ,EndTime=DateTime.Parse("8/23/2017 08:14:01"),GameName="Marriage" ,StartTime=DateTime.Parse("8/23/2017 07:14:02")},
new {ID=4,CreatedDate=DateTime.Parse("8/23/2017 09:14:01"),DeviceID="A12" ,EndTime=DateTime.Parse("8/23/2017 09:14:01"),GameName="Chess" ,StartTime=DateTime.Parse("8/23/2017 07:14:03")},
new {ID=5,CreatedDate=DateTime.Parse("8/23/2017 07:14:03"),DeviceID="A12" ,EndTime=DateTime.Parse("8/23/2017 10:14:01"),GameName="Marriage" ,StartTime=DateTime.Parse("8/23/2017 07:14:03")},
new {ID=6,CreatedDate=DateTime.Parse("8/23/2017 09:57:28"),DeviceID="B12" ,EndTime=DateTime.Parse("8/23/2017 10:57:28"),GameName="Marriage" ,StartTime=DateTime.Parse("8/23/2017 09:57:28")},
};
DateTime currentDate=DateTime.UtcNow.Date.AddDays(-30);
var currentMonthData=Device_GameDevices
.Where(x=>x.CreatedDate>=currentDate)
.ToList();
// Get total game list
var gamesList=currentMonthData
.Select(x=>x.GameName)
.Distinct()
.ToList();
var chart=new RootObject
{
chart=new Chart{ type="bar"},
title=new Title{ text="My title" },
xAxis=new XAxis { categories=gamesList },
yAxis=new YAxis { min=0, title=new Title2 {text="Total Game Time"}},
legend=new Legend {reversed=true},
plotOptions=new PlotOptions { series=new Series {stacking="normal"}},
series=currentMonthData
.GroupBy(d=>new {d.DeviceID,d.GameName})
.Select(d=>new {
DeviceID=d.Key.DeviceID,
GameName=d.Key.GameName,
HoursPlayed=d.Sum(x=>(x.EndTime - x.StartTime).TotalMinutes)/60
})
.GroupBy(d=>d.DeviceID)
.Select(d=>new Series2 {
name=d.Key,
data=gamesList
.GroupJoin(d,a=>a,b=>b.GameName,(a,b)=>new {GameName=a,HoursPlayed=b.Sum(z=>z.HoursPlayed)})
.OrderBy(x=>gamesList.IndexOf(x.GameName))
.Select(x=>x.HoursPlayed)
.ToList()
}).ToList()
};
chart.Dump();
}
This is how the series looks: