How do I search GitHub API repositories with unauthorized access? - c#

I'm trying to create a simple C# application to consume the GitHub API, but when I try to execute the following code:
HttpWebRequest request = WebRequest.Create("https://api.github.com/users/AndreStoicov/repos") as HttpWebRequest;
request.Method = "GET";
request.Proxy = null;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
It returns Protocol Violation Section=ResponseStatusLine due to me not being an authorized user.
In other words, I want to use the GitHub API without any user authorization; is there any way to perform that?

GitHub rules state you must specify User-Agent header in request:
request.UserAgent = "appname";
It does not require registered credentials, just application name would be enough.

Related

Get full url from shorten url in C#.net

I am developing one application where I need capture basic detail like title, description and images of website based on url provided by user.
But user may be enter www.google.com insted of http://www.google.com but C#.net code failed to retrieve data for "www.google.com" through below code
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
String responseString = reader.ReadToEnd();
response.Close();
and found error like "Invalid URI: The format of the URI could not be determined."
So do know any technique to found full url based on shorten url.
for ex. google.com or www.google.com
Expected output : http://www.google.com or https://www.google.com
PS : I found online web tool (http://urlex.org/) that will return full url based on shorten url
Thanks in advance.
You can use UriBuilder to create a URL with HTTP as default scheme:
UriBuilder urb = new UriBuilder("www.google.com");
Uri uri = urb.Uri;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
string responseString;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}
}
If your URL contains a scheme, it will use that one instead of the default HTTP scheme. I have also used using to release all unmanaged resources.
So do know any technique to found full url based on shorten url.
I may have misunderstood your issue here but can't you just append "http://" if it's missing?
string url = "www.google.com";
if (!url.StartsWith("http"))
url = $"http://{url}";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.Method = WebRequestMethods.Http.Get;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
String responseString = reader.ReadToEnd();
}
This is basically what a web browser does when you don't specify any protocol.

Web API and WPF client

I've followed the following article to set up a simple Web API solution:
http://www.codeproject.com/Articles/350488/A-simple-POC-using-ASP-NET-Web-API-Entity-Framewor
I've omitted the Common project, Log4Net and Castle Windsor to keep the project as simple as possible.
Then I created a WPF project. However, now which project should I reference in order access the WebAPI and the underlying models?
Use the HttpWebRequest class to make request to the Web API. Below a quick sample for something I've used to make requests to some other restful service (that service only allowed POST/GET, and not DELETE/PUT).
HttpWebRequest request = WebRequest.Create(actionUrl) as HttpWebRequest;
request.ContentType = "application/json";
if (postData.Length > 0)
{
request.Method = "POST"; // we have some post data, act as post request.
// write post data to request stream, and dispose streamwriter afterwards.
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
writer.Close();
}
}
else
{
request.Method = "GET"; // no post data, act as get request.
request.ContentLength = 0;
}
string responseData = string.Empty;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseData = reader.ReadToEnd();
reader.Close();
}
response.Close();
}
return responseData;
There are also a nuget package available called "Microsoft ASP.NET Web API client libraries" which can be used to make requests to the WebAPI. More on that package here(http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client)

oAuth 2 with Open API

I'm trying to authorize a console app to an API that uses oAuth 2.0. I've tried DotNetOpenAuth with no success.
First step is to get the Authorization code, this is what I have but I cannot find the authorization code to proceed to step 2 (Authorization using pre-defined authorization code, with User ID and User password). I have used the following authorization headers from the documentation
https://sandbox-connect.spotware.com/draftref/GetStartAccounts.html#accounts?
In the response I do not get any headers with authentication code, how can I solve this?
string sAuthUri = "https://sandbox-connect.spotware.com/oauth/v2/auth";
string postData ="access_type=online&approval_prompt=auto&client_id=7_5az7pj935owsss8kgokcco84wc8osk0g0gksow0ow4s4ocwwgc&redirect_uri=http%3A%2F%2Fwww.spotware.com%2F&response_type=code&scope=accounts";
string sTokenUri = "https://sandbox-connect.spotware.com/oauth/v2/token";
var webRequest = (HttpWebRequest)WebRequest.Create(sAuthUri);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
try
{
using (Stream s = webRequest.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(postData.ToString());
}
using (WebResponse webResponse = webRequest.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
response = reader.ReadToEnd();
}
}
var return = response;
}
catch (Exception ex)
{
}
Using the Auhtorization code flow of OAuth2, the code should come in the query string of the redirection to redirect_uri.
I think that the problem is in the call method (should be GET), with postData as QueryString, and the redirect_uri must be a url of your system (not spotware). The authorization code should be retrieved from query string of the webResponse.
I recommend you to use DotNetOpenAuth library to implement OAuth2 requests easily.

How do I post to GitHub API v3

I am using GitHub API v3 with C#. I am able to get the access token and using that I am able to get the user information and repo info.
But when I try to create a new repo I am getting the error as Unauthorized.
I am using HttpWebRequest to post data, which can be seen below. Please suggest me some C# sample or sample code.
(..)string[] paramName, string[] paramVal, string json, string accessToken)
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.Write(json);
writer.Close();
string result = null;
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}(..)
Note: I am not sure where i need to add the accesstoken. I have tried in headers as well as in the url, but none of them works.
Are you using the C# Github API example code? I would look at that code to see if it does what you need.
You can use basic auth pretty easily by just adding auth to the request headers:
request.Headers.Add("Authorization","Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username +":"+password)));
Sorry havent used the access token stuff yet.
You need to add this token here:
req.UserAgent = "My App";
req.Headers.Add("Authorization", string.Format("Token {0}", "..token..");
Try
rec.Credentials = CredentialCache.DefaultCredentials;
or use non-default credentials.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.credentials.aspx

C# HttpWebRequest accessing RESTful web service

I have a REST web service written in jRuby with entry point http://localhost:4567/v4/start.htm
The web service downloads data from SQL server and sends it to a client.
How do I use C# and httpWebrequest to access the functions provided by the web service.
Thank you
Generally speaking you're going to do something like this:
HttpWebRequest Request = WebRequest.Create(Url) as HttpWebRequest;
Request.Method = "GET"; //Or PUT, DELETE, POST
Request.ContentType = "application/x-www-form-urlencoded";
using (HttpWebResponse Response = Request.GetResponse() as HttpWebResponse)
{
if (Response.StatusCode != HttpStatusCode.OK)
throw new Exception("The request did not complete successfully and returned status code " + Response.StatusCode);
using (StreamReader Reader = new StreamReader(Response.GetResponseStream()))
{
string ReturnedData=Reader.ReadToEnd();
}
}
I haven't mixed RoR and C# yet (let alone jRuby), but it should be just a basic modification of the above.

Categories