Json parsing in windows phone (C#) - windows-phone

I am new to Windows Phone development.I want to parse some data using json parsing.After
googling i find a number of example but I am not able to understand properly.I have follow
a link
http://dotnetbyexample.blogspot.in/2012/01/json-deserialization-with-jsonnet.html
to do json parsing But i am not able to show Storage ,Memory, ScreenSize in my List and my code is
private void Load_Click(object sender, RoutedEventArgs e)
{
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<RootObject>>(r.EventArgs.Result);
PhoneList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://www.schaikweb.net/dotnetbyexample/JSONPhones1.txt"));
}
}
public class Specs
{
public string Storage { get; set; }
public string Memory { get; set; }
public string Screensize { get; set; }
}
public class RootObject
{
public string Brand { get; set; }
public string Type { get; set; }
public Specs Specs { get; set; }
}
}
Please Help me to solve this issue or any other sample for the same is also appreciated
Thanks

The code seems ok, so if you aren't running in to any errors there might be an issue with your UI code or UI to data coupling.
You need to post the UI code to get some help with this I suspect.

Related

Using ReadAsAsync<T>() to deserialize complex Json object

I want to use ReadAsAsync() in my mvc project with .net 4.0. The result comes as null.
If I enter the uri to address bar, the result in chrome as(tag names are changed):
<ns2:MyListResponse xmlns:ns2="blablabla">
<customerSessionId>xxcustomerSessionIdxx</customerSessionId>
<numberOfRecordsRequested>0</numberOfRecordsRequested>
<moreResultsAvailable>false</moreResultsAvailable>
<MyList size="1" activePropertyCount="1">
<MySummary order="0">
<id>1234</id>
<name>...</name>
.
.
</MySummary>
</MyList>
</ns2:MyListResponse>
If I use the statement in code :
using (var client = new HttpClient())
{
var response = client.GetAsync(apiUri).Result;
var message = response.Content.ReadAsStringAsync().Result;
var result1 = JsonConvert.DeserializeObject<MyListResponse>(message);
var result2 = response.Content.ReadAsAsync<MyListResponse>().Result;
}
the message comes in string format as "{\"MyListResponse\":{\"customerSessionId\"...}" which corresponds to a json object as:
{"MyListResponse":
{"customerSessionId":"xxcustomerSessionIdxx",
"numberOfRecordsRequested":0,
"moreResultsAvailable":false,
"MyList":
{"#size":"1",
"#activePropertyCount":"1",
"MySummary":
{"#order":"0",
"id":1234,
"name":"...",
.
.
}
}
}
}
and the properties of result1 and result2 came as null or default values. Class definitions are below. I want to read the content as an object but I couldn't. What do you advice to solve this? What am I doing wrong? Thanks in advance.
public class MySummary
{
public int #Order { get; set; }
public string Id { get; set; }
public string Name { get; set; }
.
.
}
public class MyList
{
public int #Size { get; set; }
public int #ActivePropertyCount { get; set; }
public MySummary MySummary{ get; set; }
}
public class MyListResponse
{
public string CustomerSessionId { get; set; }
public int NumberOfRecordsRequested { get; set; }
public bool MoreResultsAvailable { get; set; }
public MyList MyList { get; set; }
}
I defined a new class as:
public class ResponseWrapper
{
public MyListResponse MyListResponse { get; set; }
}
then I used this wrapper with,
var result1 = JsonConvert.DeserializeObject<ResponseWrapper>(message);
var result2 = response.Content.ReadAsAsync<ResponseWrapper>().Result;
then it worked. I need only MySummary object but I should write more classes to make it work.
After reading your solution I came up with one that doesn't need an extra class:
private static async Task<U> Execute<U>(HttpClient client, string path)
{
U output = default(U);
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
var jsonAsString = await response.Content.ReadAsStringAsync();
output = JsonConvert.DeserializeObject<U>(jsonAsString);
}
else
{
throw new ApplicationException(string.Format("Response message is not OK. Issues in action: {0}", path));
}
return output;
}
For the sake of future readers, I think the correct approach is using ReadAsAsync overload that takes IEnumerable<MediaTypeFormatter> and provide a formatter with the same settings used on the server for serialization. That should fix it.
It is possible to use at client ReadAsAsync with MyListResponse directly (in consequence without ResponseWrapper). To do this, you can define "BodyStyle = WebMessageBodyStyle.Bare" in the operation contract of "apiuri" in stead of "BodyStyle = WebMessageBodyStyle.Wrapped" (server side, i.e. service contract).

MVC4 model custom function

Sorry for newbie questions, i'm brand new to MVC and OOP
I have the following model for my USER db table
namespace MyApp.Models
{
public class User
{
public int user_id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string salt { get; set; }
public string email { get; set; }
public sbyte status { get; set; }
public System.DateTime creation_date { get; set; }
public sbyte type { get; set; }
public virtual Doctor Doctor { get; set; }
public virtual Owner Owner { get; set; }
public virtual UserToken UserToken { get; set; }
public virtual Veterinarian Veterinarian { get; set; }
}
}
Actually in order to recall a particular USER based on the mail or the id i use a specific class called CustomDbFunctions
namespace MyApp.Models.DAL
{
public static class CustomDbFunctions
{
public static User GetUserEntityFromEmail(string email, DbContext db)
{
return db.Users.FirstOrDefault(u => u.email == (string)email);
}
}
}
in that way i use in my code
User user = CustomDbFunctions.GetUserEntityFromEmail(email, db)
and this it 100% OK with me, but i don't know if this kind of approach is correct or not, or if there's a better way like
//select the single user by calling only the class USER
User mySelectedUser = new User(email)
Thank you very much.
Well for understanding how to access your data in your MVC4 application you could read this tutorial from the Asp.Net MVC main page. Read the whole tutorial about MVC4 and you'll get a solid idea on how to work with it.
But I also recommend this tutorial on a good Entityframework design pattern, it's called Repository Pattern, I just a nice way to get all your code ordered (like all other patterns). Let me know.

WCF with Entity Framework Code First relationship

I'm learning WCF, and tried to make a small service that exposes a Project and its tasks (the standard Entity Framework hello world).
The class structure is the following:
public class Project
{
public int ProjectId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime CreationDate { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}
public class Task
{
public int TaskId { get; set; }
public string Title { get; set; }
public virtual Project RelatedProject { get; set; }
}
The DB context comes after:
public class ProjectContext : DbContext
{
public DbSet<Project> Projects { get; set; }
public DbSet<Task> Tasks { get; set; }
}
Finally, the service endpoint:
public IEnumerable<Project> getProjects()
{
ProjectContext p = new ProjectContext();
return p.Projects.AsEnumerable();
}
The problem is that this model will throw a System.ServiceModel.CommunicationException, but, If I remove the virtual properties from the model, It would work, but I would loose the entity framework links between Project and Task.
Anyone with a similar setup?
I banged my head against the wall several hours with this one. After extensive debugging, google gave the answer and I feel right to post it here since this was the first result I got in google.
Add this class on top of your [ServiceContract] interface declaration (typically IProjectService.cs
public class ApplyDataContractResolverAttribute : Attribute, IOperationBehavior
{
public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
{
}
public void ApplyClientBehavior(OperationDescription description, System.ServiceModel.Dispatcher.ClientOperation proxy)
{
var dataContractSerializerOperationBehavior =
description.Behaviors.Find<DataContractSerializerOperationBehavior>();
dataContractSerializerOperationBehavior.DataContractResolver =
new ProxyDataContractResolver();
}
public void ApplyDispatchBehavior(OperationDescription description, System.ServiceModel.Dispatcher.DispatchOperation dispatch)
{
var dataContractSerializerOperationBehavior =
description.Behaviors.Find<DataContractSerializerOperationBehavior>();
dataContractSerializerOperationBehavior.DataContractResolver =
new ProxyDataContractResolver();
}
public void Validate(OperationDescription description)
{
// Do validation.
}
}
Requirements are
using System.ServiceModel.Description;
using System.Data.Objects;
using System.ServiceModel.Channels;
Then under the [OperationContract] keyword add [ApplyDataContractResolver] keyword and you are set!
Big thanks to http://blog.rsuter.com/?p=286
For sending data trough WCF you should disable lazy loading (dataContext.ContextOptions.LazyLoadingEnabled = false;).
To be sure the data you want is loaded you need to use eager loading ( trough the Include method).
You need to change your function to:
public IEnumerable<Project> getProjects()
{
ProjectContext p = new ProjectContext();
p.ContextOptions.LazyLoadingEnabled = false;
return p.Projects.Include("Tasks").AsEnumerable();
}

WkHtmlToXSharp How to add Headers and Footers?

I'm building an HTML to PDF converter with the WkHtmlToXSharp (QT webkit) library, and was wondering if someone knows how to add headers and footers to the document? I've seen a few questions about this library here, but couldn't find anything about the headers and footers.
In the wkhtmltopdf manual (http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html) there are documentation about headers and footers, but I couldn't find anything in the .NET wrapper library (WkHtmlToXSharp), it is probably not implemented?
Thanks for any help or suggestions!
Here are some snippets of how I do it:
public class HeaderFooterSettings
{
public string HtmlUrl { get; set; }
public string Right { get; set; }
public string Spacing { get; set; }
}
public class PdfObjectSettings
{
private WebSettings _webSettings = new WebSettings();
private LoadSettings _loadSettings = new LoadSettings();
private HeaderFooterSettings _headerSettings = new HeaderFooterSettings();
private HeaderFooterSettings _footerSettings = new HeaderFooterSettings();
public string Page { get; set; }
public string Cover { get; set; }
public bool ProduceForms { get; set; }
public bool PagesCount { get; set; }
public HeaderFooterSettings Header { get { return _headerSettings; } }
public HeaderFooterSettings Footer { get { return _footerSettings; } }
public WebSettings Web { get { return _webSettings; } }
public LoadSettings Load { get { return _loadSettings; } }
// TODO: Add remaining settings..
//see the following page for settings format http://www.cs.au.dk/~jakobt/libwkhtmltox_0.10.0_doc/pagesettings.html
}
Here is the main logic of setting the header and footer URL:
var objectSettings = new PdfObjectSettings();
objectSettings.Header.HtmlUrl = headerHtmlUrl;
objectSettings.Header.Spacing = ConfigurationManager.AppSettings["ContentSpacing"];
objectSettings.Footer.HtmlUrl = footerHtmlUrl;
I hope this helps.
Rafi

WCF Service Library

I am new to WCF services. I was asked to manually create a WCF service. I did the following:
Created a new project Console App.
Created a class called Evaluation
Created an interface called IEvaluatorService
Created a class EvaluationService implementing the interface IEvaluatorService
I need to use the following address: http://localhost:8000/Evaluations then test my service via WcfTestClient. I am not sure what to do next. Code below.
Thanks in advance for any help!
namespace Evaluations
{
[ServiceContract]
interface IEvaluatorService
{
[OperationContract(Name="AddEvaluation")]
int Add(string user, string content);
[OperationContract(Name="RemoveEvaluation")]
void Remove([MessageParameter(Name="existingID")] int id);
[OperationContract(Name="GetAllEvaluations")]
Evaluation[] GetAll();
[OperationContract(Name="GetEvaluation")]
Evaluation Get(int id);
[OperationContract(Name="GetAllEvaluationsFrom")]
Evaluation[] GetAll([MessageParameter(Name = "username")] string submitter);
}
}
namespace Evaluations
{
class EvaluationService : IEvaluatorService
{
List<Evaluation> myList = new List<Evaluation>();
static int count = 0;
public int Add(string user, string content)
{
Evaluation eval = new Evaluation()
{
UniqueID = count++,
Submitter = user,
SubmissionTime = DateTime.Now,
Text = content
};
myList.Add(eval);
return eval.UniqueID;
}
public void Remove(int id)
{
myList.RemoveAt(id);
}
public Evaluation[] GetAll()
{
return myList.ToArray<Evaluation>();
}
public Evaluation Get(int id)
{
throw new NotImplementedException();
}
public Evaluation[] GetAll(string submitter)
{
throw new NotImplementedException();
}
}
}
namespace Evaluations
{
[DataContract]
class Evaluation
{
[DataMember]
public string Submitter { get; set; }
[DataMember]
public int UniqueID { get; set; }
[DataMember]
public DateTime SubmissionTime { get; set; }
[DataMember]
public string Text { get; set; }
}
}
The easiest thing to do is...
go into Visual Studio
right click on your project
select Add New
choose WCF Service
See what code Visual Studio added and follow that pattern for your service.