JSON String to DataTable Object in C# - c#

So basically I SEARCHED everywhere, and I'm not finding anything that works in my situation.
I'm working with an API for Overwatch (a game) and I want to turn a String I download from the web, and check if it has a JSON string.
Let me show you the code:
< !--language: c# -->
HttpClient dc = new HttpClient();
string tag = e.Message.Text.ToString().Substring(7).Replace("#", "-");
string apiurl = (#"http://api.lootbox.eu/" + "pc/" + "global/" + tag + "/profile");
HttpResponseMessage datares = await dc.GetAsync(apiurl);
string finaldata = await datares.Content.ReadAsStringAsync();
#region PC
if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
#region XBOX LIVE
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "global/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
#region PSN
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "global/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
DataTable obj = JsonConvert.DeserializeObject(finaldata);
So an example output, in this case, wouldv'e been:
{"data":{"username":"Rezoh","level":305,"games":{"quick":{"wins":"378"},"competitive":{"wins":"82","lost":85,"played":"167"}},"playtime":{"quick":"88 hours","competitive":"36 hours"},"avatar":"https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000000D70.png","competitive":{"rank":"3392","rank_img":"https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-5.png"},"levelFrame":"https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Border.png","star":"https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Rank.png"}}
Now I need to convert that to a table of some sort or something.
I got the JSON.Net but most people said to setup a class BEFORE you convert,
Problem was that: I had 2 "wins": and 3 "competitive": as you can see in the JSON string.
So making a class wasn't possible to my belief in this case. I tried making a new DataTable as shown in the last line of code but it tells me "Cannot implicitly convert type object to System.Data.DataTable" when using JsonConvert.DeserializeObject(finaldata); I even tried doing .ToString(); and also the dates variable, and .ToString() in that too.
I need a proper way to show these stats so, for example, I can show:
"Stats for user " + obj.Name + ":"
"Wins: " + obj.Wins
"Losses: " + obj.Losses
"Rank: " + obj.Rank
And no solutions online help me in my situation.
EDIT:
This solution doesn't work either for me:
convert json String to datatable?
or this
Nested Json String to DataTable
Nor does this:
var token = JToken.Parse(finaldata);
if (token.Type == JTokenType.Object)
token = new JArray(token);
var a = token.ToObject<DataTable>();

You can use a class as they said. I used http://json2csharp.com/ but VS can do it too.
You can try it here: https://dotnetfiddle.net/iaIvOn
using System;
using Newtonsoft.Json;
public class Program
{
public void Main()
{
var json = #"{""data"":{""username"":""Rezoh"",""level"":305,""games"":{""quick"":{""wins"":""378""},""competitive"":{""wins"":""82"",""lost"":85,""played"":""167""}},""playtime"":{""quick"":""88 hours"",""competitive"":""36 hours""},""avatar"":""https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000000D70.png"",""competitive"":{""rank"":""3392"",""rank_img"":""https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-5.png""},""levelFrame"":""https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Border.png"",""star"":""https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Rank.png""}}";
// read the doc: http://www.newtonsoft.com/json
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine("Stats for user " + rootObject.Data.Username + ":");
Console.WriteLine("Wins: " + rootObject.Data.Games.Competitive.Wins);
Console.WriteLine("Losses: " + rootObject.Data.Games.Competitive.Lost);
Console.WriteLine("Rank: " + rootObject.Data.Competitive.Rank);
}
public class Quick
{
// Free case support!
public string Wins { get; set; }
}
public class Competitive
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Games
{
public Quick Quick { get; set; }
public Competitive Competitive { get; set; }
}
public class Playtime
{
public string Quick { get; set; }
public string Competitive { get; set; }
}
public class Competitive2
{
public string Rank { get; set; }
// attribute ftw! http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm
[JsonProperty(PropertyName = "rank_img")]
public string RankImg { get; set; }
}
public class Data
{
public string Username { get; set; }
public int Level { get; set; }
public Games Games { get; set; }
public Playtime Playtime { get; set; }
public string Avatar { get; set; }
public Competitive2 Competitive { get; set; }
public string LevelFrame { get; set; }
public string Star { get; set; }
}
public class RootObject
{
public Data Data { get; set; }
}
}
output
Stats for user Rezoh:
Wins: 82
Losses: 85
Rank: 3392
If Quick and Competitive are Game, maybe:
public abstract class Game
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Quick : Game // note that Quick game has Lost and PLayed now!
{
}
public class Competitive : Game
{
}
Or even (as #EpicSam proposed in comment):
public class Game
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Games
{
public Game Quick { get; set; }
public Game Competitive { get; set; }
}

Related

Set DeserializeObject in anonymous property of a class

I have this:
public class ComponentData
{
public dynamic CdHtml { get; set; }
public dynamic CdJson { get; set; }
public dynamic CdSection { get; set; }
public dynamic CdContainer { get; set; }
public dynamic CdRow { get; set; }
public dynamic CdContainerId { get; set; }
public dynamic CdColsJson { get; set; }
}
And i want to set the ComponentData Class with these values but i get an error:
var componentData = new ComponentData()
{
CdHtml = obj.htmlCD,
CdJson = JsonConvert.DeserializeObject<dynamic>(obj.jsonCD),
CdContainerId = "SECTION" + obj.CD_Container_Id,
CdSection = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson("xxx" + obj.CD_Container_Id, "width:" + tlj.width.ToString() + "%;padding-left:30px;padding-right:30px;padding-top:30px;padding-bottom:30px;" + sectionCenterStyle, "section")),
CdContainer = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson("xxx" + obj.divGUID2, containerStyle, "container")),
CdRow = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson("xxx" + obj.divGUID3, "", "row")),
CdColsJson = JsonConvert.DeserializeObject<dynamic>(pc.Build_CDxxxJson(obj.divGUID4, "", string.Format("col-xs-{0} col-sm-{1} col-md-{2} col-lg-{3} hoversel colregion{4}", bsc.xs, bsc.sm, bsc.md, bsc.lg, obj.divGUID4), bsc.xs, bsc.sm, bsc.md, bsc.lg))
};
return Json(new { componentData = componentData, html = obj.html });
how would i return this class with the json objects inside and pass it back to the client using ajax?
Change your code to this:
var componentData = new ComponentData()
{
CdHtml = obj.htmlCD,
CdJson = JsonConvert.DeserializeObject<ExpandoObject>(obj.jsonCD),
CdContainerId = "SECTION" + obj.CD_Container_Id,
CdSection = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson("xxx" + obj.CD_Container_Id, "width:" + tlj.width.ToString() + "%;padding-left:30px;padding-right:30px;padding-top:30px;padding-bottom:30px;" + sectionCenterStyle, "section")),
CdContainer = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson("xxx" + obj.divGUID2, containerStyle, "container")),
CdRow = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson("xxx" + obj.divGUID3, "", "row")),
CdColsJson = JsonConvert.DeserializeObject<ExpandoObject>(pc.Build_CDxxxJson(obj.divGUID4, "", string.Format("col-xs-{0} col-sm-{1} col-md-{2} col-lg-{3} hoversel colregion{4}", bsc.xs, bsc.sm, bsc.md, bsc.lg, obj.divGUID4), bsc.xs, bsc.sm, bsc.md, bsc.lg))
};
If you want to convert to dynamic you need to use ExpandoObject just as you would use when you want to create one with your hands.

breaking out all of the elements in a XML file C#

From another question I had, a answer almost got me there but I have hit a snag.
I need all of the deliveries from a descendant and they are all running together.
Current code I have tried (but it is only getting the first delivery section).
The problem that is being caused with the way I have tried below is that it does not handle the sections that have multiple sections.
I have a semi-working solution that uses data-tables but this is a much cleaner looking solution and I would really like to learn how to get it working like this.
var document = XDocument.Parse(xmlText);
var doc = XDocument.Parse(xmlText);
XNamespace ns0 = doc.Root.GetNamespaceOfPrefix("ns0");
XElement sender = doc.Descendants(ns0 + "SenderNameAndAddress").FirstOrDefault();
string[] senderAddress = sender.Descendants(ns0 + "Address").Elements().Select(x => (string)x).ToArray();
XElement recipientDeliveries = doc.Descendants(ns0 + "RecipientDeliveries").FirstOrDefault();
var results = recipientDeliveries.Elements(ns0 + "Recipient").Select(x => new
{
recipientCode = ((string)x.Descendants(ns0 + "RecipientCode").FirstOrDefault()),
name = (string)x.Descendants(ns0 + "Name").FirstOrDefault(),
address = x.Descendants(ns0 + "Address").Elements().Select(y => (string)y).ToArray(),
deliveries = x.Descendants(ns0 + "Deliveries").Elements().Select(y => (string)y).ToArray(),
deliveryID = (string)x.Descendants(ns0 + "DeliveryID").FirstOrDefault(),
deliveryType = (string)x.Descendants(ns0 + "DeliveryType").FirstOrDefault(),
deliveryRoute = (string)x.Descendants(ns0 + "DeliveryRoute").FirstOrDefault(),
toteID = (string)x.Descendants(ns0 + "ToteID").FirstOrDefault(),
nursingStation = (string)x.Descendants(ns0 + "NursingStation").FirstOrDefault()
}).ToList();
This is the xml sample
<?xml version="1.0" encoding="UTF-8"?>
<ns0:AdvancedShippingNotices xmlns:ns0="http://www.omnicare.com/schema/AdvancedShippingNotices.xsd">
<ns0:ASNID>4129114</ns0:ASNID>
<ns0:CourierID>4SAMEDAY</ns0:CourierID>
<ns0:SenderCode>598</ns0:SenderCode>
<ns0:SenderNameAndAddress>
<ns0:Name>Omnicare of San Diego</ns0:Name>
<ns0:Address>
<ns0:Line1>5601 Oberlin Drive, Suite 124</ns0:Line1>
<ns0:CityTownOrLocality>San Diego</ns0:CityTownOrLocality>
<ns0:StateOrProvince>CA</ns0:StateOrProvince>
<ns0:PostalCode>92121-3709</ns0:PostalCode>
</ns0:Address>
</ns0:SenderNameAndAddress>
<ns0:RecipientDeliveries>
<ns0:Recipient>
<ns0:RecipientCode>1019</ns0:RecipientCode>
<ns0:RecipientNameAndAddress>
<ns0:Name>VILLAGE SQUARE HEALTHCARE CTR</ns0:Name>
<ns0:Address>
<ns0:Line1>1586 W SAN MARCOS BLVD</ns0:Line1>
<ns0:CityTownOrLocality>SAN MARCOS</ns0:CityTownOrLocality>
<ns0:StateOrProvince>CA</ns0:StateOrProvince>
<ns0:PostalCode>92069</ns0:PostalCode>
</ns0:Address>
</ns0:RecipientNameAndAddress>
<ns0:Deliveries>
<ns0:Delivery>
<ns0:DeliveryID>8930798-5</ns0:DeliveryID>
<ns0:DeliveryType>ROUTE</ns0:DeliveryType>
<ns0:DeliveryRoute>R0130</ns0:DeliveryRoute>
<ns0:ToteID>S5-278</ns0:ToteID>
<ns0:NursingStation>2</ns0:NursingStation>
</ns0:Delivery>
<ns0:Delivery>
<ns0:DeliveryID>8934056-1</ns0:DeliveryID>
<ns0:DeliveryType>ROUTE</ns0:DeliveryType>
<ns0:DeliveryRoute>IV</ns0:DeliveryRoute>
<ns0:ToteID>B-132</ns0:ToteID>
<ns0:NursingStation>1</ns0:NursingStation>
</ns0:Delivery>
<ns0:Delivery>
<ns0:DeliveryID>8933908-1</ns0:DeliveryID>
<ns0:DeliveryType>CYCLE</ns0:DeliveryType>
<ns0:DeliveryRoute>CYCLE</ns0:DeliveryRoute>
<ns0:ToteID>B-132</ns0:ToteID>
<ns0:NursingStation>1</ns0:NursingStation>
</ns0:Delivery>
</ns0:Deliveries>
</ns0:Recipient>
<ns0:Recipient>
<ns0:RecipientCode>20366</ns0:RecipientCode>
<ns0:RecipientNameAndAddress>
<ns0:Name>OAKMONT OF ESCONDIDO HILLS</ns0:Name>
<ns0:Address>
<ns0:Line1>3012 BEAR VALLEY PKWY</ns0:Line1>
<ns0:CityTownOrLocality>ESCONDIDO</ns0:CityTownOrLocality>
<ns0:StateOrProvince>CA</ns0:StateOrProvince>
<ns0:PostalCode>92025</ns0:PostalCode>
</ns0:Address>
</ns0:RecipientNameAndAddress>
<ns0:Deliveries>
<ns0:Delivery>
<ns0:DeliveryID>8930798-4</ns0:DeliveryID>
<ns0:DeliveryType>ROUTE</ns0:DeliveryType>
<ns0:DeliveryRoute>R0130</ns0:DeliveryRoute>
<ns0:ToteID>F1-101</ns0:ToteID>
<ns0:NursingStation>AL</ns0:NursingStation>
</ns0:Delivery>
</ns0:Deliveries>
</ns0:Recipient>
</ns0:RecipientDeliveries>
</ns0:AdvancedShippingNotices>
Not sure if you actually use class models or not. But I did a little adjustment for for what's worth (It's will give you more flexibility with the data).
classes :
public class Recipient
{
public int RecipientCode { get; set; }
public RecipientInfo RecipientNameAndAddress { get; set; }
public IList<RecipientDelivery> Deliveries { get; set; }
}
public class RecipientInfo
{
public string Name { get; set; }
public RecipientAddress Address { get; set; }
}
public class RecipientAddress
{
public string Line1 { get; set; }
public string CityTownOrLocality { get; set; }
public string StateOrProvince { get; set; }
public string PostalCode { get; set; }
}
public class RecipientDelivery
{
public string DeliveryID { get; set; }
public string DeliveryType { get; set; }
public string DeliveryRoute { get; set; }
public string ToteID { get; set; }
public string NursingStation { get; set; }
}
then the work :
var doc = XDocument.Parse(file);
XNamespace ns0 = doc.Root.GetNamespaceOfPrefix("ns0");
XElement recipientDeliveries = doc.Descendants(ns0 + "RecipientDeliveries").FirstOrDefault();
var recipients = recipientDeliveries.Descendants(ns0 + "Recipient").ToList();
var RecipientList = new List<Recipient>();
foreach (var item in recipients)
{
var deliveries = item.Descendants(ns0 + "Deliveries").FirstOrDefault();
var deliveriesNodes = deliveries.Descendants(ns0 + "Delivery").ToList();
var recipientInfo = item.Descendants(ns0 + "RecipientNameAndAddress").FirstOrDefault();
var recipientAddress = recipientInfo.Descendants(ns0 + "Address").FirstOrDefault();
var deliverList = new List<RecipientDelivery>();
foreach (var del in deliveriesNodes)
{
var delivery = new RecipientDelivery()
{
DeliveryID = del.Element(ns0 + "DeliveryID").Value,
DeliveryType = del.Element(ns0 + "DeliveryType").Value,
DeliveryRoute = del.Element(ns0 + "DeliveryRoute").Value,
ToteID = del.Element(ns0 + "ToteID").Value,
NursingStation = del.Element(ns0 + "NursingStation").Value
};
deliverList.Add(delivery);
}
var recipient = new Recipient()
{
RecipientCode = Convert.ToInt32(item.Element(ns0 + "RecipientCode").Value),
RecipientNameAndAddress = new RecipientInfo()
{
Name = recipientInfo.Element(ns0 + "Name").Value.ToString(),
Address = new RecipientAddress()
{
Line1 = recipientAddress.Element(ns0 + "Line1").Value.ToString(),
CityTownOrLocality = recipientAddress.Element(ns0 + "CityTownOrLocality").Value.ToString(),
StateOrProvince = recipientAddress.Element(ns0 + "StateOrProvince").Value.ToString(),
PostalCode = recipientAddress.Element(ns0 + "PostalCode").Value.ToString()
},
},
Deliveries = deliverList
};
RecipientList.Add(recipient);
}
Then the whole Recipients will be in RecipientList, which you can use.
A small modification from previous results :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns0 = doc.Root.GetNamespaceOfPrefix("ns0");
XElement sender = doc.Descendants(ns0 + "SenderNameAndAddress").FirstOrDefault();
string[] senderAddress = sender.Descendants(ns0 + "Address").Elements().Select(x => (string)x).ToArray();
XElement recipientDeliveries = doc.Descendants(ns0 + "RecipientDeliveries").FirstOrDefault();
var results = recipientDeliveries.Elements(ns0 + "Recipient").Select(x => new
{
name = (string)x.Descendants(ns0 + "Name").FirstOrDefault(),
address = x.Descendants(ns0 + "Address").Elements().Select(y => (string)y).ToArray(),
deliveries = x.Descendants(ns0 + "Delivery").Select(y => new {
deliveryID = (string)y.Descendants(ns0 + "DeliveryID").FirstOrDefault(),
deliveryType = (string)y.Descendants(ns0 + "DeliveryType").FirstOrDefault(),
deliveryRoute = (string)y.Descendants(ns0 + "DeliveryRoute").FirstOrDefault(),
toteID = (string)y.Descendants(ns0 + "ToteID").FirstOrDefault(),
nursingStation = (string)y.Descendants(ns0 + "NursingStation").FirstOrDefault()
}).ToList()
}).ToList();
}
}
}

Parsing JSON data in Windows app

Suppose this is my JSON data received through an API:
[
{
"id": "1",
"title": "Test_rom",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.1.png"
},
{
"id": "2",
"title": "Jewelry",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.2.png"
},
{
"id": "3",
"title": "Jackets",
"subtitle": "All sizes available",
"icon": "http://lpl.info/Admin/upload/cat.3.png"
}
]
I created a class called "RootObject":
public class RootObject {
public string id { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string icon { get; set; }
}
I only want to extract values of "title" keys from the array. How can I achieve that?
I tried the following code, but I am getting error in "Encoding" word:
var result = await response.Content.ReadAsStringAsync();
RootObject TotalList = new RootObject();
RootObject childlistonly = new RootObject();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(TotalList.GetType());
TotalList = ser.ReadObject(ms) as RootObject;
string category = "";
foreach(var d in TotalList.title) {
category = category + " " + d.ToString() + "\n";
}
ResultsText.Text = category;
I used the following, but it is giving an error:
var titlevariable = myobj.title;
Textblock.Text = titlevariable; // (under a click button method)...
Try this
foreach(var d in TotalList) {
category = category + " " + d.title.ToString() + "\n";
}
#kickaha..
private async void Butoon_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
var uri = new Uri("http://www.blabla.com/alliance/App/mobilelogin.php?KG=MA&EM="+Textboxname.Text+"&PA="+password.Password);
var response = await client.GetAsync(uri);
var result = await response.Content.ReadAsStringAsync();
RootObject TotalList = new RootObject();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
RootObject resu = (RootObject)ser.ReadObject(ms);
NavigationContext nav = new NavigationContext()
{
ID = resu.USERID.ToString(),
Name = resu.NAME.ToString(),
Email = resu.EMAIL.ToString()
}
SaveFile();
RestoreFile();
}
private async void SaveFile()
{
StorageFile userdetailsfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserDetails", CreationCollisionOption.ReplaceExisting);
IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);
using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
{
// Serialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(NavigationContext));
serializer.WriteObject(outStream.AsStreamForWrite(), nav);
await outStream.FlushAsync();
}
}
private async void RestoreFile()
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("UserDetails");
if (file == null) return;
IRandomAccessStream inStream = await file.OpenReadAsync();
// Deserialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(NavigationContext));
var StatsDetails = (NavigationContext)serializer.ReadObject(inStream.AsStreamForRead());
inStream.Dispose();
string hu = StatsDetails.Name + "\n" + StatsDetails.Email;
// UserName.Text = "Welcome " + StatsDetails.Name;
// UserProfileId = StatsDetails.Id;
resultblock.Text = hu;
}
}
public class RootObject
{
public string USERID { get; set; }
public string EMAIL { get; set; }
public string NAME { get; set; }
public string FIRST_NAME { get; set; }
public string LAST_NAME { get; set; }
public string CITY { get; set; }
}
public class NavigationContext
{
public string ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Email { get; set; }
}
}
i am getting null value in "instream" property of Restorefile() method...

How to use "like" feature in facebook c# sdk 5.4.1?

in facebook developers site it seems pretty easy.just make a HTTP POST to POST_ID/likes(i got the post i.d).
in c# sdk v.5.4.1 there is a POST method but i can't figure out how to use it and make the right call.
Look at the face book API documentation..here http://developers.facebook.com/
var fb = new FacebookClient("my token");
dynamic parameters = new ExpandoObject();
parameters.message = "the publish msg";
dynamic result = fb.Post("/me/feed", parameters);
var id = result.id;
var res = fb.Post("/" + id + "/likes");
I was having the same issue so I tried few things & this worked for me
var token = "[your access token]";
var fb = new Facebook.FacebookClient(token);
var postId = "173213306032925_745288855492031"; //replace this with your big id which comprises of [userid]_[postid]
Console.WriteLine(fb.Post(id+"/likes", null).ToString()); // should print 'True'
Console.WriteLine(fb.Get("173213306032925_745288855492031/likes").ToString()); //should give you details
public void FacebookLike(AppConnect appconnect )
{
try
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string fb_exchange = appconnect.UserToken;
string url =
string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&grant_type=fb_exchange_token&fb_exchange_token={3}&redirect_uri=https://www.facebook.com/connect/login_success.html&scope={1}&client_secret={2}",
appconnect.AppID, appconnect.ExtendedPermissions, appconnect.AppSecret, fb_exchange);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject(); parameters.idobject = "";
client.Post("/" + appconnect.AppID.ToString() + "_" + appconnect.PostID.ToString() + "/Likes", parameters);
// MessageBox.Show("....... Done ..........");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message +"\n"+ex.InnerException);
}
}
class AppConnect
{
//tring appId, string Appsecret, string userToken, string userID, string PostID
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string AppID { get; set; } = "991341734653453831";
public string AppSecret { get; set; } = "99dfbf29234ergec4a";
public string UserID { get; set; } = null;
public string UserToken { get; set; } = null;
public string PostID { get; set; } = null;
public string ExtendedPermissions { get; set; } = "user_posts, publish_actions, publish_pages,manage_pages,user_likes";
}

Prevent duplicate user from being added to database

I want to prevent the same user from being added to the database automatically. I want to check this against the FacebookID field/column set in my database. How would I do this? Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCFacebookTestApp.Models;
using Facebook;
using Facebook.Web;
namespace MVCFacebookTestApp.Controllers
{
public class HomeController : Controller
{
public FacebookSession FacebookSession
{
get { return (FacebookWebContext.Current.Session); }
}
public ActionResult Index()
{
string request = Request.Form["signed_request"];
string accessToken = "";
if (Request.Form["access_token"] != null)
{
accessToken = Request.Form["access_token"];
}
FacebookApplication app = new FacebookApplication();
FacebookSignedRequest result = FacebookSignedRequest.Parse(app.InnerCurrent, request);
if (String.IsNullOrWhiteSpace(accessToken))
{
accessToken = result.AccessToken;
}
dynamic data = result.Data;
bool liked = data.page.liked;
//bool liked = true;
if (!liked)
{
Home h = Home.NotLiked();
return View(h);
}
else
{
Home h = Home.Liked();
FacebookWebClient fb = null;
if (String.IsNullOrWhiteSpace(accessToken))
{
var fbRequest = FacebookWebContext.Current;
if (fbRequest.IsAuthorized())
fb = new FacebookWebClient(fbRequest);
accessToken = fbRequest.AccessToken;
}
else
{
fb = new FacebookWebClient(accessToken);
}
if (fb != null)
{
dynamic r = fb.Get("/me");
//h.TestString2 += " Ha! We captured this data about you!";
//h.TestString2 += " Name: " + r.name;
//h.TestString2 += " Location: " + r.location;
//h.TestString2 += " Birthday: " + r.birthday;
//h.TestString2 += " About Me: " + r.aboutme;
//h.ImgUrl = "http://graph.facebook.com/" + r.id + "/picture?type=large";
//string fqlResult = "";
//var fbApp = new FacebookClient(accessToken);
//basic fql query execution
//dynamic friends = fbApp.Query("SELECT uid FROM page_admin WHERE page_id='160828267335555'");
//SELECT uid FROM page_fan WHERE page_id = 160828267335555
//"SELECT uid FROM page_fan WHERE uid=me() AND page_id=<your page id>";
//loop through all friends and get their name and create response containing friends' name and profile picture
//foreach (dynamic friend in friends)
//{
// fqlResult += friend.uid + ".... ";
// //fqlResult += friend.name + "<img src='" + friend.pic_square + "' alt='" + friend.name + "' /><br />";
//}
h.AddUser(r.id, accessToken, r.first_name, r.last_name, DateTime.ParseExact(r.birthday, "MM/dd/yyyy", new System.Globalization.CultureInfo("en-GB")), r.email, DateTime.Now, r.gender, "http://graph.facebook.com/" + r.id + "/picture?type=large");
//ViewBag.Likes = fqlResult;
}
else
{
//Display a message saying not authed....
}
// if statement to stop same user from being added to the database...
if ()
{
//condition here
}
else
{
//condition here
}
return View(h);
}
}
}
}
I'm trying it this way at the moment using the if else if and else statement.
var User = SELECT from User WHERE FBID = FBID();
if (User.Count==0)
{
User.AddUser(facebookID as string, accessToken as string, fName as string, lName as string, dob as DateTime, email as string, dateLiked as DateTime, gender as string, imageURL as string); //Create newUser
}
else if (User.Count ==1)
{
//set properties to User[0]
}
else
{
// THROW EXCEPTION
}
and these are my properties to the database that i have created;
//public string UserID { get; set; }
public string FBID { get; set; }
public string AccessToken { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string Gender { get; set; }
public DateTime DOB { get; set; }
public string Email { get; set; }
public DateTime DateLiked { get; set; }
public string ImageURL { get; set; }
//public string TestString { get; set; }
//public string TestString2 { get; set; }
public bool IsLiked { get; set; }
//public string ImgUrl { get; set; }
public void AddUser (string facebookID, string accessToken, string fName, string lName, DateTime dob, string email, DateTime dateLiked, string gender, string imageURL)
{
//UserID = userID;
FBID = facebookID;
AccessToken = accessToken;
FName = fName;
LName = lName;
DOB = dob;
Email = email;
DateLiked = dateLiked;
Gender = gender;
ImageURL = imageURL;
User newUser = new User();
Entities newContext = new Entities();
//newUser.UserID = 1;
newUser.FacebookID = facebookID;
newUser.AccessToken = accessToken;
newUser.FName = fName;
newUser.LName = lName;
newUser.Gender = gender;
newUser.DOB = DOB;
newUser.Email = email;
newUser.DateLiked = dateLiked;
newUser.ImageURL = imageURL;
newContext.Users.AddObject(newUser);
newContext.SaveChanges();
}
}
}
I hope it makes sense, newbie here so go easy on me. =)
To preserve the integrity of your database you should add a unique constraint to this column in your database and then catch the exception of the violation of this constraint when performing the UPDATE/INSERT query.

Categories

Resources