I am trying to use Google custom search API in my .NET project.
I have an API Key provided by my company.
I have created a custom search engine using my Google account and copied the 'cx' value.
I am using the following code:
string apiKey = "My company Key";
string cx = "Cx";
string query = tbSearch.Text;
WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Only a test!");
string result = webClient.DownloadString(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, query));
I am getting the following error: "The remote server returned an error: (403) Forbidden. "
I have tried the following code too:
Google.Apis.Customsearch.v1.CustomsearchService svc = new Google.Apis.Customsearch.v1.CustomsearchService();
svc.Key = apiKey;
Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
Google.Apis.Customsearch.v1.Data.Search search = listRequest.Fetch();
foreach (Google.Apis.Customsearch.v1.Data.Result result1 in search.Items)
{
Console.WriteLine("Title: {0}", result1.Title);
Console.WriteLine("Link: {0}", result1.Link);
}
Here I get the following exception at Fetch():
Google.Apis.Requests.RequestError
Access Not Configured [403]
Errors [Message[Access Not Configured] Location[ - ] Reason[accessNotConfigured] Domain[usageLimits]
Is CX parameter required?
Am I getting the error because I am using the Key provided by my company and using the CX parameter from
custom search engine using my Google account?
Is there any other way of getting 'cx'? We don't want to display Google ADs.
Thank you very much in advance for help.
I'm not sure if you are still interested in this.
To get results without ads you need to pay for it.
Info # Google
and yes the cx is required because it specifies the google custom search engine that you want to use to search.
you can create a custom search engine from This google page
and here is the current code to retrieve search results for the current api version 1.3.0-beta
string apiKey = "Your api key";
string cx = "Your custom search engine id";
string query = "Your query";
var svc = new Google.Apis.Customsearch.v1.CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey });
var listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
var search = listRequest.Fetch();
foreach (var result in search.Items)
{
Response.Output.WriteLine("Title: {0}", result.Title);
Response.Output.WriteLine("Link: {0}", result.Link);
}
Hope this helps
Instead of,
var search = listRequest.Fetch();
But now it does not supports Fetch() method, rather you need to use Execute() method.
var search = listRequest.Execute();
var listRequest = svc.Cse.List(query);
error !!!
you should use :
var listRequest = svc.Cse.List();
and then :
listRequest.Q=query
Related
I'm using the Atlassian SDK from the following location: https://bitbucket.org/farmas/atlassian.net-sdk
Right now, I'm simply trying to connect to my JIRA and just bring down some basic information like my tasks. Doing a quick google I found the following example: https://www.codeproject.com/Tips/762516/Connecting-to-Jira-using-Csharp
In the above link, he connects to JIRA using the following line:
Jira jiraConn = new Jira("http://yourjiraurl.com/", jUserID, jPassword);
But when I try the same line:
Jira jira = new Jira(url, "admin", "password");
I get the following errors:
cannot convert from 'string' to 'Atlassian.Jira.ServiceLocator'
cannot convert from 'string' to 'Atlassian.Jira.JiraCredentials'
cannot convert from 'string' to 'Atlassian.Jira.JiraCache'
I've looked around to try and find some documentation on this, but I can't find anything relating to any of the 3 errors or what sort of syntax it is expecting. I would investigate the bitbucket more, but my works firewall has it blocked for unknown reasons.
Does anyone have any experience on combating these errors?
As the prototype for Jira is:
Jira(ServiceLocator services, JiraCredentials credentials = null, JiraCache cache = null)
Then the errors you are getting are correct (strings are not JiraCredentials).
So either you need to create some credentials or you could use the other function:
public static Jira CreateRestClient(string url, string username = null, string password = null, JiraRestClientSettings settings = null)
So, something like:
Jira jira = Jira.CreateRestClient(url, "admin", "password");
Not C# ... but this is how you can communicate with Atlassian. This example is from a Google Sheet (Just change the URL and endpoints). I've done this a lot through VBA too over the years. It seems like lately, the user / password has to be encoded. I don't recall that being the case from earlier versions
function showAtlassian() {
var html = HtmlService.createHtmlOutputFromFile('atlassianform')
.setWidth(200)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(html, 'Atlassian Login');
}
function processAtlassian(myForm) {
var username = myForm.un;
var userpw = myForm.pw;
var myencoded = Utilities.base64Encode(username+":"+userpw);
var headers = {"Authorization" : "Basic " + myencoded};
var options = {
'method': 'get',
"contentType" : "application/json",
"headers": headers,
'muteHttpExceptions': false
}
var ui = SpreadsheetApp.getUi(); // Same variations.
url = 'https://---your domain---/wiki/rest/api/user/current';
try {
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response)
var result = ui.alert( 'got valid connection userkey ' + data.userKey );
} catch(error) {
var result = ui.alert( 'invalid user or password: url: '+ url +' err: ' + error.toString());
getatlassian();
}
}
function getatlassian() {
var ui = SpreadsheetApp.getUi();
showAtlassian()
}
I am using Google Plus API for .Net for implementing sharing on google plus using WebAuthenticationBroker. It returns a token after the user gets logged in but when I send a moments post request it returns error 401.
My code on clicking on image is
String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http://www.google.com&response_type=code&scope=" + Uri.EscapeDataString("https://www.googleapis.com/auth/plus.stream.write https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.login");
PlusService service = new PlusService();
System.Uri StartUri = new Uri(GoogleURL);
System.Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");
WebAuthenticationBroker.AuthenticateAndContinue(new Uri(GoogleURL), EndUri);
now when it returns after authenticating I have called method upload on google in continue which is as follows--
PlusService service = new PlusService();
Moment body = new Moment();
ItemScope itemScope = new ItemScope();
itemScope.Id = "replacewithuniqueforaddtarget";
itemScope.Image = "http://www.google.com/s2/static/images/GoogleyEyes.png";
itemScope.Type = "";
itemScope.Description = "The description for the action";
itemScope.Name = "An example of add activity";
body.Object = itemScope;
body.Type = "http://schema.org/AddAction";
MomentsResource.InsertRequest insert =
new MomentsResource.InsertRequest(
service,
body,
"me",
MomentsResource.InsertRequest.CollectionEnum.Vault);
Moment wrote = insert.Execute();
But it returns exception 401. The code to post I found on Google Console Help. Can somebody help in this?
I finally found out that google APIs are not directly open to third party developers and it just made my case void and had to use HTTP method for this. Thanks #DalmTo for answering.
I've been trying to list users in my google apps domain for a while now.
No problem in Python, but in C# i get an error message:
An error has occured:
Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
Message[Bad Request] Location[ - ] Reason[badRequest] Domain[global]
]
I'm no C# guru of any sorts but when I looked through the Google.Apis.Admin.directory_v1.cs - file it looked to me as if the UserResource ListRequest is wrong???
It's found on line 7349-7352 in the file. Anyone know's if it's not yet implemented in the API?
Edit:
I start with why I THINK the code in Google.Apis.Admin.directory_v1.cs, lines 7349-7352 is wrong(as I mentioned - I'm not a C#-guru):
The Code:
/// <summary>Retrieve either deleted users or all users in a domain (paginated)</summary>
public virtual ListRequest List() {
return new ListRequest(service);
}
Why I find it odd:
I can' see where to pass the customerid or domain as an argumant to this request, but in the APIs Explorer it's needed (otherwise I get the same error message as above, in my original post).
Edit : I looked a bit further down in the file and I guess that line 8904 and onwards is doing what I looked for earlier. My Bad!
But still I can't get my code to work?!?!?
And my code that won't work:
static void Main(string[] args)
{
// Display the header and initialize the sample.
CommandLine.EnableExceptionHandling();
Console.WriteLine("List users in a google apps domain!");
Console.WriteLine("by Jonas Bergstedt 2013");
// Get the domainname
Console.Write("Domain: ");
string domain = Console.ReadLine();
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = <myClientId>,
ClientSecret = <myClientSecret>",
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "List Users",
ApiKey = <myApiKey>
});
// Trying to add the domain
service.Users.List().Domain = domain;
Users results = service.Users.List().Execute();
foreach (User list in results.UsersValue)
{
Console.WriteLine("- " + list.Name);
}
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { DirectoryService.Scopes.AdminDirectoryUser.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.WriteLine();
Console.Write("Authorization Code: ");
string authCode = Console.ReadLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
ListRequest had those properties. It looks like those properties aren't mandatory, so they aren't part of the constructor.
You can do the following:
var listReq = service.Users.List();
listReq.Customer = "CUSTOMER_HERE";
listReq.Domain = "DOMAIN_HERE";
Users results = listReq.Execute();
So I've looked at all the of the suggestions from the Linq to Twitter documentation regarding 401 statuses with Oauth and I honestly don't know what I'm doing wrong.
var auth = new PinAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
//OAuthToken = ConfigurationManager.AppSettings["twitterOAuthToken"], //don't include this
//AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"] //or this for new users.
},
//
UseCompression = true,
GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
GetPin = () =>
{
Console.WriteLine("/nAfter twitter authorizes your application you will be returned here or something/n");
Console.Write("Enter Pin here:");
return Console.ReadLine();
}
};
auth.Authorize();
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/",
"https://search.twitter.com/"))
{
try
{
twitterCtx.Log = Console.Out;
Console.WriteLine("Please provide tweet text");
string tweet = Console.ReadLine();
twitterCtx.UpdateStatus(tweet);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
I've ran this using the Pin Authentication method as well as the single user method (providing the oauth keys with config file). I'm able to query tweets but I can't update my status or send direct messages (I receive a 403 forbidden when I try to DM). I've provided a callback URL (albeit fake) so I can't think of why this isn't working. Any help would be appreciated.
PS this runs in Main, not sure if that matters
All you need is this overload of the TwitterContext ctor and it will use the proper base URLs:
new TwitterContext(auth)
The example you're using is for v1.0 URLs and LINQ to Twitter is on Twitter API v1.1 now. It will default to the proper base URLs.
If you're querying okay, but getting errors on update and DM, double check to make sure you aren't trying to tweet the same text. That's why I append a DateTime.Now to the end of test tweets - to guarantee uniqueness.
I am using azure Access Control Service (ACS). I am trying to get the list of Identity providers which i was selected for my application. For this i am using the following code From Here:
public ActionResult IdentityProviders(string serviceNamespace, string appId)
{
string idpsJsonEndpoint = string.Format(IdentityProviderJsonEndpoint, serviceNamespace, appId);
var client = new WebClient();
var data = client.DownloadData(idpsJsonEndpoint);
return Content(Encoding.UTF8.GetString(data), "application/json");
}
Can anybody please tell me what is appId and where do i get it?
As per the link you provided you need to get that from here.
https://portal.appfabriclabs.com
Also check for the below line in the link
{ serviceNamespace = "YourServiceNamespace", appId = "https://localhost/<YourWebApp>/" }))',
The appId will be the one you will get after registration