Download attachments from Yammer - yammer

I am using Web Client to download yammer attachments i tried to use all different URL's available by yammer API / browser :
-download URL
-large preview URL
-right click and copy image URL
file is downloaded with 0 bytes
any suggestion ?

to download Yammer attachments you need both Download URl and Access token as below
string Path = #"C:\SocialMediaDownloads\Yammer\Attachments\"+MessageId;
bool isExists = System.IO.Directory.Exists(Path);
if (!isExists)
System.IO.Directory.CreateDirectory(Path);
WebClient client = new WebClient();
client.BaseAddress = "https://www.yammer.com";
client.Headers["Authorization"] = "Bearer " + accessToken;
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadFileAsync(new Uri(URL),Path+#"\"+FileName);
return Path;
}

Related

Login to web server with Google Sign-in

I'm connecting to a 3rd party web server from an HTTP client (Java or Dart - Android app) to download some resources (XML or IMG files) that belong to the current user on that server. This site requires login with Google Sing-In. I have everything set up in my Android app to login the user with Google, I obtained their authorization idToken. But how do actually use it in HTTP GET or POST methods to download the protected resources?
With BASIC authentication it's easy - just set HTTP 'Authorization' header correctly ("Basic " + user:password encoded as base64), call GET, and I download the desired resource. But I cannot find any information on how to do this with Google Sing-In. Do I send the idToken I received from Google in some headers? What other magic is needed?
Adding a Java code snippet, hope it helps:
// (Receive authCode via HTTPS POST)
if (request.getHeader('X-Requested-With') == null) {
// Without the `X-Requested-With` header, this request could be forged. Aborts.
}
// Set path to the Web application client_secret_*.json file you downloaded from the
// Google API Console: https://console.developers.google.com/apis/credentials
// You can also find your Web application client ID and client secret from the
// console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest
// object.
String CLIENT_SECRET_FILE = "/path/to/client_secret.json";
// Exchange auth code for access token
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
"https://www.googleapis.com/oauth2/v4/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
authCode,
REDIRECT_URI) // Specify the same redirect URI that you use with your web
// app. If you don't have a web version of your app, you can
// specify an empty string.
.execute();
String accessToken = tokenResponse.getAccessToken();
// Use access token to call API
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
Drive drive =
new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)
.setApplicationName("Auth Code Exchange Demo")
.build();
File file = drive.files().get("appfolder").execute();
// Get profile info from ID token
GoogleIdToken idToken = tokenResponse.parseIdToken();
GoogleIdToken.Payload payload = idToken.getPayload();
String userId = payload.getSubject(); // Use this value as a key to identify a user.
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
For detailed info, find all the required steps and references at: https://developers.google.com/identity/sign-in/web/server-side-flow#step_1_create_a_client_id_and_client_secret

Call a webapi control to return pdf, but with headers

How to retrieve a PDF using WebBrowser or WebClient in .NET?
I have a similar request to the one above, But I want this to be that download window or automatically download the file and show up at the bottom of the browser.
I need it to be able to send headers in the request (self made/read headers). How can I have a redirect to a page, that will download the file and not automatically save?
SetupWebClient is me setting up the headers I need....
WebClient wc = new WebClient();
wc = this.SetupWebClient(wc);
wc.DownloadData(http://www.testurl.com/PdfController/GetDocumentPDF/" + customerdocument.DocumentId + "/" + customerdocument.CustomerId);
Here is what I had to do, if someone else runs into this....had to hijack the stream, and do the following:
.....
Stream pdfFileStream = wc.OpenRead(url)
{
//Override stream
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=bylaws.pdf");
pdfFileStream.CopyTo(System.Web.HttpContext.Current.Response.OutputStream);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.SuppressContent = true;
System.Web.HttpContext.Current.Response.OutputStream.Flush();
System.Web.HttpContext.Current.Response.OutputStream.Close();
System.Web.HttpContext.Current.Response.End();
}

Integrating Yammer gives me 401 error

I am trying to integrate Yammer with our website. Eg: Displaying posts from yammer and show in our page and also the user can post from the website and it will be displayed on yammer website.
When I click "Sign in with Yammer" and it is authorized am I am getting access_token value. I saved that token in a session variable to use it for further data to retrieve.
I want to display posts for the signed in user in another button click event.
I use following endpoint to get the messages. But in webrequest I am getting 401 error (Unauthorized).What can be the reason. Please help.
Below is the code:
public void getmessages()
{
string endPoint = "https://www.yammer.com/api/v1/messages.json?access_token="+Session["accesstoken"].ToString()+"";
HttpWebRequest webrequest = WebRequest.Create(endPoint) as HttpWebRequest;
webrequest.Method = "GET";
string result = null;
using (HttpWebResponse resp = webrequest.GetResponse()
as HttpWebResponse)
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
}
Add yammer access token to Authorization Bearer to web request.
HttpWebRequest webrequest = WebRequest.Create(endPoint) as HttpWebRequest;
webrequest.Headers.Add("Authorization", "Bearer" + " " + Session["accesstoken"].ToString());

How to Get OAuth Access Token for Pinterest?

I am accessing Pinterest API for getting user's information by using this url but I can not find that how to generate an access token for Pinterest.
According to this blog post, it says that
Pinterest uses OAuth2 to authenticate users
Can you please tell me, from where I can generate OAuth access tokens for Pinterest?
First, register for an app and set up a redirect URI:
https://developers.pinterest.com/manage/
Then, find your client secret under Signature Tester:
https://developers.pinterest.com/tools/signature/
Bring the user to the OAuth dialog like this:
https://www.pinterest.com/oauth/?consumer_id=[client_id]&response_type=[code_or_token]&scope=[list_of_scopes]
If response type if token, it will be appended as a hash in the redirect URI.
If response type is code, see the post below for details on how to exchange code for token:
What's the auth code endpoint in Pinterest?
You need to register a client app under manager Apps option in Dropdown menu when you login
or
https://developers.pinterest.com/manage/
Register your app and you get AppID.
This follow the process in this link you have
http://wiki.gic.mx/pinterest-developers/
Hope this helps
**USING C#**
public string GetOAuthToken(string data)
{
string strResult = string.Empty;
try
{
string Clientid = WebConfigurationManager.AppSettings["Pinterest_Clientid"];
string ClientSecret = WebConfigurationManager.AppSettings["Pinterest_ClientSecret"];
string uri_token = WebConfigurationManager.AppSettings["Pinterest_Uri_Token"];
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri_token);
string parameters = "grant_type=authorization_code"
+ "&client_id="
+ Clientid
+ "&client_secret="
+ ClientSecret
+ "&code="
+ data;
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
System.IO.Stream os = null;
req.ContentLength = bytes.Length;
os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
System.Net.WebResponse webResponse = req.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string response = reader.ReadToEnd();
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(response);
strResult = "SUCCESS:" + o["access_token"].ToString();
}
catch (Exception ex)
{
strResult = "ERROR:" + ex.Message.ToString();
}
return strResult;
}
Refer
Pinterest uses the User Flow or Oauth2
When you have an app you ant to use the app flow with an access token
So you need to create the flow yourself or use this tool online
https://frederik.today/codehelper/tools/oauth-access-token-pinterest
To make it yourself
Request Token
Exchange code for Acces Token
https://developers.pinterest.com/docs/api/v5/

Using BackgroundTransferRequest for uploading to Photos to Facebook with Graph API

I am trying to upload photos form Windows phone (mango) to facebook with BackgroundTransferRequest object. This is because I want to upload photos even if the app is not running.
I am using facebook C# SDK to get access token etc and which works great but to upload using this, we need to keep the APP active.
I can use fiddler and create a Post request with access token and upload the image to facebook to a album.
https://graph.facebook.com/178040612256938/Photos/?access_token=AAACEdEose0cBAA4p0Ozqj0H39RP2tGyxdq0LAxoADyBZCPgjgrXMwU93VAOVkulemC3ZC5lVZCTiJ3rYeFXtM67tYNEZBvPQmasbT9AvX
Now, here is my code that I took off of sample here - http://msdn.microsoft.com/en-us/library/hh202959(v=vs.92).aspx
I am not sure how to add headers that fiddler adds OR how to use this for uploading photos to FB. getting 400 as response. Currently the following code can upload photo to my WCF service.
also looked at - BackgroundTransferRequest WP7
IsolatedStorageFileExtensions.SavePicture(Path.Combine(TransfersFiles, picture.FileName), picture.Data);
string fbURL = #"https://graph.facebook.com/106216062727932/Photos/?access_token=AAACEdEose0cBAA4p0Ozqj0H39RP2tGyxdq0LAxoADyBZCPgjgrXMwU93VAOVkulemC3ZC5lVZCTiJ3rYeFXtM67tYNEZBvPQmasbT9AvD";
var transferRequest = new BackgroundTransferRequest(new Uri(fbURL, UriKind.Absolute));
if (!_wifiOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
}
if (!_externalPowerOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
}
if (!_wifiOnly && !_externalPowerOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
}
//this is the place to upload to Facebook
transferRequest.Method = "POST";
//_OLD transferRequest.UploadLocation = new Uri(TransfersFiles + #"\" + picture.FileName, UriKind.Relative);
transferRequest.UploadLocation = new Uri(TransfersFiles + #"\" + picture.FileName, UriKind.Relative);
string boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
//---
transferRequest.TransferStatusChanged += OnTransferStatusChanged;
transferRequest.TransferProgressChanged += OnTransferProgressChanged;
BackgroundTransferService.Add(transferRequest);

Resources