I am trying to send a request from anroid emulator. But the application is not giving proper output and breaking on client.sendasync - xamarin.forms.listview

{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username",username),
new KeyValuePair<string, string>("password",password),
new KeyValuePair<string, string>("grant_type","password")
};
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost(delibirately written)/Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var jwt = await response.Content.ReadAsStringAsync();
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwt);
var accessToken = jwtDynamic.Value<string>("access_token");
var accessExpires = jwtDynamic.Value<DateTime>(".expires");
Settings.AccessTokenExpiration = accessExpires;
Debug.WriteLine(jwt);
return accessToken;
}
I was getting exception first and then i used try catch and then i found out that application is breaking at client.async.

Related

Can not create a team from scratch via microsoft graph api

I follow this document and tried to create a team in the code
https://learn.microsoft.com/en-us/graph/api/team-post?view=graph-rest-1.0&tabs=csharp%2Chttp.
here is my code snippets:
var scopes = new string[] { "https://graph.microsoft.com/.default" };
// Configure the MSAL client as a confidential client
var confidentialClient = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
GraphServiceClient graphServiceClient =
new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient
.AcquireTokenForClient(scopes)
.ExecuteAsync();
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
})
);
// Make a Microsoft Graph API call
var team = new Team
{
DisplayName = "My Sample Team",
Description = "My Sample Team’s Description",
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"},
{"members#odata.bind", "[{\"#odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"57d4fc1c-f0a3-1111-b41e-22229f05911c\"}]"}
}
};
GraphServiceClient graphServiceClient =
new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient
.AcquireTokenForClient(scopes)
.ExecuteAsync();
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
})
);
// Make a Microsoft Graph API call
var team = new Team
{
DisplayName = "My Sample Team",
Description = "My Sample Team’s Description",
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"},
{"members#odata.bind", "[{\"#odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"57d4fc1c-f0a3-4105-b41e-1ba89f05911c\"}]"}
}
};
but get this error:
"message": "Bind requests not supported for containment navigation property.",\r\n
I'm using the latest Microsoft.Graph library and version is V3.1.8
does anyone have some ideas on this issue or the odata format error?
It seems that the members#odata.bind is still in change. It doesn't work currently.
You need to use members property.
POST https://graph.microsoft.com/v1.0/teams
{
"template#odata.bind":"https://graph.microsoft.com/v1.0/teamsTemplates('standard')",
"displayName":"My Sample Team555",
"description":"My Sample Team’s Description555",
"members":[
{
"#odata.type":"#microsoft.graph.aadUserConversationMember",
"roles":[
"owner"
],
"userId":"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
]
}
The corresponding C# code should be:
var team = new Team
{
DisplayName = "My Sample Team557",
Description = "My Sample Team’s Description557",
Members = (ITeamMembersCollectionPage)new List<ConversationMember>()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
UserId = "9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
},
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
}
};
Unfortunately, when I run the code, it shows:
System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List`1[Microsoft.Graph.ConversationMember]' to type 'Microsoft.Graph.ITeamMembersCollectionPage'.'
I cannot make it work. The workaround is to use httpClient to send the request in your code.
See a similar question here.
UPDATE:
I have figured it out.
You can try the following code:
var team = new Team
{
DisplayName = "My Sample Team558",
Description = "My Sample Team’s Description558",
Members = new TeamMembersCollectionPage() {
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
UserId = "9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
},
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
}
};
If you prefer httpClient method, refer to this:
string str = "{\"template#odata.bind\":\"https://graph.microsoft.com/v1.0/teamsTemplates('standard')\",\"displayName\":\"My Sample Team999\",\"description\":\"My Sample Team’s Description555\",\"members\":[{\"#odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[\"owner\"],\"userId\":\"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce\"}]}";
var content = new StringContent(str, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = client.PostAsync("https://graph.microsoft.com/v1.0/teams", content).Result;
UPDATE 2:
If you need to call it in Postman, use this format:
{
"template#odata.bind":"https://graph.microsoft.com/v1.0/teamsTemplates('standard')",
"displayName":"My Sample Team555",
"description":"My Sample Team’s Description555",
"members":[
{
"#odata.type":"#microsoft.graph.aadUserConversationMember",
"roles":[
"owner"
],
"userId":"9xxxxxc9-f062-48e2-8ced-22xxxxx6dfce"
}
]
}

MSAL TokenAcquisition from the token stored in the file

I have saved initial usertakencache in a file. Now when I want to acquire the AcquireTokenSilent, I dont know how to use that saved token cache because all the documentation I find are used on the basis of cache but not for other memory formats.
I have searched on number of microsoft MSAL repos but they do not provide any help with the solution.
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = null;
StreamReader sr = new StreamReader("D:\\Test.txt");
string line = sr.ReadLine();
var accounts = await app.GetAccountsAsync();
string[] scopes = { "Mail.Read" };
try
{
// try to get token silently
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync().ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
ViewBag.Relogin = "true";
return View();
}
catch (Exception eee)
{
ViewBag.Error = "An error has occurred. Details: " + eee.Message;
return View();
}
if (result != null)
{
// Use the token to read email
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me/messages");
string rez = await hrm.Content.ReadAsStringAsync();
ViewBag.Message = rez;
}

HTTP request on Zeppelin

is there any way to make an HTTP request inside a Zeppelin paragraph? e.g.
function get_app_name(){
//var xmlHttp = new XMLHttpRequest();
//xmlHttp.open( "GET", "https://example.com/application/key", true, 'username', 'password');
//xmlHttp.send( null );
URL url = new URL("https://example.com/application/key");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
}
I cannot import any of the resources (e.g. URL) because the interpreter doesn't allow it (mongodb interpreter). Is there any way to make a simple GET request in Zeppelin? I'm trying to fetch data for my tables that is not in the specified db as the other elements.
From HTTP request inside MongoDB
%mongodb
function wget(url){
var tmp = "/tmp";
var id = new ObjectId();
var outFile= tmp+"/wget"+id;
var p = run("wget", "--user=user", "--password=password", "-o log", "--output-document="+outFile,url);
if (p==0){
var result = cat(outFile);
removeFile(outFile);
return result;
} else {
return "";
}
}
url = "https://exampleurl.com/resource"
result = wget(url)
print(result)

Web API 2, return string as a file

I have a Web API 2 POST endpoint which takes a parameter, queries the database and returns an xml string as the response.
public async Task<IHttpActionResult> Post(long groupId)
{
People people = await _someService.GetPeople(groupId);
XElement peopleXml = _xmlService.ConverToXml(people);
return Ok(peopleXml);
}
How do I to return the xml as a file instead?
Figured it out myself, but I hope there is a simpler way -
public async Task<IHttpActionResult> Post(long groupId)
{
People people = await _someService.GetPeople(groupId);
XElement peopleXml = _xmlService.ConverToXml(people);
byte[] toBytes = Encoding.Unicode.GetBytes(peopleXml.ToString());
var stream = new MemoryStream(toBytes);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.txt"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
var response = ResponseMessage(result);
return response;
}

Missing credential from request in OOB application

I'm writing a simple Silverlight application in which I have the following code, which I think is pretty standard:
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
var request = new WebClient();
var cred = new NetworkCredential(Server.UserName, Server.Password);
request.Credentials = cred;
request.UseDefaultCredentials = false;
request.DownloadStringCompleted += TestServerCompleted;
var uri = new Uri(Server.GetRequestUrl(Methods.ping));
request.DownloadStringAsync(uri);
Yet when I view the request in Fiddler, no credentials are added to the headers. What am I missing? Shouldn't there be an "Authorization: Basic ..." header in there?
Try with something like this.
HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.UseDefaultCredentials = false;
req.Credentials = ew NetworkCredential(Server.UserName, Server.Passwor
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
return req;
req.BeginGetResponse((IAsyncResult asynchronousResultResponse) =>
{
try
{
HttpWebRequest requestResponse = (HttpWebRequest)asynchronousResultResponse.AsyncState;
HttpWebResponse response = (HttpWebResponse)requestResponse.EndGetResponse(asynchronousResultResponse);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//Your response is here in responseString
streamResponse.Close();
streamRead.Close();
response.Close();
}
catch (Exception e)
{
Callback(null, e);
}
}, webRequest);
I Hope it can help, even 2 months later...

Resources