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.
Related
I have the following code to use the Where and And filter.
public void Add(Expression<Func<T, object>> memberExpression, object memberValue)
{
if (_Query.ToString() != string.Empty)
_Query.Append(" AND ");
_Query.Append(string.Format(" [{0}] = {1}", NameOf(memberExpression), memberValue == null ? "NULL" : string.Format("'{0}'", memberValue)));
}
I took this same method and made some changes to use Like in sqlite but only works with the first letter entered if entering 2 letters no longer brings any value
Code Like:
public void Like(Expression<Func<T, object>> memberExpression, object memberValue)
{
if (_Query.ToString() != string.Empty)
_Query.Append(" AND ");
_Query.Append(string.Format(" [{0}] LIKE '{1}' ", NameOf(memberExpression), memberValue == null ? "NULL" : "%" + memberValue + "%"));
}
With a letter
With more than 1 letter
See that you should bring the record "William"
For anyone who is talking about sql injection I simply got this Sqlite example and I'm doing a little crud.
EXAMPLE CRUD
Edit:
sql to run on "Db browser for Sqlite"
Class
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SQLiteWithCSharp.Utility
{
/// <summary>
/// Author : Swaraj Ketan Santra
/// Email : swaraj.ece.jgec#gmail.com
/// Date : 25/02/2017
/// Description : Entity/model classes as T
/// </summary>
/// <typeparam name="T"> Class and newable type</typeparam>
#region Attributes
/// <summary>
/// Use this attribute to decorate the properties on your model class.
/// Only those properties that are having exactly the same column name of a DB table.
/// </summary>
public class DbColumnAttribute : Attribute
{
/// <summary>
/// Set true if implicit conversion is required.
/// </summary>
public bool Convert { get; set; }
/// <summary>
/// Set true if the property is primary key in the table
/// </summary>
public bool IsPrimary { get; set; }
/// <summary>
/// Denotes if the field is an identity type or not.
/// </summary>
public bool IsIdentity { get; set; }
}
#endregion
#region BaseService
/// <summary>
/// Use with Entity/Model class only
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BaseService<T> where T : class, new()
{
#region Constructor
public BaseService()
{
}
/// <summary>
/// Pass the connection string in constructor
/// </summary>
/// <param name="connectionString"></param>
public BaseService(string connectionString)
{
Context.ConnectionString = connectionString;
}
#endregion
#region Public methods
/// <summary>
/// To get SQLite connection object
/// </summary>
/// <returns>SQLiteConnection object</returns>
public SQLiteConnection GetConnection()
{
return new SQLiteConnection(Context.ConnectionString);
}
/// <summary>
/// Inserts the single record into table
/// </summary>
/// <param name="entity"></param>
public long Add(T entity)
{
long identity = 0;
bool hasIdentity = false;
StringBuilder columns = new StringBuilder();
StringBuilder values = new StringBuilder();
IList<PropertyInfo> propertyInfos = GetPropertyInfoList(entity);
foreach (PropertyInfo i in propertyInfos)
{
var ca = i.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;
if (ca != null)
{
if (!ca.IsIdentity)
{
columns.Append(string.Format("[{0}],", i.Name));
values.Append(string.Format("{0},",
i.GetValue(entity) == null ? "NULL" : string.Format("'{0}'", i.GetValue(entity))));
}
else
{
hasIdentity = true;
}
}
}
if (columns.ToString() != string.Empty)
{
columns.Remove(columns.Length - 1, 1); // Remove additional comma(',')
values.Remove(values.Length - 1, 1); // Remove additional comma(',')
StringBuilder qry = new StringBuilder();
qry.Append(string.Format("INSERT INTO [{0}] ( {1} ) VALUES ( {2} ); SELECT last_insert_rowid();"
, entity.GetType().Name, columns, values));
identity = hasIdentity ? Execute(qry.ToString(), true) : Execute(qry.ToString());
}
return identity;
}
/// <summary>
/// Inserts multiple records into a table
/// </summary>
/// <param name="entities"></param>
public void AddRange(IList<T> entities)
{
StringBuilder qry = new StringBuilder();
foreach (T entity in entities)
{
StringBuilder columns = new StringBuilder();
StringBuilder values = new StringBuilder();
IList<PropertyInfo> propertyInfos = GetPropertyInfoList(entity);
foreach (PropertyInfo i in propertyInfos)
{
var ca = i.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;
if (ca != null)
{
if (!ca.IsIdentity)
{
columns.Append(string.Format("[{0}],", i.Name));
values.Append(string.Format("{0},",
i.GetValue(entity) == null ? "NULL" : string.Format("'{0}'", i.GetValue(entity))));
}
}
}
if (columns.ToString() != string.Empty)
{
columns.Remove(columns.Length - 1, 1); // Remove additional comma(',')
values.Remove(values.Length - 1, 1); // Remove additional comma(',')
qry.AppendLine(string.Format("INSERT INTO [{0}] ( {1} ) VALUES ( {2} );"
, entity.GetType().Name, columns, values));
}
}
try
{
Execute(qry.ToString());
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Updates single entity
/// </summary>
/// <param name="entity"></param>
public void Update(T entity)
{
StringBuilder columns = new StringBuilder();
StringBuilder clause = new StringBuilder();
IList<PropertyInfo> propertyInfos = GetPropertyInfoList(entity);
foreach (PropertyInfo i in propertyInfos)
{
var ca = i.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;
if (ca != null)
{
if (!ca.IsPrimary)
{
columns.Append(string.Format("[{0}] = {1},", i.Name,
i.GetValue(entity) == null ? "NULL" : string.Format("'{0}'", i.GetValue(entity))));
}
else
{
clause.Append(string.Format("[{0}] = '{1}'", i.Name, i.GetValue(entity)));
}
}
}
if (columns.ToString() != string.Empty)
{
columns.Remove(columns.Length - 1, 1);
StringBuilder qry = new StringBuilder();
qry.Append(string.Format("UPDATE [{0}] SET {1} WHERE {2};"
, entity.GetType().Name, columns, clause));
Execute(qry.ToString());
}
}
/// <summary>
/// Updates mutiple entities in single query
/// </summary>
/// <param name="entities"></param>
public void UpdateRange(IList<T> entities)
{
StringBuilder qry = new StringBuilder();
foreach (T entity in entities)
{
StringBuilder columns = new StringBuilder();
StringBuilder clause = new StringBuilder();
#region MyRegion
IList<PropertyInfo> propertyInfos = GetPropertyInfoList(entity);
foreach (PropertyInfo i in propertyInfos)
{
var ca = i.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;
if (ca != null)
{
if (!ca.IsPrimary)
{
columns.Append(string.Format("[{0}] = {1},", i.Name,
i.GetValue(entity) == null ? "NULL" : string.Format("'{0}'", i.GetValue(entity))));
}
else
{
clause.Append(string.Format("[{0}] = '{1}'", i.Name, i.GetValue(entity)));
}
}
}
if (columns.ToString() != string.Empty)
{
columns.Remove(columns.Length - 1, 1);
qry.AppendLine(string.Format("UPDATE [{0}] SET {1} WHERE {2};"
, entity.GetType().Name, columns, clause));
}
#endregion
}
Execute(qry.ToString());
}
/// <summary>
/// Find single item
/// </summary>
/// <param name="cmdText"></param>
public T GetById(object id)
{
T entity = new T();
StringBuilder clause = new StringBuilder();
IList<PropertyInfo> pInfos = GetPropertyInfoList(entity);
foreach (var pi in pInfos)
{
var pk = pi.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;
if (pk != null && pk.IsPrimary)
{
clause.Append(string.Format("[{0}]='{1}'", pi.Name, id));
break;
}
}
if (clause.ToString() != string.Empty)
{
StringBuilder qry = new StringBuilder();
qry.Append(string.Format("SELECT * FROM [{0}] WHERE {1}", entity.GetType().Name, clause));
var _entities = ExecuteGet(qry.ToString());
if (_entities != null && _entities.Count > 0)
entity = _entities[0];
}
return entity;
}
public IList<T> Find(IEnumerable<object> ids)
{
IList<T> entities = new List<T>();
StringBuilder clause = new StringBuilder();
var entity = new T();
IList<PropertyInfo> pInfos = GetPropertyInfoList(entity);
foreach (var pi in pInfos)
{
var pk = pi.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;
if (pk != null && pk.IsPrimary)
{
string _ids = string.Empty;
foreach (var id in ids)
{
if (_ids != string.Empty)
_ids = _ids + ",";
_ids = _ids + id.ToString();
}
clause.Append(string.Format("[{0}] IN ({1})", pi.Name, _ids));
break;
}
}
if (clause.ToString() != string.Empty)
{
StringBuilder qry = new StringBuilder();
qry.Append(string.Format("SELECT * FROM [{0}] WHERE {1}", entity.GetType().Name, clause));
entities = ExecuteGet(qry.ToString());
}
return entities;
}
public IList<T> Find(IFilter<T> filter)
{
T entity = new T();
return ExecuteGet<T>(filter);
}
/// <summary>
/// Get all records
/// </summary>
/// <param name="cmdText"></param>
public IList<T> GetAll()
{
T entity = new T();
return ExecuteGet(string.Format("SELECT * FROM [{0}]", entity.GetType().Name));
}
/// <summary>
/// Pass comman text to get values
/// </summary>
/// <param name="commandText"></param>
/// <returns></returns>
public IList<T> GetAll(string commandText)
{
return ExecuteGet(commandText);
}
public IList<TEntity> GetAll<TEntity>(string commandText)
where TEntity : class, new()
{
return ExecuteGet<TEntity>(commandText);
}
#endregion
#region Private methods
/// <summary>
/// Execute Only ; No return
/// </summary>
/// <param name="cmdText"></param>
//private void Execute(string cmdText)
//{
// using (var connection = GetConnection())
// {
// connection.Open();
// SQLiteCommand cmd = new SQLiteCommand(cmdText, connection);
// cmd.ExecuteNonQuery();
// }
//}
private long Execute(string cmdText, bool returnIdentity = false)
{
using (var connection = GetConnection())
{
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(cmdText, connection);
if (returnIdentity)
{
return (long)cmd.ExecuteScalar();
}
else
{
cmd.ExecuteNonQuery();
return 0;
}
}
}
/// <summary>
/// Execute and get records. of the native type
/// </summary>
/// <param name="cmdText"></param>
/// <returns></returns>
private IList<T> ExecuteGet(string cmdText)
{
using (var connection = GetConnection())
{
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(cmdText, connection);
using (var reader = cmd.ExecuteReader())
{
return new EntityMapper().Map<T>(reader);
}
}
}
/// <summary>
/// Get list of items by specifying the type
/// </summary>
/// <param name="cmdText"></param>
/// <returns></returns>
private IList<TEntity> ExecuteGet<TEntity>(string cmdText)
where TEntity : class, new()
{
using (var connection = GetConnection())
{
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(cmdText, connection);
using (var reader = cmd.ExecuteReader())
{
return new EntityMapper().Map<TEntity>(reader);
}
}
}
/// <summary>
/// Pass filter to get records in entity format
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="filter"></param>
/// <returns></returns>
private IList<TEntity> ExecuteGet<TEntity>(IFilter<TEntity> filter)
where TEntity : class, new()
{
using (var connection = GetConnection())
{
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(filter.Query, connection);
using (var reader = cmd.ExecuteReader())
{
return new EntityMapper().Map<TEntity>(reader);
}
}
}
/// <summary>
/// Pass SQLite reader to get the specified entity type
/// when you are reading dataset or multiple records
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private IList<TEntity> ExecuteGet<TEntity>(SQLiteDataReader reader)
where TEntity : class, new()
{
return new EntityMapper().Map<TEntity>(reader);
}
private IList<PropertyInfo> GetPropertyInfoList(T entity)
{
return entity.GetType().GetProperties()
.Where(p => p.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(DbColumnAttribute)) != null).ToList();
}
private IList<PropertyInfo> GetPropertyInfoList<TEntity>(TEntity entity)
{
return entity.GetType().GetProperties()
.Where(p => p.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(DbColumnAttribute)) != null).ToList();
}
#endregion
}
#endregion
#region Cache/Storage
public static class Context
{
public static string ConnectionString { get; set; }
}
#endregion
#region Entity Mapper
public class EntityMapper
{
// Complete
public IList<T> Map<T>(SQLiteDataReader reader)
where T : class, new()
{
IList<T> collection = new List<T>();
while (reader.Read())
{
T obj = new T();
foreach (PropertyInfo i in obj.GetType().GetProperties()
.Where(p => p.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(DbColumnAttribute)) != null).ToList())
{
try
{
var ca = i.GetCustomAttribute(typeof(DbColumnAttribute));
if (ca != null)
{
if (((DbColumnAttribute)ca).Convert == true)
{
if (reader[i.Name] != DBNull.Value)
i.SetValue(obj, Convert.ChangeType(reader[i.Name], i.PropertyType));
}
else
{
if (reader[i.Name] != DBNull.Value)
i.SetValue(obj, reader[i.Name]);
}
}
}
catch (Exception ex)
{
#if DEBUG
Console.WriteLine(ex.Message);
Console.ReadLine();
#endif
#if !DEBUG
throw ex;
#endif
}
}
collection.Add(obj);
}
return collection;
}
}
#endregion
#region Interfaces
public interface IFilter<T> where T : class, new()
{
string EntityName { get; }
string Query { get; }
void Add(Expression<Func<T, object>> memberExpression, object memberValue);
}
#endregion
#region Filter
public class Filter<T> : IFilter<T> where T : class, new()
{
public Filter()
{
_Query = new StringBuilder();
EntityName = typeof(T).Name;
}
public void Add(Expression<Func<T, object>> memberExpression, object memberValue)
{
if (_Query.ToString() != string.Empty)
_Query.Append(" AND ");
_Query.Append(string.Format(" [{0}] = {1}", NameOf(memberExpression), memberValue == null ? "NULL" : string.Format("'{0}'", memberValue)));
}
public void Like(Expression<Func<T, object>> memberExpression, object memberValue)
{
if (_Query.ToString() != string.Empty)
_Query.Append(" AND ");
_Query.Append(string.Format(" [{0}] LIKE '{1}' ", NameOf(memberExpression), memberValue == null ? "NULL" : "%" + memberValue + "%"));
}
public string EntityName { get; private set; }
private readonly StringBuilder _Query;
/// <summary>
/// Returns SELECT statement with WHERE clause based on the expression passed; This is CommandText
/// </summary>
public string Query
{
get
{
return string.Format("SELECT * FROM [{0}] {1} {2};"
, EntityName
, _Query.ToString() == string.Empty ? string.Empty : "WHERE"
, _Query.ToString());
}
}
private string NameOf(Expression<Func<T, object>> exp)
{
MemberExpression body = exp.Body as MemberExpression;
if (body == null)
{
UnaryExpression ubody = (UnaryExpression)exp.Body;
body = ubody.Operand as MemberExpression;
}
return body.Member.Name;
}
}
#endregion
}
Class Employee
using SQLiteWithCSharp.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLiteWithCSharp.Models
{
public class Employee
{
[DbColumn(IsIdentity =true, IsPrimary =true)]
public long EmployeeId { get; set; }
[DbColumn]
public string Name { get; set; }
[DbColumn]
public string Surname { get; set; }
[DbColumn]
public string Date_Birth { get; set; }
[DbColumn]
public string Home_Address { get; set; }
[DbColumn]
public string City { get; set; }
[DbColumn]
public string Postcode { get; set; }
[DbColumn]
public string Telephone { get; set; }
[DbColumn]
public string Mobile { get; set; }
[DbColumn]
public string Email { get; set; }
}
}
Look at your video on 0:13 and 0:14. The scroll bar disappears partly at the top. The top part of your table is hidden behind the header.
Check if your Sqlite has case sensitive LIKE on.
PRAGMA case_sensitive_like=ON;
PRAGMA case_sensitive_like=OFF;
I modified the String.Format as shown below. You cannot enclose NULL in quotes. So I am composing single quotes also as part of replacement. This works fine for me in sqlite.
_Query.Append(string.Format(" [{0}] LIKE {1} "
, NameOf(memberExpression)
, memberValue == null ? "NULL" : "'%" + memberValue + "%'"));
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 have a paradigm which plays audio stimuli followed by images of the stimuli to be selected by the user. I need to replace the audio stimuli with video. Here is the original session code/implementation of the paradigm. At the end is one of my failed attempts at editing the session code that freezes trying to play. I could not fit all of the code, please let me know what else I should add of use.
Session:
using System;
using System.Linq;
using System.Media;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text;
namespace Memory
{
/// <summary>
/// this handles the creation, tracking, and scoring of a single session
/// </summary>
class Session
{
#region class Vars/Properties
File save;
ItemsPool _all, _presented, _selected, _displayed;
initVars Vars = initVars.defaults;
sessTimer _timer;
System.Timers.Timer onset;
bool p_onset = false;
string _output = "Memdata." + DateTime.Now.ToString("Mdyy-HHmm") + ".txt";
int _sessCount = 0;
SoundPlayer player;
/// <summary>
/// a collection of the sum of the scores for this session
/// </summary>
List<int[]> ScoreSum;
/// <summary>
/// the Sum of time results
/// </summary>
int TimesSum = 0;
/// <summary>
/// the number of items to display
/// </summary>
int _itemCount;
/// <summary>
/// the number of items to display
/// </summary>
public int itemCount
{
get { return _itemCount; }
set { _itemCount = value; }
}
/// <summary>
/// the session count
/// </summary>
public int SessionCount { get { return _sessCount; } }
string _prefix = "";
/// <summary>
/// the prefix for the Rows
/// </summary>
public string RowPrefix
{
get { return _prefix; }
set { _prefix = value; }
}
/// <summary>
/// the image width for each item
/// </summary>
public int ImgWidth { get; set; }
/// <summary>
/// the max runs for this session
/// </summary>
public int maxRuns { get; set; }
/// <summary>
/// debug value
/// </summary>
public bool debug { get { return Vars.debug; } }
/// <summary>
/// the onset value
/// </summary>
public int onsetValue { get { return Vars.onset; } }
/// <summary>
/// view Images before Audio
/// </summary>
public bool ViewImages { get { return Vars.ViewImages; } }
/// <summary>
/// allow correction
/// </summary>
public bool AllowCorrection { get { return Vars.allowCorrection; } }
/// <summary>
/// play sounds one at a time
/// </summary>
public bool playOne { get { return Vars.playOne; } }
#endregion
#region constructors
/// <summary>
/// create a new session and load settings from an XML string or file
/// </summary>
/// <param name="xml">either a path or a string of XML</param>
/// <param name="SaveName">the name of the output file</param>
public Session(string xml, string output, bool makeUnique)
{
if (output != "")
{ _output = output; }
save = new File(_output);
if (makeUnique)
{ save.MakeUnique(); }
XDocument setupXML;
//check to see if there are any XML nodes ie. is this a string of XML, or a path
string fchar = xml.Substring(0, 1);
if (fchar == "<")
{ setupXML = XDocument.Parse(xml); }
else
{ setupXML = XDocument.Load(xml); }
LoadXML(setupXML);
//set some class vars based on the initial vars
//these are variables that may change during the session
_itemCount = Vars.Columns;
ScoreSum = new List<int[]>();
ImgWidth = Vars.width;
maxRuns = Vars.maxRuns;
_presented = new ItemsPool();
_selected = new ItemsPool();
_timer = new sessTimer();
_timer.Update += new EventHandler<StringEventArgs>(_timer_Update);
}
void LoadXML(XDocument setupXML)
{
// get the initial variables
var initVars = from feed in setupXML.Descendants("var")
select new
{
Name = feed.Attribute("Name").Value,
Value = feed.Value
};
foreach (var feed in initVars)
{ Vars.SetVar(feed.Name, feed.Value); }
// parse the image and audio filename
var ifiles = from feed in setupXML.Descendants("stim")
select new Item
{
Name = feed.Attribute("Name").Value,
audio = feed.Element("audio").Value,
image = feed.Element("image").Value
};
_all = new ItemsPool();
foreach (Item it in ifiles)
{
_all.add(Item.getItem(it.Name
, Vars.ImageDirectory + it.image
, Vars.AudioDirectory + it.audio
));
}
}
#endregion
#region public methods
/// <summary>
/// randomly generate an items pool for playback
/// </summary>
/// <returns></returns>
public ItemsPool RandPresentation()
{
_presented = new ItemsPool();
_presented = RandPool(_itemCount, _all);
if (Vars.Randomize)
{
_displayed = new ItemsPool();
_displayed = RandPool(_itemCount, _presented);
}
else
{ _displayed = _presented; }
return _displayed;
}
ItemsPool RandPool(int count, ItemsPool pool)
{
ItemsPool rp = new ItemsPool();
Item it = RandItem(pool);
//get new randoms until we have enough
do
{
//since only unique items may be added to an ItemPool,
//we don't need to check if the the pool contains the random item
it = RandItem(pool);
rp.add(it);
} while (rp.count < count);
return rp;
}
/// <summary>
/// clear all, and start a new session
/// </summary>
public void startNew()
{
if (_timer.Active)
{ stopTimer(); }
_sessCount++;
_selected = new ItemsPool();
}
/// <summary>
/// decrement the session count
/// </summary>
public void decSessCount()
{
if (_sessCount > 0)
{ _sessCount--; }
}
/// <summary>
/// log the results to the save file
/// </summary>
public void LogResults()
{
if (_sessCount > 0)
{ logResults(); }
}
/// <summary>
/// add an item to the selected pool.
/// </summary>
/// <param name="it"></param>
public void Selected(Item it)
{
_selected.add(it);
if (_selected.count == _itemCount)
{
stopTimer();
LogResults();
}
}
private void stopTimer()
{
_timer.stop();
timerStopped(this, new EventArgs());
}
/// <summary>
/// remove an item from the selected pool
/// </summary>
/// <param name="it"></param>
public void remove(Item it)
{
if (_selected.Contains(it))
{
_selected.remove(it);
}
}
public void logSummary()
{
string[] lineSC = new string[_itemCount + 3];
string lineF = "\t\t{0}\t{1}";
string sumHdr1 = "\t\tPart\tN";
if (RowPrefix.Length > 7)
{
lineF = "\t{0}\t{1}";
sumHdr1 = "\tPart\t\tN";
}
lineSC[0] = String.Format(lineF, RowPrefix, _sessCount.ToString());
int ItemSum = 0;
//go through each column, get the sum
for (int i = 0; i < _itemCount; i++)
{
int cSum = 0;
//go through the list and get the score results for this column
foreach (int[] iarr in ScoreSum)
{
cSum += iarr[i];
}
ItemSum += cSum;
lineSC[i + 1] = cSum.ToString();
}
//Mean Time
double MTime = ((double)TimesSum / (double)_sessCount);
MTime = Math.Round(MTime, 3);
lineSC[_itemCount + 1] = MTime.ToString();
//Mean Sum
//double MSum = ((double)ItemSum / (double)_itemCount);
//MSum = Math.Round(MSum, 3);
//lineSC[_itemCount + 2] = MSum.ToString();
//Sum
lineSC[_itemCount + 2] = ItemSum.ToString();
//create the header
string[] sumHdr = new string[_itemCount + 2];
sumHdr[0] = sumHdr1;
for (int i = 0; i < _itemCount; i++)
{
sumHdr[i + 1] = "Itm" + (i + 1).ToString();
}
sumHdr[_itemCount + 1] = "M_Time\tSum";
//put to file
save.Append(dashBreak());
save.Append(sumHdr);
save.Append(lineSC);
save.Append(dashBreak());
}
string dashBreak()
{
StringBuilder sb = new StringBuilder("|--------");
for (int i = 0; i < _itemCount + 3; i++)
{
sb.Append("--------");
if (i == _itemCount + 2)
{
sb.Append("-----------|");
}
}
return sb.ToString();
}
#endregion
#region private methods
/// <summary>
/// save the session's results to a text file
/// </summary>
void logResults()
{
//there should be a scoring method here and perhaps an option to
//output scores instead of text options, but Susan did not want that.
//added scoring 5/8/09
int iCount = _presented.count;
string[] score = new string[iCount + 2];
int[] scs = new int[iCount];
for (int i = 0; i < iCount; i++)
{
Item pre = _presented.getItem(i);
Item sel = _selected.getItem(i);
int sc = 1;
//if (Item.Compare(pre,sel))
//{ sc = 1; }
if (pre.Name == sel.Name )
{ sc = 0; }
score[i + 1] = sc.ToString();
scs[i] = sc;
}
//log for the summary
ScoreSum.Add(scs);
TimesSum += _timer.Time;
//create array for log file
score[0] = String.Format("{0}\t{1}\t{2}", RowPrefix, _sessCount.ToString(), "errs");
score[iCount + 1] = _timer.Time.ToString();
//add the presented line
save.Append(MakeRow(_presented, "pres"));
//add the selected line
save.Append(MakeRow(_selected, "sel"));
//add the score line
save.Append(score);
//put an extra line in there
save.Append("");
}
string[] MakeRow(ItemsPool ip, string prefix)
{
string[] row = new string[ip.count + 1]; // 2];
row[0] = String.Format("{0}\t{1}\t{2}",RowPrefix, _sessCount.ToString(), prefix);
if (ip.count > 0)
{
for (int i = 0; i < ip.count; i++)
{
Item it = ip.getItem(i);
row[i + 1] = it.Name;
}
}
//row[ip.count + 1] = _timer.Time.ToString();
return row;
}
Item RandItem(ItemsPool pool)
{
//setup a new random object
Random r = new Random();
/* the random generator has a fear of the last option,
* so I'm giving it two chances to grab the last item...
* this may need adjustment.
*/
int _play = r.Next(pool.count + 1);
if (_play >= pool.count)
{ _play -= 1; }
Item ri = pool.getItem(_play);
return ri;
}
#endregion
#region audio player methods
void playItem(Item it)
{
player = new SoundPlayer();
player.LoadCompleted += new System.ComponentModel.AsyncCompletedEventHandler(player_LoadCompleted);
player.SoundLocation = it.audio;
player.Load();
}
void player_LoadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (p_onset)
{ player.Play(); }
else
{
player.PlaySync();
if (!Vars.playOne)
{ PlayNext(); }
}
}
int playQueue = 0;
public void playLast()
{
int p = playQueue;
if (p > 0)
{ p--; }
playItem(_presented.getItem(p));
}
public void PlayNext()
{
if (playQueue < _presented.count)
{
Item it = _presented.getItem(playQueue);
playQueue++;
playItem(it);
}
else
{
playQueue = 0;
_timer.start();
if (p_onset)
{
onset.Stop();
onset.Enabled = false;
onsetPlayFinished(this, new EventArgs());
}
}
}
public void playOnset()
{
p_onset = true;
onset = new System.Timers.Timer(Vars.onset);
onset.Elapsed += new System.Timers.ElapsedEventHandler(onset_Elapsed);
onset.Enabled = true;
if (!Vars.playOne)
{
PlayNext();
onset.Start();
}
}
void onset_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (!Vars.playOne)
{ PlayNext(); }
}
#endregion
#region events & handlers
public event EventHandler onsetPlayFinished;
public event EventHandler<StringEventArgs> TimerUpdate;
public event EventHandler timerStopped;
void _timer_Update(object sender, StringEventArgs e)
{ TimerUpdate(sender, e); }
#endregion
}
}
My Code:
using System;
using System.Linq;
using System.Media;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text;
using WMPLib;
using AxWMPLib;
namespace Memory
{
/// <summary>
/// this handles the creation, tracking, and scoring of a single session
/// </summary>
class Session
{
#region class Vars/Properties
File save;
ItemsPool _all, _presented, _selected, _displayed;
initVars Vars = initVars.defaults;
sessTimer _timer;
System.Timers.Timer onset;
bool p_onset = false;
string _output = "Memdata." + DateTime.Now.ToString("Mdyy-HHmm") + ".txt";
int _sessCount = 0;
AxWindowsMediaPlayer axWindowsMediaPlayer1;
/// <summary>
/// a collection of the sum of the scores for this session
/// </summary>
List<int[]> ScoreSum;
/// <summary>
/// the Sum of time results
/// </summary>
int TimesSum = 0;
/// <summary>
/// the number of items to display
/// </summary>
int _itemCount;
/// <summary>
/// the number of items to display
/// </summary>
public int itemCount
{
get { return _itemCount; }
set { _itemCount = value; }
}
/// <summary>
/// the session count
/// </summary>
public int SessionCount { get { return _sessCount; } }
string _prefix = "";
/// <summary>
/// the prefix for the Rows
/// </summary>
public string RowPrefix
{
get { return _prefix; }
set { _prefix = value; }
}
/// <summary>
/// the image width for each item
/// </summary>
public int ImgWidth { get; set; }
///<summary>
///video width for each item
/// </summary>
public int VidWidth { get; set; }
/// <summary>
/// the max runs for this session
/// </summary>
public int maxRuns { get; set; }
/// <summary>
/// debug value
/// </summary>
public bool debug { get { return Vars.debug; } }
/// <summary>
/// the onset value
/// </summary>
public int onsetValue { get { return Vars.onset; } }
/// <summary>
/// view Images before Audio
/// </summary>
public bool ViewImages { get { return Vars.ViewImages; } }
/// <summary>
/// allow correction
/// </summary>
public bool AllowCorrection { get { return Vars.allowCorrection; } }
/// <summary>
/// play sounds one at a time
/// </summary>
public bool playOne { get { return Vars.playOne; } }
#endregion
#region constructors
/// <summary>
/// create a new session and load settings from an XML string or file
/// </summary>
/// <param name="xml">either a path or a string of XML</param>
/// <param name="SaveName">the name of the output file</param>
public Session(string xml, string output, bool makeUnique)
{
if (output != "")
{ _output = output; }
save = new File(_output);
if (makeUnique)
{ save.MakeUnique(); }
XDocument setupXML;
//check to see if there are any XML nodes ie. is this a string of XML, or a path
string fchar = xml.Substring(0, 1);
if (fchar == "<")
{ setupXML = XDocument.Parse(xml); }
else
{ setupXML = XDocument.Load(xml); }
LoadXML(setupXML);
//set some class vars based on the initial vars
//these are variables that may change during the session
_itemCount = Vars.Columns;
ScoreSum = new List<int[]>();
ImgWidth = Vars.width;
maxRuns = Vars.maxRuns;
_presented = new ItemsPool();
_selected = new ItemsPool();
_timer = new sessTimer();
_timer.Update += new EventHandler<StringEventArgs>(_timer_Update);
}
void LoadXML(XDocument setupXML)
{
// get the initial variables
var initVars = from feed in setupXML.Descendants("var")
select new
{
Name = feed.Attribute("Name").Value,
Value = feed.Value
};
foreach (var feed in initVars)
{ Vars.SetVar(feed.Name, feed.Value); }
// parse the image and audio filename
var ifiles = from feed in setupXML.Descendants("stim")
select new Item
{
Name = feed.Attribute("Name").Value,
video = feed.Element("video").Value,
image = feed.Element("image").Value
};
_all = new ItemsPool();
foreach (Item it in ifiles)
{
_all.add(Item.getItem(it.Name
, Vars.ImageDirectory + it.image
, Vars.VideoDirectory + it.video
));
}
}
#endregion
#region public methods
/// <summary>
/// randomly generate an items pool for playback
/// </summary>
/// <returns></returns>
public ItemsPool RandPresentation()
{
_presented = new ItemsPool();
_presented = RandPool(_itemCount, _all);
if (Vars.Randomize)
{
_displayed = new ItemsPool();
_displayed = RandPool(_itemCount, _presented);
}
else
{ _displayed = _presented; }
return _displayed;
}
ItemsPool RandPool(int count, ItemsPool pool)
{
ItemsPool rp = new ItemsPool();
Item it = RandItem(pool);
//get new randoms until we have enough
do
{
//since only unique items may be added to an ItemPool,
//we don't need to check if the the pool contains the random item
it = RandItem(pool);
rp.add(it);
} while (rp.count < count);
return rp;
}
/// <summary>
/// clear all, and start a new session
/// </summary>
public void startNew()
{
if (_timer.Active)
{ stopTimer(); }
_sessCount++;
_selected = new ItemsPool();
}
/// <summary>
/// decrement the session count
/// </summary>
public void decSessCount()
{
if (_sessCount > 0)
{ _sessCount--; }
}
/// <summary>
/// log the results to the save file
/// </summary>
public void LogResults()
{
if (_sessCount > 0)
{ logResults(); }
}
/// <summary>
/// add an item to the selected pool.
/// </summary>
/// <param name="it"></param>
public void Selected(Item it)
{
_selected.add(it);
if (_selected.count == _itemCount)
{
stopTimer();
LogResults();
}
}
private void stopTimer()
{
_timer.stop();
timerStopped(this, new EventArgs());
}
/// <summary>
/// remove an item from the selected pool
/// </summary>
/// <param name="it"></param>
public void remove(Item it)
{
if (_selected.Contains(it))
{
_selected.remove(it);
}
}
public void logSummary()
{
string[] lineSC = new string[_itemCount + 3];
string lineF = "\t\t{0}\t{1}";
string sumHdr1 = "\t\tPart\tN";
if (RowPrefix.Length > 7)
{
lineF = "\t{0}\t{1}";
sumHdr1 = "\tPart\t\tN";
}
lineSC[0] = String.Format(lineF, RowPrefix, _sessCount.ToString());
int ItemSum = 0;
//go through each column, get the sum
for (int i = 0; i < _itemCount; i++)
{
int cSum = 0;
//go through the list and get the score results for this column
foreach (int[] iarr in ScoreSum)
{
cSum += iarr[i];
}
ItemSum += cSum;
lineSC[i + 1] = cSum.ToString();
}
//Mean Time
//Same as original code
//Mean Sum
//same as original code
//Sum
lineSC[_itemCount + 2] = ItemSum.ToString();
//create the header
string[] sumHdr = new string[_itemCount + 2];
sumHdr[0] = sumHdr1;
for (int i = 0; i < _itemCount; i++)
{
sumHdr[i + 1] = "Itm" + (i + 1).ToString();
}
sumHdr[_itemCount + 1] = "M_Time\tSum";
//put to file
save.Append(dashBreak());
save.Append(sumHdr);
save.Append(lineSC);
save.Append(dashBreak());
}
string dashBreak()
{
StringBuilder sb = new StringBuilder("|--------");
for (int i = 0; i < _itemCount + 3; i++)
{
sb.Append("--------");
if (i == _itemCount + 2)
{
sb.Append("-----------|");
}
}
return sb.ToString();
}
#endregion
#region private methods
/// <summary>
/// save the session's results to a text file
/// </summary>
void logResults()
{
//there should be a scoring method here and perhaps an option to
//output scores instead of text options, but Susan did not want that.
//added scoring 5/8/09
int iCount = _presented.count;
string[] score = new string[iCount + 2];
int[] scs = new int[iCount];
for (int i = 0; i < iCount; i++)
{
Item pre = _presented.getItem(i);
Item sel = _selected.getItem(i);
int sc = 1;
//if (Item.Compare(pre,sel))
//{ sc = 1; }
if (pre.Name == sel.Name )
{ sc = 0; }
score[i + 1] = sc.ToString();
scs[i] = sc;
}
//log for the summary
ScoreSum.Add(scs);
TimesSum += _timer.Time;
//create array for log file
score[0] = String.Format("{0}\t{1}\t{2}", RowPrefix, _sessCount.ToString(), "errs");
score[iCount + 1] = _timer.Time.ToString();
//add the presented line
save.Append(MakeRow(_presented, "pres"));
//add the selected line
save.Append(MakeRow(_selected, "sel"));
//add the score line
save.Append(score);
//put an extra line in there
save.Append("");
}
string[] MakeRow(ItemsPool ip, string prefix)
{
string[] row = new string[ip.count + 1]; // 2];
row[0] = String.Format("{0}\t{1}\t{2}",RowPrefix, _sessCount.ToString(), prefix);
if (ip.count > 0)
{
for (int i = 0; i < ip.count; i++)
{
Item it = ip.getItem(i);
row[i + 1] = it.Name;
}
}
//row[ip.count + 1] = _timer.Time.ToString();
return row;
}
Item RandItem(ItemsPool pool)
{
//setup a new random object
Random r = new Random();
/* the random generator has a fear of the last option,
* so I'm giving it two chances to grab the last item...
* this may need adjustment.
*/
int _play = r.Next(pool.count + 1);
if (_play >= pool.count)
{ _play -= 1; }
Item ri = pool.getItem(_play);
return ri;
}
#endregion
#region video player methods
void playItem(Item it)
{
axWindowsMediaPlayer1 = new AxWindowsMediaPlayer();
axWindowsMediaPlayer1.PlayStateChange += new PlayStateChangeHandler(axWindowsMediaPlayer1_PlayStateChange);
this.axWindowsMediaPlayer1.URL ="it.video";
axWindowsMediaPlayer1.Ctlcontrols.play();
}
void axWindowsMediaPlayer1_LoadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (p_onset)
{ axWindowsMediaPlayer1.Ctlcontrols.play(); }
else
{
axWindowsMediaPlayer1.Ctlcontrols.play();
if (!Vars.playOne)
{ PlayNext(); }
}
}
int playQueue = 0;
new EventArgs());
}
}
}
...end of code block same as original
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 have an excel file. I am taking the first two columns of the file and using the values of those cells to fill the the first two string members of a class. The rest of the string members of this class are initiated and set in the class constructor. This class is called (ColumnsColumn).
I have a second class (called Columns) that has a member that is an array of ColumnsColumn's. This class I am passing as the "object o" parameter in the method XMLSerializer.Selerialize(Stream s, Object o). This method prints an XML to the command line.
The problem, is that it is only printing the first two members of ColumnsColumn (the two I got out of the Excel file).
Here is my Program.cs (main) file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Xml.Serialization;
namespace Excel_Dictionary
{
public class Program
{
public static Columns c = new Columns();
public static List<ColumnsColumn> objects = new List<ColumnsColumn>();
public static void Main(string[] args)
{
#if (DEBUG)
Parser excel = new Parser("stuff.xlsx");
#else
Console.Write("File name: ");
Parser excel = new Parser(Console.ReadLine());
#endif
XmlSerializer x = new XmlSerializer(typeof(Columns));
List<ColumnsColumn> temp = new List<ColumnsColumn>();
temp = excel.Parse();
c.Items = temp.ToArray();
x.Serialize(Console.Out, c);
Console.ReadLine();
for (int i = 0; i < objects.Count; i++)
{
}
}
}
public class Parser
{
private Excel.Application xlApp;
private Excel.Workbook xlBook;
private Excel.Worksheet xlSheet;
public Parser(string filename)
{
xlApp = new Excel.Application();
xlBook = xlApp.Workbooks.Open(filename);
xlSheet = xlBook.Worksheets[1];
xlApp.Visible = true;
Start();
}
public List<ColumnsColumn> Parse()
{
List<ColumnsColumn> arr = new List<ColumnsColumn>();
Start();
do
{
ColumnsColumn t = new ColumnsColumn();
t.ColumnType = CellValue();
Move(0, 1);
t.FieldKey = CellValue();
Move(1, -1);
t.EmptyValue = "";
t.FieldParameters = "";
t.TypeKey = "";
t.RelationshipIdentifier = "";
t.Title = "";
t.Section = "";
t.ColumnStyle = "";
t.ShowAggregation = "None";
t.AggregationTotalLevel = "All";
t.WeightedByFieldKey = "";
t.WeightedByFieldParameters = "";
t.CalculateProportion = "False";
t.ProportionTo = "GrandTotal";
t.TotalColumnStyle = "";
t.GroupColumnStyle = "";
t.Show = "True";
arr.Add(t);
} while (CellValue() != "" && CellValue() != null);
return arr;
}
public void Move(int row, int col)
{
xlApp.ActiveCell.get_Offset(row, col).Select();
}
/// <returns>Value of Active Cell</returns>
public string CellValue()
{
return xlApp.ActiveCell.Value2;
}
public void Start()
{
xlSheet.get_Range("A2").Select();
}
}
}
and my XMLSchema file which contains the XML deserialized classes (don't be taken off by it's size, it has A LOT of get set commands):
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.5472
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Columns {
private ColumnsColumn[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Column", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public ColumnsColumn[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class ColumnsColumn {
private string columnTypeField;
private string fieldKeyField;
private string emptyValueField;
private string fieldParametersField;
private string typeKeyField;
private string relationshipIdentifierField;
private string titleField;
private string sectionField;
private string columnStyleField;
private string showAggregationField;
private string aggregationTotalLevelField;
private string weightedByFieldKeyField;
private string weightedByFieldParametersField;
private string calculateProportionField;
private string proportionToField;
private string totalColumnStyleField;
private string groupColumnStyleField;
private string showField;
public ColumnsColumn() {
this.emptyValueField = "";
this.fieldParametersField = "";
this.typeKeyField = "";
this.relationshipIdentifierField = "";
this.titleField = "";
this.sectionField = "";
this.columnStyleField = "";
this.showAggregationField = "None";
this.aggregationTotalLevelField = "All";
this.weightedByFieldKeyField = "";
this.weightedByFieldParametersField = "";
this.calculateProportionField = "False";
this.proportionToField = "GrandTotal";
this.totalColumnStyleField = "";
this.groupColumnStyleField = "";
this.showField = "True";
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ColumnType {
get {
return this.columnTypeField;
}
set {
this.columnTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string FieldKey {
get {
return this.fieldKeyField;
}
set {
this.fieldKeyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string EmptyValue {
get {
return this.emptyValueField;
}
set {
this.emptyValueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string FieldParameters {
get {
return this.fieldParametersField;
}
set {
this.fieldParametersField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string TypeKey {
get {
return this.typeKeyField;
}
set {
this.typeKeyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string RelationshipIdentifier {
get {
return this.relationshipIdentifierField;
}
set {
this.relationshipIdentifierField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string Title {
get {
return this.titleField;
}
set {
this.titleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string Section {
get {
return this.sectionField;
}
set {
this.sectionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string ColumnStyle {
get {
return this.columnStyleField;
}
set {
this.columnStyleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("None")]
public string ShowAggregation {
get {
return this.showAggregationField;
}
set {
this.showAggregationField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("All")]
public string AggregationTotalLevel {
get {
return this.aggregationTotalLevelField;
}
set {
this.aggregationTotalLevelField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string WeightedByFieldKey {
get {
return this.weightedByFieldKeyField;
}
set {
this.weightedByFieldKeyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string WeightedByFieldParameters {
get {
return this.weightedByFieldParametersField;
}
set {
this.weightedByFieldParametersField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("False")]
public string CalculateProportion {
get {
return this.calculateProportionField;
}
set {
this.calculateProportionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("GrandTotal")]
public string ProportionTo {
get {
return this.proportionToField;
}
set {
this.proportionToField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string TotalColumnStyle {
get {
return this.totalColumnStyleField;
}
set {
this.totalColumnStyleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string GroupColumnStyle {
get {
return this.groupColumnStyleField;
}
set {
this.groupColumnStyleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.ComponentModel.DefaultValueAttribute("True")]
public string Show {
get {
return this.showField;
}
set {
this.showField = value;
}
}
}
In your schema definition, try removing all of the
[System.ComponentModel.DefaultValueAttribute("")]
lines. The reason (I believe) why the nodes are not printing is because you are setting the other columns to default values, and so there's no reason for them to get serialized from .NET xmlserializer's "point of view". You know, if a class had a point of view.