How can I upload image to imgur using VPN? - c#

In my county -Turkey- to upload and see images in Imgur is forbidden. When I tried to upload image with my client-id it throws a 403 Forbidden error. So I think the solution is upload using VPN. But I don't know how. I tried it as below
using (var w = new WebClient())
{
var values = new NameValueCollection
{
{"image", Convert.ToBase64String(File.ReadAllBytes(path))}
};
WebProxy pr = new WebProxy("euro217.vpnbook.com");
pr.Credentials = new NetworkCredential("vpnbook", "caPhahu4");
pr.UseDefaultCredentials = false;
pr.BypassProxyOnLocal = false;
w.Proxy = pr;
w.Headers.Add("Authorization", "Client-ID " + clid);
byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
Console.WriteLine(XDocument.Load(new MemoryStream(response)));
//now process response as you'd like. the link is encapsulated by <link></link> in the response.
}
I have found the VPN adress and credential infos from a public site. I think the informations is not wrong. But not sure.Please help!.
EDIT: I have solved the problem. The problem is I got the clientID from developer.google.com for OAuth API. I thought I was right,but I was wrong. The id must be taken from https://api.imgur.com/oauth2/addclient. This solved the issue. Thanks everyone tried to help.

Related

Youtube Live API - Broadcast premission denied using OAuth

I am trying to broadcast live from my .Net application using Youtube.Data.Api v3.
I have set up OAuth and downloaded the .JSON file, and that works fine. I know that, because I have already successfully obtained a list of channels resp. videos on my account, i.e., following code works:
var channelsRequest = ytService.Channels.List("contentDetails, snippet");
channelsRequest.Mine = true;
var channelsListResponse = channelsRequest.Execute();
But if I try to execute a insert request (for completeness I show you the whole method),
public static LiveBroadcast CreateImmediateBroadcast(string title = "DefaultBroadcast") {
var snippet = new LiveBroadcastSnippet();
snippet.Title = title;
snippet.ScheduledStartTime = DateTime.Now;
snippet.ScheduledEndTime = DateTime.Now + TimeSpan.FromMinutes(60);
var status = new LiveBroadcastStatus();
status.PrivacyStatus = "unlisted";
var broadcast = new LiveBroadcast();
broadcast.Kind = "youtube#liveBroadcast";
broadcast.Snippet = snippet;
broadcast.Status = status;
var insertBroadcastRequest = ytService.LiveBroadcasts.Insert(broadcast, "snippet, status");
insertBroadcastRequest.Execute();
return broadcast;
}
I get an exception when calling insertBroadcastRequest.Execute(), namely:
Google.GoogleApiException was unhandled
HResult=-2146233088
Message=Google.Apis.Requests.RequestError
Insufficient Permission [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]
ServiceName=youtube
Source=Google.Apis
StackTrace:
at Google.Apis.Requests.ClientServiceRequest`1.Execute() in C:\Users\cloudsharp\Documents\GitHub\google-api-dotnet-client\Src\Support\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 96
at YoutubeConsole.YouTubeAPI.CreateImmediateStream(String title) in C:\Users\bussg\Source\Workspaces\OwnExperimental\YoutubeConsole\YoutubeConsole\YouTubeAPI.cs:line 87
at YoutubeConsole.YouTubeAPI.Test() in
...
Also, for completeness, here is my authorization,
using (var stream = new FileStream(Directory.GetCurrentDirectory() + #"\GoogleAuthOtherApplication.json", FileMode.Open, FileAccess.Read)) {
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeForceSsl},
"user",
CancellationToken.None,
new FileDataStore("YouTubeAPI")
).Result;
}
Also, For the YouTubeService.Scope I have tried all options. The insert method should work with ForceSsl according to the documentation.
Also this documentation page sais
Note: A channel must be approved to use the YouTube Live feature, which enables the channel owner to stream live content to that channel. If you send API requests on behalf of an authenticated user whose channel is not enabled or eligible to stream live content, the API will return an insufficientPermissions error.
But all my channels are approved for Youtube Live. Any ideas how to get this to work?
Ok after some testing between us over Email.
You need to have the correct scope "YouTubeService.Scope.YoutubeForceSsl" by changing "user" we forced it to request permissions again. My tutorial on how filedata store works in the Google .net client library
remove the space "snippet, status" by sending "snippet,status" it worked for me.
For the fun of it: Issue 8568:LiveBroadcasts: insert - spaces in part

Calling MailChimp API v3.0 with .Net

I'm trying to access our MailChimp account via the new 3.0 REST API. I've done the following:
using(var http = new HttpClient())
{
var creds = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:mailchimpapikey-us1"));
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", creds);
string content = await http.GetStringAsync(#"https://us1.api.mailchimp.com/3.0/lists");
Console.WriteLine(content);
}
However, when I run this code, I get a 401 error with the following json details:
{"type":"http://kb.mailchimp.com/api/error-docs/401-api-key-invalid","title":"API Key Invalid","status":401,"detail":"Your API key may be invalid, or you've attempted to access the wrong datacenter.","instance":"a9fe4028-519e-41d6-9f77-d2caee4d4683"}
The datacenter I'm using in my URI (us1 in this example) matches the dc on my API key. My API key works if I use the MailChimp SDK so I know my key isn't invalid. Also, using Fiddler, I can see that the MailChimp SDK is calling the same dc as I'm doing in my URI.
Any Ideas as to why I am having trouble Authenticating?
EDIT
As noted in the question, I'm asking specifically about accessing the new 3.0 REST API. I'm trying to do this directly as opposed to using a third party wrapper.
The new API is composed of http calls so it should be pretty straight forward. I'm simply having trouble with the authentication piece.
So I was able to finally chat with a super tech support person at MailChimp.
The MailChimp docs state the following
The easiest way to authenticate is using HTTP Basic Auth. Enter any string
as the username and supply your API Key as the password.
Your HTTP library should have built-in support for basic authorization.
Their documentation is a bit misleading. Typically the Auth header for Basic Auth would look like what I was sending:
Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
where the row of x would represent the base64 encoded username:password.
However, talking with the support tech, the actual implementation they use is:
Authorization: username keyid
No base64 encoding, no Basic keyword. Username doesn't even have to be your username.
So, here is the working code:
using(var http = new HttpClient())
{
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", mailchimpapikey-us1);
string content = await http.GetStringAsync(#"https://us1.api.mailchimp.com/3.0/lists");
Console.WriteLine(content);
}
EDIT
Note the comments. TooMuchPete was correct in that the normal HTTP Basic Auth headers do work. Apparently I was hitting some old code or something on the MailChimp side.
I'm leaving the post as a reference for anyone who is trying to call the new 3.0 API.
I wrote an article on a simple way up adding subscribers to a list using:
Dim mailchimp As New ZmailChimp
Dim ListId$ = "9b2e63f0b9" 'List Sage' List
Dim email$ = "samsmith20#anymail.com" '"sam19#postcodelite.com"
Dim fieldListOnAdd = "FNAME,Sam,LNAME,Smith,MTYPE,User,MID,631637"
Dim fieldListOnUpdate = "FNAME,Sam,LNAME,Smith,MID,631637" 'Don't change MTYPE
'Put on 'Sage One' and 'Sage 50' group
Dim groupList = "407da9f47d,05086211ba"
With mailchimp
.API$ = "46cMailChimpAPIKeyd1de-us14" 'MailChimp API key
.dataCenter$ = "us14" 'Last 4 letters of API key
.password$ = "Password!"
MsgBox(.addSubscriber(ListId$, email, fieldListOnAdd, fieldListOnUpdate, groupList))
End With
mailchimp = Nothing
see:http://www.codeproject.com/Tips/1140339/Mail-Chimp-Add-Update-e-mail-to-List-and-Subscribe
this may save someone some time
Mailchimp Ecommerce
var mcorder = new Standup.Ecomm.MailChimpManager(ConfigurationManager.AppSettings["MailChimpApiKey"]);
var orders = new MailOrder();
orders.CampaignId = ConfigurationManager.AppSettings["MailChimpCampaignId"];
orders.EmailId = ConfigurationManager.AppSettings["MailChimpEmailId"];
orders.Id = orderNumber;
orders.StoreId = "abcde";
orders.StoreName = "E-Commerce Store";
orders.Total = Convert.ToDouble(orderTotal);
orders.Tax = Convert.ToDouble(tax);
orders.Items = new List<MailOrderItem>();
foreach (var orderItem in orderItemList)
{
var item = new MailOrderItem();
item.ProductId = orderItem.OrderNumber;
item.ProductName = orderItem.Title;
item.SKU = orderItem.Sku;
item.CategoryId = 0;
item.CategoryName = " ";
item.Quantity = orderItem.Quantity;
item.Cost = Convert.ToDouble(orderItem.ProductCost);
orders.Items.Add(item);
}
mcorder.AddOrder(orders);

SignatureDoesNotMatch error when trying to access file on Amazon s3

I am trying to access the file that has been uploaded to Amazon S3 by using the method GetPreSignedUrlRequest. The code I am using is as below:-
string bucketName = string.Empty;
if (ConfigurationManager.AppSettings["S3BucketName"] != null)
{
bucketName = ConfigurationManager.AppSettings["S3BucketName"].ToString();
}
AmazonS3Client s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = file.FileName,
Expires = DateTime.Now.AddMinutes(5),
Protocol = Protocol.HTTP
};
string url = s3Client.GetPreSignedURL(request);
The url generated by this is then used to point to the file.
It looks like
http://s3.amazonaws.com/mybucketname/VZcbKsZgR2qyOMkLU1XT_jquery_ui_touch-punch_min_js.txt?X-Amz-Expires=300&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIMGQJ6D5L5SNBGHA/20140114/us-east-1/s3/aws4_request&X-Amz-Date=20140114T194159Z&X-Amz-SignedHeaders=host&X-Amz-Signature=922719dd2286600aebaca5701a8e142d327342b541569c9a4d7d8afc822d9a76/VZcbKsZgR2qyOMkLU1XT_jquery_ui_touch-punch_min_js.txt
But that gives me signature doesnot match error as shown in the image below:-
Update - version 2.0.6 of the SDK, released Jan 16th, contains a fix for this issue.
Your code is fine, unfortunately a bug in the SDK is causing the presigned url to be malformed. I've just tested it with our latest codebase and we've fixed the issue; this new version should be released soon.
I'll ping this issue once we release the patch. Sorry for the inconvenience.
Regards,
This can also occur if some of the details about the request are not set up properly:
e.g. For me the following lines fixed the problem
request1.ContentType = "image/jpeg";
request1.Verb = HttpVerb.PUT;

Error Uploading Video to YouTube

I am using following code to upload a video to YouTube.
It always gives following error.
The remote server returned an error: (403) Forbidden.
My Code is
YouTubeRequestSettings settings;
YouTubeRequest request;
string devkey = YouTubeDeveloperKey;
string username = YoutubeUserName;
string password = YoutubePassword;
settings = new YouTubeRequestSettings("VideoEditor", devkey, username, password) { Timeout = -1 };
request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = Title;
newVideo.Description = Description;
newVideo.Private = true;
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(FilePath, "video/flv");
Video createdVideo = request.Upload(newVideo);
Please do you have any idea about this error
As per the Youtube API V2 documentation, error 403 is an authorization error.
Most probably the username and password might be wrong.
My guess: Did you enable two step authentication on your Google account ?
If so, you must use an application-specific password.
Try to go to your youtube application via https://console.developers.google.com then select your application go to APIs and auth -> APIs.
It will display a list of multiple available APIs, click on Youtube Data API, and then click "enable". This will enable this API to be used by your app and most likely will solve your issue.

Accessing GData Calender from Google Apps account?

I'm building a simple app too that needs to access a calendar that's in my Google Apps account. But I'm having problems with authentication. I've tried the following code but it doesn't work:
Service service = new Service("<appname>");
service.setUserCredentials("<email>", "<password>");
CalendarEntry entry = (CalendarEntry)service.Get("<eventUrl>");
How do you get this to work with Google Apps? Is there any other type of authentication that I have to use for Google apps?
Update:
Unlocking the captcha solved my problem with getting the feed. Now I've hit the next wall: updating an event.
entry.Title.Text = "Foo";
entry.Update();
Gives me the GDataRequestException exception: "Can not update a read-only entry".
Im using the private calendar xml address that I got under kalendarsettings:
https://www.google.com/calendar/feeds/_%40group.calendar.google.com/private-/basic
I would recommend using Fiddler to see what http response you are getting back from Google. When I ran your code against my google apps account, I was getting back an "Error=CaptchaRequired" response. This required that I go to https://www.google.com/a/yourgoogleappdomain.com/UnlockCaptcha (replacing with your domain obviously). After I did that I was able to properly connect. You may be getting a different error code too so check for that and post it here. You could have an invalid password or invalid url or this functionality is disabled by your google apps administrator. Here is my sample code:
var calendarService = new CalendarService("company-app-version");
calendarService.setUserCredentials("<email>", "<password>");
var eventQuery = new EventQuery("http://www.google.com/calendar/feeds/user%40domain.com/private/full");
var eventFeed = calendarService.Query(eventQuery);
foreach (var atomEntry in eventFeed.Entries)
{
Console.WriteLine(atomEntry.Title.Text);
}
Make sure to replace the email, password, and email inside of the URL (url encode the # sign too).
using Google.GData.Client;
public bool ValidateGoogleAccount(string login, string password)
{
try
{
Service bloggerService = new Service("blogger", "App-Name");
bloggerService.Credentials = new GDataCredentials(login, password);
string token = bloggerService.QueryAuthenticationToken();
if (token != null)
return true;
else
return false;
}
catch (Google.GData.Client.InvalidCredentialsException)
{
return false;
}
}
Yet another solution Austin from google provides (it worked for me):
http://groups.google.com/group/google-calendar-help-dataapi/browse_thread/thread/400104713435a4b4?pli=1

Categories