storing JSON data in db - c#

I'm trying to store data from fb wall into database.
My *.cs code
public ActionResult GetWall()
{
JSONObject wallData = helper.Get("/me/feed");
if (wallData != null)
{
var data = wallData.Dictionary["data"];
List<JSONObject> wallPosts = data.Array.ToList<JSONObject>();
ViewData["Wall"] = wallPosts;
}
return View("Index");
}
Which gets posts from fb wall.
And then I have an *.aspx file, which "breaks" my wallposts into pieces (objects) or whatever you like to call them.
foreach (Facebook.JSONObject wallItem in wallPosts)
{
string wallItemType = wallItem.Dictionary["type"].String;
//AND SO ON...
What i'm trying to say is that I can access to elements inside fb JSON.
Is there a way i can access to the JSON elements inside *.cs file.
Or is there a way I can store elements inside the *.aspx file to db?
And if its possible, I would like to know how. =)
Thanks for help

Don't use the SDK. Fetch the JSON Data using HttpWebRequest and then Deserialize it using System.Runtime.Serialization.Json.DataContractJsonSerializer. You just have to Create a class with same properties returned in JSON data. See the example below
string Response = Utilities.HttpUtility.Fetch("https://graph.facebook.com/me?access_token=" + AccessToken, "GET", string.Empty);
using (System.IO.MemoryStream oStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(Response)))
{
oStream.Position = 0;
return (Models.FacebookUser)new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Models.FacebookUser)).ReadObject(oStream);
}

I'm not familiar with the facebook API and the question isn't too clear, but I assume that the string wallItemType is itself a JSON string, and you wish to parse it.
I'd use the Json.Net library to parse this.
using Newtonsoft.Json;
//your code as above
foreach (Facebook.JSONObject wallItem in wallPosts)
{
string wallItemType = wallItem.Dictionary["type"].String;
//I assume wallItemType is a JSON string {"name":"foobar"} or similar
JObject o = JObject.Parse(wallItemType);
string name = (string)o["name"]; //returns 'foobar'
//and so on
you can also use the Json.Net to deserialize to a custom type. This custom type could be mapped to a SQL database using NHibernate.
If you wish to store the entire json string in a database, then you could use a document database such as CouchDB.

Related

how to store stringify json data into mongodb using C# MongoDB.Driver

i am fetching data in strigify json format
"[{\"ApplytoAllYesNo\":\"\",\"PartNumber\":\"\",\"Description\":\"\",\"LotNumber\":\"\",\"Revision\":\"\",\"Comment\":\"\",\"QualStatus\":\"\",\"Upload\":\"\",\"buildID\":\"62161d4fee3776fba3d8b83e\"},{\"ApplytoAllYesNo\":\"\",\"PartNumber\":\"\",\"Description\":\"\",\"LotNumber\":\"\",\"Revision\":\"\",\"Comment\":\"\",\"QualStatus\":\"\",\"Upload\":\"\",\"buildID\":\"62161d4fee3776fba3d8b83e\"},{\"ApplytoAllYesNo\":\"\",\"PartNumber\":\"\",\"Description\":\"\",\"LotNumber\":\"\",\"Revision\":\"\",\"Comment\":\"\",\"QualStatus\":\"\",\"Upload\":\"\",\"buildID\":\"62161d4fee3776fba3d8b83e\"},{\"ApplytoAllYesNo\":\"\",\"PartNumber\":\"\",\"Description\":\"\",\"LotNumber\":\"\",\"Revision\":\"\",\"Comment\":\"\",\"QualStatus\":\"\",\"Upload\":\"\",\"buildID\":\"62161d4fee3776fba3d8b83e\"},{\"ApplytoAllYesNo\":\"\",\"PartNumber\":\"\",\"Description\":\"\",\"LotNumber\":\"\",\"Revision\":\"\",\"Comment\":\"\",\"QualStatus\":\"\",\"Upload\":\"\",\"buildID\":\"62161d4fee3776fba3d8b83e\"}]"
every time this data will change, that's why I am unable to use fixed model hear as my object won't have fixed number of columns, and number columns will change in each request, these columns created in front end.
I just want to insert json strigify data into mongoDB whatever it comes in that object.
[HttpPost("saveBuildData")]
public async void saveBuildData(BuildSchema data)
{
await _buildsService.insertBuildConfigData(data.buildData);
}
public async Task insertBuildConfigData(dynamic obj)
{
var connectionString = _configuration["DatabaseSettings:ConnectionString"];
var client = new MongoClient(connectionString);
var database = client.GetDatabase("cascade");
var collection = database.GetCollection<BsonDocument>("buildconfig_MATERIAL");
var q = BsonSerializer.Deserialize<BsonDocument>(obj);
await collection.InsertOneAsync(q);
}
above code is not working and I am unable to insert the data into mongoDB.
enter image description here
This might help someone looking for a solution to this problem. It worked for me when I changed
collection.InsertOne(q)
instead of
await collection.InsertOneAsync(q);
I am not claiming this is the best solution but it worked in my case, where I am only interested in uploading a json file to Mongodb collection using c#.

Adding object to JSON file

I'm creating a software on which I added a profiles feature where the user can create profile to load his informations faster. To store these informations, I'm using a JSON file, which contains as much objects as there are profiles.
Here is the format of the JSON file when a profile is contained (not the actual one, an example) :
{
"Profile-name": {
"form_email": "example#example.com",
//Many other informations...
}
}
Here is the code I'm using to write the JSON and its content :
string json = File.ReadAllText("profiles.json");
dynamic profiles = JsonConvert.DeserializeObject(json);
if (profiles == null)
{
File.WriteAllText(jsonFilePath, "{}");
json = File.ReadAllText(jsonFilePath);
profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);
}
profiles.Add(profile_name.Text, new Profile_Name { form_email = form_email.Text });
var newJson = JsonConvert.SerializeObject(profiles, Formatting.Indented);
File.WriteAllText(jsonFilePath, newJson);
profile_tr.Nodes.Add(profile_name.Text, profile_name.Text);
debug_tb.Text += newJson;
But when the profiles.json file is completely empty, the profile is successfully written, but when I'm trying to ADD a profile when another one already exists, I get this error :
The best overloaded method match for 'Newtonsoft.Json.Linq.JObject.Add(string, Newtonsoft.Json.Linq.JToken)' has some invalid arguments on the profiles.Add(); line.
By the way, you can notice that I need to add {} by a non-trivial way in the file if it's empty, maybe it has something to do with the error ?
The expected output would be this JSON file :
{
"Profile-name": {
"form_email": "example#example.com",
//Many other informations...
},
"Second-profile": {
"form_email": "anotherexample#example.com"
//Some other informations...
}
}
Okay so I found by reading my code again, so I just replaced dynamic profiles = JsonConvert.DeserializeObject(json); to dynamic profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);.
But it still don't fix the non-trivial way I use to add the {} to my file...
The object the first DeserializeObject method returns is actually a JObject, but below you deserialize it as a Dictionary. You shouldn't be mixing the types, choose either one.
If you use the JObject then to add objects you need to convert them to JObjects:
profiles.Add(profile_name.Text, JObject.FromObject(new Profile_Name { form_email = form_email.Text }));
In both cases, when the profile is null you just need to initialize it:
if (profiles == null)
{
profiles = new JObject(); // or new Dictionary<string, Profile_Name>();
}

How to make a model to carry only a boolean value without database?

I have a settings page and one of them is called "Enable News" And it have to return a boolean value
What i want to do is to carry the value of this field and call it again in another pages like
if (model.Boolean == true)
{
//Code
}
WITHOUT using database because this option is made for only 1 User
The purpose is to save this data in the model without database and be able to edit it later
Storing configurations can be done using XML, JSON and other formats according to the project requirements and what you're comfortable using.
JSON format is fairly simple if you have an object like
class UserSettings {
public bool EnableNews {get; set}
...
}
Then you can simple use Json.NET to store and retrieve an object of this class as follows:
var settings = new UserSettings();
settings.EnableNews = True;
....
string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
//store it to file settings.json for example
//when you want to edit it you can load the file to string
string json_string = File.ReadAllText("file_path");
//then convert json string to model back to edit and read it
UserSettings userSettings = JsonConvert.DeserializeObject<UserSettings>(json_string);
for more details read Newtonsoft Json Package samples

Using Json to Create FormDialog

I am trying to build user and conversation specific dialogs using json schema and I have the LINQ queries generating the json perfectly. If I save a sample of the json to disk and use it like the annotatedsandwich example where it is read from a file on disk, it works great. The json is unique per user and conversation and instead of writing to disk I want to use it in memory. I do not see how to pass the json string to the BuildJsonForm method or alternately how to get the userID information in the BuildJsonForm method in order to generate the json based on the user and conversation. I know I am missing something that will let me do this but I am not finding it. Any assistance with how this should be done would be appreciated. Thank you.
Instead of doing (using the AnnotatedSandwich code)
FormDialog.FromForm(SandwichOrder.BuildJsonForm)
You could just build the BuildFormDelegate and pass your parameters:
string schema = "your jsonform schema";
BuildFormDelegate<JObject> formDelegate = () => SandwichOrder.BuildJsonForm(schema);
FormDialog.FromForm(formDelegate)
Create a custom form builder to which you pass your custom form json schema
[Serializable]
public class CustomFormBuilder
{
public string FormJson { get; set; }
public CustomFormBuilder(string formJson)
{
FormJson = formJson;
}
public IForm<JObject> BuildJsonForm()
{
var schema = JObject.Parse(FormJson);
var form = new FormBuilderJson(schema)
.AddRemainingFields()
.Build();
return form;
}
}
Use as follows (where formJson is your user specific form)
var formBuilder = new CustomFormBuilder(formJson);
var jsonFormDialog = FormDialog.FromForm(
formBuilder.BuildJsonForm,
FormOptions.PromptInStart);
This will avoid the ClosureCaptureExcept‌​ion.

Silverlight access an ashx JSON response

I have a Silverlight application that is calling out to an ashx that is hosted in the same application as the Silverlight control.
The ashx does the following (stripped down):
// Basic object
class SomeObject
{
int ID { get; set; }
string Description { get; set; }
double Value { get; set; }
}
// ASHX details
DataLayer dl = GetDataLayer();
List<SomeObject> lst = dl.ListObjects();
string result = "";
if (lst != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
result = serializer.Serialize(lst);
}
context.Response.ContentType = "application/json";
context.Response.Write(result);
context.Response.End();
Now the part I am having trouble with is what to do with the ashx on my Silverlight control.
I am looking to call the ashx and then map the JSON result into my internal silverlight objects. Seems like a pretty simple task but I am not sure how to access the ashx or deal with the response from it. Since Silverlight has a stripped down version of .NET it is throwing me for off.
Any help / suggestions?
Using Silverlight 3, ASP.NET 3.5.
Use System.Json to load the string into a JsonArray. JsonValue.Load() takes a response stream and can populate a JsonArray - from there, you can either iterate through or use LINQ to query the values.
Links:
Working with JSON Data on MSDN
JsonValue.Load on MSDN
Blog post with some sample code
Thanks for the reply Jon. Your links helped me figure it out and I thought I should include the code I used in this question for others that come across this question in the future.
Two ways of handling the Json. For both methods you need to setup a handler to get the Json data.
// This gets the URL to call to get the Json data
Uri uri = GetSomeUrl();
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
downloader.OpenReadAsync(uri);
You then need to implement the event handler downloader_OpenReadCompleted specified above with the code to handle the Json. In both case the code below should be wrapped in a using statement:
using (System.IO.Stream strResult = e.Result)
{
}
First way to handle the Json data that is part of the Silverlight framework is to add a reference to System.Json.
JsonArray jsonArray = (JsonArray)JsonArray.Load(e.Result);
List<SomeObject> lst = new List<SomeObject>();
foreach (System.Json.JsonObject obj in jsonArray)
{
SomeObject obj = new SomeObject();
obj.ID = int.Parse(obj["ID"].ToString();
obj.Description = obj["Description"].ToString();
obj.Value = double.Parse(obj["Value"].ToString());
lst.Add(obj);
}
The other way that is possible with or without Silverlight is:
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<SomeObject>));
List<SomeObject> lst = (List<SomeObject>)(serializer.ReadObject(strResult));
Both methods end up getting me a list of my objects which I can then use as I see fit.
Thanks for the help Jon!

Categories

Resources