Windows phone creating custom objects to columns? - c#

as the question title says, I am trying to map a custom object to a db column on windows phone how can I do this? the exception I am getting: "Unable to determine SQL type for 'Layer'."
layer is a custom object, what is the correct way to store this, can someone please provide me with a example. thank you
code:
...
[Table]
public class Product : INotifyPropertyChanged, INotifyPropertyChanging
{
#region ID
//not autogenerated, this is from the client
private String _id;
[Column(IsPrimaryKey = true, IsDbGenerated = false, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public String Id
{
get { return _id; }
set
{
if (_id != value)
{
NotifyPropertyChanging("id");
_id = value;
NotifyPropertyChanged("id");
}
}
}
#endregion
#region Product Layer
private Layer _productlayer;
[Column]
public Layer ProductLayer
{
get { return _productlayer; }
set
{
if (_productlayer != value)
{
NotifyPropertyChanging("ProductLayer");
_productlayer = value;
NotifyPropertyChanged("ProductLayer");
}
}
}
#endregion
....
public class Layer
{
public string name{ get; set; }
public string des { get; set; }
public string pos { get; set; }
}

Related

CsvHelper Looking for Non-existent Columns

The propblem: There is no "Name" field in the object or csv file, yet CsVHelper keeps looking for "Name" in the header. So why is it tripping there and what are some fixes?
When trying to build objects from a csv file, the following error comes up:
CsvHelper.HeaderValidationException: Header with name 'Name' was not found. If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.
at CsvHelper.Configuration.ConfigurationFunctions.HeaderValidated(Boolean isValid, String[] headerNames, Int32 headerNameIndex, ReadingContext context)
I have tried setting HeaderValidated to null, but got the same results.
The header of the csv:
Id|Title|Description|AssignedToUserId|SourceUserId|DateCreated|DateAssigned|DateCompleted|Notes
The parsing code:
private static IEnumerable<T> GetCSVData<T>(string fullFileName)
{
PrintMembers<T>();
using (var reader = new StreamReader(fullFileName))
{
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.IncludePrivateMembers = false;
csv.Parser.Configuration.Delimiter = "|";
var records = csv.GetRecords<T>().ToList();
return records;
}
}
}
A quick function for listing the public properties and fields of the class (T) being passed in outputs the following:
Properties...
Id
AssignedToUserId
SourceUserId
Title
Description
AssignedTo
Source
DateCreated
DateAssigned
DateCompleted
RelatedTasks
Notes
Fields...
[None]
They all have getters and setters.
EDIT
The IntermediateTask is the generic being fed into GetCSVData(). It has a default constructor. IntermediateTask is internal, but is in the same assembly as GetCSVData().
Code for the class(es) in question:
internal class IntermediateTask : Task
{
private int _Id;
new public int Id
{
get { return _Id; }
set { _Id = value; }
}
private int _AssignedToUserId;
public int AssignedToUserId
{
get { return _AssignedToUserId; }
set
{
_AssignedToUserId = value;
base.AssignedTo = userManager.Get(_AssignedToUserId);
}
}
private int _SourceUserId;
public int SourceUserId
{
get { return _SourceUserId; }
set
{
this._SourceUserId = value;
base.Source = userManager.Get(_SourceUserId);
}
}
public IntermediateTask() : base("", "", new IntermediateUser(), new IntermediateUser())
{
}
}
public class Task
{
public Task(string title, string description, User assignedTo, User source, DateTime? dateCreated = null, int id = 0)
{
this.RelatedTasks = new List<Task>();
this.Title = title;
this.Description = description;
this.AssignedTo = assignedTo;
this.Source = source;
this.DateCreated = dateCreated ?? DateTime.Now;
this.Id = id;
}
private int _Id;
public int Id
{
get { return _Id; }
protected set { _Id = value; }
}
public string Title { get; set; }
public string Description { get; set; }
public User AssignedTo { get; set; }
public User Source { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateAssigned { get; set; }
public DateTime? DateCompleted { get; set; }
public IList<Task> RelatedTasks { get; set; }
public string Notes { get; set; }
override public string ToString()
{
return $"Id: {Id}; Title: {Title}";
}
}
In my case it complained about AssignedTo missing, but that is actually a property in the class that is not in the csv, so I had to add these two lines to make it work:
csv.Configuration.HeaderValidated = null;
csv.Configuration.MissingFieldFound = null;
I don't know why it would come up with 'Name' unless you have something different.

JSON to List<class> & List<class> to JSON?

Hi guys how do I get this to work? I searched in SO and this was the most promissing but it doesnt work either.
errormessage:
The deserialized type should be a normal .NET type (i.e. not a
primitive type like integer, not a collection type like an array or
List) or a dictionary type (i.e. Dictionary).
so how do i split the individual objects from my json?
List<class> a = JsonConvert.DeserializeObject<List<class>>(JSON_String)
the JSON string:
{
"SPALTEN": [{
"NUMMER": 1,
"NAME": "BREITE",
"TYP": "Double",
"LAENGE": 0,
"EINHEIT": "m",
"EDITIERBAR": true,
"OPTIONAL": true,
"LAYER": null,
"LAYER_SPALTE": null,
"D_SPAL_NAME": null,
"D_SPAL_MIN": 0,
"D_SPAL_MAX": null,
"D_SPAL_VAL": null
}, {
"NUMMER": 2,
"NAME": "KOMMENTAR",
"TYP": "String",
"LAENGE": 255,
"EINHEIT": null,
"EDITIERBAR": true,
"OPTIONAL": true,
"LAYER": null,
"LAYER_SPALTE": null,
"D_SPAL_NAME": null,
"D_SPAL_MIN": null,
"D_SPAL_MAX": null,
"D_SPAL_VAL": null
}]
}
here is my class:
public class CONFIG_CLASS
{
private int _NUMMER;
public int NUMMER
{
get { return _NUMMER; }
set { _NUMMER = value; }
}
private string _NAME;
public string NAME
{
get { return _NAME; }
set { _NAME = value; }
}
private string _TYP;
public string TYP
{
get { return _TYP; }
set { _TYP = value; }
}
private double _LAENGE;
public double LAENGE
{
get { return _LAENGE; }
set { _LAENGE = value; }
}
private string _EINHEIT;
public string EINHEIT
{
get { return _EINHEIT; }
set { _EINHEIT = value; }
}
private bool _EDITIERBAR;
public bool EDITIERBAR
{
get { return _EDITIERBAR; }
set { _EDITIERBAR = value; }
}
private bool _OPTIONAL;
public bool OPTIONAL
{
get { return _OPTIONAL; }
set { _OPTIONAL = value; }
}
private string _LAYER;
public string LAYER
{
get { return _LAYER; }
set { _LAYER = value; }
}
private int _LAYER_SPALTE;
public int LAYER_SPALTE
{
get { return _LAYER_SPALTE; }
set { _LAYER_SPALTE = value; }
}
private string _D_SPAL_NAME;
public string D_SPAL_NAME
{
get { return _D_SPAL_NAME; }
set { _D_SPAL_NAME = value; }
}
private int _D_SPAL_MIN;
public int D_SPAL_MIN
{
get { return _D_SPAL_MIN; }
set { _D_SPAL_MIN = value; }
}
private int _D_SPAL_MAX;
public int D_SPAL_MAX
{
get { return _D_SPAL_MAX; }
set { _D_SPAL_MAX = value; }
}
private string _D_SPAL_VAL;
public string D_SPAL_VAL
{
get { return _D_SPAL_VAL; }
set { _D_SPAL_VAL = value; }
}
}
(I would also like to encode it again later)
thank you!
You should specify the type of thing you want to deserialise, I don't think object will work.
List<MyClass> a = JsonConvert.DeserializeObject<List<MyClass>>("[{some json}]")
Sorry I cannot put comments yet
First,you have some type mismatch between your data and your convert class:
LAYER_SPALTE, D_SPAL_MIN and D_SPAL_MAX are null in your data.
put try putting your array inside another class
this code has to work for you:
public class MyClass
{
public SPALTEN[] SPALTEN { get; set; }
}
public class SPALTEN
{
public int NUMMER { get; set; }
public string NAME { get; set; }
public string TYP { get; set; }
public int LAENGE { get; set; }
public string EINHEIT { get; set; }
public bool EDITIERBAR { get; set; }
public bool OPTIONAL { get; set; }
public string LAYER { get; set; }
public int? LAYER_SPALTE { get; set; }
public string D_SPAL_NAME { get; set; }
public int? D_SPAL_MIN { get; set; }
public int? D_SPAL_MAX { get; set; }
public string D_SPAL_VAL { get; set; }
}
and then
MyClass a = JsonConvert.DeserializeObject<MyClass>(JSON_String)
To convert it on Internet, you can use the below URL for JSON to C#. I have been using from so long.
http://json2csharp.com/

Reflection getting dataContext and Table

I'm trying to create an app just for learing purposes.
I'd Like to dynamically save any object to the right context.
So my idea is something like this:
My businessmodel for the player is this:
[Table]
public class PLAYER:ISiedlerEntity
{
[Column(CanBeNull = false, IsPrimaryKey = true, DbType = "INT NOT NULL Identity", IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public long ID { get; set; }
[Column]
public string Name { get; set; }
[Column]
public int GamesPlayed { get; set; }
}
}
The context is this:
public class PLAYERS:DataContext
{
private const string CONNECTION_STRING = "isostore:/tblPLAYERs.sdf";
public Table<PLAYER> Entities;
public PLAYERS()
: base(CONNECTION_STRING)
{
}
}
Do you think there is a possibility to handle the saving in one function just by passing the ISiedlerEntitiy?
My approach so far:
public static bool Save(ISiedlerEntity entity)
{
bool result = true;
string dcName = entity.GetType().Name + "S";
PropertyInfo pi = CurrentApp.GetType().GetProperty(dcName);
DataContext dc = pi.GetValue(CurrentApp) as DataContext;
foreach (var prop in dc.GetType().GetProperties())
{
if (prop.Name == "Entities")
{
var t = prop.GetValue(dc);
}
}
return result;
}
So far so fine, but now I need to cast the datacontext to the specified context, to access the Entities property.
Do you think this is possible so far? Or is there a easier solution?
Thanks and a good evening to everybody.
Matthias Müller

linq2sql insert data in database one-to-many relationship

I'm writing a wpf app. I have a local database (sqlCE) with two entity classes that correspond to different tables. The first one class is Account and the second one is Movements. There's a relationship one-to-many between the two tables: an account can have more movements.
Here is Account class:
[Table]
public class Account
{
.....other private fields...
private Int16 iDA;
private EntitySet<Movement> movements;
...other properties with column attribute....
//primary key
[Column(IsPrimaryKey = true, Storage="iDA", IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "smallint")]
public Int16 IDA
{
get { return iDA; }
private set { iDA = value; }
}
//association
[Association(Storage = "movements", OtherKey = "IDA")]
public EntitySet<Movement> Movements
{
get { return movements; }
set { this.movements.Assign(value); }
}
public Account()
{
this.movements = new EntitySet<Movement>();
}
}
and here's Movement class:
[Table]
public class Movement
{
...other fields...
private Int16 iDA;
private int iDM;
private EntityRef<Account> myAcc;
//primary key
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "int NOT NULL IDENTITY", Storage = "iDM")]
public int IDM
{
get { return iDM; }
set { iDM = value; }
}
//property links the two tables
[Column(DbType = "smallint", Storage="iDA", isPrimaryKey=true)]
public Int16 IDA
{
get { return iDA; }
set { iDA = value; }
}
//association
[Association(Storage = "myAcc", ThisKey = "IDA")]
public Account MyAccount
{
get { return this.myAcc.Entity; }
set { this.myAcc.Entity = value; }
}
......
public Movement()
{
this.myAcc = new EntityRef<Account>();
}
}
I define IDA property to link the two tables. After that I write datacontext class:
public class DataBase : DataContext
{
public Table<Account> AccountTable
{
get { return this.GetTable<Account>(); }
}
public Table<Movement> MovementTable
{
get { return this.GetTable<Movement>(); }
}
public DataBase(string connection) : base(connection) { }
}
In mainclass I create database, but when i try to populate it with an account object, I get a sql exception! I can insert data calling InsertOnSubmit(Account a) without problems, but when I call SubmitChanges() the program stops and the exception says "The column can not contain null values. [Column name = IDA, Table name = Account]".
Anyone can help me?
Try using DbType = "smallint not null identity" and CanBeNull = false parameters for the Column attribute of the IDA field.
I've solved my problem, changing in Int the IDA property in both classes and making some adjustment.

How to map with Linq to SQL one to many

I have a table 'Article'
private int id;
[ColumnAttribute(Storage = "id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id
{
get { return id; }
set { id = value; }
}
private string title;
[ColumnAttribute(Storage = "title", DbType = "NVarChar(250) NOT NULL", CanBeNull = false)]
public string Title
{
get { return title; }
set { title = value; }
}
private string description;
[ColumnAttribute(Storage = "description", DbType = "NVarChar(350) NOT NULL", CanBeNull = false)]
public string Description
{
get { return description; }
set { description = value; }
}
and a table comment
[Table(Name = "dbo.Comments")]
public class CommentDto
{
private int id;
[ColumnAttribute(Storage = "id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id
{
get { return id; }
set { id = value; }
}
private string content;
[ColumnAttribute(Storage = "content", DbType = "NVarChar(600) NOT NULL", CanBeNull = false)]
public string Content
{
get { return content; }
set { content = value; }
}
private string date;
[ColumnAttribute(Storage = "date", DbType = "DateTime NOT NULL", CanBeNull = false)]
public string Date
{
get { return date; }
set { date = value; }
}
}
One Article can have many comments and each comment can be placed by a User
[TableAttribute(Name = "dbo.Users")]
public class UserDto
{
private int id;
[ColumnAttribute(Storage = "id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id
{
get { return id; }
set { id = value; }
}
private string username;
[ColumnAttribute(Storage = "username", DbType = "NVarChar(150) NOT NULL", CanBeNull = false)]
public string Username
{
get { return username; }
set { username = value; }
}
How do I map the relatinship between these tables?
Thanks
I think you are creating your table classes manually. there is no need to do that.
add a LINQ to SQL (dbml) file to your solution, open Server Explorer window and connect to your database,
drag and drop the tables into the design of your dbml class.
if there are foreign key constraints in your tables, then link will create respective properties in both classes.
and if you want to do it manually (which I can't see why),
create a property with the type of the referenced class and this is the attribute needed:
[Association(Name="your_fk_constraint_name", Storage="name_of_your_private_backup_field", ThisKey="name_of_the_key_in_this_table", IsForeignKey=true)]
hope I helped a little
You can read about mapping associations here.
In your case:
class Article
{
private EntitySet<CommentDto> _Comments;
[Association(OtherKey = "ArticleID")]
public virtual IList<CommentDto> Comments
{
get
{
if (_Comments == null)
_Comments = new EntitySet<CommentDto>();
return _Comments;
}
set
{
Comments.Assign(value);
}
}
}
class Comment
{
[Association(ThisKey="ArticleID")]
public ArticleDto Article { get; set; }
}
Of course, you should first add ArticleID column to Comments table in database.
The part below is not presented in MSDN code from the link above, but without it I had a lot of problems with DTO in WCF service. So, now I prefer to add it to every association:
if (_Comments == null)
_Comments = new EntitySet<CommentDto>();

Categories

Resources