I using Realm database at my Xamarin project
I have realm object with this model
public class UserModel: RealmObject
{
public string Id { get; set;}
public string Email { get; set; }
public string Password { get; set; }
public byte[] UserAvatar { get; set; }
public string ApiKey { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Birthday { get; set; }
public int Country_id { get; set; }
public bool IsAuthorized { get; set; }
public string Base64Avatar { get; set; }
public string Telephone { get; set; }
}
I need to update Name property.
How I try to do this
var realm = Realm.GetInstance();
var user_check = realm.All<UserModel>().First();
user_check.Name = "Test"
and get this error
How I can fix this?
Adding/Updating/Deleting to Realm object must be done inside a transaction, easiest way is to wrap it in Write method.
realm.Write(() =>
{
user_check.Name = "Test";
});
For more info, check the Rleam Write docs
Related
I am trying to figure out how to use the Refit library to make GET requests but I do not know why it is not working. I am following the example on the refit github page. What am I missing? It seems like the GetUser("octocat") method is not working. I've tried searching for other examples on how to use refit but wasn't able to find anything.
private static async void getUser()
{
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");
}
public class User
{
[JsonProperty("login")]
public string Login { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("avatar_url")]
public string AvatarUrl { get; set; }
[JsonProperty("gravatar_id")]
public string GravatarId { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("html_url")]
public string HtmlUrl { get; set; }
[JsonProperty("followers_url")]
public string FollowersUrl { get; set; }
[JsonProperty("following_url")]
public string FollowingUrl { get; set; }
[JsonProperty("gists_url")]
public string GistsUrl { get; set; }
[JsonProperty("starred_url")]
public string StarredUrl { get; set; }
[JsonProperty("subscriptions_url")]
public string SubscriptionsUrl { get; set; }
[JsonProperty("organizations_url")]
public string OrganizationsUrl { get; set; }
[JsonProperty("repos_url")]
public string ReposUrl { get; set; }
[JsonProperty("events_url")]
public string EventsUrl { get; set; }
[JsonProperty("received_events_url")]
public string ReceivedEventsUrl { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("site_admin")]
public bool SiteAdmin { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("company")]
public string Company { get; set; }
[JsonProperty("blog")]
public string Blog { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("email")]
public object Email { get; set; }
[JsonProperty("hireable")]
public object Hireable { get; set; }
[JsonProperty("bio")]
public object Bio { get; set; }
[JsonProperty("public_repos")]
public long PublicRepos { get; set; }
[JsonProperty("public_gists")]
public long PublicGists { get; set; }
[JsonProperty("followers")]
public long Followers { get; set; }
[JsonProperty("following")]
public long Following { get; set; }
[JsonProperty("created_at")]
public System.DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")]
public System.DateTimeOffset UpdatedAt { get; set; }
}
interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
If you want to query GitHub API you need to set a User-Agent
There's 2 way to do this with Refit:
1 - Set the headers on your contract
[Headers("User-Agent: My Favorite User Agent!")]
public interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
2 - Use a HttpClient and set it there
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", "My Favorite User Agent!");
httpClient.BaseAddress = new Uri("https://api.github.com");
var gitHubApi = RestService.For<IGitHubApi>(httpClient);
var user = await gitHubApi.GetUser("octocat");
If you are using the Github API than You need to set the UserAgent in the Header,
just as follows,
{
BaseAddress = new Uri("https://api.github.com"),
DefaultRequestHeaders = {UserAgent = { ProductInfoHeaderValue.Parse("NakWarsi")}} //here I have put my username("NakWarsi") what you need to replace with your username
};
_restApiService = RestService.For<IGitHubApi>(_client);
Here I have created a sample project using Github take a look for detailed information
I am using a C# LdapConnection to get a SearchResponse at work. I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse. The Json string is properly formatted. Am I using the Newtonsoft.Json library in the wrong way? Is there a better way to do this? My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.
My Console Application:
class Program
{
static void Main(string[] args)
{
LdapClient client = new LdapClient();
List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
string query = "(|(uupid=name1)(uupid=name2))";
string[] attributes = new string[] { };
string host = "id.directory.univ";
int port = 1234;
SearchResponse response = client.RawQuery(query, attributes, host, port);
string json = JsonConvert.SerializeObject(response);
var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
}
}
My DirectoryEntity Class:
public class DirectoryEntity
{
public string EntityDN { get; set; }
public int MailStop { get; set; }
public List<string> UniversityAffiliation { get; set; }
public int UniversityId { get; set; }
public string GivenName { get; set; }
public string Title { get; set; }
public string PasswordState { get; set; }
public string MiddleName { get; set; }
public string AccountState { get; set; }
public int Uid { get; set; }
public string Mail { get; set; }
public string MailPreferredAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string> GroupMembership { get; set; }
public string DegreeType { get; set; }
public int ClassLevelCode { get; set; }
public string AuthId { get; set; }
public string Major { get; set; }
public string ClassLevel { get; set; }
public bool SupressDisplay { get; set; }
public string UnderGraduateLevel { get; set; }
public string ObjectClass { get; set; }
public int DepartmentNumber { get; set; }
public List<string> EduPersonAffiliation { get; set; }
public string LocalPostalAddress { get; set; }
public string Uupid { get; set; }
public string LocalPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Department { get; set; }
public string Sn { get; set; }
}
My DirectoryEntities Class:
public class DirectoryEntities
{
public List<DirectoryEntity> Entities { get; set; }
public int Count { get; set; }
}
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:
public DirectoryEntity() { }
I'm programming a C# implementation for the Qualtrics API (v 2.5) using RestSharp. When calling the method getUserIds, it returns a list of users in JSON format (see the example output below).
The problem/question I face is that for each user object (the list of objects under Result) it generates a different id, starting with URH_. When using json2csharp it assumes ofcourse that it's always a different class, while in fact it's absolutely the same one as you can see in the output, and as is stated in the documentation of the api. How can I best resolve this - so that I can make a class UserData that I can reuse? Because now I obviously always see these random URH_ prefixed classes in each response.
NOTE: I was thinking I could try to massage the response first, and when I get the response replace each URH_ prefixed object under the root Result object with a "UserData" string - but I feel this is breaking the rules a bit, and thought the community would have a better solution?
Below is the raw JSON output (note that I removed sensitive information):
{"Meta":{"Status":"Success","Debug":""},"Result":{"URH_3wpA9pxGbE0c7Xu":{"DivisionID":null,"UserName":"user.name#domain.com","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_4SjjZmbPphZGKDq","UserEmail":"x.x#x.x","UserAccountStatus":"Active"},"URH_57vQr8MVXgpcPUo":{"DivisionID":"DV_XXXXXXXX","UserName":"jxxxx#xx.xxx","UserFirstName":"X","UserLastName":"X","UserAccountType":"UT_BRANDADMIN","UserEmail":"xxxx#xxg.xxx","UserAccountStatus":"Active"},"URH_6ujW1EP0QJOUaoI":{"DivisionID":"DV_XXXXXXXYZ","UserName":"x.xckx#xxx.xyz","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_XXXXXABCD","UserEmail":"c.c#cc.com","UserAccountStatus":"Active"}}}
This is what I get when generating a model using json2csharp:
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class URH3wpA9pxGbE0c7Xu
{
public object DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH57vQr8MVXgpcPUo
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH6ujW1EP0QJOUaoI
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class Result
{
public URH3wpA9pxGbE0c7Xu URH_3wpA9pxGbE0c7Xu { get; set; }
public URH57vQr8MVXgpcPUo URH_57vQr8MVXgpcPUo { get; set; }
public URH6ujW1EP0QJOUaoI URH_6ujW1EP0QJOUaoI { get; set; }
}
public class RootObject
{
public Meta Meta { get; set; }
public Result Result { get; set; }
}
It's simple - just use Dictionary<string, UserData> generic type for Result field:
public class Response
{
public Meta Meta { get; set; }
public Dictionary<string, UserData> Result { get; set; }
}
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class UserData
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
I am new to C#. I have successfully consumed the Mailchip API with a simple console app. I am pulling in relevant data and I have successfully used a JSON deserializer on the returned data (Newtonsoft.Json via NuGet). What I need to find is the best way to place the data into variables which I can then pass to a stored procedure to save the data. I know SQL and I know how to pass variables to a stored procedure in C# (connection strings and such).
What I don't know is how to parse through the deserialized data and then place each value into a variable or something I can pass to SQL. I know this is a vague question so here is the current code.
Class MailChimpAPIClient.cs:
//Declare the API Key
public const string APIKey = "My API Key Here";
public static void APIGet(string url)
{
//Syncronious Consumption
var syncClient = new WebClient();
syncClient.Headers.Add(APIKey);
var content = syncClient.DownloadString(url);
//Deseralize the Json String
MailChimpData data = JsonConvert.DeserializeObject<MailChimpData>(content);
}
Class: MailChimpData.cs:
[DataContract]
public class MailChimpData
{
[DataMember]
public List<Unsubscribes> unsubscribes { get; set; }
[DataMember]
public string campaign_id { get; set; }
[DataMember]
public List<Link2> _links { get; set; }
[DataMember]
public int total_items { get; set; }
[DataMember]
public Link link { get; set; }
[DataMember]
public MergeFields mergefields { get; set; }
[DataMember]
public Stats stats { get; set; }
[DataMember]
public Location location { get; set; }
[DataMember]
public List<Member> members { get; set; }
[DataMember]
public string list_id { get; set; }
}
//Unsubscribe Data
public class Link
{
public string rel { get; set; }
public string href { get; set; }
public string method { get; set; }
public string targetSchema { get; set; }
public string schema { get; set; }
}
public class Unsubscribes
{
public string email_id { get; set; }
public string email_address { get; set; }
public string timestamp { get; set; }
public string reason { get; set; }
public string campaign_id { get; set; }
public string list_id { get; set; }
public List<Link> _links { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
public string method { get; set; }
public string targetSchema { get; set; }
public string schema { get; set; }
}
//List Data
public class MergeFields
{
public string FNAME { get; set; }
public string LNAME { get; set; }
}
public class Stats
{
public double avg_open_rate { get; set; }
public int avg_click_rate { get; set; }
}
public class Location
{
public double latitude { get; set; }
public double longitude { get; set; }
public int gmtoff { get; set; }
public int dstoff { get; set; }
public string country_code { get; set; }
public string timezone { get; set; }
}
public class Member
{
public string id { get; set; }
public string email_address { get; set; }
public string unique_email_id { get; set; }
public string email_type { get; set; }
public string status { get; set; }
public MergeFields merge_fields { get; set; }
public Stats stats { get; set; }
public string ip_signup { get; set; }
public string timestamp_signup { get; set; }
public string ip_opt { get; set; }
public string timestamp_opt { get; set; }
public int member_rating { get; set; }
public string last_changed { get; set; }
public string language { get; set; }
public bool vip { get; set; }
public string email_client { get; set; }
public Location location { get; set; }
public string list_id { get; set; }
public List<Link> _links { get; set; }
}
Program.cs:
class Program
{
static void Main(string[] args)
{
MailChimpApiClient.APIGet("Custom URL Here");
}
}
So when I run this and look in the Autos window of VS2013 I see this:
members: Count = 4 System.Collections.Generic.List
[0] {MailChimpAPI.Member} MailChimpAPI.Member
_links: Count = 8 System.Collections.Generic.List
email_address: email address here string
email_client: string
email_type: html string
id: (ID Here) string
ip_opt: (IP Here) string
ip_signup: string
language: string
last_changed: 9/16/15 19:31 string
list_id: (List ID Here) string
location: {MailChimpAPI.Location} MailChimpAPI.Location
member_rating: 3 int
merge_fields {MailChimpAPI.MergeFields} MailChimpAPI.MergeFields
stats: {MailChimpAPI.Stats} MailChimpAPI.Stats
status: unsubscribed string
timestamp_opt: 9/16/15 19:26 string
timestamp_signup: string
unique_email_id: (Unique Email ID Here) string
vip: FALSE bool
[1] {MailChimpAPI.Member}: MailChimpAPI.Member
[2] {MailChimpAPI.Member}: MailChimpAPI.Member
[3] {MailChimpAPI.Member}: MailChimpAPI.Member
Raw View
So for each member (0-3), I need to pull each fields value (Field names in bold) into a variable and save it to a database. I just don't know how to parse through each member.
I know this is a long question for a simple C# problem, but if you can remember way back to the beginning of the post I stated "I am new to C#"
Thanks in advance.
While I am trying to call the
`var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})`
it keeps throwing me unable to deserialize exception.
To check if my json string was well formed i decided to
Parse the string and called
JsonSchema schema = JsonSchema.Parse({myjsonString});
now i get the error below, not quite sure what it means
Additional information: Expected object while parsing schema object,
got String. Path ''
**UPDATE**
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}"
UPDATE 2
"\"{\\\"Id\\\":5,\\\"Username\\\":\\\"Sid\\\",\\\"FirstName\\\":\\\"Siddharth \\\",\\\"LastName\\\":\\\"Kosta\\\",\\\"Email\\\":\\\"Skosta#gmail.com\\\",\\\"Password\\\":\\\"PAssword\\\",\\\"GravatarHash\\\":\\\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8c4bcd5adc1?d=retro&?s=50\\\",\\\"Country\\\":\\\"India\\\",\\\"OrganizationId\\\":1,\\\"IsLocked\\\":false,\\\"CreatedDate\\\":\\\"2013-12-13T02:34:28.037\\\",\\\"UpdatedDate\\\":\\\"2013-12-13T02:34:28.23\\\",\\\"DataLoaded\\\":true}\""
The User Model
public class UserModel
{
public Int32 Id { get; set; }
public String Username { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public String GravatarHash { get; set; }
public String Country { get; set; }
public Int32 OrganizationId { get; set; }
public Boolean IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
}
I also tried
public String CreatedDate { get; set; }
public String UpdatedDate { get; set; }
thinking if the dates were causing a problem
Update:
It works perfectly fine with your UserModel, at least for me.
Assume you have such UserModel:
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
var input =
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}";
var userModel = JsonConvert.DeserializeObject<UserModel>(input);
I think the problem with your model, can you please provided it?
It looks to me like your JSON is getting double serialized. (Having a bunch of extra backslashes in your JSON is a symptom of this.) I notice in the comments on another answer that you said you are using Web API. The Web API framework takes care of serialization for you, so you do not need to call JsonConvert.SerializeObject() in those methods. Instead just return your result directly. Then you should be able to deserialize it normally in your client. See this question.
Is there a reason why you have the curly braces in
var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})
That seems like the source of the error. Change it to:
var obj = JsonConvert.DeserializeObject<UserModel>(myjsonString)
You're missing the DataLoaded property.
public bool DataLoaded { get; set; }
In future, use this website to generate your C# classes from JSON.
http://json2csharp.com/
EDIT:
Try this step by step...
Copy and paste this class exactly as is.
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public string CreatedDate { get; set; }
public string UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
Now in the console have this:
var jsonString = #"{""Id"":5,""Username"":""Sid"",""FirstName"":""Sid "",""LastName"":""LastSid"",""Email"":""test#gmail.com"",""Password"":""sample"",""GravatarHash"":""http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50"",""Country"":""Moon"",""OrganizationId"":1,""IsLocked"":false,""CreatedDate"":""12/13/2013 2:34:28 AM"",""UpdatedDate"":""12/13/2013 2:34:28 AM"",""DataLoaded"":true}";
var user = JsonConvert.DeserializeObject<UserModel>(jsonString);
Console.WriteLine(user.Country);
Console.ReadLine();