I have to integrate Ecom express shipping API in my code. This api is for pre generation of AWB Number at the time of order. Here is the document instruction to integrate shipping api :
Test Server URL:http://staging.ecomexpress.in/apiv2/fetch_awb/
Test Server Credentials: Username: ecomexpress Password: Ke$3c#4oT5m6h#$
Sample Request Body :
For PPD
username=ecomexpress&password=Ke$3c#4oT5m6h#$&count=1&type=PPD
For COD
username=ecomexpress&password=Ke$3c#4oT5m6h#$&count=1&type=COD
This API works fine with postman and generate AWB number also, But trying with C# code gives null object.
Check here the code I am using :
var client = new HttpHandler.Client("http://staging.ecomexpress.in/apiv2/fetch_awb/");
var newUrl = "http://staging.ecomexpress.in/apiv2/fetch_awb/?username=ecomexpress&password=Ke$3c#4oT5m6h#$&count=1&type=PPD";
var data = client.PostData<dynamic>(newUrl, new { username= "ecomexpress", password= "Ke$3c#4oT5m6h#$", count=1,type= "PPD" });
if (data!=null){ // do some stuff here }
I am using http handler nuget package (https://www.nuget.org/packages/VerveLogic.HttpHandler/)
Please help or suggest a way in which I can get AWB Number using C# code.Also check the postman and document instruction here :
You can easily make this work using HttpClient and Newtonsoft.Json, so might be something with that particular library not sending the parameters as form-urlencoded.
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", "ecomexpress"),
new KeyValuePair<string, string>("password", "Ke$3c#4oT5m6h#$"),
new KeyValuePair<string, string>("count", "1"),
new KeyValuePair<string, string>("type", "PPD"),
});
var response = await client.PostAsync("http://staging.ecomexpress.in/apiv2/fetch_awb/", content);
var body = await response.Content.ReadAsStringAsync();
var responseObject = JsonConvert.DeserializeObject<ResponseObject>(body);
}
Where ResponseObject is:
public class ResponseObject
{
[JsonProperty("reference_id")]
public int ReferenceId { get; set; }
[JsonProperty("success")]
public string SuccessText { get; set; }
[JsonIgnore]
public bool Success => SuccessText.Equals("yes", StringComparison.OrdinalIgnoreCase);
[JsonProperty("awb")]
public int[] Awb { get; set; }
}
Related
I am learning as I create, that being said, I have spent quite a few hours on JUST the login/register pages in the app I am trying to make.
I have finally got to the point where I am able to make the API call to get the response back with the information I need.
I just don't know how to save the token once it comes back.
I am using SQLite for local storage, and I have a "Token" nclass to save it to, but I can't figure out how to actually save it and continue forward.
(I could be completely wrong and it doesn't work at all, but that's all part of learning, I guess.)
anyways, here is my Token class
public class Token
{
[PrimaryKey]
public int Id { get; set; }
public string accessToken { get; set; }
public string errorDescription { get; set; }
public DateTime expireDate { get; set; }
public int expireIn { get; set; }
public Token() { }
}
and here is my APIServices class (some stuff is commented because I am working with my buddy to get everything sorted on the API side)
public class ApiServices
{
public string JsonResult { get; private set; }
public async Task<bool> RegisterUserAsync(string email, string name, /*string first_name, string last_name,*/ string password)
{
var client = new HttpClient();
var model = new RegisterBindingModel
{
Email = email,
//FirstName = first_name,
//LastName = last_name,
Name = name,
Password = password,
};
var json = JsonConvert.SerializeObject(model);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("https://myurl/v1/auth/register", httpContent);
if (response.IsSuccessStatusCode)
{
var result = JsonConvert.DeserializeObject(JsonResult);
return true;
}
return false;
}
public async Task<string> LoginAsync(string email, string password)
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
var request = new HttpRequestMessage(HttpMethod.Post, "https://myurl/auth/login" + "Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(content);
var accessTokenExpiration = jwtDynamic.Value<DateTime>(".expires");
var accessToken = jwtDynamic.Value<string>("access_token");
//Settings.AccessTokenExpirationDate = accessTokenExpiration;
Debug.WriteLine(accessTokenExpiration);
Debug.WriteLine(content);
return accessToken;
}
}
Lets explain it step by step:
1.Install the sqlite-net-pcl package(Nuget URL). This package will help you to work with database in an easy way.
2.After installing it successfully, You need to add the using statement of SQLite to your class:
using SQLite;
3.In order to make a request to database, you will need to first make a connection to database. to do so, you need to declare a variable for aforementioned goal:
var db = new SQLiteConnection (dbPath);
4.Once you have the database connection object, you are ready to make requests to database. for example to save an object of type Token class, just do this:
var tokenInfo= new Token();
tokenInfo.accessToken="...";//set value to other properties like this
db.Insert(tokenInfo);
These are all you need to do an Insert request to database!
You might want to read more about aforementioned package in these urls:
https://github.com/praeclarum/sqlite-net
https://learn.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-sqlite-orm
I am trying to get this azure API to work:
https://learn.microsoft.com/en-us/rest/api/machinelearning/webservices/createorupdate
The following code runs a GET request which returns successfully (200 OK and return body), but the Put request to the exact same uri at the bottom fails with a 400 "Bad request".
The code inbetween basically just unwraps the json output of the first request and tried to send the same unchanged data in the input format of the PUT on the same uri.
Could anyone help me see why this fails?
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await httpClient.GetAsync($"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.MachineLearning/webServices/{serviceName}?api-version=2016-05-01-preview");
var json = await response.Content.ReadAsStringAsync();
var f = JsonConvert.DeserializeObject<WebService>(json);
var requestBody = new RequestBody()
{
location = f.Location,
name = f.Name,
tags = f.Tags,
properties = f.Properties
};
var jsoncontent = JsonConvert.SerializeObject(requestBody, Formatting.None);
var content = new StringContent(jsoncontent, Encoding.UTF8, "application/json"); //tried simpler things like "{\"location\":\"West Europe\"}" with no result
var response2 = await httpClient.PutAsync($"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.MachineLearning/webServices/{serviceName}?api-version=2016-05-01-preview", content, new JsonMediaTypeFormatter());
// last line returns a 400 bad request only.
And then I use this custom object;
private class RequestBody
{
public string location { get; set; }
public string name { get; set; }
public WebServiceProperties properties { get; set; }
public IDictionary<string, string> tags { get; set; }
}
It seems it was one of those obvious things.
The ", new JsonMediaTypeFormatter()" snippet at the end ruined it. Removing it fixed the issue and it returns 200 OK without it.
i use asp.net mvc and c#,
i my bank setion project i use this code for banking
var requestContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("amount", payment.Amount), //i want change this section for <string,int>
new KeyValuePair<string, string>("transid", "id"),
new KeyValuePair<string, string>("pin","pin" )
});
var client = new HttpClient();
HttpResponseMessage response = await client.PostAsync("http://address.com/api/verify/", requestContent);
HttpContent responseContent = response.Content;
string result = "";
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
result = await reader.ReadToEndAsync();
}
now my bank scenario is change and i should pass integer for amount,how i can do i from mycode?
because FormUrlEncodedContent accept <string,string>
thank you for your help
Try this, It is working for me.
public class PaymentActionsRequest
{
[JsonProperty("payment_intent")]
public string PaymentIntent { get; set; }
[JsonProperty("amount")]
public long Amount { get; set; }
}
var keyValueContent = PaymentActionsRequest.ToKeyValue();
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
You need to use something like Amount.ToString() as this content would eventually be string/encoded as part of POST body.
Okay I have limited understanding of working with API's
Im trying to get to grips with Adobe Sign API and hit a dead end, on there test page i have enterd this and it works
But i have no idea on how then do that in C#
I have tried the following, but know its missing the OAuth stuff and I'm just not sure what to try next.
by the way foo.GetAgreementCreationInfo() just gets the string that is in the screen shot, I just moved it out cus it was big and ugly
var foo = new Models();
var client = new RestClient("https://api.na1.echosign.com/api/rest/v5");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("agreements/{AgreementCreationInfo}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("AgreementCreationInfo", foo.GetAgreementCreationInfo()); // replaces matching token in request.Resource
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
You are misinterpreting the API documentation. The Access-Token parameter needed in your API is clearly an HTTP header, while the AgreementCreationInfo is simply the request body in JSON format. There is no URI segment, so rewrite your code as follows:
var foo = new Models();
//populate foo
var client = new RestClient("https://api.na1.echosign.com/api/rest/v5");
var request = new RestRequest("agreements", Method.POST);
request.AddHeader("Access-Token", "access_token_here!");
// request.AddHeader("x-api-user", "userid:jondoe"); //if you want to add the second header
request.AddParameter("application/json", foo.GetAgreementCreationInfo(), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var content = response.Content;
Please also be aware that in RESTSharp you do not need to manually serialize your body into JSON at all. If you create a strongly typed object (or just an anonymous object could be enough) that has the same structure of your final JSON, RESTSharp will serialize it for you.
For a better approach I strongly suggest you to replace this line:
request.AddParameter("application/json", foo.GetAgreementCreationInfo(), ParameterType.RequestBody);
With those:
request.RequestFormat = DataFormat.Json;
request.AddBody(foo);
Assuming your foo object is of type Models and has the following structure along with its properties:
public class Models
{
public DocumentCreationInfo documentCreationInfo { get; set; }
}
public class DocumentCreationInfo
{
public List<FileInfo> fileInfos { get; set; }
public string name { get; set; }
public List<RecipientSetInfo> recipientSetInfos { get; set; }
public string signatureType { get; set; }
public string signatureFlow { get; set; }
}
public class FileInfo
{
public string transientDocumentId { get; set; }
}
public class RecipientSetInfo
{
public List<RecipientSetMemberInfo> recipientSetMemberInfos { get; set; }
public string recipientSetRole { get; set; }
}
public class RecipientSetMemberInfo
{
public string email { get; set; }
public string fax { get; set; }
}
Link to AdobeSign Repository:
ADOBE SIGN SDK C# SHARP API Ver. 6
Adobe Sign API integrators - this is kind of hidden away in AdobeSigns GIT repositories. The link to all the generated SWAGGER classes (models/methods) for C# and REST client integrated C# project in a GIT project you can compile and use right inside your project as a project reference or compiled DLL. This project has been updated to use version 6 of the API. This was a huge time saver for me. I have provided a quick example below on how to use it. I hope this helps others save time as well.
Note you might have to switch out BasePath in the configuration.cs so you can retrieve the initial Adobe URI "BaseURI" call if you get 404 error.
Change BasePath = "http://localhost/api/rest/v6";
To:
BasePath = "https://api.echosign.com/api/rest/v6";
//include namespaces:
using IO.Swagger.Api;
using IO.Swagger.model.agreements;
using IO.Swagger.model.baseUris;
using IO.Swagger.model.transientDocuments;
using System.IO;
Then this quick minimal demonstrates BaseUri, Upload PDF a.k.a. Transient Document, then Create Agreement (Example 1 Basic Signer Minimal Options)
string transientDocumentId = "";
string adobesignDocKey = "";
string baseURI = "";
var apiInstanceBase = new BaseUrisApi();
var authorization = "Bearer " + apiKey; //Example as Integration Key, see adobesign docs For OAuth.
try
{
//___________________GET BASEURI ADOBE SIGN_________________________
BaseUriInfo resultBase = apiInstanceBase.GetBaseUris(authorization);
baseURI = resultBase.ApiAccessPoint; //return base uri
//___________________UPLOAD YOUR PDF THEN REF ADOBE SIGN_________________________
var apiInstanceFileUpload = new TransientDocumentsApi(baseURI + "api/rest/v6/");
TransientDocumentResponse resultTransientID = apiInstanceFileUpload.CreateTransientDocument(authorization, File.OpenRead([ENTER YOUR LOCAL FILE PATH]), null, null, _filename, null);
if (!String.IsNullOrEmpty(resultTransientID.TransientDocumentId))
{
transientDocumentId = resultTransientID.TransientDocumentId; //returns the transient doc id to use below as reference
}
var apiInstance = new AgreementsApi(baseURI + "api/rest/v6/");
//___________________CREATE ADOBE SIGN_________________________
var agreementId = ""; // string | The agreement identifier, as returned by the agreement creation API or retrieved from the API to fetch agreements.
var agreementInfo = new AgreementCreationInfo();
//transientDocument, libraryDocument or a URL (note the full namespace/conflicts with System.IO
List<IO.Swagger.model.agreements.FileInfo> useFile = new List<IO.Swagger.model.agreements.FileInfo>();
useFile.Add(new IO.Swagger.model.agreements.FileInfo { TransientDocumentId = transientDocumentId });
agreementInfo.FileInfos = useFile;
//Add Email To Send To:
List<ParticipantSetMemberInfo> partSigners = new List<ParticipantSetMemberInfo>();
partSigners.Add( new ParticipantSetMemberInfo { Email = "[ENTER VALID EMAIL SIGNER]", SecurityOption=null });
//Add Signer To Participant
List<ParticipantSetInfo> partSetInfo = new List<ParticipantSetInfo>();
partSetInfo.Add(new ParticipantSetInfo { Name = "signer1", MemberInfos = partSigners, Role = ParticipantSetInfo.RoleEnum.SIGNER, Order=1, Label="" });
agreementInfo.ParticipantSetsInfo = partSetInfo;
agreementInfo.SignatureType = AgreementCreationInfo.SignatureTypeEnum.ESIGN;
agreementInfo.Name = "Example Esign For API";
agreementInfo.Message = "Some sample Message To Use Signing";
agreementInfo.State = AgreementCreationInfo.StateEnum.INPROCESS;
AgreementCreationResponse result = apiInstance.CreateAgreement(authorization, agreementInfo, null, null);
adobesignDocKey = result.Id; //returns the document Id to reference later to get status/info on GET
}
catch (Exception ex)
{
//Capture and write errors to debug or display to user
System.Diagnostics.Debug.Write(ex.Message.ToString());
}
I am trying to use http Client to make a call to Web API to get the token.I have one MVC app and Web API app.below is the MVC controller action I have.
[HttpPost]
public ActionResult Login()
{
LoginModel m = new LoginModel();
m.grant_type = "password";
m.username = "xxx";
m.password = "xxx1234";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:51540/");
var response = client.PostAsJsonAsync("Token", m).Result;
response.EnsureSuccessStatusCode();
return View();
}
But when I make the request the API responds as BAD request. I tried to add the content type as "application/json" and have confirmed using fiddler that the request is of type json.
I am able to register the user using Web API so at WebAPI side things are looking fine to me,I am using default project created by VS2013 using Individual account and haven't modified any thing on API side.
I am following this tutorial http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api and trying to use HTTP Client instead of fiddler.
I will be thankful if someone helps me
TokenEndpointRequest seems doesn't support JSON yet, but you can use query string
var response = client.PostAsync("Token", new StringContent("grant_type=password&username=xxx&password=xxx1234", Encoding.UTF8)).Result;
Here's my code from the answer & comment above
using (var client = new HttpClient{ BaseAddress = new Uri(BaseAddress) })
{
var token = client.PostAsync("Token",
new FormUrlEncodedContent(new []
{
new KeyValuePair<string,string>("grant_type","password"),
new KeyValuePair<string,string>("username",user.UserName),
new KeyValuePair<string,string>("password","P#ssW#rd")
})).Result.Content.ReadAsAsync<AuthenticationToken>().Result;
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(token.token_type, token.access_token);
// actual requests from your api follow here . . .
}
created an AuthenticationToken class for beautification purposes:
public class AuthenticationToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
}