Post to and display web page from Silverlight - silverlight

I want to post to a web page from my Silverlight application and have the web page appear in a new window.
I can show a web page in a new window using the GET method, using the following code:
var options = new HtmlPopupWindowOptions();
HtmlPage.PopupWindow(new Uri("http://localhost:12345/test.aspx"), "_blank", options);
I can post to a web page and get the resulting data back using this code:
var request = (HttpWebRequest)WebRequest.Create(new Uri("http://localhost:12345/test.aspx"));
request.Method = "POST";
request.ContentType = "text/xml";
request.BeginGetRequestStream(requestResult =>
{
using (var stream = request.EndGetRequestStream(requestResult))
{
using (var writer = new StreamWriter(stream))
{
writer.Write("hello");
}
}
request.BeginGetResponse(responseResult =>
{
var response = request.EndGetResponse(responseResult);
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var str = reader.ReadToEnd();
}
}
}, null);
}, null);
But what I can't do is the two together - post to the page but instead of getting the data back have the resulting page shown in a browser window. I don't know if this is possible, but any help to achieve this would be much appreciated.

Related

Listen for callbacks in dotNetBrowser

How can I use dotnetbrowser doing the following in a winform application?
Create a listener that listen for callbacks to a specific redirect url.
Open url in dotnetbrowser. The url makes the callback to the redirect url in another thread
The listener catches the response from the callback.
I can do this with an ordinary webbrowser, but I would like it to be silent. That's why I try to use dotnetbrowser instead.
Is dotNetBrowser a good choice for this, or is there a better option?
This is from my test code with a non silent webbrowser. First I create a listener that listen to a redirectUri:
var listener = new HttpListener();
listener.Prefixes.Add(redirectURI);
listener.Start();
Then I start the url in a webbrowser:
Process p = Process.Start(url);
The started url will send a callback to the redirectUri. The listener will get it.
var context = await listener.GetContextAsync(); ;
string formData = string.Empty;
using (var body = context.Request.InputStream)
{
using (var reader = new System.IO.StreamReader(body, context.Request.ContentEncoding))
{
formData = reader.ReadToEnd();
}
}
listener.Close();
I found a solution with help from dotnetbrowser support site.
This is the winform constructor in my new test project:
public Form1()
{
webView = new BrowserView() { Dock = DockStyle.Fill };
Task.Run(() =>
{
engine = EngineFactory.Create(new EngineOptions.Builder
{
RenderingMode = RenderingMode.HardwareAccelerated,
LicenseKey = "your license key here"
}
.Build());
browser = engine.CreateBrowser();
})
.ContinueWith(t =>
{
webView.InitializeFrom(browser);
var listener = new HttpListener();
listener.Prefixes.Add(redirectURI);
listener.Start();
browser.Navigation.LoadUrl(url);
var context = listener.GetContextAsync().GetAwaiter().GetResult();
//Get data from redirectUri. You find this code from test example above, but not really relevant for the problem.
var formData = GetRequestPostData(context.Request);
listener.Close();
}, TaskScheduler.FromCurrentSynchronizationContext());
InitializeComponent();
FormClosing += Form1_FormClosing;
Controls.Add(webView);
this.Visible = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
browser?.Dispose();
engine?.Dispose();
}

401 When passing the token using graphic onenote api

I am new to Microsoft graph so this might be a dumb question.
So I am writing a command line application trying to update a page in our team onenote. (enterprise onenote)
Here is the code I got work getting the token.
https://login.microsoftonline.com/common/oauth2/authorize?client_id=my_client_Id&response_type=code&redirect_uri=Some_uri&resource=https://graph.microsoft.com&scope=Notes.ReadWrite.All
I got the token as strCode and trying to retrieve all the notes under this account by these codes:
var baseAddress = new Uri("https://graph.microsoft.com/v1.0/me/onenote");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
var request = new HttpRequestMessage(HttpMethod.Get, #"/pages");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", strCode);
using (var response = httpClient.SendAsync(request).Result)
{
string responseData = response.Content.ReadAsStringAsync().Result;
}
}
And in the response data I got
"{ \"error\": { \"code\": \"InvalidAuthenticationToken\", \"message\": \"CompactToken parsing failed with error code: -2147184105\", \"innerError\": { \"request-id\": \"*********************", \"date\": \"2017-06-08T18:25:06\" } } }"
Any idea how to fix this..?
Problem resolved .
I need to convert the authentication code into a "real" access token..
The one that I got is not an access token.

Get user profile pic from O365 - microsoft graph api

I have tried to get user profile pic from O365 using Microsoft Graph API. When I used following API it returns only the metadata related to the profile pic.
https://graph.microsoft.com/beta/me/photo
Through https://graph.microsoft.com/beta/me/photo/$value returns a gibberish object which doesn't make any sense. However, I believe that it is the data related to the user profile. Need help to extract those data into base64.
The returned data is the binary data of the image type. If you use JavaScript to retrieve the user photo, please get the photo data as blob type in a XMLHttpRequest, and then retrieve the blob URL from the response. For your reference:
var request = new XMLHttpRequest;
var photoUri=config.endpoints.graphApiUri + "/v1.0/me/photo/$value";
request.open("GET",photoUri);
request.setRequestHeader("Authorization","Bearer "+token);
request.responseType = "blob";
request.onload = function (){
if(request.readyState == 4 && request.status == 200){
var image = document.createElement("img");
var url = window.URL || window.webkitURL;
var blobUrl = url.createObjectURL(request.response);
image.src = blobUrl;
document.getElementById("UserShow").appendChild(image);
}
};
request.send(null);
For making that photo viewable in view we have to convert the response in 64 byte.
I have make this done in by project by below code. Hope this answer useful for someone..
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
using (FileStream fs = new FileStream(#"D:\image.jpg", FileMode.Create))
{
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
responseStream.Close();
}
}

Web api large file download with HttpClient

I have a problem with large file download from the web api to the win forms app. On the win form app I'm using HttpClient for grabbing data. I have following code on server side:
[HttpPost]
[Route]
public async Task<HttpResponseMessage> GetBackup(BackupRequestModel request)
{
HttpResponseMessage response;
try
{
response = await Task.Run<HttpResponseMessage>(() =>
{
var directory = new DirectoryInfo(request.Path);
var files = directory.GetFiles();
var lastCreatedFile = files.OrderByDescending(f => f.CreationTime).FirstOrDefault();
var filestream = lastCreatedFile.OpenRead();
var fileResponse = new HttpResponseMessage(HttpStatusCode.OK);
fileResponse.Content = new StreamContent(filestream);
fileResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return fileResponse;
});
}
catch (Exception e)
{
logger.Error(e);
response = Request.CreateResponse(HttpStatusCode.InternalServerError);
}
return response;
}
on client side:
private async void btnStart_Click(object sender, EventArgs e)
{
var requestModel = new BackupRequestModel();
requestModel.Username = txtUsername.Text;
requestModel.Password = txtPassword.Text;
requestModel.Path = txtServerPath.Text;
var client = new HttpClient();
var result = await client.PostAsJsonAsync("http://localhost:50116/api/backup", requestModel);
var stream = await result.Content.ReadAsStreamAsync();
var localPath = #"d:\test\filenew.bak";
var fileStream = File.Create(localPath);
stream.CopyTo(fileStream);
fileStream.Close();
stream.Close();
fileStream.Dispose();
stream.Dispose();
client.Dispose();
}
}
This is actually working, but the purpose of this program is to grab large files over 3GB and save it to the client.
I have tried this on files sized 630MB what I notice is: When I call web api with http client, http client actually loads 630MB in the memory stream, and from the memory stream to the file stream, but when I try to load a different file I'm getting OutOfMemoryException. This is happening because the application doesn't release memory from the previous loaded file. I can see in task manager that it is holding 635MB of ram memory.
My question is how can I write data directly from HttpClient to file without using memory stream, or in other words how can I write data to file while HttpClient is downloading data?
To make the request, use a SendAsync overload that allows you to specify a HttpCompletionOption and use ResponseHeadersRead. You'll have to manually build the request though, without using the PostAsJsonAsync convenience method.

Facebook Album Picture using Facebook C# SDK

I'm tring to get an album picture from facebook using the facebook C# SDK within Silverlight app with the following code:
FacebookClient client = new FacebookClient(this.Profile.AccessToken);
client.GetAsync(string.Format("/{0}/picture?type=small", this.ID));
client.GetCompleted += (s, e) =>
{
dynamic result = e;
};
Where this.ID is the ID of the album, but I get this error:
Unexpected character encountered while parsing value: �. Line 1, position 1.
from the DeserializeObject method in the JsonSerializer. The problem is that facebook does'n return json data with the imge uri or something like this, but they actually return the image itself in a binary data. Anybody has any idea how I can handle this result or just get Uri to the image?
I have a workaround for this using this code:
var request = WebRequest.Create(string.Format("https://graph.facebook.com/{0}/picture?access_token={1}", this.ID, this.Profile.AccessToken));
request.BeginGetResponse(ar =>
{
using (var response = ((WebRequest)ar.AsyncState).EndGetResponse(ar))
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.Picture = new BitmapImage(new Uri(response.ResponseUri.AbsoluteUri));
}
);
}
}, request);
But I really wanted to use only Facebook C# SDK for getting the data.
Here is the solution that I'm going to use:
FacebookClient client = new FacebookClient(this.Profile.AccessToken);
client.QueryAsync(String.Format("SELECT src_small, src_big, src FROM photo WHERE pid IN (SELECT cover_pid FROM album WHERE object_id={0})", this.ID));
client.GetCompleted += (s, e) =>
{
dynamic result = e.GetResultData();
Deployment.Current.Dispatcher.BeginInvoke(() => this.Picture = result[0].src_small);
};
I was facing a similar issue. Wanted to use Facebook C# SDK only as well.
Solved it like this:
FacebookClient facebookAlbumClient = new FacebookClient(_albumAccessToken);
dynamic facebookAlbumCover = facebookAlbumClient.Get(string.Format("/{0}?fields=picture&type=thumbnail", (string)facebookAlbum["id"]));
This way you are getting the json array and not the picture
I think I found an acceptable solution for my problem. I'll just use FQL instead of Graph API. This will do the job:
FacebookClient client = new FacebookClient(this.Profile.AccessToken);
client.QueryAsync(String.Format("SELECT src_small, src_big, src FROM photo WHERE pid IN (SELECT cover_pid FROM album WHERE object_id={0})", this.ID));
client.GetCompleted += (s, e) =>
{
dynamic result = e.GetResultData();
Deployment.Current.Dispatcher.BeginInvoke(() => this.Picture = result[0].src_small);
};

Resources