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()
}
Related
I'm using Ackara/Plaid.NET (https://github.com/Ackara/Plaid.NET) but for lack of documentation, I'm stuck on how to get the Routing # and Account #.
Have anyone implemented Plaid with .Net willing to share?
Tried to use the code below but didn't work
var request = await client.FetchAccountInfoAsync(new Acklann.Plaid.Auth.GetAccountInfoRequest()
{
AccessToken = accessToken.AccessToken,
ClientId = "<clientid>",
Secret = "<secret>",
Options = new Acklann.Plaid.Auth.GetAccountInfoOptions
{
AccountIds = bankId
}
});
Sorry I should have been more specific when I said it didn't work. This is the error message I got but I'm lost on how to make it work.
Error Message:
You are passing a string as an AccountId. AccountID is an array of strings. I changed the following line and it worked for me.
AccountIds = new string[] { "xxxxxxxxxxx" }
I'm finding very little documentation online for implementing the PayPal REST API in C#.
I have gotten past the first step of getting an access token, but I keep seeing conflicting methods for sending API calls and nothing I have tried works.
Here's my current code:
private async void cmdRefund_Click(object sender, EventArgs e)
{
//var apiContext = Configuration.GetAPIContext();
string AccessToken;
string Nonce;
string AppID;
string TokenType;
try
{
// ClientId of your Paypal app API
//This is the live ID
string APIClientId = "AZxxxx-8";
//this is the live secret Key
string APISecret = "Exxxx39";
using (var client = new HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
//this is the live url
var url = new Uri("https://api.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var resp = await webresponse.Content.ReadAsStringAsync();
MessageBox.Show(resp);
if (resp.IndexOf("access_token") == -1)
{
MessageBox.Show("PayPal Authorization Failed.");
return;
}
AccessToken = resp.Substring(resp.IndexOf("access_token") + 15);
AccessToken = AccessToken.Substring(0, AccessToken.IndexOf("\""));
Nonce = resp.Substring(resp.IndexOf("nonce") + 8);
Nonce = Nonce.Substring(0, Nonce.IndexOf("\""));
AppID = resp.Substring(resp.IndexOf("app_id") + 9);
AppID = AppID.Substring(0, AppID.IndexOf("\""));
TokenType = resp.Substring(resp.IndexOf("token_type") + 13);
TokenType = TokenType.Substring(0, TokenType.IndexOf("\""));
MessageBox.Show("Access Token: \r\n" + AccessToken + "\r\nNonce:\r\n" + Nonce + "\r\nAppID:\r\n" + AppID + "\r\nToken Type:\r\n" + TokenType);
// response will deserialized using Jsonconver
//return JsonConvert.DeserializeObject<PayPalGetTokenResponse>(resp);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
//Authorization has been achieved here - now I want to process a refund
var apiContext = new APIContext(AccessToken);
Amount refundAmount = new Amount();
refundAmount.total = "0.01";
refundAmount.currency = "USD";
Refund refund = new Refund();
refund.amount = refundAmount;
string saleId = "9XY489008U7836633";
//*************THIS NEXT LINE CAUSES AN ERROR
Refund refundforreal = Sale.Refund(apiContext, saleId, refund);
//*************
string refundId = refund.id;
}
The last line causes the Error: "PayPal.IdentityException: 'The remote server returned an error: (401) Unauthorized.'"
As far as I can tell, my access token is completely valid, but this does not work. I should note that I the transactions I'm trying to get information on and refund are NOT placed via the REST API, but are simply placed through the regular PayPal interface integrated on our website. I don't know if that causes a problem or not, but that is what I need to do.
I am using a Windows Forms App written in C# in Visual Studios 2017 because I'm replacing an old VB6 program that required that the user log into a PayPal session in a browser in the program and need to replace that program with something that is both usable and familiar for our employees, AND is more forward thinking by using the REST API instead of the old method of filling in fields in a WebBrowser control.
***********EDIT************ - I added this as a follow up:
I took #shamanthGowdraShankaramurthy's advice and used Postman and managed to do what I wanted, so thank you - that did help me to know that at least what I want to do is possible.
I still don't know how to do the POST in C#. I think perhaps I'll stay away from the built in "Refund" object in the SDK and instead try to POST some other way.
The url I'm using is in Postman is: https://api.paypal.com/v1/payments/sale/9XY489008U7836633/refund
I sent this as the body to do a $0.01 refund on my test transaction:
{
"amount": {
"total": "0.01",
"currency": "USD"
},
"invoice_number": "INV-1234567"
}'
I added a Bearer Token authorization to the POST with my Access Token that I had from my working code.
Finally, in Postman, I changed the body from "Text" to "JSON (application/json).
How do I incorporate all these elements (the URL, my bearer token, the body, and the information that the body is json) into a POST in a C# winforms application?
In case anyone else is looking for this, the answer turned out to be much simpler than I figured. I think I was messing myself up by not using the AccessTokens that are easily obtained by the PayPal SDK.
First, make sure that you have the App.Config file set up properly:
<!-- PayPal SDK settings -->
<paypal>
<settings>
//specify sandbox or live
<add name="mode" value="sandbox" />
<add name="clientId" value="insert_clientid_key_here" />
<add name="clientSecret" value="Insert_client_secret_key_here" />
</settings>
</paypal>
Then this is all the code I needed to make the refunds work:
private void cmdRefund_Click(object sender, EventArgs e)
{
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
Amount refundAmount = new Amount();
refundAmount.total = "0.01";
refundAmount.currency = "USD";
RefundRequest refund = new RefundRefundRequest();
refund.amount = refundAmount;
string saleId = "9XY489008U7836633";
Refund refundforreal = Sale.Refund(apiContext, saleId, refund);
MessageBox.Show("Refund status:" + refundforreal.state + "\r\n" + "Txn #:" + refundforreal.id);
}
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 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
I'm struggling with the final part of getting my first bit of code working with the AWS - I have got this far, I attached the web reference in VS and this have this
amazon.AWSECommerceService service = new amazon.AWSECommerceService();
// prepare an ItemSearch request
amazon.ItemSearchRequest request = new amazon.ItemSearchRequest();
request.SearchIndex = "DVD";
request.Title = "scream";
request.ResponseGroup = new string[] { "Small" };
amazon.ItemSearch itemSearch = new amazon.ItemSearch();
itemSearch.AssociateTag = "";
itemSearch.Request = new ItemSearchRequest[] { request };
itemSearch.AWSAccessKeyId = ConfigurationManager.AppSettings["AwsAccessKeyId"];
itemSearch.Request = new ItemSearchRequest[] { request };
ItemSearchResponse response = service.ItemSearch(itemSearch);
// write out the results
foreach (var item in response.Items[0].Item)
{
Response.Write(item.ItemAttributes.Title + "<br>");
}
I get the error
The request must contain the parameter Signature.
I know you have to 'sign' requests now, but can't figure out 'where' I would do this or how? any help greatly appreciated?
You have to add to the SOAP request headers including your Amazon access key ID, a timestamp, and the SHA256 hash of the request operation and the timestamp. To accomplish that, you would need access to the SOAP message just before it is going to be sent out. There's a walkthrough and a sample project I put together at http://flyingpies.wordpress.com/2009/08/01/17/.
For the record:
Another reason to get this error is due to keywords with spaces in it.
Example:
'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=xxx&AssociateTag=usernetmax-20&Version=2011-08-01&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=All&Keywords=Baby
Stroller&MerchantId=All&Condition=All&Availability=Available&ItemPage=1&Timestamp=2012-05-16T02:17:32Z&Signature=ye5c2jo99cr3%2BPXVkMyXX8vMhTC21UO4XfHpA21%2BUCs%3D'
It should be:
'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=xxx&AssociateTag=usernetmax-20&Version=2011-08-01&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=All&Keywords=Baby%20Stroller&MerchantId=All&Condition=All&Availability=Available&ItemPage=1&Timestamp=2012-05-16T02:17:32Z&Signature=ye5c2jo99cr3%2BPXVkMyXX8vMhTC21UO4XfHpA21%2BUCs%3D'
PHP solution:
$Keywords = str_replace(' ', '%20', $Keywords);
or
$Keywords = urlencode($Keywords);