I'm trying to send the Unicode value to WCF web service from Android app but I keep getting the string value as ????? in WCF web service. Below are the android code and C# code for web service.
GTPostData gtPostData = new GTPostData(); //DTO Object
Gson gson = new Gson();
String post = "イメージお願いし";
gtPostData.setPortalId(portalId);
gtPostData.setPost(post);
gtPostData.setProjectId(data.getProjectId());
gtPostData.setQuestionId(data.getQuestionId());
gtPostData.setUserId(panelistId);
GTPostDataRequest request = new GTPostDataRequest();
request.setGtPostData(gtPostData);//creating the request object
JSONObject jsonObject = new JSONObject(gson.toJson(request));
String webServiceUrl= ResourcePicker.getServiceURL(session.getPortal(),session.getPortalId(),true);
String addGtPostMethod = ResourcePicker.getString(portal, "add_gt_post");
AsyncPostRequest asyncRequest = new AsyncPostRequest();
asyncRequest.setServiceMethod(addGtPostMethod);
asyncRequest.setServiceUrl(webServiceUrl);
asyncRequest.setPostObject(jsonObject);//set object for post call
SendGtPostAsyncService asyncService = new SendGtPostAsyncService(asyncRequest, context, session, db, data.getPostId());
asyncService.execute();//call the async task
WCF web service call (C#)
public bool AddGTPost(GTPostData GtPostData)
{
bool isAdded = false;
try
{
sci.Debug(frendlyName, screenName, "", "Enter AddGTPost ->> " + GtPostData);//These are trace methods which will print the results in txt file.
sci.Debug(frendlyName, screenName, "", "Enter AddGTPost - Unicode Post ->> " + GtPostData.post);//These are trace methods which will print the results in txt file. Here I'm getting results as "??????"
So please some one help me what is my mistake here?
For your webservice I hope you are not missing UTF-16 format
also in the configuration you are using :
Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
GlobalizationSection configSection = (GlobalizationSection)config.GetSection("system.web/globalization");
configSection.RequestEncoding = Encoding.Unicode;
configSection.ResponseEncoding = Encoding.Unicode;
Related
I am totally new to SalesForce Marketing cloud.
We have a “Triggered Send” created using “Content Builder” with an email body with HTML attribuites. For eg. %%=v(#EVENT)=%% Invitation
There is a Customer_key for this TriggerSendDefinition
I am using FuelSDK – to TriggerSend this email.
I have NUget Package manager install Fuel SDK in my Visual studio 2019 project.
The App.config has the “clientId” and “clientSecret” values in the FuelSDK config section.
Here is my code below.
public void TestInvitationSend(string CustomerKey)
{
string myName = "John Adams";
string myEvent = "13989";
string fullurl = baseAPIAuthURL + AuthTokenUrl; // Values passed in
NameValueCollection parameters = new NameValueCollection();
parameters.Add("clientId", clientId);
parameters.Add("clientSecret",clientSecret);
parameters.Add("accountId", "account123");
**ETClient myclient = new ETClient(parameters);**
TriggeredSendDefinition definition = new TriggeredSendDefinition();
definition.CustomerKey = customerKey;
//subscriber to whom email is sent
Subscriber subscriber = new Subscriber();
subscriber.EmailAddress = myTest#test.com;
subscriber.SubscriberKey = myTest#test.com;
TriggeredSend triggeredsend = new TriggeredSend();
triggeredsend.TriggeredSendDefinition = definition;
triggeredsend.AuthStub = myclient;
triggeredsend.CustomerKey = customerKey;
triggeredsend.Subscribers = new Subscriber[] { subscriber };
SendReturn results = triggeredsend.Send();
Console.WriteLine("Send Status: " + results.Status.ToString());
}
I am getting a 404 error at the line in “bold” when initializing myClient and unable to pass-in values dynamically. Could not find much documentation for email send through code.
Can you point me to some examples of TriggerSend emails using REST API ?
Thanks
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);
}
I am trying to integrate Paypal payments in a .NET 4.0 C# WinForm application doing a DirectPayment (without opening the browser with the paypal site) trought an asmx webservices calling this method from a WebMethod
public DoDirectPaymentResponseType DoDirectPaymentAPIOperation(string
amountinUSDollar, string creditCardType, string creditCardNumber, int
exp_month, int exp_year, string firstName, string middleName, string
lastName, string address1, string address2, string city, string state,
string zip, string phoneNumber, string CVV2)
{
DoDirectPaymentResponseType response = new
DoDirectPaymentResponseType();
DoDirectPaymentReq wrapper = new DoDirectPaymentReq();
DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
DoDirectPaymentRequestDetailsType requestDetails = new
DoDirectPaymentRequestDetailsType();
requestDetails.PaymentAction = (PaymentActionCodeType)
Enum.Parse(typeof(PaymentActionCodeType), "SALE");
CreditCardDetailsType creditCard = new CreditCardDetailsType();
PayerInfoType cardOwner = new PayerInfoType();
PersonNameType payer = new PersonNameType();
payer.FirstName = firstName;
payer.MiddleName = middleName;
payer.LastName = lastName;
cardOwner.PayerName = payer;
creditCard.CardOwner = cardOwner;
creditCard.CreditCardNumber = creditCardNumber;
if (creditCardType == "VISA")
{
creditCard.CreditCardType = CreditCardTypeType.VISA;
}
else if (creditCardType == "MasterCard")
{
creditCard.CreditCardType = CreditCardTypeType.MASTERCARD;
}
creditCard.CVV2 = CVV2;
creditCard.ExpMonth = exp_month;
creditCard.ExpYear = exp_year;
requestDetails.PaymentDetails = new PaymentDetailsType();
requestDetails.PaymentDetails.NotifyURL = "http://IPNhost";
BasicAmountType paymentAmount = new
BasicAmountType(CurrencyCodeType.USD, amountinUSDollar);
requestDetails.PaymentDetails.OrderTotal = paymentAmount;
wrapper.DoDirectPaymentRequest = request;
Dictionary<string, string> config = getConfigDict();
PayPalAPIInterfaceServiceService service = new
PayPalAPIInterfaceServiceService(config);
response = service.DoDirectPayment(wrapper);
}
When it try to make the call to the API, in the last line of the code I get this error:
"Exception in HttpConnection Execute: Invalid HTTP response The request was aborted: Could not create SSL/TLS secure channel."} System.Exception {PayPal.Exception.PayPalException}.
I had a .NET 4.5 WebForm web application with Paypal integrated in which I had to define this
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
in its Global.asax file and it solves the problem for that specific application and I have found I have to use this
ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072;
for .NET 4.0 but my question is:
If this would be the solution to may problem, where should I put this line in my code? Because there is no Global.asax in my asmx webservice.
Outlining the source of the reported issue above as per the comments in the OP. The exception was thrown because the NotifyURL wasn't in https.
I'm hoping someone can help. I have been asked to write a test application to consume a Web API.
The method I'm trying to consume, has the following signature:
[Transaction]
[HttpPost]
[Route("api2/Token/")]
public ApiToken Token(Guid companyId, DateTime dateTime, string passCode)
I've written a simple C# console application. However whatever I send to the API returns with a 404 error message and I can't see what my issue is.
My code to consume the API is as follows:
_client.BaseAddress = new Uri("http://localhost:1390");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var companyId = Guid.Parse("4A55A43A-5D58-4245-AD7C-A72300A69865");
var apiKey = Guid.Parse("FD9AEE25-2ABC-4664-9333-B07D25ECE046");
var dateTime = DateTime.Now;
var sha256 = SHA256.Create();
var bytes = Encoding.UTF8.GetBytes(string.Format("{0}:{1:yyyyMMddHHmmss}:{2}", companyId, dateTime, apiKey));
var hash = sha256.ComputeHash(bytes);
var sb = new StringBuilder();
foreach (var b in hash)
{
sb.Append(b.ToString());
}
try
{
Console.WriteLine("Obtain an authorisation token");
var response = await _client.PostAsJsonAsync("api2/Token/", new { companyId = companyId, dateTime = dateTime, passCode = sb.ToString() });
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
All examples I've googled seem to post an object to a Web API method that accepts an object. Is it possible to post multiple simple types?
I don't think it's possible, from the documentation (https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api)
They've stated that
If the parameter is a "simple" type, Web API tries to get the value
from the URI.
For complex types, Web API tries to read the value from the message body
You can try to use uri parameters instead
var response = await _client.PostAsJsonAsync("api2/Token/{companyId}/{dateTime}/{sb.ToString()}");
I want to update the contents of the already uploaded Google Doc file.
I'm using the below code:
DocumentsService service = new DocumentsService("app-v1");
string auth = gLogin2();
service.SetAuthenticationToken(auth);
Stream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(
"CONTENTS PLEASE CHANGE"));
DocumentEntry entry = service.Update(new Uri("feedURL"), stream, "text/plain",
"nameOfDoc") as DocumentEntry;
For "feedURL" I tried using all the possible links: alternate, self, edit, edit-media even resumable-edit-media, but I keep on getting exceptions.
Also how do I read a response with such requests?
I just started using this API. Earlier, I was using it on the protocol level so was sending GET/POST requests and receiving web responses. I don't know how to get or read response in this case.
UPDATE:
Now the code I'm using is:
RequestSettings _settings;
string DocumentContentType = "text/html";
_settings = new RequestSettings("Stickies", "EMAIL", "PASSWORD");
var request = new DocumentsRequest(_settings);
//var entryToUpdate = doc.DocumentEntry;
var updatedContent = "new content..."; ;
var mediaUri = new Uri(string.Format(DocumentsListQuery.mediaUriTemplate, rid));
Trace.WriteLine(mediaUri);
var textStream = new MemoryStream(Encoding.UTF8.GetBytes(updatedContent));
var reqFactory = (GDataRequestFactory)request.Service.RequestFactory;
reqFactory.CustomHeaders.Add(string.Format("{0}: {1}", GDataRequestFactory.IfMatch, et));
var oldEtag = et;
DocumentEntry entry = request.Service.Update(mediaUri, textStream, DocumentContentType, title) as DocumentEntry;
Debug.WriteLine(string.Format("ETag changed while saving {0}: {1} -> {2}", title, oldEtag,et));
Trace.WriteLine("reached");
And the exception I'm getting is:
{"The remote server returned an error: (412) Precondition Failed."}
I'm getting this exception at DocumentEntry entry = request.Service.Update(mediaUri, textStream, DocumentContentType, title) as DocumentEntry;
Solved.. Exception precondition Failed was due to Etag mismatch
The above UPDATED code works perfectly for saving a document.