I'm able to create .txt file with below code:
public void CreatFile(string filename,string filetype,string content)
{
var authenticator = new TokenProvider(clientId, clientSecret);
var oAuthToken = authenticator.RefreshAccessToken(refreshToken);
accessToken = oAuthToken.AccessToken;
// Instantiate a BoxManager with your api key and a user's auth token
var boxManager = new BoxManager(accessToken);
// Create a new file in the root folder
boxManager.CreateFile(Folder.Root, filename + filetype, Encoding.UTF8.GetBytes(content));
}
And using below i can create office documents files:
public void UploadFile(string filename,string fileType,string fileUrl)
{
try
{
var authenticator = new TokenProvider(clientId, clientSecret);
var oAuthToken = authenticator.RefreshAccessToken(refreshToken);
accessToken = oAuthToken.AccessToken;
var client = new RestClient("https://upload.box.com/api/2.0");
var request = new RestRequest("files/content", Method.POST);
request.AddParameter("parent_id", Folder.Root);
request.AddHeader("Authorization", "Bearer " + accessToken);
byte[] byteArray = System.IO.File.ReadAllBytes(fileUrl);
request.AddFile("filename", byteArray, filename + fileType);
var responses = client.Execute(request);
var content = responses.Content;
}
catch(Exception e)
{
}
}
But the same above codes is not working, for Google type documents creation.
I have gone thru many online samples, none of those helped for me.
Please.... help me, how to create Google type documents(.gdoc, .gsheet) in Box.com using Box SDK.
It's not possible to create a Google document through the Box API. It is possible to do this through the Box web app.
Related
I need to read the gmail inbox feed using Oauth2.0. Simulating in the postman,
Auth URL : https://accounts.google.com/o/oauth2/auth
Access Token URL : https://accounts.google.com/o/oauth2/token
Client ID : XXXXX.apps.googleusercontent.com
Client Secret : XXXXX
Scope : https://mail.google.com/mail/feed/atom
GrantType: Authorization Code
I requested the token and used it on the header
Authorization - Bearer XXXXXXXXXX.
And I made the request via GET right in my scope and got my email feeds. Works!!!
The postman generates a code in C #, but the token expires.
var client = new RestClient("https://mail.google.com/mail/feed/atom/");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "d48cac24-bd3e-07b5-c616-XXXXXXXX");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Bearer ya29.a0AfH6SMDZlUmw0xLHAoYIJuIfTkXXXXXXXXQSPP17GmXT26fJEfWB9w8UiwQ2YF32-nOp6zY9H_lwJEEXXXXXXXXXXXYK4e0tcZkieGbBl5Eow2M-7Gxp20kfDtXXXXXVjiXymLXyMkYEI");
IRestResponse response = client.Execute(request);
I'm trying to do it via Google.Api, using GoogleAuthorizationCodeFlow and already using token refresh.
With the code below, I got authorization from the application, but I can't read the xml atom feed
GoogleAuthorizationCodeFlow flow;
var assembly = Assembly.GetExecutingAssembly();
var clientfile = #"client_secrets.json";
using (var stream = new FileStream(clientfile, FileMode.Open, FileAccess.Read))
{
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore("StoreTest"),
ClientSecretsStream = stream,
Scopes = new[] { "https://mail.google.com/mail/feed/atom/" }
});
}
var uri = Request.Url.ToString();
var code = Request["code"];
if (code != null)
{
var token = flow.ExchangeCodeForTokenAsync(UserId, code,
uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
// Extract the right state.
var oauthState = AuthWebUtility.ExtracRedirectFromState(
flow.DataStore, UserId, Request["state"]).Result;
Response.Redirect(oauthState);
}
else
{
var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
CancellationToken.None).Result;
if (result.RedirectUri != null)
{
// Redirect the user to the authorization server.
Response.Redirect(result.RedirectUri);
}
else
{
// The data store contains the user credential, so the user has been already authenticated.
var gmailfeed = new GmailService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "GetFeed",
});
var inboxlistRequest = gmailfeed.Users.Messages.List("me");
inboxlistRequest.LabelIds = "Label_19780355190759038";
inboxlistRequest.IncludeSpamTrash = false;
var emailListResponse = inboxlistRequest.Execute();
foreach (var mail in emailListResponse.Messages)
{
var mailId = mail.Id;
var threadId = mail.ThreadId;
Message message = gmailfeed.Users.Messages.Get("me", mailId).Execute();
Console.WriteLine((message.Snippet));
}
}
}
I got to read the email, but I need the xml atom feed.
Could someone help me how I make this call to get the atom feed, using the granted token. If there is an easier way to do it too, it would be cool to share.
Thank you
Resolved using respsharp, restclient!!
tks
I am trying to read an email attachment using Microsoft Graph API(v2) but I am getting "Object reference not set to an instance" error
I have verified the app permissions in Azure Active Directory and has all the permissions set mentioned in microsoft documentation
Mail.Read
Group.Read.All (Added extra permission to try)
I am able to read the message and its content correctly and even the message "HasAttachments" property is true but when I call API again to fetch attachments it gives error.
Also tried to create new token for fetching attachments considering the fact that existing one would have expired but no luck
OutlookServicesClient client = new OutlookServicesClient(new Uri(OutlookAPI), GetAccessToken);
client.Context.SendingRequest2 +=
new EventHandler<Microsoft.OData.Client.SendingRequest2EventArgs>((sender, e) => InsertXAnchorMailboxHeader(sender, e, userEmail));
var attachments = await client.Me.MailFolders.GetById(constInbox).Messages.GetById(strMessageID).Attachments.ExecuteAsync();
public async Task<string> GetAccessToken()
{
string accessToken = null;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(TokenUri);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var requestContent = string.Format("grant_type=password" + "&client_id=" + appId +
"&client_secret=" + appPassword +
"&resource=" + Resource +
"&username=" + userEmail +
"&password=" + passwd);
var content = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = client.PostAsync(client.BaseAddress, content).Result;
var result = response.Content.ReadAsStringAsync().Result;
var jobject = JsonConvert.DeserializeObject<JObject>(result);
accessToken = jobject.GetValue("access_token").ToString();
}
return accessToken;
}
Attaching Quickwatch for client.Kindly check
How can I get ID Token from custom token?
[Fact]
public void Get_ID_Token_For_Service_Account_Test()
{
using (Stream stream = new FileStream(ServiceAccountJsonKeyFilePath, FileMode.Open, FileAccess.Read))
{
ServiceAccountCredential credential = ServiceAccountCredential.FromServiceAccountData(stream);
FirebaseApp.Create(new AppOptions
{
Credential = GoogleCredential.FromServiceAccountCredential(credential),
ServiceAccountId = ServiceAccountId,
});
var uid = "Some UID";
var additionalClaims = new Dictionary<string, object>
{
{"dmitry", "pavlov"}
};
string customToken = FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid, additionalClaims).Result;
string idToken= null; // How to get this?
FirebaseToken token = FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken, CancellationToken.None).Result;
Assert.NotNull(token);
Assert.True(token.Claims.ContainsKey("dmitry"));
}
}
I see samples for some other languages/platforms but not for C# - how to get ID token via current user here - Retrieve ID tokens on clients. But for C# neither UserRecord nor FirebaseAuth provides ID Token. Any pointers are much appreciated.
I have found the way to get the ID token in FirebaseAdmin integration tests - see method SignInWithCustomTokenAsync. The only thing I have to adjust was base URL: according to Firebase Auth REST API documentation it should be
https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken
The API KEY refers to the Web API Key, which can be obtained on the project settings page in your admin console.
So the adjusted code looks like this:
private static async Task<string> SignInWithCustomTokenAsync(string customToken)
{
string apiKey = "..."; // see above where to get it.
var rb = new Google.Apis.Requests.RequestBuilder
{
Method = Google.Apis.Http.HttpConsts.Post,
BaseUri = new Uri($"https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken")
};
rb.AddParameter(RequestParameterType.Query, "key", apiKey);
var request = rb.CreateRequest();
var jsonSerializer = Google.Apis.Json.NewtonsoftJsonSerializer.Instance;
var payload = jsonSerializer.Serialize(new SignInRequest
{
CustomToken = customToken,
ReturnSecureToken = true,
});
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var parsed = jsonSerializer.Deserialize<SignInResponse>(json);
return parsed.IdToken;
}
}
I am trying to upload a file to following the API information in this service. Easy Post API.
I am able to successfully send the first GET request with Digest authentication.
I'm getting a 403 - Unauthorized when trying to upload the file with 'PUT'.
This is the code I have. I am using a custom web client to set parameters in the web request.
public class CustomWebClient : WebClient
{
private BingMailConfigOptions ConfigOptions;
public CustomWebClient(BingMailConfigOptions configOptions) : base()
{
ConfigOptions = configOptions;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.ServicePoint.Expect100Continue = false;
request.Method = "PUT";
request.Credentials = GetCredentialCache(address, ConfigOptions);
return request;
}
public static CredentialCache GetCredentialCache(Uri uri, BingMailConfigOptions options)
{
var credentialCache = new CredentialCache
{
{
new Uri(uri.GetLeftPart(UriPartial.Authority)),
"Digest",
new NetworkCredential(options.AuthUserName, options.AuthPassword, uri.GetLeftPart(UriPartial.Authority))
}
};
return credentialCache;
}
}
// in a separate class.
private void Upload(string sessionId, string filePath)
{
_log.Trace("Trying to upload the file: " + filePath);
var file = new FileInfo(filePath);
if (file.Exists)
{
using (var uploader = new CustomWebClient(ConfigOptions))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
Uri uri = new Uri("https://bingmail.com.au/" + "direct_upload/{0}/{1}"(sessionId, HttpUtility.UrlEncode(file.Name)));
uploader.UploadFile(uri, "PUT", filePath);
}
}
else
{
throw new Exception("File Not found");
}
}
Can you please tell me what I'm doing wrong or point me in the right direction?
Thanks
I finally figured out a solution. Hope it will help someone someday.
Complete solution except some easy-to-figure-out methods are posted in this gist. Bing-Mail Easy Post Api - Version 1.3
What i did was modified the DigestAuthFixer from https://stackoverflow.com/a/3117042/959245 to support any HTTP method.
Then used that to create the session, when we create the session using DigestAuthFixer it stores the Digest-Auth headers which i can reuse when uploading the files.
using (var client = new WebClient())
{
var uri = new Uri(_easypostHosts[2] + UploadUri.FormatWith(sessionId, HttpUtility.UrlEncode(fileName)));
// get the auth headers which are already stored when we create the session
var digestHeader = DigestAuthFixer.GetDigestHeader(uri.PathAndQuery, "PUT");
// add the auth header to our web client
client.Headers.Add("Authorization", digestHeader);
// trying to use the UploadFile() method doesn't work in this case. so we get the bytes and upload data directly
byte[] fileBytes = File.ReadAllBytes(filePath);
// as a PUT request
var result = client.UploadData(uri, "PUT", fileBytes);
// result is also a byte[].
content = result.Length.ToString();
}
I am developing social networks integration for my asp.net mvc4 application.
Twitter and Facebook were very easy for me but I am seriously stuck with LinkedIn.
Here is my code.
public ActionResult LinkedInTest(string text)
{
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials()
};
var request = new RestRequest {Path = "requestToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
textToPost = text;
Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus");
return null;
textToPost = text;
return RedirectToAction("LinkedInCallback");
}
public ActionResult LinkedInCallback()
{
verifier = Request["oauth_verifier"];
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials(token, tokenSecret, verifier),
Method = WebMethod.Post
};
var request = new RestRequest {Path = "accessToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
LinkedInSocialHelper.Post(textToPost, token, tokenSecret);
return RedirectToAction("Calendar");
}
public static void Post(string text, string accessToken, string accessTokenSecret)
{
var tokenManager = new TokenManager(ApiKey, ApiSecret);
tokenManager.ExpireRequestTokenAndStoreNewAccessToken(null, null, accessToken, accessTokenSecret);
var authorization = new WebOAuthAuthorization(tokenManager, UserToken);
LinkedInService service = new LinkedInService(authorization);
//var user = service.GetCurrentUser(ProfileType.Public); - IT IS GIVING ME THE SAME ERROR - Access denied
service.CreateShare(text, VisibilityCode.ConnectionsOnly);
}
Everything works fine except last thing - posting shares - I get Access to posting shares denied exception despite the fact that I generate token using all the necessary permissions:
"https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus"
Hope you good guys help me.
See the last post here - it describes how to solve it
https://developer.linkedin.com/forum/permission-scope-request-token-query-not-working?page=1