Azure AD Graph API add member to group - c#

I am trying to add a member to a group using the aad graph api and I am keep getting 404.
A similar code works for me when I am trying to get the group members.
This is the code:
string requestUrl = string.Format("https://graph.windows.net/{0}/groups/{1}/$linkes/members?api-version=2013-04-05", tenantName, group.ObjectId);
string postData = string.Format("\"url\":\"https://graph.windows.net/{0}/users/{1}?api-version=2013-04-05\"", tenantName, user.ObjectId);
HttpWebRequest webRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Headers["Authorization"] = authenticationResult.CreateAuthorizationHeader();
webRequest.ContentType = "application/json"; //"application/x-www-form-urlencoded";
webRequest.Host = "graph.windows.net";
webRequest.ContentLength = postData.Length;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
string jsonText;
var httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (var streamReader =
new StreamReader(httpResponse.GetResponseStream()))
{
jsonText = streamReader.ReadToEnd();
}
I know there are other ways to do the same work, for example using the graph connection, but I prefer to use this way because it should work for roles as well.
Thanks

Your URL does seem to have a typo: $linkes. Should be $links.

Related

OAuth2.0 - Exchange authorisation code for access token

I'm trying to exchange an authorisation code for an access token using C# on HRMRC Making Tax Digital API. I'm able to get the authorisation code alright which I thought would be the difficult bit.
I've also been able to use Postman to exchange the authorisation code my app has obtained for the access token. See the attached screen shots of Postman and below is my C# :
uri = "https://api.service.hmrc.gov.uk/oauth/token"
body = "client_id=MyClientId&client_secret=MyClientSecret&code=MyAuthorisationCode&grant_type=authorization_code&redirect_uri=http%253A%252F%252Flocalhost%253A80%252F"
private static AccessTokens GetTokens(string uri, string body)
{
AccessTokens tokens = null;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/vnd.hmrc.1.0+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = body.Length;
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(body);
writer.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
string json = reader.ReadToEnd();
reader.Close();
tokens = JsonConvert.DeserializeObj[1]ect(json, typeof(AccessTokens)) as AccessTokens;
}
return tokens;
}

C# Calling Salesforce Rest Api with custom header

I am trying to insert a new contact in Salesforce using Rest Api but unfortunately getting 400 Bad request exception.While using Postman everything is perfect but via code it is throwing exception. Someone guide me plz where I am wrong.
string new_Contact_url = ConfigurationManager.AppSettings["SalesForceBaseUrl"] + "sobjects/contact";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new_Contact_url);
request.Method = "POST";
request.Headers.Add("Authorization", "Access_Token");
request.ContentType = "application/json; charset=utf-8";
var keyValues = new Dictionary<string, string>
{
{ "LastName", "Nafees" },
{ "Email", "email "},
{ "Tools_User_ID__c", "login_id" }
};
JavaScriptSerializer js = new JavaScriptSerializer();
string postData = js.Serialize(keyValues);
byte[] byteArray = Encoding.UTF8.GetBytes(postData.Trim());
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var resp = reader.ReadToEnd();
var serializer = new JavaScriptSerializer();
var responseBody = (IDictionary<string, object>)serializer.DeserializeObject(resp);
if (!string.IsNullOrEmpty(responseBody["access_token"].ToString()))
{
string id = responseBody["Id"].ToString();
}
Salesforce recently switched from supporting TLS1.0 to TLS1.2.
In your C# code can you add this:
using System.Net;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
The ServicePointManager part should be before you send the request.

Bad Request(400) is alsways returned when I try to get access token from live.com

I already got the authorization code.
I try to get access token with the following code:
string requestUrl = "https://login.live.com/oauth20_token.srf";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string fields = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code", clientId_, "https://login.live.com/oauth20_desktop.srf", clientSecret_, authorizationCode_);
var data = Encoding.ASCII.GetBytes(fields);
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
The last string always raises an WebException: Bad Request
Update: Just remove client_secret from fields and get the access token:
string fields = string.Format("client_id={0}&redirect_uri={1}&code={2}&grant_type=authorization_code", clientId_, "https://login.live.com/oauth20_desktop.srf", authorizationCode_);

Get html source from internet meet some issue

I want to fetch a web page to analyze stock information. I use the following sample code to get html data using c#. While it compiles, running it always ends in an error.
The following is my sample code:
string urlAddress = "http://pchome.syspower.com.tw/stock/sto0/ock2/sid2404.html";
var request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 1414;
var requestStream = request.GetRequestStream();
requestStream.Write(Encoding.UTF8.GetBytes("is_check=1"), 0, 10);
requestStream.Close();
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string rawData = sr.ReadToEnd();
sr.Close();
response.Close();
Does anyone know how to solve this issue?
The errors were mostly related to the order of your code and the closing of Stream objects your were still going to use.
Also I recommend to use using where possible to correctly dispose objects.
Use this code:
string rawData;
byte[] bytes = Encoding.UTF8.GetBytes("is_check=1");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
rawData = sr.ReadToEnd();
}
}
}

Programmatically login to google app engine c#

I've tried to login to my google app engine application from ASP.NET for a few days, but no luck. I've read the following articles and got the basic ideas. But nothing works for me.
http://code.activestate.com/recipes/577217-routines-for-programmatically-authenticating-with-/
http://dalelane.co.uk/blog/?p=303
http://dalelane.co.uk/blog/?p=894
http://krasserm.blogspot.com/2010/01/accessing-security-enabled-google-app.html
http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app
I know what to do. 1) Get an auth token from ClientLogin. 2) Get a cookie from Google App Engine. 3) Post data to my app with the cookie (Yes, I want to post data, not redirect after the second part). But the third part doesn't work for me at all. It give me 403 error. Here is my code:
void PostToGAE()
{
var auth = GetAuth(); // I can get the authtoken
var cookies = GetCookies(auth); // I can get the ACSID cookie
var url = string.Format("http://test.appspot.com/do/something/");
var content = "testvalue=test";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.CookieContainer = cookies;
byte[] byteArray = Encoding.UTF8.GetBytes(content);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // This gives me 403
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
reader.Close();
}
CookieContainer GetCookies(string auth)
{
CookieContainer cookies = new CookieContainer();
var url = string.Format("http://test.appspot.com/_ah/login?auth={0}",
System.Web.HttpUtility.UrlEncode(auth));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
reader.Close();
return cookies;
}
string GetAuth()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/accounts/ClientLogin");
var content = "Email=test#gmail.com&Passwd=testpass&service=ah&accountType=HOSTED_OR_GOOGLE";
byte[] byteArray = Encoding.UTF8.GetBytes(content);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string loginStuff = reader.ReadToEnd();
reader.Close();
var auth = loginStuff.Substring(loginStuff.IndexOf("Auth")).Replace("Auth=", "").TrimEnd('\n');
return auth;
}
My app.yaml looks like this:
- url: /do/something/
script: something.py
login: admin
If I change the method POST to GET, that works. Could anyone tell me how I can post data?
Thanks.
EDITED:
Still no luck. I've tried several ways such as changing to [login: required] in app.yaml, adding [secure: always] to app.yaml and changing the request protocol to https, appending continue parameter to /_ah/login, but all of them don't work :(
I totally have no idea why POST doesn't work at all but GET. Any ideas?
I made it. I was on the wrong track. That was not the problem of app engine but Django. I am using Django-nonrel on google app engine, and I totally forgot to put #csrf_exempt decorator to my handler. I had the same problem before, but again. Anyway, the code above has been apparently working correctly since at the beginning. What a smart boy :)

Categories

Resources