Set proxy for Google.Apis.YouTube.v3 - c#

I have the following bit of code to make a call to the
YouTubeService service = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = AppSettings.Variables.YouTube_APIKey,
ApplicationName = AppSettings.Variables.YouTube_AppName
});
Google.Apis.YouTube.v3.VideosResource.ListRequest request = service.Videos.List("snippet,statistics");
request.Id = string.Join(",", videoIDs);
VideoListResponse response = request.Execute();
This all works but when we deploy it to our live server, it needs to get through a proxy so we put the following into the web.config:
<defaultProxy useDefaultCredentials="false" enabled="true">
<proxy usesystemdefault="False" proxyaddress="http://192.111.111.102:8081" />
</defaultProxy>
However, this doesn't seem to be working as when the call is made, I get the following error:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 216.58.213.74:443
Is there a way to manually set the proxy in code?
Something along the lines of:
WebProxy proxy = new WebProxy("192.111.111.102", 8081);
proxy.Credentials = new NetworkCredential(AppSettings.Variables.ProxyUser, AppSettings.Variables.ProxyPassword, AppSettings.Variables.ProxyDomain);
// apply this to the service or request object here

Yes of course!
You can set a System.Net.WebProxy for a YouTubeService instance:
var _youtubeService = new YouTubeService(yourInitializer);
_youtubeService.HttpClient.MessageHandler.InnerHandler = new HttpClientHandler
{
Proxy = new WebProxy(your parameters..)
};
NOTE : Don't forget to set other HttpClientHandler properties if needed(for example AutomaticDecompression)

To get around this I had to make a webrequest to the url and map the result back to the VideoListResponse object:
try
{
Uri api = new Uri(string.Format("https://www.googleapis.com/youtube/v3/videos?id={0}&key={1}&part=snippet,statistics", videoIds, AppSettings.Variables.YouTube_APIKey));
WebRequest request = WebRequest.Create(api);
WebProxy proxy = new WebProxy(AppSettings.Variables.ProxyAddress, AppSettings.Variables.ProxyPort);
proxy.Credentials = new NetworkCredential(AppSettings.Variables.ProxyUsername, AppSettings.Variables.ProxyPassword, AppSettings.Variables.ProxyDomain);
request.Proxy = proxy;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
return JsonConvert.DeserializeObject<VideoListResponse>(streamReader.ReadToEnd());
}
}
}
catch (Exception ex)
{
ErrorLog.LogError(ex, "Video entity processing error: ");
}

The solution of #ABS looks more efficient and "compact" to me.
Here's how i use it in VB.NET with the Youtube Channel API:
Dim uriProxy As New Uri("*proxy_url:IP*")
Dim wpyProxy As New WebProxy With {.Address = uriProxy }
Dim get_youtube_channel_channel_work As New youtube_channel
Dim youtube_initialiser As New Google.Apis.Services.BaseClientService.Initializer()
youtube_initialiser.ApiKey = ConfigurationManager.AppSettings("youtube_api_key")
youtube_initialiser.ApplicationName = ConfigurationManager.AppSettings("youtube_api_application_name")
Dim youtube_service As Google.Apis.YouTube.v3.YouTubeService = New YouTubeService(youtube_initialiser)
Dim objChannelListRequest As ChannelsResource.ListRequest = youtube_service.Channels.List("id, snippet, statistics")
youtube_service.HttpClient.MessageHandler.InnerHandler = New HttpClientHandler With {.Proxy = wpyProxy}

Related

HTTP Post Authentication error

Here is my code
string URL = "https://api.fastspring.com/accounts";
using (var wb = new WebClient())
{
var data = new NameValueCollection();
var contact = new NameValueCollection();
data["contact"] = "first="+FirstName+"&last="+LastName+"&email="+Email+"&company="+Company;
data["language"] = Language;
data["country"] = Country;
var headers = new WebHeaderCollection();
headers["Authorization"] = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("username:password"));
headers["User-Agent"] = "request";
//headers["Content-Type"] = "application/json";
wb.Headers = headers;
var response = wb.UploadValues(URL, "POST", data);
return (System.Text.Encoding.UTF8.GetString(response)).Split('"')[3];
}
My problem is that i keep on getting a 401 error saying unauthorised. For one, is my authentication syntax correct? also is my entire setup for sending an HTTP request to the server correct?
here are some useful resources about the fastspring api if it would help:
http://docs.fastspring.com/integrating-with-fastspring/fastspring-api/accounts#id-/accounts-Createanaccount
http://docs.fastspring.com/integrating-with-fastspring/fastspring-api

HttpClient throws error with the Rest services

I am trying to call multiple rest services from the Web API I am creating and I am getting the below error while one of the Sharepoint rest service is called
This instance has already started one or more requests. Properties can only be modified before sending the first request.
Below is the code for calling the rest services using the HttpClient
try
{
var credential = new NetworkCredential(userName_SP, password_SP, domain_SP);
var myCache = new CredentialCache();
myCache.Add(new Uri(core_URL), "NTLM", credential);
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.Credentials = myCache;
using (var client_sharePoint = new HttpClient(handler))
{
var response = client_sharePoint.GetAsync(core_URL).Result;
client_sharePoint.BaseAddress = uri;
client_sharePoint.DefaultRequestHeaders.Accept.Clear();
client_sharePoint.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var responsedata = await response.Content.ReadAsStringAsync();
var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(
responsedata);
return returnObj;
}
...
I have never encountered this error before. Can anyone please suggest me if I need set the timeout
Try this:
var credential = new NetworkCredential(userName_SP, password_SP, domain_SP);
var myCache = new CredentialCache();
myCache.Add(new Uri(core_URL), "NTLM", credential);
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.Credentials = myCache;
using (var client_sharePoint = new HttpClient(handler))
{
client_sharePoint.BaseAddress = uri;
client_sharePoint.DefaultRequestHeaders.Accept.Clear();
client_sharePoint.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client_sharePoint.GetAsync(core_URL);
var responsedata = await response.Content.ReadAsStringAsync();
var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(
responsedata);
return returnObj;
}
Headers and BaseAddress must be set before you make the request with GetAsync.
I also took the liberty to change from .Result to await since calling .Result is poor practice and I can see this is in an async method.
You should also read this: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

C# Service Request

I stack on Apple GSX Api request in c# project. Everything is ok but I cannot get response from api.
Certificates done, Static IPs have whitelisted.
Return this error when i request to "https://gsxapiut.apple.com/gsx-ws/services/emea/asp"
{"An error occurred while making the HTTP request to
https://gsxapiut.apple.com/gsx-ws/services/emea/asp. This could be due
to the fact that the server certificate is not configured properly
with HTTP.SYS in the HTTPS case. This could also be caused by a
mismatch of the security binding between the client and the server."}
Request Function :
public void Authenticate()
{
try
{
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
EndpointAddress endpoint = new EndpointAddress("https://gsxapiut.apple.com/gsx-ws/services/emea/asp");
var sslCertFilename = "test.p12";
var sslCertPassword ="xxxxx";
GsxApi3.GsxWSEmeaAspPortClient service = new GsxApi3.GsxWSEmeaAspPortClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
service.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(
sslCertFilename,
sslCertPassword, X509KeyStorageFlags.MachineKeySet);
var auth = new GsxApi3.authenticateRequestType()
{
languageCode = "EN",
serviceAccountNo = "xxxxxxxxx",
userId = "xxxxxxxxxxx",
userTimeZone = "CET"
};
var session = service.Authenticate(auth);
var userSessionId = new GsxApi3.gsxUserSessionType { userSessionId = session.userSessionId };
}
catch (Exception err)
{
}
}

Windows 8.1 store app Download file using authentication and header

I'm trying to download a file from a server and adding authentication and range header in my app, so is this syntax correct?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Headers["Range"] = "bytes=0-";
request.Credentials = new NetworkCredential("username","password");
Of course the code has other parts for reading the file as a stream and storing it but i'm concerned with the range header and authentication part because it's not working.
I get an exception
{"The 'Range' header must be modified using the appropriate property or method.\r\nParameter name: name"}
Here's how to do it:
public async Task<byte[]> DownloadFileAsync(string requestUri)
{
// Service URL
string serviceURL = "http://www.example.com";
// Http Client Handler and Credentials
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new NetworkCredential(username, passwd, domain);
// Initialize Client
HttpClient client = new HttpClient(httpClientHandler)
client.BaseAddress = new Uri(serviceURL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
// Add Range Header
client.DefaultRequestHeaders.Add("Range", "bytes=0-");
// Deserialize
MemoryStream result = new MemoryStream();
Stream stream = await client.GetStreamAsync(requestUri);
await stream.CopyToAsync(result);
result.Seek(0, SeekOrigin.Begin);
// Bson Reader
byte[] output = null;
using (BsonReader reader = new BsonReader(result))
{
var jsonSerializer = new JsonSerializer();
output = jsonSerializer.Deserialize<byte[]>(reader);
}
return output;
}
I'm current using the BSON media format. If you need addtional information regarding BSON in your backend, herre's a great article on how to implement it and consume it:
http://www.strathweb.com/2012/07/bson-binary-json-and-how-your-web-api-can-be-even-faster/
Here is another way to do it
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("username", "password");
var client = new HttpClient(httpClientHandler);
System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, new Uri(url));
request.Headers.Range = new RangeHeaderValue(0, null);
HttpResponseMessage response = await client.SendAsync(request);

Reading external XML via a proxy

I want to read some external xml, but I have to connect via a proxy, but I'm not sure how to do it. I have the following code, the xmlurl contains a path to the external xml:
if (content > 0)
{
using (XmlTextReader xml = new XmlTextReader(xmlurl))
{
while (xml.Read())
{
Console.WriteLine(xml.Name);
}
}
}
I had the following proxy code for another HttpWebRequest piece I had:
if(Convert.ToBoolean(ConfigurationManager.AppSettings["behindproxy"]) == true)
{
WebProxy proxy = new WebProxy();
Uri proxyUri = new Uri("srvisa01");
proxy.Address = proxyUri;
proxy.BypassProxyOnLocal = true;
proxy.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["proxyusername"].ToString(), ConfigurationManager.AppSettings["proxypassword"].ToString());
}
But I'm not sure this will work in this case.
Help appreciated.
Kind regards
Chris
I found the answer to this question with some determined Googling:
XmlTextReader xml;
WebRequest web;
web = WebRequest.Create(xmlurl);
if(Convert.ToBoolean(ConfigurationManager.AppSettings["behindproxy"].ToString()))
{
WebProxy prxy = new WebProxy();
Uri prxyUri = new Uri("http://xxx:8080");
prxy.Address = prxyUri;
prxy.BypassProxyOnLocal = true;
prxy.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["proxyusername"].ToString(), ConfigurationManager.AppSettings["proxypassword"].ToString());
web.Proxy = prxy;
}
var response = web.GetResponse().ToString();
xml = new XmlTextReader(response);
Hope this answer helps peeps :)

Categories

Resources