Facebook C# SDK Post Image more than once - c#

I am uploading or Posting Image to Facebook using Facebook C# SDK but I call this function one time but it uploads the same Image three times or more. It should only upload the Image one time but it does at least three times, I am using 5.4.1 SDK.
Code is:
public void AddCover(string accessToken, string imageName, string folder, string loggedinuserId)
{
FacebookClient facebookClient = new FacebookClient(accessToken);
var fbUpl = new Facebook.FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
var bytes = System.IO.File.ReadAllBytes(#"F:\Websites\Covers\" + folder + "\\" + imageName);
fbUpl.SetValue(bytes);
var photoDetails = new Dictionary<string, object>();
photoDetails.Add("message", "Facebook Covers");
photoDetails.Add("image", fbUpl);
var response = facebookClient.Post(#"/" + loggedinuserId + "/photos", photoDetails);
var result = (IDictionary<string, object>)response;
var postedcoverId = result["id"];
}
Am I missing something here? Please see the code and tell me what I am doing wrong.
Thanks

Related

Reading Multipart Data from Xamarin

We have a requirement of sending the jpeg files of a given directory to a Xamarin App.
Following is the code in the Web API.
public HttpResponseMessage DownloadMutipleFiles()
{
name = "DirectoryName";
var content = new MultipartContent();
var ids = new List<int> { 1,2};
var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
content.Add(objectContent);
var file1Content = new StreamContent(new FileStream(#"D:\Photos\" + name+"\\"+ "BL1408037_20191031124058_0.jpg", FileMode.Open));
file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file1Content);
var file2Content = new StreamContent(new FileStream(#"D:\Photos\" + name + "\\" + "BL1408037_20191031124058_1.jpg", FileMode.Open));
file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file2Content);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = content;
return response;
}
Can some one help out with how to read from Xamarin app? Thanks in advance
This is the function I was able to use to send an image as a multi part data file! I just took the byte array given to me by the Xamarin Essentials image picker and passed it into this function:
public async Task SubmitImage(byte[] image, string imageName)
{
using (var client = new HttpClient())
{
string url = $"..."; // URL goes here
var token = Preferences.Get("AccessToken", "");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var stream = new MemoryStream(image);
var content = new StreamContent(stream);
//Without a name we can't actually put the file in IFormFile. We need the equivalent
//"name" value to be "file" (used if you upload via an <input> tag). We could call it
//anything but file is simple
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = imageName,
Name = "file"
};
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(content);
var result = await client.PostAsync(url, multipartContent);
}
}
You can test this using a console application as well and just send over a picture from your computer, instead of doing this through the app

Having issue on viewing Excl file generated by SSRS report with cube data source in ASP.net MVC Using view.officeapps.live.com/op/embed.aspx?src=url

These are the following are my requirements.
There is URL from SSRS Report which renders the report in EXCEL file
We have setup for MVC application as web app and the webapi as App server.
Since the ssrs inside the firewall the app server will connect only through Appserver. In Appserver, The report has been rendered as follows
public HttpResponseMessage GenerateLegacyReport()
{
try
{
string endTypeString = "&rs:Format=Excel";
url = url + businessSegmentFormat(businessSegment) + regionStringFormat(region) +
facilitySiteStringFormat(selectedSite) + fromDateFormat(FromDate) +
toDateFormat(ToDate) + salesPersonFormat(userName) + SortstringFormat(sortOrder) +
buildSortOrderUrl(sortByList) + groupByFormat(reportName, groupBy) + endTypeString;
//AlertMailer setalert = new AlertMailer();
//setalert.NOtifyError("Report", null, url);
if (!string.IsNullOrEmpty(url))
{
string _sessionPipelineReport = "PipelineReport" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
byte[] excelBytes = null;
using (WebClient webclient = new WebClient())
{
webclient.Credentials = CredentialCache.DefaultCredentials;
//Sample URL replaced with Actual SSRS URL
url = "https://online.utpb.edu/webapps/dur-browserCheck-bb_bb60/samples/sample.xlsx?CRMReports/CustomerProfileSummary&rs:Command=Render&BusinessSegment=%5BBusiness%20Segment%5D.%5BBUSINESS%20SEGMENT%20CODE%5D.%26%5BES%5D&Region=%5BRegion%5D.%5BREGION%20NAME%5D.%5BAll%5D&Facility=%5BFacility%5D.%5BFACILITY%20NAME%5D.%5BAll%5D&FromDate=%5BEARNED%20DATE%5D.%5BDATE%5D.%26%5B2015-01-26T00:00:00%5D&ToDate=%5BEARNED%20DATE%5D.%5BDATE%5D.%26%5B2016-01-26T00:00:00%5D&User=%5BSalesperson%5D.%5BUSERNAME%5D.%26%5BAPeterson%5D&SortOrder=Desc&SortBy=Revenue&rs:Format=Excel";
excelBytes = webclient.DownloadData(url);
}
//var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(excelBytes) };
//result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
//result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(excelBytes) };
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = _sessionPipelineReport
};
return result;
}
return Request.CreateResponse(HttpStatusCode.Gone);
}
catch (Exception ex)
{
throw new Exception("Internal Server Error. Please try again...");
}
}
And we have start reading this from Web app and render it as
Response.Redirect("https://view.officeapps.live.com/op/embed.aspx?src=" +fileURL , false);
We are able to download the report but excel file nor rendered it int he viewer.
Please suggest us the solutions are any other better online viewer (supports MVC and HTML 5)
If we get the information with any sample solution would be more appreciated :)

Dropbox API Unable to upload a file Issue while uploading

I use HigLabo.Net.Dropbox to upload a file to Dropbox. I created a App named synch and I am trying to upload a file. Below is my code
byte[] bytes = System.IO.File.ReadAllBytes(args[1]);
UploadFile(bytes,"sundas.jpg","/Apps/synch/");
public static void UploadFile(byte[] content, string filename, string target)
{
string App_key = "xxxxxxxxxxxxxxx";
string App_secret = "yyyyyyyyyyyyyy";
HigLabo.Net.OAuthClient ocl = null;
HigLabo.Net.AuthorizeInfo ai = null;
ocl = HigLabo.Net.Dropbox.DropboxClient.CreateOAuthClient(App_key, App_secret);
ai = ocl.GetAuthorizeInfo();
string RequestToken= ai.RequestToken;
string RequestTokenSecret= ai.RequestTokenSecret;
string redirect_url = ai.AuthorizeUrl;
AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret);
string Token= t.Token;
string TokenSecret= t.TokenSecret;
DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand();
ul.Root = RootFolder.Sandbox;
Console.WriteLine(ul.Root);
ul.FolderPath = target;
ul.FileName = filename;
ul.LoadFileData(content);
Metadata md = cl.UploadFile(ul);
Console.WriteLine("END");
}
The code executes fine but the file is not getting upload in Dropbox.
Am I missing something? Is the path to upload correct? How do I view the file in Dropbox whether it is uploaded or not?
Is there a setting which I am missing while creating the app? I am just looking at the home page and I am expecting the file at the root folder. Am I correct?
Or do I need to look into some other location?
Thanks #smarx and
#Greg.
The below is the code to accomplish the task. Thanks again for your support, I hope this will be helpful for some one.
string filePath="C:\\Tim\\sundar.jpg";
RestClient client = new RestClient("https://api-content.dropbox.com/1/");
IRestRequest request = new RestRequest("files_put/auto/{path}", Method.PUT);
FileInfo fileInfo = new FileInfo(filePath);
long fileLength = fileInfo.Length;
request.AddHeader("Authorization", "Bearer FTXXXXXXXXXXXXXXXXXXXisqFXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
request.AddHeader("Content-Length", fileLength.ToString());
request.AddUrlSegment("path", string.Format("Public/{0}", fileInfo.Name));
byte[] data = File.ReadAllBytes(filePath);
var body = new Parameter
{
Name = "file",
Value = data,
Type = ParameterType.RequestBody,
};
request.Parameters.Add(body);
IRestResponse response = client.Execute(request);

Youtube v3 api 401 Unauthorized

I am trying to upload a file using v3 of the youtube api and without using the c# library. I really can't use the library because I am making my own library that allows me to use a few common apis (youtube, vimeo, facebook, etc)
I have already got my access token and refresh token which is fine. Now I need to upload a file using the youtube resumable uploads defined here:
https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol
but for some reason my code is coming back with a 401 Unauthorized error but I can't see why.
Here is my code that is creating the request:
private void CreateUploadRequest(SynchronisedAsset asset)
{
var endPoint = api.ApiUrl + "/videos?uploadType=resumable&part=snippet&key=" + api.Tokens.ConsumerKey; // read for the different ways to interact with videos https://developers.google.com/youtube/v3/docs/#Videos
var maxSize = 68719476736; // 64 gig
try
{
var location = CompanyProvider.GetUploadLocation(this.baseUploadDirectory, companyId, FileType.Asset);
var filePath = System.IO.Path.Combine(location, asset.FileName);
using (var data = new FileStream(filePath, FileMode.Open))
{
if (maxSize > data.Length && (asset.MimeType.ToLower().StartsWith("video/") || asset.MimeType.ToLower().Equals("application/octet-stream")))
{
var json = "{ \"snippet\": { \"title\": \"" + asset.FileName + "\", \"description\": \"This is a description of my video\" } }";
var buffer = Encoding.ASCII.GetBytes(json);
var request = WebRequest.Create(endPoint);
request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", api.Tokens.AccessToken);
request.Headers["X-Upload-Content-Length"] = data.Length.ToString();
request.Headers["X-Upload-Content-Type"] = asset.MimeType;
request.ContentType = "application/json; charset=UTF-8";
request.ContentLength = buffer.Length;
request.Method = "POST";
using (var stream = request.GetRequestStream())
{
stream.Write(buffer, 0, (int)buffer.Length);
}
var response = request.GetResponse();
}
}
}
catch (Exception ex)
{
eventLog.WriteEntry("Error uploading to youtube.\nEndpoint: " + endPoint + "\n" + ex.ToString(), EventLogEntryType.Error);
}
}
api.ApiUrl is https://www.googleapis.com/youtube/v3. I am not sure if the key is needed, it doesn't show it in the documentation but I added it to see if I could solve my Unauthorized issue.
Also, I figured that without the key, how would it know what account to upload to?
Can anyone see what is wrong with my code?
Any help would be greatly appreciated.
Update 1
After a bit of time sorting stuff out, I have now added some code that checks the youtube credentials before trying to do an upload. This is done with these bits of code:
public string GetAuthorizeApplicationUrl()
{
var sb = new StringBuilder();
var dictionary = new Dictionary<string, string>
{
{"client_id", Tokens.ConsumerKey},
{"redirect_uri", callbackUrl},
{"response_type", "code"},
{"scope", "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtubepartner"},
{"approval_prompt", "force"},
{"access_type", "offline"},
{"state", ""}
};
sb.Append(requestTokenUrl);
foreach (var parameter in dictionary)
{
var query = (sb.ToString().Contains("?")) ? "&" : "?";
sb.Append(query + parameter.Key + "=" + parameter.Value);
}
return sb.ToString();
}
This bit of code is responsible for building the URL that allows us to ask the user for access.
With the code that is returned to our return URL we call this bit of code:
public void RequestAccessToken(string code)
{
var dictionary = new Dictionary<string, string>
{
{"code", code},
{"client_id", Tokens.ConsumerKey},
{"client_secret", Tokens.ConsumerSecret},
{"redirect_uri", callbackUrl},
{"grant_type", "authorization_code"}
};
var parameters = NormalizeParameters(dictionary);
var resultString = "";
using (var wc = new WebClient())
{
//wc.Headers[HttpRequestHeader.Host] = "POST";
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
resultString = wc.UploadString(requestAccessTokenUrl, parameters);
}
var json = JObject.Parse(resultString);
Tokens.AccessToken = json["access_token"].ToString();
Tokens.RefreshToken = (json["refresh_token"] != null) ? json["refresh_token"].ToString() : null;
Tokens.Save(companyId);
}
Now because we have declared our app as offline, when we do any api calls we can just use this bit of code:
public bool CheckAccessToken()
{
try
{
RefreshToken(); // Get and store our new tokens
return true;
}
catch
{
return false;
}
}
private void RefreshToken()
{
var dictionary = new Dictionary<string, string>
{
{"refresh_token", Tokens.RefreshToken},
{"client_id", Tokens.ConsumerKey},
{"client_secret", Tokens.ConsumerSecret},
{"grant_type", "refresh_token"}
};
var parameters = NormalizeParameters(dictionary);
var resultString = "";
using (var wc = new WebClient())
{
//wc.Headers[HttpRequestHeader.Host] = "POST";
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
resultString = wc.UploadString(requestAccessTokenUrl, parameters);
}
var json = JObject.Parse(resultString);
Tokens.AccessToken = json["access_token"].ToString();
Tokens.Save(companyId);
}
In my windows service I have this code:
public void SynchroniseAssets(IEnumerable<SynchronisedAsset> assets)
{
if (api.CheckAccessToken())
{
foreach (var asset in assets)
{
var uploadAssetThread = new Thread(() => CreateUploadRequest(asset));
uploadAssetThread.Start(); // Upload our assets at the same time
}
}
}
which as you can see calls the Original code above.
The error which I am getting when I parse it into json is this:
{
"error":{
"errors":[
{
"domain":"youtube.header",
"reason":"youtubeSignupRequired",
"message":"Unauthorized",
"locationType":"header",
"location":"Authorization"
}
],
"code":401,
"message":"Unauthorized"
}
}
So, if anyone could help me work out what that means, that would be great.
Cheers,
/r3plica
The reason "youtubeSignupRequired" usually means the YouTube account has not been set up properly or you have not created your YouTube channel yet. This is a requirement before you can upload videos.
It would be great if Google could improve their error message for this case and make it a bit more verbose.
The issue returning 401 Unautorized was because the account I was gaining access to did not have a youtube account associated with it.

Image not uploaded after publishing using facebook c# SDK

I am using Facebook c# SDK to post status & images on users wall.
I am able to post status but image is not getting posted
Here is my code:
[HttpPost]
public ActionResult PostPhotoOnWall(HttpPostedFileBase file)
{
var client = new FacebookClient();
// Post to user's wall
var postparameters = new Dictionary<string, object>();
postparameters["access_token"] = Session["access_token"].ToString();
postparameters["picture"] = "http://localhost:8691/Content/themes/base/images/12WIPJ50240-2V91.jpg";
var result = client.Post("/me/feed", postparameters);
return View("PostPhoto");
}
On user wall status is posted without image.
Can any one help me .
I Solved It, Bellow is the code
[HttpPost]
public ActionResult PostPhotoOnWall(HttpPostedFileBase file)
{
var filename = Path.GetFileName(file.FileName);
var client = new FacebookClient();
// Post to user's wall
var postparameters = new Dictionary<string, object>();
var media = new FacebookMediaObject
{
FileName = filename,
ContentType = "image/jpeg"
};
var path = Path.Combine(Server.MapPath("~/Content/themes/base/images"),filename);
file.SaveAs(path);
byte[] img = System.IO.File.ReadAllBytes(path);
media.SetValue(img);
postparameters["source"] = media;
postparameters["access_token"] = Session["access_token"].ToString();
// postparameters["picture"] = "http://localhost:8691/Content/themes/base/images/12WIPJ50240-2V91.jpg";
var result = client.Post("/me/photos", postparameters);
return View("PostPhoto");
}

Categories

Resources