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";
}
Related
im trying to get a this value that i send with JSON string POST, when i receive the response in postman, there's value like status, id, etc that i not POST, while i do understand get the value from JSON string,
i dont quite understand to get a receive API value like status and Name
what i do tried recently
public class Condition
{
public string status { get; set; }
public string name { get; set; }
public string positition { get; set; }
public int no_id { get; set; }
public string time_auth { get; set; }
public string account_type { get; set; }
}
for the method
public partial class ResponseJSON
{
public bool Result(string jsonData, string URL, out string status)
{
bool resultresponse = false;
var request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "POST";
var writer = new StreamWriter(request.GetRequestStream());
string wrote = jsonData;
writer.Write(wrote);
var httpResponse = (HttpWebResponse)request.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var result = streamReader.ReadToEnd();
dynamic R = JsonConvert.DeserializeObject<dynamic>(wrote);
status = R.auth_type;
return resultresponse;
}
}
and for the main
string jsonData = #"{
'auth_type':'7',
'staff_id':'1234567890',
'staff_pin': '1234'}";
dynamic data = JObject.Parse(jsonData);
string URL = "Link URL";
string status = string.Empty;
ResponseJSON responseJSON = new ResponseJSON();
responseJSON.Result(jsonData, URL, out status);
You might want to declare the same class "Condition" on your client side, so you can deserialize the response with Newtonsoft with something like this:
var conditionResponse = JsonConvert.DeserializeObject<Condition>(jsonData);
I've got some problems with getting REST API response that allows to get members of the group( GET {serviceUrl}/v3/conversations/{conversationId}/members). I'm debugging my bot in Bot Emulator, and it runs fine here
- that's what it shows in the Bot Simulator
- But that's how it shows on Azure.
The main problem is that i really can't recognize the problem.I know that the problem is in requesting because the getResponse method crash all programm when it is on server(but why this works in the bot emulator?).Here is the code(I'm using .NET CORE, Microsoft Bot Framework). P.S.{id} in Authorization is correct, and i get it from another request(but unlike the problem request that request works everywhere), the {url} is turnContext.Activity.ServiceUrl
HttpWebRequest webRequest23 = (HttpWebRequest)WebRequest.Create($"{url}/v3/conversations/{turnContext.Activity.Conversation.Id}/members");
await turnContext.SendActivityAsync($"{url}/v3/conversations/{turnContext.Activity.Conversation.Id}/members");
await turnContext.SendActivityAsync(turnContext.Activity.Conversation.Id);
webRequest23.ContentType = "application/json";
webRequest23.Headers["Authorization"] = $"Bearer {id}";
WebResponse response2 = webRequest23.GetResponse();//crash here
await turnContext.SendActivityAsync("3");
string smth25 = "";
using (StreamReader stream = new StreamReader(response2.GetResponseStream(), true))
{
smth25 = stream.ReadToEnd();
}
JArray jsonArray = JArray.Parse(smth25);
List<string> names = new List<string>();
foreach(var x in jsonArray)
{
var name = JObject.Parse(x.ToString())["name"].ToString();
names.Add("#" + name);
}
string s = "This group consists of - ";
foreach (var x in names){
s += "" + x + ",";
}
await turnContext.SendActivityAsync(s);
Here is how i get id:
string stringData = "grant_type=client_credentials&client_id=66b16ef5-d086-40b7-ae9c-2f50a1f028c6&client_secret=yRUYg4g.:ANuw3Y_01V=#.JkAv=#g3EE&scope=https%3A%2F%2Fapi.botframework.com%2F.default";
var data = Encoding.Default.GetBytes(stringData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token");
webRequest.Host = "login.microsoftonline.com";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
var newStream = webRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
WebResponse response = webRequest.GetResponse();
string line = string.Empty;
string smone = "";
using (StreamReader stream = new StreamReader(response.GetResponseStream(), true))
{
smone = stream.ReadToEnd();
}
var id = JObject.Parse(smone)["access_token"].ToString();
I don't understand exactly what your "turnContext.SendActivityAsync" lines are supposed to do, but it might be working in the bot emulator because the emulator doesn't require a proper authenticated session like Teams does. Anyway, something like this should actually help you:
First, define this class somewhere:
public class MicrosoftTeamUser
{
public string Id { get; set; }
public string ObjectId { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string UserPrincipalName { get; set; }
public string TenantId { get; set; }
}
then use:
List<ChannelAccount> teamMembers = (await turnContext.TurnState.Get<IConnectorClient>().Conversations.GetConversationMembersAsync(
turnContext.Activity.GetChannelData<TeamsChannelData>().Team.Id).ConfigureAwait(false)).ToList();
List<MicrosoftTeamUser> teamsUsers = new List<MicrosoftTeamUser>();
foreach (var item in teamMembers)
{
var teamsUser = JsonConvert.DeserializeObject<MicrosoftTeamUser>(item.Properties.ToString());
teamsUser.Id = item.Id;
teamsUsers.Add(teamsUser);
}
Then you'll have the list of members in the teamMembers variable
I have an api http://oversea-download.hikvision.com/uploadfile/Leaflet/ISAPI/HIKVISION%20ISAPI_2.0-IPMD%20Service.pdf I want to receive which uses a HTTP get and wants connection keep-alive.
Once connected it sends XML responses which I want to deserialise. I've created a class to represent the data structure, but I'm not sure how to continually update a list or similar as and when the data is sent back, for example the response (from wireshark) looks like:
I'm not concerned with the parsing of data and updating the list, more how I can keep listening on a socket and see that its XML data and needs to be serialised.. without processing the stream into a buffer and looking for delimiters?
So far the code I had been unsuccessfully playing with looks like:
public static async Task NewTask()
{
var client = new RestClient("http://192.168.0.152:80/");
client.Authenticator = new HttpBasicAuthenticator("admin", "ThePassword");
client.Encoding = Encoding.UTF8;
var request = new RestRequest("ISAPI/Event/notification/alertStream", Method.GET);
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Type", "application/xml");
IRestResponse<EventNotificationAlert> response2 = client.Execute<EventNotificationAlert>(request);
var name = response2.Data.eventType;
Console.WriteLine(name);
//var asyncHandle = client.ExecuteAsync<EventNotificationAlert>(request, response => {
// Console.WriteLine(response.Data.eventDescription);
//});
}
and the class:
public class EventNotificationAlert
{
public string version { get; set; }
public string ipAddress { get; set; }
public string portNo { get; set; }
public string protocol { get; set; }
public string macAddress { get; set; }
public string channelID { get; set; }
public string dateTime { get; set; }
public string activePostCount { get; set; }
public string eventType { get; set; }
public string eventState { get; set; }
public string eventDescription { get; set; }
}
disregard my comment, can't format it.. this kind of works.. but given I get boundary and content-type text I've got crude processing in...
var messageBuffer = string.Empty;
var request = WebRequest.Create("http://192.168.0.152:80/ISAPI/Event/notification/alertStream");
request.Credentials = new NetworkCredential("admin", "ThePassword");
request.BeginGetResponse(ar =>
{
var req = (WebRequest)ar.AsyncState;
// TODO: Add exception handling: EndGetResponse could throw
using (var response = req.EndGetResponse(ar))
using (var reader = new StreamReader(response.GetResponseStream()))
{
// This loop goes as long as the api is streaming
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line == xmlEndStr)
{
messageBuffer += line;
GotMessage(messageBuffer);
messageBuffer = string.Empty;
}
else if (line.StartsWith("<"))
{
messageBuffer += line;
}
}
}
}, request);
static void GotMessage(string msg)
{
var mySerializer = new XmlSerializer(typeof(EventNotificationAlert));
var stringReader = new StringReader(msg);
var eventAlert = (EventNotificationAlert)mySerializer.Deserialize(stringReader);
Console.WriteLine($"DateTime: {eventAlert.dateTime} Channel: {eventAlert.channelID} Type: {eventAlert.eventType} Description: {eventAlert.eventDescription}");
}
Happy to hear of better ways (as you can tell I'm not great with c#!)
I am going to use Constant contact for email marketing. I am not getting how to get userContactList which are all there in my constant contact account.If anyone have any idea please help me.
Thanks in advance
Here is some code I wrote a while ago that returns the user list ID based on the name of an existing user list. its all C# and uses RESTSharp library which you can install inside your VS project using Nuget.
public static string GetContactListIDByListName(string listname)
{
feedData = string.Empty;
id = string.Empty;
name = string.Empty;
status = string.Empty;
modified_date = string.Empty;
created_date = string.Empty;
contact_count = 0;
Stream stream = null;
StreamReader streamReader = null;
var client = new RestClient(ccURL);
var request = new RestRequest("/v2/lists?modified_since=[DATE]&api_key=[API-KEY]", Method.GET);
request.AddHeader("Authorization", "Bearer [ACCESS-TOKEN]");
request.AddHeader("X-Originating-Ip", "[SERVER-IP]");
request.AddHeader("Accept", "application/json");
IRestResponse response = client.Execute(request);
feedData = response.Content;
// DESERIALIZE Mashery JSON Response
byte[] byteArray = Encoding.ASCII.GetBytes(feedData);
MemoryStream myStream = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Mashery.GetAllListsDef[]));
object result = serializer.ReadObject(myStream);
Mashery.GetAllListsDef[] jsonObj = result as Mashery.GetAllListsDef[];
foreach (Mashery.GetAllListsDef myResult in jsonObj)
{
if (myResult.name.ToUpper().Equals(listname.ToUpper()))
{
return myResult.id.ToString();
}
}
return "";
}
// JSON Definition For [GET All Lists] End Point Method
[Serializable, XmlRoot("GetAllListsDef"), DataContract(Name = "GetAllListsDef")]
public class GetAllListsDef
{
[XmlElement("id"), DataMember(Name = "id")]
public string id { get; set; }
[XmlElement("name"), DataMember(Name = "name")]
public string name { get; set; }
[XmlElement("status"), DataMember(Name = "status")]
public string status { get; set; }
[XmlElement("created_date"), DataMember(Name = "created_date")]
public string created_date { get; set; }
[XmlElement("modified_date"), DataMember(Name = "modified_date")]
public string modified_date { get; set; }
[XmlElement("contact_count"), DataMember(Name = "contact_count")]
public string contact_count { get; set; }
}
If I understand Ufuk Hacıoğulları here
I can simplify this code:
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
if (arr.Count <= 0) break;
foreach (JObject obj in arr)
{
id = obj.Value<int?>("Id") ?? 0;
var _deptId = obj.Value<int?>("deptId") ?? 0;
var _subdeptId = obj.Value<int?>("subdeptId") ?? 0;
var _deptIdSubdeptId = Convert.ToDouble(String.Format("{0}.{1}", _deptId, _subdeptId));
var _subdeptName = obj.Value<string>("subdeptName") ?? "";
subDeptList.subDepartments.Add(new HHSUtils.Subdepartment
{
Id = id,
deptIdSubdeptId = (float)_deptIdSubdeptId,
subDeptName = _subdeptName
});
} // foreach
} // if ((webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse
...if I were to "use custom types instead of JArray or JObject types"
If I understand what he's saying, I could replace this line:
var arr = JsonConvert.DeserializeObject<JArray>(s);
...with something like:
var subDeptList = new SubdeptsList();
. . .
var arr = JsonConvert.DeserializeObject<Subdepartment>(s);
foreach (HHSUtils.Subdepartment obj in arr)
{
subDeptList.subDepartments.Add(obj);
}
Yet doing so fails with, "Exception: Cannot deserialize JSON array into type 'HHS.HHSUtils+Subdepartment'."
What the server passes is an IEnumerable which is defined there as:
public class Redemption
{
[Key]
public long Id { get; set; }
[Required]
public string RedemptionId { get; set; }
[Required]
public string RedemptionName { get; set; }
[Required]
public string RedemptionItemId { get; set; }
[Required]
public double RedemptionAmount { get; set; }
public string RedemptionDept { get; set; }
public string RedemptionSubDept { get; set; }
}
And it converts that data to JSON when passing it back; in the client, I'm attempting to convert the sent JSON back to this:
public class Redemption
{
public long Id { get; set; }
public string RedemptionId { get; set; }
public string RedemptionItemId { get; set; }
public string RedemptionName { get; set; }
public double RedemptionAmount { get; set; }
public string RedemptionDept { get; set; }
public string RedemptionSubDept { get; set; }
}
...with the code shown above. The only mismatch I can see (besides the class member "decorations" (Key, Required) the Redemption has on the server, which are missing on the client), is that on the server the generic list is an IEnumerable, whereas on the client it's a List:
public class SubdeptsList
{
public List<Subdepartment> subDepartments = new List<Subdepartment>();
}
So how can I more directly transfer the JSON object to my client, rather than use the JArray/JObject? Is it really feasible?
This is what I ended up with; Ufuk's suggestion has led to much more streamlined/elegant code:
// the old way:
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
if (arr.Count <= 0) break;
foreach (JObject obj in arr)
{
id = obj.Value<int?>("Id") ?? 0;
var _redemptionId = obj.Value<string>("RedemptionId") ?? "";
var _redemptionItemId = obj.Value<string>("RedemptionItemId") ?? "";
var _redemptionName = obj.Value<string>("RedemptionName") ?? "";
double _redemptionAmount = obj.Value<double?>("RedemptionAmount") ?? 0.0;
var _redemptionDept = obj.Value<string>("RedemptionDept") ?? "";
var _redemptionSubdept = obj.Value<string>("RedemptionSubDept") ?? "";
redemptionsList.redemptions.Add(new Redemption
{
Id = id,
RedemptionId = _redemptionId,
RedemptionItemId = _redemptionItemId,
RedemptionName = _redemptionName,
RedemptionAmount = _redemptionAmount,
RedemptionDept = _redemptionDept,
RedemptionSubDept = _redemptionSubdept
});
} // foreach
} // if ((webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse
And now the new and improved way:
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string jsonizedRedemptions = reader.ReadToEnd();
List<Redemption> redemptions = JsonConvert.DeserializeObject<List<Redemption>>(jsonizedRedemptions);
if (redemptions.Count <= 0) break;
foreach (Redemption redemption in redemptions)
{
redemptionsList.redemptions.Add(redemption);
}
} // if ((webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse