parsing by Linq to JSON - silverlight

I was trying to parse this using System.Json but I'm a bit confused how to use LINQ on this. The JSON string returned was something like:
{"SearchResults":[{"PageCount":"1"},
{"SEARCHVAL":"Result","CATEGORY":"Category1","X":"1","Y":"2"},
{"SEARCHVAL":"AnotherResult","CATEGORY":"Category1","X":"2","Y":"2"}]}
My code starts out as:
WebClient client = new WebClient();
client.OpenReadCompleted +=
new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(uri);
then proceeds to the event handler where the result is stored in a Stream. Any example how to get just the SEARCHVALs, CATEGORYs, Xs and Ys from the stream using LINQ?

The DataContractJSonSerializer is one way to do it but the presence of the "PageCount" object makes its use awkard. It looks to me as though someone has goofed on the server end, it would make much more sense to have the page count a property of the outer object and therefore leave the search results array to contain an homogeneous set of objects.
The System.Json namespace is handy for this sort of JSON since its very flexible.
JsonObject searchResults = (JsonObject)JsonValue.Load(e.Result);
Now you could use some Linq to get a set of objects out of this but first so we need to create a DTO type for it:-
public class SearchResult
{
public string SearchValue {get; set;}
public string Category {get; set;}
public string X {get; set;}
public string Y {get; set;}
}
So now the results query is:-
var resultList = ((JsonArray)searchResults["SearchResults"])
.OfType<JsonObject>()
.Where(o => o.ContainsKey("SEARCHVAL"))
.Select(o => new SearchResult() {
SearchValue = o["SEARCHVALUE"],
Category = o["CATEGORY"].
X = o["X"],
Y = o["Y"]
}).ToList();
The resultList is List<SearchResult> which you can now bind into some Xaml for display.

Related

map key value pair with entity properties in entity framework

Below is my code for entity and a function where I need to map entity TblEmployee from a key value pair.
In foreach loop I am getting values based on keys, what should be the best approach to do it?
public class TblEmployee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
}
public int Create()
{
tblEmployee employee = new tblEmployee();
using (var ctx = new theparkeee_testEntities())
{
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
string value = HttpContext.Current.Request.Form[key];
//how to map value from key value pair to entity employee.
}
}
}
You can use System.Reflection to get the Properties of an object by their name with Type.GetProperty(string name). After you got the PropertyInfo, you can use SetValue to assign a value to it.
foreach (string key in HttpContext.Current.Request.Form.AllKeys) {
// note that "value" is a reserved word, do not use it as variable name
string val = HttpContext.Current.Request.Form[key];
var propertyInfo = typeof(TblEmployee).GetProperty(key); // can maybe be moved outside of the loop
if (propertyInfo != null) {
propertyInfo.SetValue(employee, val);
}
}
This will work for string properties. If the property is of another type, you have to find the correct type (again, using reflection) and cast the string value before assigning it.
Note that this is not the correct approach to store data in MVC. You should not work with the Request.Form directly, instead your POST action should accept a ViewModel that can be mapped (e.g. using Automapper) to the DB entity. I.e. let the ASP ModelBinder do its work, instead of reinventing the wheel!
[HttpPost]
public ActionResult Submit(MyViewModel postData) {
var employee = Mapper.Map<TblEmployee>(postData);
_ctx.Employees.Add(employee);
_ctx.SaveChanges();
return new HttpStatusCodeResult((int)HttpStatusCode.OK);
}

Value is not a convertible object

I have a simple query and Poco that I'm using with Dapper like so:
var jc = this.dbConnection.ExecuteScalar<JcUser>("SELECT loginid as Username,Password,coalesce(CustomerId,0) as CustomerId,TextProfileId,UxProfileId from \"user\" where id = #id", new {id = id});
Poco:
public class JcUser
{
public string UserName { get; set; }
public string Password { get; set; }
public int CustomerId{ get; set; }
public int TextProfileId { get; set; }
public int UxProfileId { get; set; }
}
When this executes it throws an exception with the message
Value is not a convertible object: System.String to JcUser
The stack trace ends up at: at System.Convert.ToType (System.Object value, System.Type conversionType, IFormatProvider provider, Boolean try_target_to_type)
Any ideas why its doing this?
Thanks
UPDATE: Using var jc = this.dbConnection.Query<JcUser>("SELECT loginid as Username,Password,coalesce(CustomerId,0) as CustomerId,TextProfileId,UxProfileId from \"user\" where id = #id", new {id = id}).First(); appears to work. I also realise I'm a moron and ExecuteScalar is only for one value. However, is my update the best way to retrieve only one row?
ExecuteScalar maps to the ADO.NET method of the same name. It returns at most one cell: one grid, one row, one column. As such, it is not intended for use with complex objects, and cannot work correctly in your case as you have multiple columns.
Dapper assumes you would only use that with simple types like int, string etc.
In your case, use:
var jc = this.dbConnection.Query<JcUser>(
sql, args).SingleOrDefault();
If you want to avoid a hidden List<> allocation you could also pass buffered: false.

Dynamic Entity for Raw Sql Query using Entity Framework

I am scratching my head here. I have a bootstrap modal that has a field for entering in a sql query. The query I pass uses an AJAX call to a controller and executes the sql query using the code below and returns a JSON object. Something like this:
context.Database.SqlQuery(typeof(object), query);
But all I get are empty objects. I can't pass a type when I don't know the columns. For instance I could do something like this:
public class CusType {
public CusType(){}
public int Id { get; set; }
public string Name { get; set; }
}
and then do something like this:
context.Database.SqlQuery(typeof(CusType), query);
But that won't help me when I don't know or can't know the columns. I even tried an idea using ExpandoObjects. Example:
List<string> columns = new List<string>();
string tmpCol = query;
string[] seperator = new string[] { "from" };
tmpCol = query.ToLower()
.Replace(#"\s+", "")
.Replace("select", "");
tmpCol = tmpCol.Split(seperator, 1, StringSplitOptions.RemoveEmptyEntries)[0];
for (int i = 0; i < tmpCol.Split(',').Length; i++)
{
columns.Add(tmpCol.Split(',')[i]);
}
dynamic data = new ExpandoObject();
IDictionary<string, object> props = (IDictionary<string, object>)data;
foreach (var column in columns)
{
props.Add(column.ToString(), column.ToString());
}
return context.Database.SqlQuery(data.GetType(), query);
But what do I do when I want to execute the query?
context.Database.SqlQuery(data.GetType()??, query);
Even when I do put in the data.GetType() it returns empty objects.
In both examples (using typeof(object) and typeof(data.GetType()) I get this JSON object returned:
[{},{},{},{},{},{},{},{},{},{},{},{},{}]
Any ideas/suggestions?
Entity Framework populates a model based on the type specified. You'll need to use something else or go old school with a DataReader.

How to parse dynamic object in mvc?

I am working on ASP.NET MVC4.0.
My string is posting like this from view :-
[{"name":"AddressNumber","value":"1"},{"name":"OrganizationProd","value":""},{"name":"ClientId","value":""},{"name":"ProductId","value":""},{"name":"TaxId1","value":""},{"name":"TaxId2","value":""},{"name":"LaborID","value":"0"}]
And below is my controller's action method for that,which is receiving the input :-
[AllowAnonymous]
[HttpPost]
public ActionResult UpdateProducts(string ModelString){
}
And below is the string which i am getting in action(in ModelString variable):-
[{"name":"AddressNumber","value":"1"},{"name":"OrganizationProd","value":""},{"name":"ClientId","value":""},{"name":"ProductId","value":""},{"name":"TaxId1","value":""},{"name":"TaxId2","value":""},{"name":"LaborID","value":"0"}]
And after that i am deserializing the string like that :-
var sear = new JavaScriptSerializer();
var dictDynamic = sear.Deserialize<dynamic>(ModelString);
And i am getting the dynamic array in dictDynamic variable.And now i want to get the properties by its name not by indexing from dictDynamic object.
Currently i am getting the properties by indexing like this :-
dictDynamic[0]["value"]
dictDynamic[1]["value"]
But i want to parse it by properties name like this :-
dictDynamic["Name"]["value"]
dictDynamic["Description"]["value"]
Can anyone help me out on this ?
You could use ViewModel on server side, not sending model string.
You create ViewModel like this:
class ProductViewModel {
public int AddressNumber { get; set; }
public int ProductId { get; set; }
...
}
Then change your controller method:
[AllowAnonymous]
[HttpPost]
public ActionResult UpdateProducts(ProductViewModel vm){
...
}
And from your View you'll send json object like this:
{
"AddressNumber":"10",
"OrganizationProd":"1",
"ClientId":"1",
"ProductId":"1",
"TaxId1":"23",
"TaxId2":"23",
"LaborID":"10"
}
This will automaticaly bind your values from View to ViewModel on controller, and you can than use ViewModel object in your code, and you then have strongly typed entity.
Instead of this:
dictDynamic["AddressNumber"]
dictDynamic["OrganizationProd"]
now you can write this:
vm.AddressNumber
vm.OrganizationProd
You need to pass a JavaScript object to your function instead of an array. Array is not the correct data structure to use in this case. Objects have keys and values. The keys will be AddressNumber, OrganizationProd, ClientId, ProductId, TaxId1 etc. Their values will be 1, "", "0" etc.
For instance, for your example, this will be your object:
{
"AddressNumber":1,
"OrganizationProd":"",
"ClientId":"",
"ProductId":"",
"TaxId1":"",
"TaxId2":"",
"LaborID":0
}
You deserialize it like you do now:
var s = "{\"AddressNumber\":1, \"OrganizationProd\":\"\", \"ClientId\":\"\", \"ProductId\":\"\", \"TaxId1\":\"\", \"TaxId2\":\"\", \"LaborID\":0}";
var sear = new JavaScriptSerializer();
var dictDynamic = sear.Deserialize<dynamic>(s);
Once you deserialize, you will be able to reference the values like this:
dictDynamic["AddressNumber"]
dictDynamic["OrganizationProd"]

How to bind WPF Datagrid to a joined table

I have a big problem. I try to bind my WPF DataGrid to a table, created with inner join. I have created a class for the info to convert successfully:
public class NeshtoSi
{
public NeshtoSi() { }
public string ssn;
public string name;
public string surname;
}
And then I create the inner-joined tables. Still when I assign the ItemsSource and all values are transferred properly, but the DataGrid does not visualize them.
var dd = from d in dataContext.Medical_Examinations
join p in dataContext.Patients on d.SSN equals p.SSN
select new NeshtoSi { ssn = d.SSN, name = p.Name, surname = p.Surname };
IQueryable<NeshtoSi> sQuery = dd;
if (!string.IsNullOrEmpty(serName.Text))
sQuery = sQuery.Where(x => x.name.Contains(serName.Text));
if (!string.IsNullOrEmpty(serSurame.Text))
sQuery = sQuery.Where(x => x.surname.Contains(serSurame.Text));
if (!string.IsNullOrEmpty(serSSN.Text))
sQuery = sQuery.Where(x => x.ssn.Contains(serSSN.Text));
var results = sQuery.ToList();
AnSearch.ItemsSource = sQuery;
I hope that someone can help me...
The code that you presented seems ok - it doesn't matter how an object is created - what matters is the object itself.
Rather than showing us this, you should show the xaml.
One more thing - are we talking about DataGridView from winforms or rather the one that comes with WPF Toolkit ?
=======================================
Sorry. I've missed it in the first place - you don't have properties in your class! You've created public fields instead of properties and that's probably the problem.
The code should look like this:
public class NeshtoSi
{
public NeshtoSi() { }
public string ssn{get; set;}
public string name{get; set;}
public string surname{get; set;}
}
I went through this recently, and the answer is outlined in a post of mine that is here

Resources