I am creating an API for project tasks. It has a TasksController as listed below. I am generating hypermedia using WebApi.Hal and the service supports hal+json and hal+xml media types also.
Following is the response I currently have for the GET request http://localhost:51910/api/tasks/1. In the response there is a list of links for priorities – but they don’t have associated name in the response (to show in the UI – like Low, Medium, High, etc.).
What is the best HAL approach for getting name of the priorities also, using WebApi.HAL?
Note: The list of priorities can be enhanced in the future.
Priority
public class Priority
{
public int PriorityID { get; set; }
public string PriorityName { get; set; }
public string Revision { get; set; }
public DateTime ApprovalDate { get; set; }
}
Controller
public class TasksController : ApiController
{
// GET api/values/5
[HttpGet]
public TaskRepresentation Get(int id)
{
Task selectedTask = TasksHelper.GetTask(id);
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
//PUT For Setting Priority
[HttpPut]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public TaskRepresentation PutSetPriority(int taskID, int priorityID)
{
Task selectedTask = TasksHelper.GetTask(taskID);
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
//Update Task
if (selectedPriority != null)
{
selectedTask.CurrentPriority = selectedPriority.PriorityName;
}
else
{
throw new Exception("Not available");
}
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
[HttpGet]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public Priority Get(int taskID, int priorityID)
{
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
return selectedPriority;
}
}
HAL Generation Related Classes
public static class LinkTemplates
{
public static class TaskLinks
{
public static Link TaskEntry { get { return new Link("self", "~/api/tasks/{taskID}"); } }
public static Link PriorityLink { get { return new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}"); } }
}
}
public class TaskRepresentation : Representation
{
Task theTask;
public int TaskID{get{return theTask.TaskID;}}
public string TaskName{get{return theTask.Name;}}
public string CurrentPriority{get{return theTask.CurrentPriority;}}
public string Category{get{return theTask.Category;}}
public TaskRepresentation(Task t)
{
theTask = t;
}
public override string Rel
{
get { return LinkTemplates.TaskLinks.TaskEntry.Rel; }
set { }
}
public override string Href
{
get { return LinkTemplates.TaskLinks.TaskEntry.CreateLink(new { taskID = theTask.TaskID }).Href; }
set { }
}
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Links.Add(LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID }));
}
}
}
HAL Specification mentions title - this will meet the requirement.
Following is the updated response.
{
"TaskID": 1,
"TaskName": "Task1",
"CurrentPriority": "Medium",
"Category": "IT",
"_links": {
"self": {
"href": "/api/tasks/1"
},
"priorities": [
{
"href": "/api/tasks/1/priorities/101",
"title": "Low"
},
{
"href": "/api/tasks/1/priorities/103",
"title": "High"
},
{
"href": "/api/tasks/1/priorities/104",
"title": "Critical"
}
]
}
}
WebAPI.HAL changes
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Link lnk = LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID });
lnk.Title = p.PriorityName;
Links.Add(lnk);
}
}
Code
public static class LinkTemplates
{
public static class TaskLinks
{
public static Link TaskEntry { get { return new Link("self", "~/api/tasks/{taskID}"); } }
//public static Link PriorityLink { get { return new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}"); } }
public static Link PriorityLink
{
get
{
Link l = new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}");
return l;
}
}
}
}
public class TasksController : ApiController
{
// GET api/values/5
[HttpGet]
public TaskRepresentation Get(int id)
{
Task selectedTask = TasksHelper.GetTask(id);
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
//PUT For Setting Priority
[HttpPut]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public TaskRepresentation PutSetPriority(int taskID, int priorityID)
{
Task selectedTask = TasksHelper.GetTask(taskID);
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
//Update Task
if (selectedPriority != null)
{
selectedTask.CurrentPriority = selectedPriority.PriorityName;
}
else
{
throw new Exception("Not available");
}
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
[HttpGet]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public Priority Get(int taskID, int priorityID)
{
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
return selectedPriority;
}
}
public class TaskRepresentation : Representation
{
Task theTask;
public int TaskID{get{return theTask.TaskID;}}
public string TaskName{get{return theTask.Name;}}
public string CurrentPriority{get{return theTask.CurrentPriority;}}
public string Category{get{return theTask.Category;}}
public TaskRepresentation(Task t)
{
theTask = t;
}
public override string Rel
{
get { return LinkTemplates.TaskLinks.TaskEntry.Rel; }
set { }
}
public override string Href
{
get { return LinkTemplates.TaskLinks.TaskEntry.CreateLink(new { taskID = theTask.TaskID }).Href; }
set { }
}
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Link lnk = LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID });
lnk.Title = p.PriorityName;
Links.Add(lnk);
}
}
}
public class Task
{
public string Name { get; set; }
public int TaskID { get; set; }
public string Category { get; set; }
public string CurrentPriority { get; set; }
public List<Priority> PossiblePriorities { get; set; }
}
public class Priority
{
public int PriorityID { get; set; }
public string PriorityName { get; set; }
public string Revision { get; set; }
public DateTime ApprovalDate { get; set; }
}
public static class TasksPrioritiesHelper
{
public static List<Priority> GetAllPriorities()
{
List<Priority> possiblePriorities = new List<Priority>();
Priority pLow = new Priority { PriorityID = 101, PriorityName = "Low" };
Priority pMedium = new Priority { PriorityID = 102, PriorityName = "Medium" };
Priority pHigh = new Priority { PriorityID = 103, PriorityName = "High" };
Priority pCritical = new Priority { PriorityID = 104, PriorityName = "Critical" };
possiblePriorities.Add(pLow);
possiblePriorities.Add(pMedium);
possiblePriorities.Add(pHigh);
possiblePriorities.Add(pCritical);
return possiblePriorities;
}
public static List<Priority> GetAdministrativePriorities()
{
List<Priority> possiblePriorities = new List<Priority>();
Priority pLow = new Priority { PriorityID = 101, PriorityName = "Low" };
Priority pHigh = new Priority { PriorityID = 103, PriorityName = "High" };
possiblePriorities.Add(pLow);
possiblePriorities.Add(pHigh);
return possiblePriorities;
}
public static List<Priority> GetPossiblePrioritiesForTask(Task t)
{
List<Priority> possibleTaskPriorities = new List<Priority>();
if (String.Equals(t.Category, "IT"))
{
possibleTaskPriorities = GetAllPriorities();
}
else
{
possibleTaskPriorities = GetAdministrativePriorities();
}
Priority currentTaskPriority = null;
foreach(Priority p in possibleTaskPriorities )
{
if(String.Equals(t.CurrentPriority,p.PriorityName ))
{
currentTaskPriority=p;
}
}
if(currentTaskPriority!=null)
{
possibleTaskPriorities.Remove(currentTaskPriority);
}
return possibleTaskPriorities;
}
}
public static class TasksHelper
{
public static Task GetTask(int id)
{
Task selectedTask = null;
List<Task> tasks = GetAllTasks();
foreach (Task t in tasks)
{
if(t.TaskID==id)
{
selectedTask = t;
}
}
return selectedTask;
}
public static List<Task> GetAllTasks()
{
List<Task> tasks;
tasks = new List<Task>();
Task t1 = new Task{Category = "IT",CurrentPriority = "Medium",Name = "Task1",TaskID = 1};
t1.PossiblePriorities = TasksPrioritiesHelper.GetPossiblePrioritiesForTask(t1);
tasks.Add(t1);
return tasks;
}
}
Related
I am trying to make a DataGridViewComboBox Column that will accept new data and add it to it's list items.
I am building this for a quoting system I sort of did this another way but I just couldn't get it to function reliably.
I keep getting a System.NullReferenceException on the OnSelectedIndexChanged.
I want to be able to type a value into the the ComboBox cell have it added to the list items in order.
Can someone help me out on this?
#region DataGridViewVariableComboBoxColumn
public class DataGridViewVariableComboBoxColumn : DataGridViewComboBoxColumn
{
[Browsable(true)]
[Category("Behavior")]
[DefaultValue(false)]
public bool AddNewItems { get; set; }
private System.Windows.Forms.AutoCompleteMode comboxAutoCompleteMode;
[Browsable(true)]
[Category("Behavior")]
[DefaultValue(false)]
public System.Windows.Forms.AutoCompleteMode ComboBoxAutoCompleteMode
{
get { return comboxAutoCompleteMode; }
set
{
comboxAutoCompleteMode = value;
}
}
public DataGridViewVariableComboBoxColumn()
{
this.CellTemplate = new DataGridViewVariableComboBoxCell();
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
if (value != null &&
!value.GetType().IsAssignableFrom(typeof(DataGridViewVariableComboBoxCell)))
{
throw new InvalidCastException("Must be a DataGridViewVariableComboBoxCell");
}
base.CellTemplate = value;
}
}
public override object Clone()
{
var c = (DataGridViewVariableComboBoxColumn)base.Clone();
if (c != null)
{
c.AddNewItems = this.AddNewItems;
c.ComboBoxAutoCompleteMode = this.ComboBoxAutoCompleteMode;
c.DisplayStyle = this.DisplayStyle;
c.FlatStyle = this.FlatStyle;
}
return c;
}
}
public class DataGridViewVariableComboBoxCell : DataGridViewComboBoxCell
{
public DataGridViewVariableComboBoxCell() : base()
{
}
public override object Clone()
{
DataGridViewVariableComboBoxCell cell = base.Clone() as DataGridViewVariableComboBoxCell;
return cell;
}
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
try
{
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
DataGridViewVariableComboBoxEditingControl TheControl = (DataGridViewVariableComboBoxEditingControl)DataGridView.EditingControl;
var c = (DataGridViewVariableComboBoxColumn)this.OwningColumn;
TheControl.OwningColumn = this.OwningColumn;
TheControl.AddNewItems = c.AddNewItems;
TheControl.EditingComboBoxAutoCompleteMode = c.ComboBoxAutoCompleteMode;
TheControl.EditingAutoCompleteSource = AutoCompleteSource.ListItems;
TheControl.EditingComboBoxStyle = ComboBoxStyle.DropDown;
if (TheControl != null)
{
TheControl.SelectedIndex = 0;
}
}
catch { }
}
public override Type EditType
{
get
{
return typeof(DataGridViewVariableComboBoxEditingControl);
}
}
public override Type ValueType
{
get
{
// Return the type of the value that DataGridViewVariableComboBoxCell contains.
return typeof(string);
}
}
}
internal class DataGridViewVariableComboBoxEditingControl : DataGridViewComboBoxEditingControl, IDataGridViewEditingControl
{
private DataGridView dataGridViewControl;
private int rowIndex;
private bool valueChanged = false;
public System.Windows.Forms.AutoCompleteMode EditingComboBoxAutoCompleteMode
{
get
{return this.AutoCompleteMode; }
set
{
this.AutoCompleteMode = value;
}
}
public ComboBoxStyle EditingComboBoxStyle
{
get
{ return this.DropDownStyle; }
set
{
this.DropDownStyle = value;
}
}
public AutoCompleteSource EditingAutoCompleteSource
{
get
{ return this.AutoCompleteSource; }
set
{
this.AutoCompleteSource = value;
}
}
public DataGridViewVariableComboBoxEditingControl() : base()
{
}
public bool AddNewItems { get; set; }
public DataGridViewColumn OwningColumn { get; set; }
private string editingControlFormattedValue;
public string EditingControlFormattedValue
{
get
{
return editingControlFormattedValue;
}
set
{
editingControlFormattedValue = value;
}
}
public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
{
editingControlFormattedValue = this.Text;
if (this.SelectedIndex == -1 && this.AddNewItems && editingControlFormattedValue != "")
{
List<string> list = new List<string>();
if (this.Items.Count > 0)
{
list = this.Items.Cast<string>()
.Select(x => x)
.ToList();
}
else
{
list = new List<string>();
}
if (!list.Contains(editingControlFormattedValue) && editingControlFormattedValue != "")
{
list.Add(editingControlFormattedValue);
list = list.Distinct().OrderBy(o => o).ToList();
}
((DataGridViewVariableComboBoxColumn)OwningColumn).Items.Clear();
((DataGridViewVariableComboBoxColumn)OwningColumn).Items.AddRange(list.ToArray());
this.Items.Clear();
this.Items.AddRange(list.ToArray());
int index = ((DataGridViewVariableComboBoxColumn)OwningColumn).Items.IndexOf(editingControlFormattedValue);
EditingControlValueChanged = true;
//base.SelectedIndex = index;
//this.Text = text;
// EditingControlDataGridView.NotifyCurrentCellDirty(true);
}
return editingControlFormattedValue;
}
public DataGridView EditingControlDataGridView
{
get
{
return dataGridViewControl;
}
set
{
dataGridViewControl = value;
}
}
public int EditingControlRowIndex
{
get
{
return rowIndex;
}
set
{
rowIndex = value;
}
}
public bool EditingControlWantsInputKey(
Keys key, bool dataGridViewWantsInputKey)
{
// Let the DateTimePicker handle the keys listed.
switch (key & Keys.KeyCode)
{
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Right:
case Keys.Home:
case Keys.End:
case Keys.PageDown:
case Keys.PageUp:
return true;
default:
return false;
}
}
// Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit
// method.
public void PrepareEditingControlForEdit(bool selectAll)
{
// No preparation needs to be done.
}
// Implements the IDataGridViewEditingControl
// .RepositionEditingControlOnValueChange property.
public bool RepositionEditingControlOnValueChange
{
get
{
return false;
}
}
// Implements the IDataGridViewEditingControl
// .EditingControlValueChanged property.
public bool EditingControlValueChanged
{
get
{
return valueChanged;
}
set
{
valueChanged = value;
}
}
// Implements the IDataGridViewEditingControl
// .EditingPanelCursor property.
public Cursor EditingPanelCursor
{
get
{
return base.Cursor;
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (valueChanged)
{
base.OnSelectedIndexChanged(e);
}
}
protected override void OnSelectedValueChanged(EventArgs e)
{
if (valueChanged)
{
base.OnSelectedValueChanged(e);
}
}
protected override void OnSelectedItemChanged(EventArgs e)
{
if (valueChanged)
{
base.OnSelectedItemChanged(e);
}
}
}
#endregion
After updating to ABP v3.0.0, I started getting DbContext disposed exception when running parallel requests to repository that create new UnitOfWork like this:
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
I looked in the source code and found some code in AsyncLocalCurrentUnitOfWorkProvider that I don't understand. When setting current uow, it sets property in wrapper:
private static readonly AsyncLocal<LocalUowWrapper> AsyncLocalUow = new AsyncLocal<LocalUowWrapper>();
private static void SetCurrentUow(IUnitOfWork value)
{
lock (AsyncLocalUow)
{
if (value == null)
{
if (AsyncLocalUow.Value == null)
{
return;
}
if (AsyncLocalUow.Value.UnitOfWork?.Outer == null)
{
AsyncLocalUow.Value.UnitOfWork = null;
AsyncLocalUow.Value = null;
return;
}
AsyncLocalUow.Value.UnitOfWork = AsyncLocalUow.Value.UnitOfWork.Outer;
}
else
{
if (AsyncLocalUow.Value?.UnitOfWork == null)
{
if (AsyncLocalUow.Value != null)
{
AsyncLocalUow.Value.UnitOfWork = value;
}
AsyncLocalUow.Value = new LocalUowWrapper(value);
return;
}
value.Outer = AsyncLocalUow.Value.UnitOfWork;
AsyncLocalUow.Value.UnitOfWork = value;
}
}
}
private class LocalUowWrapper
{
public IUnitOfWork UnitOfWork { get; set; }
public LocalUowWrapper(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
}
That does not look thread-safe, as any thread can set new UnitOfWork and then dispose it.
Is it a bug? I can use my own implementation of ICurrentUnitOfWorkProvider, without wrapping, but I'm not sure if that is correct.
Update
I can't give an example with DbContext disposed exception, but here is one with null reference exception in repository.GetAll() method. I think it has the same reason.
namespace TestParallelEFRequest
{
public class Ent1 : Entity<int> { public string Name { get; set; } }
public class Ent2 : Entity<int> { public string Name { get; set; } }
public class Ent3 : Entity<int> { public string Name { get; set; } }
public class Ent4 : Entity<int> { public string Name { get; set; } }
public class DomainStartEvent : EventData {}
public class DBContext : AbpDbContext {
public DBContext(): base("Default") {}
public IDbSet<Ent1> Ent1 { get; set; }
public IDbSet<Ent2> Ent2 { get; set; }
public IDbSet<Ent3> Ent3 { get; set; }
public IDbSet<Ent4> Ent4 { get; set; }
}
public class TestService : DomainService, IEventHandler<DomainStartEvent>
{
private readonly IRepository<Ent1> _rep1;
private readonly IRepository<Ent2> _rep2;
private readonly IRepository<Ent3> _rep3;
private readonly IRepository<Ent4> _rep4;
public TestService(IRepository<Ent1> rep1, IRepository<Ent2> rep2, IRepository<Ent3> rep3, IRepository<Ent4> rep4) {
_rep1 = rep1;_rep2 = rep2;_rep3 = rep3;_rep4 = rep4;
}
Task HandleEntityes<T>(IRepository<T> rep, int i) where T : class, IEntity<int> {
return Task.Run(() => {
using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.RequiresNew)) {
Thread.Sleep(i); // Simulating work
rep.GetAll(); // <- Exception here
}
});
}
public void HandleEvent(DomainStartEvent eventData) {
using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.RequiresNew)) {
var t1 = HandleEntityes(_rep1, 10);
var t2 = HandleEntityes(_rep2, 10);
var t3 = HandleEntityes(_rep3, 10);
var t4 = HandleEntityes(_rep4, 1000);
Task.WaitAll(t1, t2, t3, t4);
}
}
}
[DependsOn(typeof(AbpEntityFrameworkModule))]
public class ProgrammModule : AbpModule
{
public override void PreInitialize() { Configuration.DefaultNameOrConnectionString = "Default"; }
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
Database.SetInitializer<DBContext>(null);
}
}
class Program {
static void Main(string[] args) {
using (var bootstrapper = AbpBootstrapper.Create<ProgrammModule>()) {
bootstrapper.Initialize();
bootstrapper.IocManager.Resolve<IEventBus>().Trigger(new DomainStartEvent());
Console.ReadKey();
}
}
}
}
Let's say that you have the following code
public class MyClass {
public double Latitude {get; set;}
public double Longitude {get; set;}
}
public class Criteria
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public MyClass MyProp {get; set;}
}
[HttpGet]
public Criteria Get([FromUri] Criteria c)
{
return c;
}
I'd like to know if someone is aware of a library that could transform any object into query string that is understood by a WEB API 2 Controller.
Here is an example of what I'd like
SerializeToQueryString(new Criteria{StartDate=DateTime.Today, EndDate = DateTime.Today.AddDays(1), MyProp = new MyProp{Latitude=1, Longitude=3}});
=> "startDate=2015-10-13&endDate=2015-10-14&myProp.latitude=1&myProp.longitude=3"
A full example with httpClient might look like :
new HttpClient("http://localhost").GetAsync("/tmp?"+SerializeToQueryString(new Criteria{StartDate=DateTime.Today, EndDate = DateTime.Today.AddDays(1), MyProp = new MyProp{Latitude=1, Longitude=3}})).Result;
At the moment, I use a version (taken from a question I do not find again, maybe How do I serialize an object into query-string format? ...).
The problem is that it is not working for anything else than simple properties.
For example, calling ToString on a Date will not give something that is parseable by WEB API 2 controller...
private string SerializeToQueryString<T>(T aObject)
{
var query = HttpUtility.ParseQueryString(string.Empty);
var fields = typeof(T).GetProperties();
foreach (var field in fields)
{
string key = field.Name;
var value = field.GetValue(aObject);
if (value != null)
query[key] = value.ToString();
}
return query.ToString();
}
"Transform any object to a query string" seems to imply there's a standard format for this, and there just isn't. So you would need to pick one or roll your own. JSON seems like the obvious choice due to the availability of great libraries.
Since it seems no one has dealt with the problem before, here is the solution I use in my project :
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Web;
namespace App
{
public class QueryStringSerializer
{
public static string SerializeToQueryString(object aObject)
{
return SerializeToQueryString(aObject, "").ToString();
}
private static NameValueCollection SerializeToQueryString(object aObject, string prefix)
{
//!\ doing this to get back a HttpValueCollection which is an internal class
//we want a HttpValueCollection because toString on this class is what we want in the public method
//cf http://stackoverflow.com/a/17096289/1545567
var query = HttpUtility.ParseQueryString(String.Empty);
var fields = aObject.GetType().GetProperties();
foreach (var field in fields)
{
string key = string.IsNullOrEmpty(prefix) ? field.Name : prefix + "." + field.Name;
var value = field.GetValue(aObject);
if (value != null)
{
var propertyType = GetUnderlyingPropertyType(field.PropertyType);
if (IsSupportedType(propertyType))
{
query.Add(key, ToString(value));
}
else if (value is IEnumerable)
{
var enumerableValue = (IEnumerable) value;
foreach (var enumerableValueElement in enumerableValue)
{
if (IsSupportedType(GetUnderlyingPropertyType(enumerableValueElement.GetType())))
{
query.Add(key, ToString(enumerableValueElement));
}
else
{
//it seems that WEB API 2 Controllers are unable to deserialize collections of complex objects...
throw new Exception("can not use IEnumerable<T> where T is a class because it is not understood server side");
}
}
}
else
{
var subquery = SerializeToQueryString(value, key);
query.Add(subquery);
}
}
}
return query;
}
private static Type GetUnderlyingPropertyType(Type propType)
{
var nullablePropertyType = Nullable.GetUnderlyingType(propType);
return nullablePropertyType ?? propType;
}
private static bool IsSupportedType(Type propertyType)
{
return SUPPORTED_TYPES.Contains(propertyType) || propertyType.IsEnum;
}
private static readonly Type[] SUPPORTED_TYPES = new[]
{
typeof(DateTime),
typeof(string),
typeof(int),
typeof(long),
typeof(float),
typeof(double)
};
private static string ToString(object value)
{
if (value is DateTime)
{
var dateValue = (DateTime) value;
if (dateValue.Hour == 0 && dateValue.Minute == 0 && dateValue.Second == 0)
{
return dateValue.ToString("yyyy-MM-dd");
}
else
{
return dateValue.ToString("yyyy-MM-dd HH:mm:ss");
}
}
else if (value is float)
{
return ((float) value).ToString(CultureInfo.InvariantCulture);
}
else if (value is double)
{
return ((double)value).ToString(CultureInfo.InvariantCulture);
}
else /*int, long, string, ENUM*/
{
return value.ToString();
}
}
}
}
Here is the unit test to demonstrate :
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Framework.WebApi.Core.Tests
{
[TestClass]
public class QueryStringSerializerTest
{
public class EasyObject
{
public string MyString { get; set; }
public int? MyInt { get; set; }
public long? MyLong { get; set; }
public float? MyFloat { get; set; }
public double? MyDouble { get; set; }
}
[TestMethod]
public void TestEasyObject()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EasyObject(){MyString = "string", MyInt = 1, MyLong = 1L, MyFloat = 1.5F, MyDouble = 1.4});
Assert.IsTrue(queryString.Contains("MyString=string"));
Assert.IsTrue(queryString.Contains("MyInt=1"));
Assert.IsTrue(queryString.Contains("MyLong=1"));
Assert.IsTrue(queryString.Contains("MyFloat=1.5"));
Assert.IsTrue(queryString.Contains("MyDouble=1.4"));
}
[TestMethod]
public void TestEasyObjectNullable()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EasyObject() { });
Assert.IsTrue(queryString == "");
}
[TestMethod]
public void TestUrlEncoding()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EasyObject() { MyString = "&=/;+" });
Assert.IsTrue(queryString.Contains("MyString=%26%3d%2f%3b%2b"));
}
public class DateObject
{
public DateTime MyDate { get; set; }
}
[TestMethod]
public void TestDate()
{
var d = DateTime.ParseExact("2010-10-13", "yyyy-MM-dd", CultureInfo.InvariantCulture);
var queryString = QueryStringSerializer.SerializeToQueryString(new DateObject() { MyDate = d });
Assert.IsTrue(queryString.Contains("MyDate=2010-10-13"));
}
[TestMethod]
public void TestDateTime()
{
var d = DateTime.ParseExact("2010-10-13 20:00", "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
var queryString = QueryStringSerializer.SerializeToQueryString(new DateObject() { MyDate = d });
Assert.IsTrue(queryString.Contains("MyDate=2010-10-13+20%3a00%3a00"));
}
public class InnerComplexObject
{
public double Lat { get; set; }
public double Lon { get; set; }
}
public class ComplexObject
{
public InnerComplexObject Inner { get; set; }
}
[TestMethod]
public void TestComplexObject()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new ComplexObject() { Inner = new InnerComplexObject() {Lat = 50, Lon = 2} });
Assert.IsTrue(queryString.Contains("Inner.Lat=50"));
Assert.IsTrue(queryString.Contains("Inner.Lon=2"));
}
public class EnumerableObject
{
public IEnumerable<int> InnerInts { get; set; }
}
[TestMethod]
public void TestEnumerableObject()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EnumerableObject() {
InnerInts = new[] { 1,2 }
});
Assert.IsTrue(queryString.Contains("InnerInts=1"));
Assert.IsTrue(queryString.Contains("InnerInts=2"));
}
public class ComplexEnumerableObject
{
public IEnumerable<InnerComplexObject> Inners { get; set; }
}
[TestMethod]
public void TestComplexEnumerableObject()
{
try
{
QueryStringSerializer.SerializeToQueryString(new ComplexEnumerableObject()
{
Inners = new[]
{
new InnerComplexObject() {Lat = 50, Lon = 2},
new InnerComplexObject() {Lat = 51, Lon = 3},
}
});
Assert.Fail("we should refuse something that will not be understand by the server");
}
catch (Exception e)
{
Assert.AreEqual("can not use IEnumerable<T> where T is a class because it is not understood server side", e.Message);
}
}
public enum TheEnum : int
{
One = 1,
Two = 2
}
public class EnumObject
{
public TheEnum? MyEnum { get; set; }
}
[TestMethod]
public void TestEnum()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EnumObject() { MyEnum = TheEnum.Two});
Assert.IsTrue(queryString.Contains("MyEnum=Two"));
}
}
}
I'd like to thank all the participants even if this is not something that you should usually do in a Q&A format :)
In my WP7 project i'm using nested Observable collection. However, my problem is sorting this nested collection by with its nested collection in descending order.
Data Structure of Collection:
public class SubCategory : INotifyPropertyChanged
{
private string _catName;
public string CatName
{
get { return _catName; }
set
{
_catName = value; NotifyPropertyChanged("CatName");
}
}
private ObservableCollection<ToDoList> _lists;
public ObservableCollection<ToDoList> Lists
{
get { return _lists; }
set
{
if (_lists != value)
{
_lists = value;
NotifyPropertyChanged("lists");
}
}
}
And this is the nested collection
public class ToDoList : INotifyPropertyChanged//, INotifyPropertyChanging
{
#region NotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region NotifyPropertyChanging Members
// public event PropertyChangingEventHandler PropertyChanging;
/* private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}*/
#endregion
[Column(IsVersion = true)]
private Binary _version;
private int _ItemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int ItemId
{
get { return _ItemId; }
set
{
if (_ItemId != value)
{
//NotifyPropertyChanging("ItemdId");
_ItemId = value;
NotifyPropertyChanged("ItemId");
}
}
}
private string _ItemTitle;
[Column]
public string ItemTitle
{
get { return _ItemTitle; }
set
{
if (_ItemTitle != value)
{
//NotifyPropertyChanging("ItemTitle");
_ItemTitle = value;
NotifyPropertyChanged("ItemTitle");
}
}
}
private double _ItemLatitude;
[Column]
public double ItemLatitude
{
get { return _ItemLatitude; }
set
{
if (_ItemLatitude != value)
{
//NotifyPropertyChanging("ItemLatitude");
_ItemLatitude = value;
NotifyPropertyChanged("ItemLatitude");
}
}
}
private string _ItemAddress;
[Column]
public string ItemAddress
{
get { return _ItemAddress; }
set
{
if (_ItemAddress != value)
{
//NotifyPropertyChanging("ItemAddress");
_ItemAddress = value;
NotifyPropertyChanged("ItemAddress");
}
}
}
private double _ItemLongtitude;
[Column]
public double ItemLongtitude
{
get { return _ItemLongtitude; }
set
{
if (_ItemLongtitude != value)
{
//NotifyPropertyChanging("ItemLongtitude");
_ItemLongtitude = value;
NotifyPropertyChanged("ItemLongtitude");
}
}
}
private string _ItemDescription;
[Column]
public string ItemDescription
{
get { return _ItemDescription; }
set
{
if (_ItemDescription != value)
{
//NotifyPropertyChanging("ItemDescription");
_ItemDescription = value;
NotifyPropertyChanged("ItemDescription");
}
}
}
private bool isScheduled;
[Column]
public bool IsScheduled
{
get { return isScheduled; }
set
{
if (isScheduled != value)
{
//NotifyPropertyChanging("IsScheduled");
isScheduled = value;
NotifyPropertyChanged("IsScheduled");
}
}
}
private string _reminderId;
[Column]
public String ReminderId
{
get { return _reminderId; }
set
{
if (_reminderId != value)
{
//NotifyPropertyChanging("ReminderId");
_reminderId = value;
NotifyPropertyChanged("ReminderId");
}
}
}
private String _ItemTime;
[Column]
public String ItemTime
{
get { return _ItemTime; }
set
{
if (_ItemTime != value)
{
//NotifyPropertyChanging("ItemTime");
_ItemTime = value;
NotifyPropertyChanged("ItemTime");
}
}
}
private bool _isComplete;
[Column]
public bool IsComplete
{
get { return _isComplete; }
set
{
if (_isComplete != value)
{
//NotifyPropertyChanging("IsComplete");
_isComplete = value;
NotifyPropertyChanged("IsComplete");
}
}
}
private char _importance;
[Column]
public char Importance
{
get { return _importance; }
set
{
if (_importance != value)
{
//NotifyPropertyChanging("Importance");
_importance = value;
NotifyPropertyChanged("Importance");
}
}
}
[Column]
internal int _categoryId;
private EntityRef<Category> _category;
public Category ToDoCategory
{
get { return _category.Entity; }
set
{
//NotifyPropertyChanging("ToDoCategory");
_category.Entity = value;
if (value != null)
{
_categoryId = value.CategoryId;
}
//NotifyPropertyChanging("ToDoCategory");
}
}
}
I solved by changing the get method. Here is how i did.
public ObservableCollection<ToDoList> Lists
{
get
{
var l = from ToDoList lis in _lists
orderby lis.ItemId descending
select lis;
return new ObservableCollection<ToDoList>(l);
}
set
{
if (_lists != value)
{
_lists = value;
NotifyPropertyChanged("lists");
}
}
}
I created a local db with helper app project. and deployed it from isolate storage to installation folder,i added to project directory with content build action by add existing item. my problem is that i want to insert data, but i don't know how to move the db file to isolate storage to insert and data must add to my .sdf file that is locate in my project directory also.
Souphia,
While learning to use WP, I wrote a simple application that tracked tasks.
One version of that app stored all task data in Sql on the phone.
You can read the post and download all the code for the app here:
http://www.ritzcovan.com/2012/02/building-a-simple-windows-phone-app-part-3/
But, here is some of the code from that project:
First we have the model class decorated with the appropriate attributes:
[Table]
public class Task : INotifyPropertyChanged, INotifyPropertyChanging
{
[Column(IsDbGenerated = false, IsPrimaryKey = true, CanBeNull = false)]
public string Id
{
get { return _id; }
set
{
NotifyPropertyChanging("Id");
_id = value;
NotifyPropertyChanging("Id");
}
}
[Column]
public string Name
{
get { return _name; }
set
{
NotifyPropertyChanging("Name");
_name = value;
NotifyPropertyChanged("Name");
}
}
[Column]
public string Category
{
get { return _category; }
set
{
NotifyPropertyChanging("Category");
_category = value;
NotifyPropertyChanged("Category");
}
}
[Column]
public DateTime? DueDate
{
get { return _dueDate; }
set
{
NotifyPropertyChanging("DueDate");
_dueDate = value;
NotifyPropertyChanged("DueDate");
}
}
[Column]
public DateTime? CreateDate
{
get { return _createDate; }
set
{
NotifyPropertyChanging("CreateDate");
_createDate = value;
NotifyPropertyChanged("CreateDate");
}
}
[Column]
public bool IsComplete
{
get { return _isComplete; }
set
{
NotifyPropertyChanging("IsComplete");
_isComplete = value;
NotifyPropertyChanged("IsComplete");
}
}
[Column(IsVersion = true)] private Binary _version;
private string _id;
private bool _isComplete;
private DateTime? _createDate;
private DateTime? _dueDate;
private string _name;
private string _category;
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
public void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
public void NotifyPropertyChanging(string property)
{
if (PropertyChanging != null)
PropertyChanging(this, new PropertyChangingEventArgs(property));
}
}
In the constructor in app.xaml.cs, I have the following:
TaskMasterDataContext = new TaskMasterDataContext();
if (!TaskMasterDataContext.DatabaseExists())
{
TaskMasterDataContext.CreateDatabase();
DatabaseHelper.SetupDatabase(TaskMasterDataContext);
}
and here is the TaskMasterDataContext.cs code
public class TaskMasterDataContext : DataContext
{
public TaskMasterDataContext() : base("Data Source=isostore:/TaskMasterData.sdf")
{
}
public Table<Task> Tasks;
}
public static class DatabaseHelper
{
public static void SetupDatabase(TaskMasterDataContext dataContext)
{
string category = string.Empty;
var tasks = new List<Task>();
for (int i = 0; i < 20; i++)
{
tasks.Add(new Task()
{
Id = System.Guid.NewGuid().ToString(),
Category = GetCategoryString(i),
CreateDate = DateTime.Now,
DueDate = DateTime.Now.AddDays(new Random().Next(1, 30)),
IsComplete = false,
Name = String.Format("{0} Task # {1}", GetCategoryString(i), i)
});
}
dataContext.Tasks.InsertAllOnSubmit(tasks);
dataContext.SubmitChanges();
}
private static string GetCategoryString(int i)
{
if (i%2 == 0)
return "home";
if (i%3 == 0)
return "personal";
return "work";
}
}
The DatabaseHelper class is just there to populate the DB with some test data after its created.
I hope this helps.