Problems with Getting Response on the deployed bot; - c#

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

Related

How to do a Post using WebRequest from a Class Library?

I want to call to a API using a class library.
Here is the way they need us to send the post request
Or
To achecive this I use this code
public class Keey
{
public string username { get; set; }
public string passward { get; set; }
public string src { get; set; }
public string dst { get; set; }
public string msg { get; set; }
public string dr { get; set; }
}
public void SendSms(string phoneNo, string SMS)
{
Keey account = new Keey
{
username = "*****",
passward = "*********",
src = "test.com",
dst = phoneNo,
msg = SMS,
dr = "1",
};
WebRequest request = WebRequest.Create("http://testserver.com ");
// Set the Method property of the request to POST.
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = SMS.Length;
CredentialCache.DefaultNetworkCredentials.UserName = account.username;
CredentialCache.DefaultNetworkCredentials.Password = account.passward;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
WebResponse response = request.GetResponse();
}
But I dont know where to add those port,src,dst,msg etc... Please help me
Code is in C#
That is depend on your Web-Api Service. for what input parameter needed.
There are several ways to perform POST requests:
HttpWebRequest (not recommended for new work)
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
var request = (HttpWebRequest)WebRequest.Create("http://testserver.com/test.aspx");
//your data should place in here
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
recommended way to get this work:
using System.Net.Http;
private static readonly HttpClient client = new HttpClient();
POST
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://testserver.com/test.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

Google vision connection to API without external google DLL

How to connect to google cloud vision without using external dlls?
First, you will have to generate JSON request, simple example:
Request req = new Request();
req.addFeature("DOCUMENT_TEXT_DETECTION"); //Add here all the feature types
req.Image.content = Convert.ToBase64String(qq);//qq is a byte[]
Requests reqList = new Requests(req);
json = JsonConvert.SerializeObject(reqList);
Secondly, you need to post simple HTTP request:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://vision.googleapis.com/v1/images:annotate?key="PLACE_YOURKEY_HERE"");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
Memebers of the JSON classes (The methods should be implemented):
class Requests
{
public List<Request> Request { get; set; }
}
class Request
{
public Image1 Image { get; set; }
public List<Feature> Features { get; set; }
}
public class Feature
{
public string Type { get; set; }
}
public class Image1
{
public string content { get; set; }
}
Relevant to the topic links
Google Vision API Document_Text_Detection
Feature types
Google vision

Calling WebApi with complex object parameter using WebClient

I need to call a WebApi using WebClient where have to pass an object as parameter. I have my WebApi method as similar to bellow code:
example URI: localhost:8080/Api/DocRepoApi/PostDoc
[HttpPost]
public string PostDoc (DocRepoViewModel docRepo)
{
return string.enpty;
}
and then DocRepoViewModel is:
public class DocRepoViewModel
{
public string Roles { get; set; }
public string CategoryName { get; set; }
public List<AttachmentViewModel> AttachmentInfo { get; set; }
}
AttachmentViewModel is:
public class AttachmentViewModel
{
public string AttachmentName { get; set; }
public byte[] AttachmentBytes { get; set; }
public string AttachmentType { get; set; }
}
New I need to call PostDoc method from my MVC controller (not javascript ajax). How can I pass this specific parameter that I can make the call and get all data in my WebApi method. Can we do it by WebClient? Or there are better way. Please help.
You could use the PostAsJsonAsync method as follows:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("localhost:8080/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var docViewModel = new DocRepoViewModel() { CategoryName = "Foo", Roles= "role1,role2" };
var attachmentInfo = new List<AttachmentViewModel>() { AttachmentName = "Bar", AttachmentType = "Baz", AttachmentBytes = File.ReadAllBytes("c:\test.txt" };
docViewModel.AttachmentInfo = attachmentInfo;
response = await client.PostAsJsonAsync("DocRepoApi/PostDoc", docViewModel);
if (response.IsSuccessStatusCode)
{
// do stuff
}
}
}
Asp .net reference
Check out following code.
string url = "Your Url";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.KeepAlive = false;
request.ContentType = "application/json";
request.Method = "POST";
var entity = new Entity(); //your custom object.
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(entity));
request.ContentLength = bytes.Length;
Stream data = request.GetRequestStream();
data.Write(bytes, 0, bytes.Length);
data.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string message = reader.ReadToEnd();
var responseReuslt = JsonConvert.Deserialize<YourDataContract>(message);
}
}

Sample code for calling Marketo Rest Api in .net/c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
Does anyone have an example of calling a Marketo Rest API from .net/C#.
I am particularly interested in the oauth authentication piece.
http://developers.marketo.com/documentation/rest/authentication/
I plan to call this endpoint
http://developers.marketo.com/documentation/rest/get-multiple-leads-by-list-id/
I cannot find any example out there on the interweb.
I was able to code up a solution for calling a Marketo Rest API and do the OAuth. Below is a how-to
The below code shows the basics, but needs clean up, logging and error handling to be production worthy.
You need to get the Rest api URL's for your Marketo instance. To do this, log into marketo, and navigate to Admin\Integration\Web Services, and use the URLs in the Rest API Section.
You need to get your user id and secret from marketo - navigate to Admin\Integration\Launch Pont. View the details of your Rest Service to get id and secret. If you don't have a Service, then follow these instructions http://developers.marketo.com/documentation/rest/custom-service/.
Finally, you need your list id for the list of leads you want to get. You can get this by navigating to your list and copying the numeric portion of the id out of the url. Example: https://XXXXX.marketo.com/#ST1194B2 —> List ID = 1194
private void GetListLeads()
{
string token = GetToken().Result;
string listID = "XXXX"; // Get from Marketo UI
LeadListResponse leadListResponse = GetListItems(token, listID).Result;
//TODO: do something with your list of leads
}
private async Task<string> GetToken()
{
string clientID = "XXXXXX"; // Get from Marketo UI
string clientSecret = "XXXXXX"; // Get from Marketo UI
string url = String.Format("https://XXXXXX.mktorest.com/identity/oauth/token?grant_type=client_credentials&client_id={0}&client_secret={1}",clientID, clientSecret ); // Get from Marketo UI
var fullUri = new Uri(url, UriKind.Absolute);
TokenResponse tokenResponse = new TokenResponse();
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(fullUri);
if (response.IsSuccessStatusCode)
{
tokenResponse = await response.Content.ReadAsAsync<TokenResponse>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return tokenResponse.access_token;
}
private async Task<LeadListResponse> GetListItems(string token, string listID)
{
string url = String.Format("https://XXXXXX.mktorest.com/rest/v1/list/{0}/leads.json?access_token={1}", listID, token);// Get from Marketo UI
var fullUri = new Uri(url, UriKind.Absolute);
LeadListResponse leadListResponse = new LeadListResponse();
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(fullUri);
if (response.IsSuccessStatusCode)
{
leadListResponse = await response.Content.ReadAsAsync<LeadListResponse>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return leadListResponse;
}
private class TokenResponse
{
public string access_token { get; set; }
public int expires_in { get; set; }
}
private class LeadListResponse
{
public string requestId { get; set; }
public bool success { get; set; }
public string nextPageToken { get; set; }
public Lead[] result { get; set; }
}
private class Lead
{
public int id { get; set; }
public DateTime updatedAt { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public DateTime datecreatedAt { get; set; }
public string firstName { get; set; }
}
Old question, just hoping to help the next guy who ends up here from a google search :-)
This page was probably not there at the time of this post, but there is now a good page with examples in several languages. The page is at
http://developers.marketo.com/documentation/rest/get-multiple-leads-by-list-id
Just in case the link goes dead, here is the code example that they provide for C#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Samples
{
class LeadsByList
{
private String host = "CHANGE ME"; //host of your marketo instance, https://AAA-BBB-CCC.mktorest.com
private String clientId = "CHANGE ME"; //clientId from admin > Launchpoint
private String clientSecret = "CHANGE ME"; //clientSecret from admin > Launchpoint
public int listId;
public int batchSize;//max 300, default 300
public String[] fields;//array of field names to retrieve
public String nextPageToken;//paging token
/*
public static void Main(String[] args)
{
MultipleLeads leads = new MultipleLeads();
leads.listId = 1001
String result = leads.getData();
Console.WriteLine(result);
while (true)
{
}
}
*/
public String getData()
{
StringBuilder url = new StringBuilder(host + "/rest/v1/list/" + listId + "/leads.json?access_token=" + getToken());
if (fields != null)
{
url.Append("&fields=" + csvString(fields));
}
if (batchSize > 0 && batchSize < 300)
{
url.Append("&batchSize=" + batchSize);
}
if (nextPageToken != null)
{
url.Append("&nextPageToken=" + nextPageToken);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.ContentType = "application/json";
request.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
return reader.ReadToEnd();
}
private String getToken()
{
String url = host + "/identity/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
String json = reader.ReadToEnd();
//Dictionary<String, Object> dict = JavaScriptSerializer.DeserializeObject(reader.ReadToEnd);
Dictionary<String, String> dict = JsonConvert.DeserializeObject<Dictionary<String, String>>(json);
return dict["access_token"];
}
private String csvString(String[] args)
{
StringBuilder sb = new StringBuilder();
int i = 1;
foreach (String s in args)
{
if (i < args.Length)
{
sb.Append(s + ",");
}
else
{
sb.Append(s);
}
i++;
}
return sb.ToString();
}
}
}
At the time of this response - this page has all of the api calls documented
http://developers.marketo.com/documentation/rest/

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";
}

Categories

Resources