Box API Create Shared link - c#

I am trying to upload some documents to Box and create and retrieve a shared link for each of them.
This is the code I am using for it, but I always retrieve 403:access_denied_insufficient_permissions.
Any idea of why this is happening?
Hope you can help me! Thanks.
// CREATE THE FILE
BoxFileRequest req = new BoxFileRequest
{
Name = zipFile.Name,
Parent = new BoxRequestEntity { Id = newFolder.Id}
};
BoxFile uploadedFile = client.FilesManager.UploadAsync(req, stream).Result;
//REQUEST SHARED LINK
BoxSharedLinkRequest sharedLinkReq = new BoxSharedLinkRequest()
{
Access = BoxSharedLinkAccessType.open,
Permissions = new BoxPermissionsRequest
{
Download = BoxPermissionType.Open,
Preview = BoxPermissionType.Open,
}
};
BoxFile fileLink = fileManager.CreateSharedLinkAsync(uploadedFile.Id, sharedLinkReq).Result;

you need to give the access token and url. I have use the Following code and in JSON Format you will get the Response. For more reference check the box API document
HttpWebRequest httpWReq = HttpWebRequest)WebRequest.Create("https://api.box.com/2.0/folders/" + FolderID);
ASCIIEncoding encoding = new ASCIIEncoding();
string putData = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] data = encoding.GetBytes(putData);
httpWReq.Method = "PUT";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
Use the httpwebrequest PUT method after this.
Mark it as Answer if its helpful.

It looks as if you are using the 3rd party BoxSync V2 API object. If you would like to just code to the API directly I had a similar issue that you are having. If you view this post you will see the answer. Here is the code I use and it works.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;

Related

Get GitHub Rest API User info C# code

https://api.github.com/users/[UserName] can be accessed via browser. I get a Json result. But I want to retrieve the same information programmatically.
I'm using the below code, which is not working as expected. Please advice.
var credentials =
string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:",
githubToken);
credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic", credentials);
var contents =
client.GetStreamAsync("https://api.github.com/users/[userName]").Result;
As a result of the above code, I'm getting "Aggregate Exception".
How to achieve the requirement using c# code??? Please help
Note: Not expecting a solution with Octokit. Need proper c# code.
I found the solution. Here is the code.
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.UserAgent = "Anything";
webRequest.ServicePoint.Expect100Continue = false;
try
{
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
string reader = responseReader.ReadToEnd();
var jsonobj = JsonConvert.DeserializeObject(reader)
}
}
catch
{
return;
}
}

Can't create workitem via webrequest in RTC

I'm trying to create a .NET web application integration with RTC, where I would insert new workitems using RTC change management services, as defined in this article (specifically in "Create a Change Request"). I was able to get the URL-to-be-used inside services.xml file (/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/) and my goal is to insert data using JSON.
My code is basically the following:
CookieContainer cookies = new CookieContainer();
HttpWebRequest documentPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/order");//"Order" is the workitem name
documentPost.Method = "POST";
documentPost.CookieContainer = cookies;
documentPost.Accept = "application/json";
documentPost.ContentType = "application/x-oslc-cm-change-request+json";
documentPost.Timeout = TIMEOUT_SERVICO;
string json = "{ \"dc:title\":\"" + title + "\", \"rtc_cm:filedAgainst\": [ { \"rdf:resource\" : \"" + rtcServerUrl + "/resource/itemOid/com.ibm.team.workitem.Category/" + idCategory + "\"} ] }"; //dc:title and rtc_cm:filedAgainst are the only two mandatory data from the workitem I'm trying to create
using (var writer = new StreamWriter(documentPost.GetRequestStream()))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Encoding encode = System.Text.Encoding.UTF8;
string retorno = null;
//Login
HttpWebRequest formPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/j_security_check");
formPost.Method = "POST";
formPost.Timeout = TIMEOUT_REQUEST;
formPost.CookieContainer = request.CookieContainer;
formPost.Accept = "text/xml";
formPost.ContentType = "application/x-www-form-urlencoded";
String authString = "j_username=" + userName + "&j_password=" + password; //create authentication string
Byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes(authString); //store in byte buffer
formPost.ContentLength = outBuffer.Length;
System.IO.Stream str = formPost.GetRequestStream();
str.Write(outBuffer, 0, outBuffer.Length); //update form
str.Close();
//FormBasedAuth Step2:submit the login form and get the response from the server
HttpWebResponse formResponse = (HttpWebResponse)formPost.GetResponse();
var rtcAuthHeader = formResponse.Headers["X-com-ibm-team-repository-web- auth-msg"];
//check if authentication has failed
if ((rtcAuthHeader != null) && rtcAuthHeader.Equals("authfailed"))
{
//authentication failed. You can write code to handle the authentication failure.
//if (DEBUG) Console.WriteLine("Authentication Failure");
}
else
{
//login successful
HttpWebResponse responseRetorno = (HttpWebResponse)request.GetResponse();
if (responseRetorno.StatusCode != HttpStatusCode.OK)
retorno = responseRetorno.StatusDescription;
else
{
StreamReader reader = new StreamReader(responseRetorno.GetResponseStream());
retorno = "[Response] " + reader.ReadToEnd();
}
responseRetorno.Close();
formResponse.GetResponseStream().Flush();
formResponse.Close();
}
As I was managed to search for in other forums, this should be enough in order to create the workitem (I have a very similar code working to update workitems using "" URL and PUT method). However, instead of create the workitem in RTC and give me some response with item's identifier, the request's response returns a huge JSON file that ends with "oslc_cm:next":"https:///oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/%7B0%7D?oslc_cm.pageSize=50&_resultToken=_AAY50FEkEee1V4u7RUQSjA&_startIndex=50. It's a JSON representation of the XML I receive when I access /oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/ directly from browser, like I was trying to do a simple query inside the workitem's collection (even though I'm using POST, not GET).
I also tried to use PUT method, but then I receive a 405 status code.
Does anyone have an idea of what am I missing here? My approach is wrong, even though with the same approach I'm able to update existing workitem data in RTC?
Thanks in advance.

How to download the attach files in jira using C#

I'm trying to download the attach files in from jira using the jira techtalk to get the issue and attachments.
foreach (var img in issue.fields.attachment)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(img.ToString());
System.Drawing.Image attachImg = Utilities.DownloadImageFromUrl(item["content"].ToString());
if (attachImg != null) {
var sPath = Path.Combine(Server.MapPath("~/Content/Uploads/"), item["filename"].ToString());
attachImg.Save(sPath);
}
}
and in utilities.downloadimagefromurl this is the full code:
public static System.Drawing.Image DownloadImageFromUrl(string imageUrl)
{
System.Drawing.Image image = null;
try
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
webRequest.AllowWriteStreamBuffering = true;
webRequest.Timeout = 30000;
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
image = System.Drawing.Image.FromStream(stream);
webResponse.Close();
}
catch (Exception ex)
{
return null;
}
return image;
}
but gives a null return.
Anybody knows how to do this?
Thanks
I found the solution to download the attachment in jira API: I'm using tecktalk Jira Rest Client https://github.com/techtalk/JiraRestClient
Here's the code:
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(new Uri(remoteUri + "?&os_username=usernamehere&os_password=passwordhere"), dPath);
}
use your jira login username and password.
For anyone using RestSharp:
using RestSharp.Extensions;
.
Uri uri = new Uri($"http://{jira}/secure/attachment/{attachmentID.ToString()}/" +
$"?&os_username={userName}&os_password={password}");
IRestRequest request = new RestRequest(uri, Method.GET);
restClient.DownloadData(request).SaveAs($"{saveLocation}");
This really helped me. My URI was was built as:
string uri = string.Format("{0}/secure/attachmentzip/{1}.zip?&os_username={2}&os_password={3}", jira, issue.id, user, password);

Get retweets of a tweet in C# oAuthTwitterWrapper

My goal is to get all the retweet IDs of a specific tweet. I tried to use oAuthTwitterWrapper for C# twitter authentication and tried changing the code, but without any success. I am getting Forbidden message from twitter when I change the searchFormat to suit my requirement.
Someone please help!
oAuthTwitterWrapper Wrapper - https://github.com/andyhutch77/oAuthTwitterWrapper
Stack Exchange Link - Authenticate and request a user's timeline with Twitter API 1.1 oAuth
Thanks in advance..
Ok, I think this is how you would do this manually to begin with.
I have not tested it so there may be some typos, let me know and I will update it the answer accordingly.
This makes a call to the api specified here:
https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid
// You need to set your own keys and tweet id
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var tweetId = "21947795900469248";
// Do the Authenticate
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
Uri.EscapeDataString((oAuthConsumerSecret)))
));
var postBody = "grant_type=client_credentials";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream stream = authRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}
authRequest.Headers.Add("Accept-Encoding", "gzip");
WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
using (var reader = new StreamReader(authResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objectText = reader.ReadToEnd();
twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
}
}
// Get the retweets by Id
var retweetFormat = "https://api.twitter.com/1.1/statuses/retweets/{0}.json";
var retweetsUrl = string.Format(retweetFormat, tweetId);
HttpWebRequest retweetRequest = (HttpWebRequest)WebRequest.Create(retweetsUrl);
var retweetHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(retweetHeaderFormat, twitAuthResponse.token_type,
twitAuthResponse.access_token));
retweetRequest.Method = "Get";
WebResponse retweetResponse = timeLineRequest.GetResponse();
var retweetJson = string.Empty;
using (retweetResponse)
{
using (var reader = new StreamReader(retweetResponse.GetResponseStream()))
{
retweetJson = reader.ReadToEnd();
}
}
//parse the json from retweetJson to read the returned id's
public class TwitAuthenticateResponse {
public string token_type { get; set; }
public string access_token { get; set; }
}
If this works and you have time please submit a pull request via GitHub and I will include it in oauthtwitterwrapper.

Google Translate V2 cannot hanlde large text translations from C#

I've implemented C# code using the Google Translation V2 api with the GET Method.
It successfully translates small texts but when increasing the text length and it takes 1,800 characters long ( including URI parameters ) I'm getting the "URI too large" error.
Ok, I burned down all the paths and investigated the issue across multiple pages posted on Internet. All of them clearly says the GET method should be overriden to simulate a POST method ( which is meant to provide support to 5,000 character URIs ) but there is no way to find out a code example to of it.
Does anyone has any example or can provide some information?
[EDIT] Here is the code I'm using:
String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
String url = String.Format(apiUrl, Constants.apiKey, sourceLanguage, targetLanguage, text);
Stream outputStream = null;
byte[] bytes = Encoding.ASCII.GetBytes(url);
// create the http web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.KeepAlive = true;
webRequest.Method = "POST";
// Overrride the GET method as documented on Google's docu.
webRequest.Headers.Add("X-HTTP-Method-Override: GET");
webRequest.ContentType = "application/x-www-form-urlencoded";
// send POST
try
{
webRequest.ContentLength = bytes.Length;
outputStream = webRequest.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();
}
catch (HttpException e)
{
/*...*/
}
try
{
// get the response
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK && webRequest != null)
{
// read response stream
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string lista = sr.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationRootObject));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(lista));
TranslationRootObject tRootObject = (TranslationRootObject)serializer.ReadObject(stream);
string previousTranslation = string.Empty;
//deserialize
for (int i = 0; i < tRootObject.Data.Detections.Count; i++)
{
string translatedText = tRootObject.Data.Detections[i].TranslatedText.ToString();
if (i == 0)
{
text = translatedText;
}
else
{
if (!text.Contains(translatedText))
{
text = text + " " + translatedText;
}
}
}
return text;
}
}
}
catch (HttpException e)
{
/*...*/
}
return text;
}
Apparently using WebClient won't work as you cannot alter the headers as needed, per the documentation:
Note: You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).
You can use WebRequest, but you'll need to add the X-HTTP-Method-Override header:
var request = WebRequest.Create (uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-HTTP-Method-Override", "GET");
var body = new StringBuilder();
body.Append("key=SECRET");
body.AppendFormat("&source={0}", HttpUtility.UrlEncode(source));
body.AppendFormat("&target={0}", HttpUtility.UrlEncode(target));
//--
body.AppendFormat("&q={0}", HttpUtility.UrlEncode(text));
var bytes = Encoding.ASCII.GetBytes(body.ToString());
if (bytes.Length > 5120) throw new ArgumentOutOfRangeException("text");
request.ContentLength = bytes.Length;
using (var output = request.GetRequestStream())
{
output.Write(bytes, 0, bytes.Length);
}
The accepted answer appears to be out of date. You can now use the WebClient (.net 4.5) successfully to POST to the google translate API making sure to set the X-HTTP-Method-Override header.
Here is some code to show you how.
using (var webClient = new WebClient())
{
webClient.Headers.Add("X-HTTP-Method-Override", "GET");
var data = new NameValueCollection()
{
{ "key", GoogleTranslateApiKey },
{ "source", "en" },
{ "target", "fr"},
{ "q", "<p>Hello World</p>" }
};
try
{
var responseBytes = webClient.UploadValues(GoogleTranslateApiUrl, "POST", data);
var json = Encoding.UTF8.GetString(responseBytes);
var result = JsonConvert.DeserializeObject<dynamic>(json);
var translation = result.data.translations[0].translatedText;
}
catch (Exception ex)
{
loggingService.Error(ex.Message);
}
}
? What? it is trivial to post using C# - it is right there in the documentation.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
{
// Set type to POST
request.Method = "POST";
From there on you bascially put the data into fom fields into the content stream.
This is not "simulate a post meethod", it is fully doing a post request as per specifications.
Btw. hwhere does json enter here? You say "in C#". There is no need to use json?

Categories

Resources