Post a message to slack - c#

I want to post a message to slack on x channel I need to send the following x parameters how do I send the following parameters to a website
"channel": "XXXXX", "token": "token", "text": "text"
I am coding in c# mvc application.
public async Task<HttpResponseMessage> SendMessageAsync(string message, string channel = null, string userName = null)
{
using (var client = new HttpClient())
{
string url = "https://fake2604.slack.com/api/chat.postMessage?token=myToken&channel=" + channel + "&text=Hello World";
var payLoad = new
{
text = message,
channel,
userName,
};
var serializedPayload = JsonConvert.SerializeObject(payLoad);
var response = await client.PostAsync(url, new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
}
This is not working.It just adds an integration to the channel that I select in the OAuth page which again I got through Add to Slack button.

I suppose the problem is with your webhook url which you are adding some more stuff to that.this code definitely work:
public async Task<HttpResponseMessage> SendMessageAsync(string message)
{
var payload = new
{
text = message,
channel="x",
userName="y",
};
HttpClient httpClient = new HttpClient();
var serializedPayload = serializer.ToJson(payload);
var response = await httpClient.PostAsync("url",
new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}

Related

sending headrs to web API from winForm client

i have a simple demo winform app and im trying to make a post request with header to web api.
i received access token and refreash token form the server and i stored that in text file.
and im trying to make a post request by sending the refreash token with the body and sending the access token with the header but i dont know how to include the header with the post request.
this my post method
public static async Task<string> sendMessage(string name, string contents)
{
using (HttpClient client = new HttpClient())
{
//reading the access token and refreash token from file
StreamReader sr = new StreamReader(#"C:\Users\noorm\Desktop\noor.txt");
string accessToken, refreashToken;
accessToken = sr.ReadLine();
refreashToken = sr.ReadLine();
//defining new instance of message opject
var newMessage = new messages()
{
name = name,
content = contents,
refreashToken = refreashToken
};
//sening the opject using post async and returning the response
var newPostJson = JsonConvert.SerializeObject(newMessage);
var payLoad = new StringContent(newPostJson, Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await client.PostAsync(baseURL + "/messages", payLoad))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
return data;
}
}
}
}
return string.Empty;
}
and this is the button
private async void btnSend_Click(object sender, EventArgs e)
{
var responce = await restHelper.sendMessage(txtName.Text.Trim(),txtContent.Text.Trim());
rtxt.Text = responce;
}
You can try something like the following:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
this is how i was able to send the access token with the header
client.DefaultRequestHeaders.Add("x-auth-token", accessToken);

Sending Data to SalesForce by HttpClient(C#) Post Method, Not Working

I am trying to send a json Object to SalesFroce using HttpClient, but this behaves Weirdly...
First i login in to Salesforce Via following code
var sendPaylod = new Dictionary<string, string>
{
{"grant_type","password"},
{"client_id",s_clientId},
{"client_secret",s_clientSecrate},
{"username",s_username},
{"password",s_password}
};
HttpClient auth = new HttpClient();
HttpContent content = new FormUrlEncodedContent(sendPaylod);
HttpResponseMessage response = await auth.PostAsync(s_tokenRequestEndpointUrl, content);
string msg = await response.Content.ReadAsStringAsync();
Console.WriteLine(msg);
string authToken = (String)jsonObj["access_token"];
Now I have got authToken as a bearer token to send data to salesFroce
I am doing that by Following
var obj = new { Director = "003e000001MQYjB",
CityName = "XXAA",
CityId = "000000",
RegionName = "India",
RegionId = "00000" };
string c_url = "URL to which data will sent";
var c_Obj = JsonConvert.SerializeObject(obj);
var c_content = new System.Net.Http.StringContent(c_Obj, Encoding.UTF8, "application/json");
HttpClient c_client = new HttpClient();
c_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization","Bearer "+authToken);
HttpContent c_content = new StringContent(c_Obj, Encoding.UTF8, "application/json");
c_content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var c_response = await c_client.PostAsync(c_url, content);
var c_msg = await c_response.Content.ReadAsStringAsync();
Now Am getting Following Response...
"status": "success",
"recordId": "",
"message": ""
If i Use Same Bearer Token in Postman and Send same Json Object I receive Following response.
"status": "success",
"recordId": "a16e0000002qV6aE",
"message": ""
Please Help in this matter.
Fix the next errors:
Change:
var c_response = await c_client.PostAsync(c_url, content);
to:
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
c_client.DefaultRequestHeaders.Accept.Add(contentType);
var c_response = await c_client.PostAsync(c_url, c_content);
var c_msg = await c_response.Content.ReadAsStringAsync();
var result =JsonConvert.DeserializeObject<your return class>(c_msg);
and change your authorization to:
c_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken );

How to convert response of post request to bool in c#?

I have an endpoint in my ASP.NET Core 2.1 Controller
[HttpPost]
public async Task<bool> CheckStatus([FromBody] StatusModel model)
{
...code ommited
return true;
}
And I call this endpoint from other place in code like this:
await client.PostAsync('/CheckStatus', payloayd)
How can I retrive a bool value from this request?
Using Newtonsoft.Json, you can read the response of the request and parse it into a bool.
using Newtonsoft.Json;
public async Task<bool> GetBooleanAsync()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new { };
var url = "my site url";
var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
var req = await client.PostAsync(url, payload);
var response = await req.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<bool>(response);
}
}
UPDATE
Looking back on this from a few years on, this can be simplified without the use of Newtonsoft.Json to read the response, by simply parsing the string data to a boolean.
public async Task<bool> GetBooleanAsync()
{
var data = new { };
var url = "my site url";
var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
using var client = new HttpClient();
var response = await client.PostAsync(url, payload);
var data = await response.Content.ReadAsStringAsync();
return boolean.Parse(data);
}
However, if your boolean value is returned in a JSON object, then Newtonsoft.Json could be used to read that value.

Get HTTP response message from JSON POST method in C#

I am trying to get the response from an API but I am not getting any luck. I am running a async method using C# ASP.NET, but the info which comes from the response displays status and many things but the real response.
This is my code:
private static async Task PostBasicAsync(CancellationToken cancellationToken)
{
Michael Maik = new Michael();
Maik.name = "Michael";
Maik.id = "114060502";
Maik.number = "83290910";
string Url = "http://my-api.com/testing/give-your-data";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
{
var json = JsonConvert.SerializeObject(Maik);
using (var stringContent = new StringContent(
json,
Encoding.UTF8,
"application/json"))
{
request.Content = stringContent;
using (var response = await client
.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
}
}
}
}
What is wrong with my code?
It should return something like:
{
"message": "Hi Michael we have received your data succesfully!",
"data": {
"name": "Michael",
"id": "114060502",
"number": "83290910"
}
}
After the call response.EnsureSuccessStatusCode() you can do:
string resString = await response.Content.ReadAsStringAsync() to get the actual response body.

Executing POST request for Microsoft Graph API to add members to an AD group

I am trying to add members to an AD groups invoking Microsoft Graph API through an Azure Function
It is very easy and straightforward to execute GET requests through Graph API's, but I can't find any examples how I could execute post requests for the Graph API
I do have an example of a post request for the Graph API which is
POST https://graph.microsoft.com/v1.0/groups/{id}/members/$ref
Content-type: application/json
Content-length: 30
{
"#odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/{id}"
}
Here is the code I successfully use to retrieve the Graph response
public static async Task<HttpResponseMessage> GetDirectoryUsers(string graphToken, TraceWriter log, string displayName)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
string requestUrl = "https://graph.microsoft.com/v1.0/groups?$top=2&$filter=displayName eq '" + displayName + "'&$expand=Members";
var request = new HttpRequestMessage(new HttpMethod("GET"), requestUrl);
var response = await client.SendAsync(request);
return response;
}
However, I am completely lost how I could execute the request through a C# code within the Azure function to ADD the retrieved users to another AD. How can construct the request URL? How should I handle the odata id within that request URL?
If anyone could help me in any way, I would greatly appreciate it
A reuse method for add sub-group/member to group(O365 doesn't support add sub-group to group now)
/// <param name="graphClient"></param>
/// <param name="groupId"></param>
/// <param name="memberId">memberId/sub-group id</param>
/// <returns></returns>
public static async Task AddGroupMember1(GraphServiceClient
graphClient, string groupId, string memberId)
{
User memberToAdd = new User { Id = memberId };
//Group memberToAdd= new Group { Id = memberId };
await graphClient.Groups[groupId].Members.References.Request().AddAsync(memberToAdd);
}
Here is the answer that worked for me
public static async Task<string> AddGroupMember(string accessToken, string groupId, string memberId)
{
var status = string.Empty;
try
{
string endpoint = "https://graph.microsoft.com/v1.0/groups/" + groupId + "/members/$ref";
string queryParameter = "";
// pass body data
var keyOdataId = "#odata.id";
var valueODataId = "https://graph.microsoft.com/v1.0/directoryObjects/" + memberId;
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(keyOdataId, valueODataId)
};
var jsonData = $#"{{ ""{keyOdataId}"": ""{valueODataId}"" }}";
var body = new StringContent(jsonData, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Post, endpoint + queryParameter))
{
request.Content = body;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var response = await client.SendAsync(request))
{
if (response.StatusCode == HttpStatusCode.NoContent)
status = "Member added to Group";
else
status = $"Unable to add Member to Group: {response.StatusCode}";
}
}
}
}
catch (Exception ex)
{
status = $"Error adding Member to Group: {ex.Message}";
}
return status;
}
I'm using graph api for sending email. The code in below
public async Task<dynamic> SendMail(string accessToken, MailWrapper mail)
{
try
{
GraphServiceClient graphClient = SDKHelper.GetMicrosoftAuthenticatedClient(accessToken);
Message message = await BuildEmailMessage(graphClient, mail);
await graphClient.Me.SendMail(message, true).Request().PostAsync(CancellationToken.None);
var response = await graphClient.Me.MailFolders.SentItems.Messages.Request()
.OrderBy(sendDateTimeDesc)
.Top(1)
.GetAsync();
return await Task.FromResult(response);
}
catch (ServiceException ex)
{
throw ex;
}
}
Assembly Microsoft.Graph, Version=1.9.0.0
That's what worked for me
public void AddUserToGroup(string groupId)
{
var requestUri = $"{_graphApiUrl}/v1.0/groups/{groupId}/members/$ref";
var id = "user_id";
var OdataId = "#odata.id";
var ODataValue = $"https://graph.microsoft.com/v1.0/users/{id}";
var content = $#"{{ ""{OdataId}"": ""{ODataValue}"" }}";
using (var httpClient = new HttpClient())
using (var httpRequest = CreateHttpRequest(HttpMethod.Post, requestUri, content))
{
var response = httpClient.SendAsync(httpRequest).GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
{
var reason = $"Status code: {(int)response.StatusCode}, Reason: {response.StatusCode}";
throw new Exception(reason);
}
}
}
And important thing was when creating a request to use:
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
it didn't work with:
request.Content = new StringContent(content);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");

Categories

Resources