i have a program that take json to a list and load the list to 2 data grid view
i need to filter the view trying to do it on the data source here is the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace WindowsFormsApplication1
{
/// <summary>
///
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Set the Auto complete on combobox
/// load data table for items
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'typeidDataSet.Sheet1' table. You can move, or remove it, as needed.
// https://esi.tech.ccp.is/dev/markets/10000069/orders/?type_id=34&order_type=all&page=1&datasource=tranquility
this.sheet1TableAdapter.Fill(this.typeidDataSet.Sheet1);
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown;
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
}
/// <summary>
/// Gets system ID base on system pick in combobox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
label1.Text = comboBox1.SelectedValue.ToString();
}
catch
{
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
var cheklist = checkedListBox1.CheckedItems;
var result = new System.Collections.Generic.List<JsonResult>();
foreach (var sys in cheklist)
{
/// <summary>
/// The next few lines of code help build the URL for the region that have been pick giveing the var pick the system id the are 64 regions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string identifierName = sys.ToString();
dictionary["Aridia"] = "10000054";
dictionary["Black Rise"] = "10000069";
dictionary["Branch"] = "10000055";
dictionary["Cache"] = "10000007";
dictionary["Catch"] = "10000014";
dictionary["Cloud Ring"] = "10000051";
dictionary["Cobalt Edge"] = "10000053";
dictionary["Curse"] = "10000012";
dictionary["Deklein"] = "10000035";
dictionary["Delve"] = "10000060";
dictionary["Derelik"] = "10000001";
dictionary["Detorid"] = "10000005";
dictionary["Devoid"] = "10000036";
dictionary["Domain"] = "10000043";
dictionary["Esoteria"] = "10000039";
dictionary["Essence"] = "10000064";
dictionary["Etherium Reach"] = "10000027";
dictionary["Everyshore"] = "10000037";
dictionary["Fade"] = "10000046";
dictionary["Feythabolis"] = "10000056";
dictionary["Fountain"] = "10000058";
dictionary["Geminate"] = "10000029";
dictionary["Genesis"] = "10000067";
dictionary["Great Wildlands"] = "10000011";
dictionary["Heimatar"] = "10000030";
dictionary["Immensea"] = "10000025";
dictionary["Impass"] = "10000031";
dictionary["Insmother"] = "10000009";
dictionary["Kador"] = "10000052";
dictionary["Khanid"] = "10000049";
dictionary["Kor-Azor"] = "10000065";
dictionary["Lonetrek"] = "10000016";
dictionary["Malpais"] = "10000013";
dictionary["Metropolis"] = "10000042";
dictionary["Molden Heath"] = "10000028";
dictionary["Oasa"] = "10000040";
dictionary["Omist"] = "10000062";
dictionary["Outer Passage"] = "10000021";
dictionary["Outer Ring"] = "10000057";
dictionary["Paragon Soul"] = "10000059";
dictionary["Period Basis"] = "10000063";
dictionary["Perrigen Falls"] = "10000066";
dictionary["Placid"] = "10000048";
dictionary["Providence"] = "10000047";
dictionary["Pure Blind"] = "10000023";
dictionary["Querious"] = "10000050";
dictionary["Scalding Pass"] = "10000008";
dictionary["Sinq Laison"] = "10000032";
dictionary["Solitude"] = "10000044";
dictionary["Stain"] = "10000022";
dictionary["Syndicate"] = "10000041";
dictionary["Tash-Murkon"] = "10000020";
dictionary["Tenal"] = "10000045";
dictionary["Tenerifis"] = "10000061";
dictionary["The Bleak Lands"] = "10000038";
dictionary["The Citadel"] = "10000033";
dictionary["The Forge"] = "10000002";
dictionary["The Kalevala Expanse"] = "10000034";
dictionary["The Spire"] = "10000018";
dictionary["Tribute"] = "10000010";
dictionary["Vale of the Silent"] = "10000003";
dictionary["Venal"] = "10000015";
dictionary["Verge Vendor"] = "10000068";
dictionary["Wicked Creek"] = "10000006";
string pick = dictionary[identifierName];
WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData("https://esi.tech.ccp.is/dev/markets/" + pick + "/orders/?type_id=" + comboBox1.SelectedValue.ToString() + "&order_type=all&page=1&datasource=tranquility")))
{
using (var reader = new StreamReader(stream))
{
string input = reader.ReadToEnd();
result.AddRange(JsonConvert.DeserializeObject<List<JsonResult>>(input));
}
}
}
BindingSource source1 = new BindingSource();
source1.DataSource = result;
source1.Filter = "is_buy_order LIKE true";
dataGridView1.DataSource = source1;
BindingSource source2 = new BindingSource();
source2.DataSource = result;
source2.Filter = "is_buy_order == 'false'";
dataGridView2.DataSource = source2;
}
}
public class JsonResult
{
public Int64 order_id { get; set; }
public int type_id { get; set; }
public Int64 location_id { get; set; }
public int volume_total { get; set; }
public int volume_remain { get; set; }
public int min_volume { get; set; }
public decimal price { get; set; }
public bool is_buy_order { get; set; }
public int duration { get; set; }
public DateTime issued { get; set; }
public string range { get; set; }
}
}
The filters does not filter at all i get the hole list both time what am i missing?
I'm using Microsoft Excel 15.0 Object Library and opening the .xlsx file this way:
static void readDirection(String path)
{
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
foreach (Worksheet temp in wb.Worksheets)
{
Console.WriteLine(temp.Name + " | index:" + temp.Index);
}
Console.WriteLine(wb.Worksheets.Count);
}
Since there is only one tab, it's writing:
TabName | index:1
1
But why is the only tab at index 1 and not 0? When I tried Console.WriteLine("name"+wb.Worksheets[0].Name);
I got the exception:
System.Runtime.InteropServices.COMException
Because not every sequence in every language start at 0. In Excel collections start at 1 (might there be exceptions to this).
I agree with Cetin,
Here is an example that will demonstrate indexing sheets. The second class is support for the first code block
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelHelper
{
public class ExcelInfo
{
public Exception LastException { get; set; }
private List<ExcelReferenceTable> mReferenceTables;
/// <summary>
/// List of reference tables
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public List<ExcelReferenceTable> ReferenceTables
{
get
{
return mReferenceTables;
}
}
private string[] Extensions = { ".xls", ".xlsx" };
private string mFileName;
/// <summary>
/// Valid/existing Excel file name to work with.
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public string FileName
{
get
{
return mFileName;
}
set
{
if (!(Extensions.Contains(System.IO.Path.GetExtension(value.ToLower()))))
{
throw new Exception("Invalid file name");
}
mFileName = value;
}
}
private List<string> mNameRanges = new List<string>();
/// <summary>
/// List of named ranges in current file
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public List<string> NameRanges
{
get
{
return mNameRanges;
}
}
private List<string> mSheets = new List<string>();
/// <summary>
/// List of work sheets in current file
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public List<string> Sheets
{
get
{
return mSheets;
}
}
private Dictionary<Int32, string> mSheetsData = new Dictionary<Int32, string>();
public Dictionary<Int32, string> SheetsData
{
get
{
return mSheetsData;
}
}
public ExcelInfo()
{
}
/// <summary>
/// File to get information from
/// </summary>
/// <param name="FileName"></param>
/// <remarks>
/// The caller is responsible to ensure the file exists.
/// </remarks>
public ExcelInfo(string FileName)
{
this.FileName = FileName;
}
/// <summary>
/// Retrieve worksheet and name range names.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public bool GetInformation()
{
bool Success = true;
if (!(System.IO.File.Exists(FileName)))
{
Exception ex = new Exception("Failed to locate '" + FileName + "'");
this.LastException = ex;
throw ex;
}
mSheets.Clear();
mNameRanges.Clear();
mSheetsData.Clear();
if (mReferenceTables != null)
{
mReferenceTables.Clear();
}
Excel.Application xlApp = null;
Excel.Workbooks xlWorkBooks = null;
Excel.Workbook xlWorkBook = null;
Excel.Workbook xlActiveRanges = null;
Excel.Names xlNames = null;
Excel.Sheets xlWorkSheets = null;
try
{
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlWorkBooks = xlApp.Workbooks;
xlWorkBook = xlWorkBooks.Open(FileName);
xlActiveRanges = xlApp.ActiveWorkbook;
xlNames = xlActiveRanges.Names;
for (int x = 1; x <= xlNames.Count; x++)
{
Excel.Name xlName = xlNames.Item(x);
mNameRanges.Add(xlName.Name);
Marshal.FinalReleaseComObject(xlName);
xlName = null;
}
xlWorkSheets = xlWorkBook.Sheets;
for (int x = 1; x <= xlWorkSheets.Count; x++)
{
Excel.Worksheet Sheet1 = (Excel.Worksheet)xlWorkSheets[x];
mSheets.Add(Sheet1.Name);
mSheetsData.Add(x, Sheet1.Name);
Marshal.FinalReleaseComObject(Sheet1);
Sheet1 = null;
}
GetReferenceTables(xlWorkSheets);
ReleaseComObject(xlWorkSheets);
xlWorkBook.Close();
xlApp.UserControl = true;
xlApp.Quit();
}
catch (Exception ex)
{
this.LastException = ex;
Success = false;
}
finally
{
if (xlWorkSheets != null)
{
Marshal.FinalReleaseComObject(xlWorkSheets);
xlWorkSheets = null;
}
if (xlNames != null)
{
Marshal.FinalReleaseComObject(xlNames);
xlNames = null;
}
if (xlActiveRanges != null)
{
Marshal.FinalReleaseComObject(xlActiveRanges);
xlActiveRanges = null;
}
if (xlActiveRanges != null)
{
Marshal.FinalReleaseComObject(xlActiveRanges);
xlActiveRanges = null;
}
if (xlWorkBook != null)
{
Marshal.FinalReleaseComObject(xlWorkBook);
xlWorkBook = null;
}
if (xlWorkBooks != null)
{
Marshal.FinalReleaseComObject(xlWorkBooks);
xlWorkBooks = null;
}
if (xlApp != null)
{
Marshal.FinalReleaseComObject(xlApp);
xlApp = null;
}
}
return Success;
}
private List<ExcelReferenceTable> GetReferenceTables(Excel.Sheets xlWorkSheets)
{
List<ExcelReferenceTable> Result = new List<ExcelReferenceTable>();
string Temp = "";
Excel.Worksheet xlWorkSheet = null;
Excel.ListObjects xlListObjects = null;
Excel.ListObject ThisItem = null;
for (int x = 1; x <= xlWorkSheets.Count; x++)
{
ExcelReferenceTable Item = new ExcelReferenceTable();
xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x];
xlListObjects = xlWorkSheet.ListObjects;
Int32 TotalCount = xlListObjects.Count - 1;
for (int y = 0; y <= TotalCount; y++)
{
ThisItem = xlListObjects.Item[y + 1];
Item.Name = ThisItem.Name;
Item.SheetName = xlWorkSheet.Name;
// TODO: Need to tinker with this.
try
{
Excel.QueryTable QT = ThisItem.QueryTable;
Item.SourceDataFile = QT.SourceDataFile;
ReleaseComObject(QT);
}
catch (Exception)
{
Item.SourceDataFile = "";
}
Excel.Range ThisRange = ThisItem.Range;
Temp = ThisRange.Address;
Item.Address = Temp.Replace("$", "");
Result.Add(Item);
Marshal.FinalReleaseComObject(ThisRange);
ThisRange = null;
Marshal.FinalReleaseComObject(ThisItem);
ThisItem = null;
Marshal.FinalReleaseComObject(xlListObjects);
xlListObjects = null;
}
}
ReleaseComObject(xlWorkSheet);
mReferenceTables = Result;
return Result;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <remarks>
/// Generally speaking we should not have to call
/// GC.Collect() but about one percent of the time
/// Excel will refuse to release an object dependency
/// thus no choice but to call GC.Collect(). Please
/// make every effort to use ReleaseComObjectClean
/// rather than this procedure unless a object refuses
/// to release.
/// </remarks>
private void ReleaseComObject(object obj)
{
try
{
Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception)
{
obj = null;
}
finally
{
GC.Collect();
}
}
public void ReleaseComObjectClean(object obj)
{
try
{
Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception)
{
obj = null;
}
}
}
}
Support class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelHelper
{
public class ExcelReferenceTable
{
public string Name { get; set; }
public string SheetName { get; set; }
public string Address { get; set; }
public string SelectString
{
get
{
return "SELECT * FROM [" + SheetName + "$" + Address + "]";
}
}
public string SourceDataFile { get; set; }
[System.Diagnostics.DebuggerStepThrough()]
public ExcelReferenceTable()
{
}
public override string ToString()
{
return Name;
}
}
}
Example usage
using ExcelHelper;
using System;
using System.Data;
using System.Data.OleDb;
using System.Linq;
namespace ExcelHelperTest
{
internal class Program
{
private static void Main(string[] args)
{
demo1();
ExcelInfo Helper = new ExcelInfo();
Helper.FileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File1.xlsx");
Console.WriteLine(Helper.FileName);
if (Helper.GetInformation())
{
var SheetNames = Helper.Sheets;
Console.WriteLine("Sheet names");
foreach (var Sheet in SheetNames)
{
Console.WriteLine(Sheet);
}
Console.WriteLine();
var ReferenceTables = Helper.ReferenceTables;
if (ReferenceTables !=null)
{
Console.WriteLine("Reference tables");
foreach (var item in ReferenceTables)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("No reference tables found");
}
}
Console.ReadLine();
}
}
}
When you are working with Excel in C# you have to think in a different way than you would do it normaly, as a programmer.
In Excel, every Index is starting with 1 instead of 0.
I’m experiencing a problem with the longlistselector witch is a bit strange... I’m reading a list asynchronously on a multi Pivot page, and if I don’t change the pivot until the resulto f the list Reading, it will create the contacts list successfuly ( in a longlistselector on the pivot item number 3 ) and when I go to that pivot the contacts list is displayed withou any problems, but when I open the Page and change the pivot before the longlistselector is created when the asychronous function returns the results and fills the longlistselector on pivot no.3 the contacts wont get updated ( when I go to pivot 3 no contacts are shown)...
I’ll post my code so you can have a clearer picture of the situation and maybe figure out what is happening.
The code is based in the PhoneToolkit LongListSelector example (buddies list)
public partial class Feeds : PhoneApplicationPage
{
bool isLoading = false;
bool loadingFilmates = true;
public Feeds()
{
InitializeComponent();
// ...
Loaded += FeedsPage_Loaded;
SystemTray.ProgressIndicator = new ProgressIndicator();
DataContext = this;
getFilmatesList();
longlistFilmates.SelectionChanged += FilmateSelectionChanged;
// ...
}
private async void getFilmatesList()
{
Feed userFilmates = await Feed.GetFilmates(App.Current.AppUser, App.Current.WSConfig, 0, "", 10000); // read feeds from webservice
Filmates = AlphaKeyGroup<StayObjectFilmates>.CreateGroups(AllFilmates.GetCurrent(userFilmates), CultureInfo.CurrentUICulture, (p) => { return p.Name; }, true);
//longlistFilmates.Visibility = System.Windows.Visibility.Collapsed;
longlistFilmates.Visibility = System.Windows.Visibility.Visible;
longlistFilmates.UseLayoutRounding = true;
pivotFeed.Visibility = System.Windows.Visibility.Collapsed;
pivotFeed.Visibility = System.Windows.Visibility.Visible;
}
}
Notice that I’ve even tried changing the Visibility property when it loads to force a re-render on the screen and it didn’t work.
This is the StayObjectFilmates class:
public class StayObjectFilmates
{
public string Img { get; private set; }
public string Name { get; private set; }
public string UserId { get; private set; }
public string Id { get; set; }
public User user { get; set; }
public StayObjectFilmates()
{
//Img = "";
//Name = "";
//Id = "";
}
public StayObjectFilmates(string p_img, string p_name, string p_Id)
{
Img = p_img;
Name = p_name;
UserId = p_Id;
}
public StayObjectFilmates(User p_user)
{
user = p_user;
}
public static string GetNameKey(StayObjectFilmates filmate)
{
char key = char.ToLower(filmate.Name[0]);
if (key < 'a' || key > 'z')
{
key = '#';
}
return key.ToString();
}
public static int CompareByName(object obj1, object obj2)
{
StayObjectFilmates p1 = (StayObjectFilmates)obj1;
StayObjectFilmates p2 = (StayObjectFilmates)obj2;
int result = p1.Name.CompareTo(p2.Name);
if (result == 0)
{
result = p1.Img.CompareTo(p2.Img);
}
return result;
}
}
This is the AllFilmates class:
public class AllFilmates : IEnumerable<StayObjectFilmates>
{
private static Dictionary<int, StayObjectFilmates> _filmateLookup;
private static AllFilmates _instance;
private Feed filmates;
// public List<StayObjectFilmates> Filmates { get; private set; }
public static AllFilmates GetCurrent(Feed p_filmates)
{
if (_instance == null)
{
_instance = new AllFilmates();
}
_instance.filmates = p_filmates;
return _instance;
}
public static AllFilmates Current
{
get
{
return _instance ?? (_instance = new AllFilmates());
}
}
public StayObjectFilmates this[int index]
{
get
{
StayObjectFilmates filmate;
_filmateLookup.TryGetValue(index, out filmate);
return filmate;
}
}
#region IEnumerable<StayObjectFilmates> Members
public IEnumerator<StayObjectFilmates> GetEnumerator()
{
EnsureData();
return _filmateLookup.Values.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
EnsureData();
return _filmateLookup.Values.GetEnumerator();
}
#endregion
private void EnsureData()
{
if (_filmateLookup == null)
{
_filmateLookup = new Dictionary<int, StayObjectFilmates>();
if (filmates != null)
{
int i = 0;
foreach (var item in filmates.itemsList)
{
User friend = item as User;
string userphoto = (friend.photo == null) ? "Images/avatar.jpg" : friend.photo;
StayObjectFilmates f = new StayObjectFilmates(userphoto, friend.fullName, i.ToString());
_filmateLookup[i] = f;
i++;
}
}
}
}
}
And this is the AlphaKeyGroup.cs file :
public class AlphaKeyGroup<T> : List<T>
{
private const string GlobeGroupKey = "\uD83C\uDF10";
/// <summary>
/// The delegate that is used to get the key information.
/// </summary>
/// <param name="item">An object of type T</param>
/// <returns>The key value to use for this object</returns>
public delegate string GetKeyDelegate(T item);
/// <summary>
/// The Key of this group.
/// </summary>
public string Key { get; private set; }
/// <summary>
/// Public constructor.
/// </summary>
/// <param name="key">The key for this group.</param>
public AlphaKeyGroup(string key)
{
Key = key;
}
public AlphaKeyGroup(IGrouping<string, T> grouping)
{
Key = grouping.Key;
this.AddRange(grouping);
}
/// <summary>
/// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
/// </summary>
/// <param name="slg">The </param>
/// <returns>Theitems source for a LongListSelector</returns>
private static List<AlphaKeyGroup<T>> CreateGroups(SortedLocaleGrouping slg)
{
List<AlphaKeyGroup<T>> list = new List<AlphaKeyGroup<T>>();
foreach (string key in slg.GroupDisplayNames)
{
if (key == "...")
{
list.Add(new AlphaKeyGroup<T>(GlobeGroupKey));
}
else
{
list.Add(new AlphaKeyGroup<T>(key));
}
}
return list;
}
/// <summary>
/// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
/// </summary>
/// <param name="items">The items to place in the groups.</param>
/// <param name="ci">The CultureInfo to group and sort by.</param>
/// <param name="getKey">A delegate to get the key from an item.</param>
/// <param name="sort">Will sort the data if true.</param>
/// <returns>An items source for a LongListSelector</returns>
public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, CultureInfo ci, GetKeyDelegate getKey, bool sort)
{
SortedLocaleGrouping slg = new SortedLocaleGrouping(ci);
List<AlphaKeyGroup<T>> list = CreateGroups(slg);
foreach (T item in items)
{
int index = 0;
if (slg.SupportsPhonetics)
{
//check if your database has yomi string for item
//if it does not, then do you want to generate Yomi or ask the user for this item.
//index = slg.GetGroupIndex(getKey(Yomiof(item)));
}
else
{
index = slg.GetGroupIndex(getKey(item));
}
if (index >= 0 && index < list.Count)
{
list[index].Add(item);
}
}
if (sort)
{
foreach (AlphaKeyGroup<T> group in list)
{
group.Sort((c0, c1) => { return ci.CompareInfo.Compare(getKey(c0), getKey(c1)); });
}
}
return list;
}
}
The FilmatesInGroup.cs and FilmatesByName.cs is the same as PeopleInGroup.cs and PeopleByFirstName.cs in the PhoneToolKit example with the names adapted.
The longlistFilmates LongListSelector Object is inserted directly inside the PivotItem no.3 ( no Grid and no ScrollView )
Thanks in advance for any help!
i am trying to XML serialize a class object but having the following problem:
the code compiles fine and the messagebox displays all the correct data but when i view the XML it does not seem to include the data for the actual transfer i.e. FireGridLocation data is missing from the XML.
XmlSerializer s;
StringWriter w;
FireGridUnit fireGridUnit = new FireGridUnit();
fireGridUnit.FireGridLocation = new GridUnit(GridLock.getColumn, GridLock.getRow);
MessageBox.Show("gridlock col " + GridLock.getColumn);
MessageBox.Show("column fire " + fireGridUnit.FireGridLocation.getColumn);
MessageBox.Show("row fire " + fireGridUnit.FireGridLocation.getRow);
s = new XmlSerializer(typeof(FireGridUnit));
w = new StringWriter();
s.Serialize(w, fireGridUnit);
MessageBox.Show(w.ToString());
alt text http://img52.imageshack.us/img52/220/errorce.jpg
here is the FireGridUnit:
[Serializable]
public class FireGridUnit
{
/// <summary>
/// Location storage
/// </summary>
//public GridUnit FireGridLocation { get; set; }
public GridUnit FireGridLocation;
}
and here is the GridUnit class:
public class GridUnit
{
/// <summary>
/// Default initialization
/// </summary>
public GridUnit()
{
Column = -1;
Row = -1;
}
/// <summary>
/// Initialize to supplied coordinate
/// </summary>
/// <param name="column"></param>
/// <param name="row"></param>
public GridUnit(int column, int row)
{
Column = column;
Row = row;
}
/// <summary>
/// Set/Return Column
/// </summary>
//public int Column { get; set; }
private int Column;
public int getColumn
{
get { return Column; }
}
/// <summary>
/// Set/Return Row
/// </summary>
//public int Row { get; set; }
private int Row;
public int getRow
{
get { return Row; }
}
}
if you can assist with this issue, your input is very welcome.
XML serialization can only serialize read/write properties. Your getColumn and getRow properties are read-only, so they can't be serialized.
BTW, the Serializable attribute is not necessary for XML serialization
I've got a class with a System.Version property, which looks like this:
Version
Build: 111
Major: 1
MajorRevision: 0
Minor: 1
MinorRevision: 10
Revision: 10
When I serialize the class, version is always empty:
<Version />
The Client class looks like:
[Serializable]
public class Client
{
public string Description;
public string Directory;
public DateTime ReleaseDate;
public Version Version;
}
System.Version is not serializable, if you look at it's properties on MSDN, you'll see they have no setters...so the serializer won't store them. However, this approach still works. That article (old but still works) provides a Version class that is serializable, can you switch to that and get going?
Edit by tomfanning
I have fished the code from the dead site out of archive.org, reproduced below.
using System;
using System.Globalization;
namespace CubicOrange.Version
{
/// <summary>
/// Serializable version of the System.Version class.
/// </summary>
[Serializable]
public class ModuleVersion : ICloneable, IComparable
{
private int major;
private int minor;
private int build;
private int revision;
/// <summary>
/// Gets the major.
/// </summary>
/// <value></value>
public int Major
{
get
{
return major;
}
set
{
major = value;
}
}
/// <summary>
/// Gets the minor.
/// </summary>
/// <value></value>
public int Minor
{
get
{
return minor;
}
set
{
minor = value;
}
}
/// <summary>
/// Gets the build.
/// </summary>
/// <value></value>
public int Build
{
get
{
return build;
}
set
{
build = value;
}
}
/// <summary>
/// Gets the revision.
/// </summary>
/// <value></value>
public int Revision
{
get
{
return revision;
}
set
{
revision = value;
}
}
/// <summary>
/// Creates a new <see cref="ModuleVersion"/> instance.
/// </summary>
public ModuleVersion()
{
this.build = -1;
this.revision = -1;
this.major = 0;
this.minor = 0;
}
/// <summary>
/// Creates a new <see cref="ModuleVersion"/> instance.
/// </summary>
/// <param name="version">Version.</param>
public ModuleVersion(string version)
{
this.build = -1;
this.revision = -1;
if (version == null)
{
throw new ArgumentNullException("version");
}
char[] chArray1 = new char[1] { '.' };
string[] textArray1 = version.Split(chArray1);
int num1 = textArray1.Length;
if ((num1 < 2) || (num1 > 4))
{
throw new ArgumentException("Arg_VersionString");
}
this.major = int.Parse(textArray1[0], CultureInfo.InvariantCulture);
if (this.major < 0)
{
throw new ArgumentOutOfRangeException("version", "ArgumentOutOfRange_Version");
}
this.minor = int.Parse(textArray1[1], CultureInfo.InvariantCulture);
if (this.minor < 0)
{
throw new ArgumentOutOfRangeException("version", "ArgumentOutOfRange_Version");
}
num1 -= 2;
if (num1 > 0)
{
this.build = int.Parse(textArray1[2], CultureInfo.InvariantCulture);
if (this.build < 0)
{
throw new ArgumentOutOfRangeException("build", "ArgumentOutOfRange_Version");
}
num1--;
if (num1 > 0)
{
this.revision = int.Parse(textArray1[3], CultureInfo.InvariantCulture);
if (this.revision < 0)
{
throw new ArgumentOutOfRangeException("revision", "ArgumentOutOfRange_Version");
}
}
}
}
/// <summary>
/// Creates a new <see cref="ModuleVersion"/> instance.
/// </summary>
/// <param name="major">Major.</param>
/// <param name="minor">Minor.</param>
public ModuleVersion(int major, int minor)
{
this.build = -1;
this.revision = -1;
if (major < 0)
{
throw new ArgumentOutOfRangeException("major", "ArgumentOutOfRange_Version");
}
if (minor < 0)
{
throw new ArgumentOutOfRangeException("minor", "ArgumentOutOfRange_Version");
}
this.major = major;
this.minor = minor;
this.major = major;
}
/// <summary>
/// Creates a new <see cref="ModuleVersion"/> instance.
/// </summary>
/// <param name="major">Major.</param>
/// <param name="minor">Minor.</param>
/// <param name="build">Build.</param>
public ModuleVersion(int major, int minor, int build)
{
this.build = -1;
this.revision = -1;
if (major < 0)
{
throw new ArgumentOutOfRangeException("major", "ArgumentOutOfRange_Version");
}
if (minor < 0)
{
throw new ArgumentOutOfRangeException("minor", "ArgumentOutOfRange_Version");
}
if (build < 0)
{
throw new ArgumentOutOfRangeException("build", "ArgumentOutOfRange_Version");
}
this.major = major;
this.minor = minor;
this.build = build;
}
/// <summary>
/// Creates a new <see cref="ModuleVersion"/> instance.
/// </summary>
/// <param name="major">Major.</param>
/// <param name="minor">Minor.</param>
/// <param name="build">Build.</param>
/// <param name="revision">Revision.</param>
public ModuleVersion(int major, int minor, int build, int revision)
{
this.build = -1;
this.revision = -1;
if (major < 0)
{
throw new ArgumentOutOfRangeException("major", "ArgumentOutOfRange_Version");
}
if (minor < 0)
{
throw new ArgumentOutOfRangeException("minor", "ArgumentOutOfRange_Version");
}
if (build < 0)
{
throw new ArgumentOutOfRangeException("build", "ArgumentOutOfRange_Version");
}
if (revision < 0)
{
throw new ArgumentOutOfRangeException("revision", "ArgumentOutOfRange_Version");
}
this.major = major;
this.minor = minor;
this.build = build;
this.revision = revision;
}
#region ICloneable Members
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public object Clone()
{
ModuleVersion version1 = new ModuleVersion();
version1.major = this.major;
version1.minor = this.minor;
version1.build = this.build;
version1.revision = this.revision;
return version1;
}
#endregion
#region IComparable Members
/// <summary>
/// Compares to.
/// </summary>
/// <param name="obj">Obj.</param>
/// <returns></returns>
public int CompareTo(object version)
{
if (version == null)
{
return 1;
}
if (!(version is ModuleVersion))
{
throw new ArgumentException("Arg_MustBeVersion");
}
ModuleVersion version1 = (ModuleVersion)version;
if (this.major != version1.Major)
{
if (this.major > version1.Major)
{
return 1;
}
return -1;
}
if (this.minor != version1.Minor)
{
if (this.minor > version1.Minor)
{
return 1;
}
return -1;
}
if (this.build != version1.Build)
{
if (this.build > version1.Build)
{
return 1;
}
return -1;
}
if (this.revision == version1.Revision)
{
return 0;
}
if (this.revision > version1.Revision)
{
return 1;
}
return -1;
}
#endregion
/// <summary>
/// Equalss the specified obj.
/// </summary>
/// <param name="obj">Obj.</param>
/// <returns></returns>
public override bool Equals(object obj)
{
if ((obj == null) || !(obj is ModuleVersion))
{
return false;
}
ModuleVersion version1 = (ModuleVersion)obj;
if (((this.major == version1.Major) && (this.minor == version1.Minor)) && (this.build == version1.Build) && (this.revision == version1.Revision))
{
return true;
}
return false;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
int num1 = 0;
num1 |= ((this.major & 15) << 0x1c);
num1 |= ((this.minor & 0xff) << 20);
num1 |= ((this.build & 0xff) << 12);
return (num1 | this.revision & 0xfff);
}
/// <summary>
/// Operator ==s the specified v1.
/// </summary>
/// <param name="v1">V1.</param>
/// <param name="v2">V2.</param>
/// <returns></returns>
public static bool operator ==(ModuleVersion v1, ModuleVersion v2)
{
return v1.Equals(v2);
}
/// <summary>
/// Operator >s the specified v1.
/// </summary>
/// <param name="v1">V1.</param>
/// <param name="v2">V2.</param>
/// <returns></returns>
public static bool operator >(ModuleVersion v1, ModuleVersion v2)
{
return (v2 < v1);
}
/// <summary>
/// Operator >=s the specified v1.
/// </summary>
/// <param name="v1">V1.</param>
/// <param name="v2">V2.</param>
/// <returns></returns>
public static bool operator >=(ModuleVersion v1, ModuleVersion v2)
{
return (v2 <= v1);
}
/// <summary>
/// Operator !=s the specified v1.
/// </summary>
/// <param name="v1">V1.</param>
/// <param name="v2">V2.</param>
/// <returns></returns>
public static bool operator !=(ModuleVersion v1, ModuleVersion v2)
{
return (v1 != v2);
}
/// <summary>
/// Operator <s the specified v1.
/// </summary>
/// <param name="v1">V1.</param>
/// <param name="v2">V2.</param>
/// <returns></returns>
public static bool operator <(ModuleVersion v1, ModuleVersion v2)
{
if (v1 == null)
{
throw new ArgumentNullException("v1");
}
return (v1.CompareTo(v2) < 0);
}
/// <summary>
/// Operator <=s the specified v1.
/// </summary>
/// <param name="v1">V1.</param>
/// <param name="v2">V2.</param>
/// <returns></returns>
public static bool operator <=(ModuleVersion v1, ModuleVersion v2)
{
if (v1 == null)
{
throw new ArgumentNullException("v1");
}
return (v1.CompareTo(v2) <= 0);
}
/// <summary>
/// Toes the string.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this.build == -1)
{
return this.ToString(2);
}
if (this.revision == -1)
{
return this.ToString(3);
}
return this.ToString(4);
}
/// <summary>
/// Toes the string.
/// </summary>
/// <param name="fieldCount">Field count.</param>
/// <returns></returns>
public string ToString(int fieldCount)
{
object[] objArray1;
switch (fieldCount)
{
case 0:
{
return string.Empty;
}
case 1:
{
return (this.major.ToString());
}
case 2:
{
return (this.major.ToString() + "." + this.minor.ToString());
}
}
if (this.build == -1)
{
throw new ArgumentException(string.Format("ArgumentOutOfRange_Bounds_Lower_Upper {0},{1}", "0", "2"), "fieldCount");
}
if (fieldCount == 3)
{
objArray1 = new object[5] { this.major, ".", this.minor, ".", this.build };
return string.Concat(objArray1);
}
if (this.revision == -1)
{
throw new ArgumentException(string.Format("ArgumentOutOfRange_Bounds_Lower_Upper {0},{1}", "0", "3"), "fieldCount");
}
if (fieldCount == 4)
{
objArray1 = new object[7] { this.major, ".", this.minor, ".", this.build, ".", this.revision };
return string.Concat(objArray1);
}
throw new ArgumentException(string.Format("ArgumentOutOfRange_Bounds_Lower_Upper {0},{1}", "0", "4"), "fieldCount");
}
}
}
I prefer to use approach below, so I have only one property with Type VersionXml in my class. Implicit operators are really useful here.
[Serializable]
[XmlType("Version")]
public class VersionXml
{
public VersionXml()
{
this.Version = null;
}
public VersionXml(Version Version)
{
this.Version = Version;
}
[XmlIgnore]
public Version Version { get; set; }
[XmlText]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string Value
{
get { return this.Version == null ? string.Empty : this.Version.ToString(); }
set
{
Version temp;
Version.TryParse(value, out temp);
this.Version = temp;
}
}
public static implicit operator Version(VersionXml VersionXml)
{
return VersionXml.Version;
}
public static implicit operator VersionXml(Version Version)
{
return new VersionXml(Version);
}
public override string ToString()
{
return this.Value;
}
}
You can use string proxy property:
[XmlIgnore]
public System.Version Version { get; set; }
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string version
{
get
{
if (this.Version == null)
return string.Empty;
else
return this.Version.ToString();
}
set
{
if(!String.IsNullOrEmpty(value))
this.Version = new Version(value);
}
}
You need to define your get and set accessors, as:
public class Version
{
public int Build { get; set; }
public int Major { get; set; }
public int MajorRevision { get; set; }
public int Minor { get; set; }
public int MinorRevision { get; set; }
public int Revision { get; set; }
}
// ...
new XmlSerializer(typeof (Version))
.Serialize(Console.Out,
new Version()
{
Build = 111,
Major = 1,
MajorRevision = 0,
Minor = 1,
MinorRevision = 10,
Revision = 10
}
);
I got this output:
<?xml version="1.0" encoding="ibm850"?>
<Version xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Build>111</Build>
<Major>1</Major>
<MajorRevision>0</MajorRevision>
<Minor>1</Minor>
<MinorRevision>10</MinorRevision>
<Revision>10</Revision>
</Version>
More precisely, System.Version is not XML-serializable. It is serializable with a BinaryFormatter, for example:
Version version = new Version(1, 2, 3, 4);
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, version);
stream.Position = 0;
Version deserialized = (Version)formatter.Deserialize(stream);
}
I have cleaned up Nick Craver's implementation to be much more concise and readable, added XML Serialization support (with attributes instead of separate elements), implemented a string TypeConverter as well as fixed a couple comparison issues that had the possibility for NullReferenceExceptions or infinite loops (calling the overloaded operators from within themselves).
I also used some C# 6 features as well.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Xml.Serialization;
[Serializable]
[TypeConverter(typeof(VersionCodeConverter))]
public class VersionCode : ICloneable, IComparable<VersionCode>, IEquatable<VersionCode>
{
[XmlAttribute] public int Major { get; private set; }
[XmlAttribute] public int Minor { get; private set; }
[XmlAttribute] public int Build { get; private set; } = -1;
[XmlAttribute] public int Revision { get; private set; } = -1;
public VersionCode() { }
public VersionCode(int major, int minor, int build = 0, int revision = 0)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), $"{nameof(major)} cannot be less than 0");
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), $"{nameof(minor)} cannot be less than 0");
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), $"{nameof(build)} cannot be less than 0");
if (revision < 0)
throw new ArgumentOutOfRangeException(nameof(revision), $"{nameof(revision)} cannot be less than 0");
Major = major;
Minor = minor;
Build = build;
Revision = revision;
}
public VersionCode(string version)
{
if (version == null)
throw new ArgumentNullException(nameof(version));
var components = new Stack<string>(version.Split('.'));
if (components.Count < 2 || components.Count > 4)
throw new ArgumentException(nameof(version));
Major = int.Parse(components.Pop(), CultureInfo.InvariantCulture);
if (Major < 0)
throw new ArgumentOutOfRangeException(nameof(version), $"{nameof(Major)} cannot be less than 0");
Minor = int.Parse(components.Pop(), CultureInfo.InvariantCulture);
if (Minor < 0)
throw new ArgumentOutOfRangeException(nameof(version), $"{nameof(Minor)} cannot be less than 0");
if (!components.Any())
return;
Build = int.Parse(components.Pop(), CultureInfo.InvariantCulture);
if (Build < 0)
throw new ArgumentOutOfRangeException(nameof(version), $"{nameof(Build)} cannot be less than 0");
if (!components.Any())
return;
Revision = int.Parse(components.Pop(), CultureInfo.InvariantCulture);
if (Revision < 0)
throw new ArgumentOutOfRangeException(nameof(version), $"{nameof(Revision)} cannot be less than 0");
}
public object Clone()
=> new VersionCode(Major, Minor, Build, Revision);
public int CompareTo(VersionCode version)
=> Major != version.Major ? Major.CompareTo(version.Major)
: Minor != version.Minor ? Minor.CompareTo(version.Minor)
: Build != version.Build ? Build.CompareTo(version.Build)
: Revision.CompareTo(version.Revision);
public override bool Equals(object obj)
=> obj is VersionCode && Equals((VersionCode)obj);
public bool Equals(VersionCode version)
=> Major == version.Major
&& Minor == version.Minor
&& Build == version.Build
&& Revision == version.Revision;
public override int GetHashCode()
{
var hash = 0;
hash |= (Major & 15) << 0x1c;
hash |= (Minor & 0xff) << 20;
hash |= (Build & 0xff) << 12;
hash |= (Revision & 0xfff);
return hash;
}
public static bool operator ==(VersionCode v1, VersionCode v2)
=> ReferenceEquals(v1, null) ? ReferenceEquals(v2, null) : v1.Equals(v2);
public static bool operator !=(VersionCode v1, VersionCode v2)
=> !(v1 == v2);
public static bool operator >(VersionCode v1, VersionCode v2)
=> v2 < v1;
public static bool operator >=(VersionCode v1, VersionCode v2)
=> v2 <= v1;
public static bool operator <(VersionCode v1, VersionCode v2)
=> !ReferenceEquals(v1, null) && v1.CompareTo(v2) < 0;
public static bool operator <=(VersionCode v1, VersionCode v2)
=> !ReferenceEquals(v1, null) && v1.CompareTo(v2) <= 0;
public override string ToString()
=> Build < 0 ? $"{Major}.{Minor}"
: Revision < 0 ? $"{Major}.{Minor}.{Build}"
: $"{Major}.{Minor}.{Build}.{Revision}";
}
public class VersionCodeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
=> sourceType == typeof(string)
|| base.CanConvertFrom(context, sourceType);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var version = value as string;
return version != null
? new VersionCode(version)
: base.ConvertFrom(context, culture, value);
}
}