Can not show API response message in C# Code - c#

I am going to generate Eway Bill API from below Request.The response of below request is showing fine in "Postmen" but at the same time when I execute this below request from C# Code then its shows an error message as "The remote server returned an error: (400) Bad Request.".
I would like to know how to show the postmen error message in C# Code.
URL :-
https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/GLD23985?activity_type=GENERATE_EWB
Header :-
Content-type : application/json
X-Cleartax-Auth-Token : b1f57327-96db-4829-97cf-2f3a59a3a548
taxable_entity_id : b1f57327-96db-4829-97cf-2f3a59a3a548
Body :-
{
"id": "GLD23985",
"transaction_date": "26/10/2020",
"source": "USER",
"document_number": "BQ/20/0251",
"type": "OUTWARD",
"transport_mode": "ROAD",
"dispatch_from_state": "HARYANA",
"sub_supply": "Supply",
"distance": "90",
"vehicle_number": "TN32N1049",
"document_type": "Tax Invoice",
"seller": {
"address1": "142/1,Trunk Road",
"address2": "Perumugai",
"city": "Via Vellore",
"gstin": "29AEKPV7203E1Z9",
"name": "K.H Exports India Private Limited",
"state": "HARYANA",
"zip_code": ""
},
"receiver": {
"address1": "4/74, VOC Street, Seenerkuppam Village, ",
"address2": "Poonamalle, Chennai 600 056",
"city": "",
"gstin": "33AAACR1714R1ZA",
"name": "KH EXPORTS INDIA PVT.LTD. (LGD)",
"state": "TAMIL NADU",
"zip_code": "600003"
},
"consignee": {
"city": "",
"state": "TAMIL NADU",
"zip_code": "600003"
},
"line_items": [
{
"cess_rate": "0",
"cess_val": "0",
"cgst_rate": "0",
"cgst_val": "0",
"description": "STYLE;91311 COLOUR;SVFD7 BELT & PA",
"gst_code": "4203",
"igst_rate": "28.00",
"igst_val": "16800.000000",
"item_code": "STYLE;91311 COLOUR;SVFD7 BELT & PA",
"quantity": "3.00",
"serial_number": "1",
"sgst_rate": "0",
"sgst_val": "0",
"taxable_val": "600.0000",
"unit_of_measurement": "NUMBERS"
},
{
"cess_rate": "0",
"cess_val": "0",
"cgst_rate": "0",
"cgst_val": "0",
"description": "STYLE;91307 COLOUR;ABFD2 BELT & PA",
"gst_code": "4203",
"igst_rate": "28.00",
"igst_val": "16800.000000",
"item_code": "STYLE;91307 COLOUR;ABFD2 BELT & PA",
"quantity": "3.00",
"serial_number": "2",
"sgst_rate": "0",
"sgst_val": "0",
"taxable_val": "600.0000",
"unit_of_measurement": "NUMBERS"
}
]
}
Response:-
{
"errors": {
"err_1": {
"code": "BAD_REQUEST_ATTR",
"message": "Pincode should have 6 digits.",
"error_group_code": 0,
"error_id": 0,
"severity": "ERROR"
}
},
"error_sources": {
"seller": {
"zip_code": {
"error_refs": [
"err_1"
]
}
}
}
}
C# Code:-
string DATA = JsonConvert.SerializeObject(tr, Newtonsoft.Json.Formatting.Indented);
using (var client = new WebClient())
{
client.Headers.Add("taxable_entities", ConfigurationManager.AppSettings["taxable_entities"]);
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/" + TblHeader.Rows[0]["id"].ToString() + "?activity_type=GENERATE_EWB";
string res = client.UploadString(url, "PUT", DATA);
}

Hi my friend you can use this code to handle your respond and get your answer.
The previous examples return an HttpResponseMessage message from the controller action, but you can also use HttpResponseException to return an HttpError. This lets you return a strongly-typed model in the normal success case, while still returning HttpError if there is an error
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
}
else
{
return item;
}
}

Related

CamelCase for property in data response

I have one API that return that :
{
"Success": true,
"Data": [
{
"ID": 1,
"ProcedureID": 1,
"Channel": "Channel 1",
"ResolvedTime": "Anytime",
"Description": "No description"
}
],
"StatusCode": 200,
"Message": ""
}
but actually I want is :
{
"Success": true,
"Data": [
{
"id": 1,
"procedureID": 1,
"channel": "Channel 1",
"resolvedTime": "Anytime",
"description": "No description"
}
],
"StatusCode": 200,
"Message": ""
}
what are happening with my list "Data", I just want the property names of all the objects inside that list formatted in camelCase. How can I do that? I'm using EF core 6 and my Program.cs already have this line:
builder.Services.AddControllers().AddNewtonsoftJson(options =>{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;});

Columns not returning correctly when using WIQL Queries from ADO

I am trying to get all Epics from ADO using the below code
string PAT = "sdsd";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
string query = "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.State], [System.AreaPath], [System.IterationPath], [System.TeamProject], [System.WorkItemType] FROM workitems WHERE System.WorkItemType='Epic' ORDER BY [System.ChangedDate] DESC ";
var q = JsonConvert.SerializeObject(new WiqlQuery() { query = query });
using (HttpResponseMessage response =client.PostAsync("https://dev.azure.com/{Org}/_apis/wit/wiql?api-version=6.0",new StringContent(q,Encoding.UTF8,"application/json")).GetAwaiter().GetResult())
{
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
string k = "";
}
}
Code executes without any trouble. But if I run the above query in ADO query editor, its returning all the columns in the Select statement.
But when I run the same in Code, I am not all getting any of those columns. Instead I am getting below JSON
{
"queryType": "flat",
"queryResultType": "workItem",
"asOf": "2021-07-02T08:30:15.84Z",
"columns": [
{
"referenceName": "System.Id",
"name": "ID",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.Id"
},
{
"referenceName": "System.WorkItemType",
"name": "Work Item Type",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.WorkItemType"
},
{
"referenceName": "System.Title",
"name": "Title",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.Title"
},
{
"referenceName": "System.State",
"name": "State",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.State"
},
{
"referenceName": "System.AreaPath",
"name": "Area Path",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.AreaPath"
},
{
"referenceName": "System.IterationPath",
"name": "Iteration Path",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.IterationPath"
},
{
"referenceName": "System.TeamProject",
"name": "Team Project",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.TeamProject"
},
{
"referenceName": "System.WorkItemType",
"name": "Work Item Type",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.WorkItemType"
}
],
"sortColumns": [
{
"field": {
"referenceName": "System.ChangedDate",
"name": "Changed Date",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.ChangedDate"
},
"descending": true
}
],
"workItems": [
{
"id": 61380,
"url": "https://dev.azure.com/{organization}/_apis/wit/workItems/613810"
},
{
"id": 61834
}
]
}
What could be the reason or how to get all the columns of data we have specified in Select statement
Yes, RUN WIQL returns only the list of ids. Then you can use Get Work Items Batch to get only needed fields:
POST https://dev.azure.com/fabrikam/_apis/wit/workitemsbatch?api-version=6.1-preview.1
BODY:
{
"ids": [
297,
299,
300
],
"fields": [
"System.Id",
"System.Title",
"System.WorkItemType",
"Microsoft.VSTS.Scheduling.RemainingWork"
]
}

Create Graph Event with Room as location using C# and Microsoft.Graph nuget

Not sure how to do the location with a room in C# and Microsoft.Graph.
I want to create an event that would put the event in a room. I now the room’s email - Rainier#M365x947151.onmicrosoft.com . The code I am trying is as follows using Microsoft.Graph.
Microsoft.Graph.PhysicalAddress address = new Microsoft.Graph.PhysicalAddress();
Microsoft.Graph.Location loc = new Location();
loc.Address = address;
loc.DisplayName = "Rainier conf room";
loc.LocationEmailAddress = rainier;
var newEvent = new Event();
newEvent.Subject = subject + DateTime.Now.ToLongDateString();
newEvent.Location = loc;
newEvent.Attendees = attendees;
newEvent.Body = eventBody;
newEvent.Start = eventStartTime;
newEvent.End = eventEndTime;
Microsoft.Graph.Event createdEvent = null;
try
{
// graphclient is passed into this method
// var graphClient = AuthenticationHelper.GetAuthenticatedClient();
// var graphClient = devfish.Graph.AuthenticationHelper.MyGraphClient;
createdEvent = await graphClient.Me.Events.Request().AddAsync(newEvent);
The payload I am sending up SHOULD look something like this, but what it doesn’t look like is below. Outlook doesn’t treat it as a “room”. Thanks…
PAYLOAD WE WANT - note the odatatype and microsoft.graph.physicaladdress ...
{
"subject": "Test meeting",
"body": {
"contentType": "HTML",
"content": "Does this work (note the dates are in the past)?"
},
"start": {
"dateTime": "2017-12-01T12:00:00",
"timeZone": "Pacific Standard Time"
},
"end": {
"dateTime": "2017-12-01T14:00:00",
"timeZone": "Pacific Standard Time"
},
"location":{
"address": {"#odata.type": "microsoft.graph.physicalAddress"},
"displayName": "Rainier conf room"
},
"attendees": [
{
"emailAddress": {
"address":"joseph.healy#microsoft.com",
"name": "Joe"
},
"type": "required"
},
{
"emailAddress": {
"address":"Rainier#M365x947151.onmicrosoft.com",
"name": "Rainier"
},
"type": "Resource"
}
]
}
But instead up payload looks like this when created with C# graph.
{
"subject": "23: 42:39: BASKETBALL IS OUR SUBJECT FOR TODAYTuesday, January 9, 2018",
"body": {
"contentType": "text",
"content": "Status updates, blocking issues, and next steps"
},
"start": {
"dateTime": "2017-12-01T19:30:00.0000000",
"timeZone": "UTC"
},
"end": {
"dateTime": "2017-12-01T20:00:00.0000000",
"timeZone": "UTC"
},
"location": {
"displayName": "Rainier conf room",
"locationEmailAddress": "Rainier#M365x947151.onmicrosoft.com",
"address": {}
},
"attendees": [
{
"type": "required",
"emailAddress": {
"address": "alexw#m365x947151.onmicrosoft.com"
}
},
{
"type": "required",
"emailAddress": {
"address": "maria#fabrikam.com"
}
},
{
"type": "resource",
"emailAddress": {
"address": "Rainier#M365x947151.onmicrosoft.com"
}
}
]
}
Thanks for any help.
To get the payload you want, you'll need to:
Remove loc.LocationEmailAddress = rainier;
Add the key-value "#odata.type", "microsoft.graph.physicalAddress" to
location.AdditionalData. We had someone else recently ask for
automatic #odata.type generation so this is an additional data point
for that.
Add the name property to the room emailAddress object.

C# Parsing JSON w/ Newtonsoft

I'm very new to c#, so I apologize if this doesn't make any sense!
Using a C# console application, I'm having a hard time parsing a detailed json response and assigning json values to variables. I thought I had everything working by deserializing the json to a string until about 200 iterations in (I'll be geocoding over a million addresses), I received a response with an empty result array that crashed my application. Now I'm trying a new approach using JObject, JProperty, and JToken, but not having much luck.
My json example is is follows ..
{
"input": {
"address_components": {
"number": "123",
"predirectional": "E",
"street": "Main",
"suffix": "St",
"formatted_street": "E Main St",
"city": "Mesa",
"state": "AZ",
"zip": "85209",
"country": "US"
},
"formatted_address": "123 E Main St, Mesa, AZ 85209"
},
"results": [
{
"address_components": {
"number": "123",
"predirectional": "E",
"street": "Main",
"suffix": "St",
"formatted_street": "E Main Ave",
"city": "Mesa",
"county": "Maricopa County",
"state": "AZ",
"zip": "85209",
"country": "US"
},
"formatted_address": "123 E Main St, Mesa, AZ 85209",
"location": {
"lat": 33.123456,
"lng": -111.123456
},
"accuracy": 1,
"accuracy_type": "range_interpolation",
"source": "TIGER\/Line\u00ae dataset from the US Census Bureau",
"fields": {
"congressional_district": {
"name": "Congressional District 5",
"district_number": 5,
"congress_number": "114th",
"congress_years": "2015-2017"
},
"state_legislative_districts": {
"senate": {
"name": "State Senate District 16",
"district_number": "16"
},
"house": {
"name": "State House District 16",
"district_number": "16"
}
},
"school_districts": {
"unified": {
"name": "Gilbert Unified District",
"lea_code": "0403400",
"grade_low": "PK",
"grade_high": "12"
}
},
"timezone": {
"name": "MST",
"utc_offset": -7,
"observes_dst": false
}
}
},
{
"address_components": {
"number": "123",
"predirectional": "E",
"street": "Main",
"suffix": "St",
"formatted_street": "E Main St",
"city": "Mesa",
"county": "Maricopa County",
"state": "AZ",
"zip": "85209",
"country": "US"
},
"formatted_address": "123 E Main St, Mesa, AZ 85209",
"location": {
"lat": 33.123456,
"lng": -111.123456
},
"accuracy": 0.8,
"accuracy_type": "range_interpolation",
"source": "TIGER\/Line\u00ae dataset from the US Census Bureau",
"fields": {
"congressional_district": {
"name": "Congressional District 5",
"district_number": 5,
"congress_number": "114th",
"congress_years": "2015-2017"
},
"state_legislative_districts": {
"senate": {
"name": "State Senate District 16",
"district_number": "16"
},
"house": {
"name": "State House District 16",
"district_number": "16"
}
},
"school_districts": {
"unified": {
"name": "Gilbert Unified District",
"lea_code": "0403400",
"grade_low": "PK",
"grade_high": "12"
}
},
"timezone": {
"name": "MST",
"utc_offset": -7,
"observes_dst": false
}
}
}
]
}
The json that broke my original code ..
{
"input": {
"address_components": {
"number": "123",
"predirectional": "E",
"street": "Main",
"suffix": "St",
"formatted_street": "E Main St",
"city": "Mesa",
"state": "AZ",
"zip": "85209",
"country": "US"
},
"formatted_address": "123 E Main St, Mesa, AZ 85209"
},
"results": []
}
The original code ..
Uri uri = new Uri("https://api.geocod.io/v1/geocode?q=" + geocodioAddress + "&fields=cd,stateleg,school,timezone&api_key=" + app_key);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string output = reader.ReadToEnd();
response.Close();
dynamic array = JsonConvert.DeserializeObject(output);
if (array.results[0] != null)
{
// cont.
}
The error msg was "Index was out of range. Must be non-negative and less than the size of the collection." The error occurs at "if (array.results[0] != null)".
Now I'm sure this isn't the best approach anyways, so I thought I'd try something new (found here: C# Parsing JSON array of objects) ..
Uri uri = new Uri("https://api.geocod.io/v1/geocode?q=" + geocodioAddress + "&fields=cd,stateleg,school,timezone&api_key=" + app_key);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
response.Close();
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
.Children<JObject>();
foreach (JObject result in resultObjects)
{
foreach (JProperty property in result.Properties())
{
JToken _county = property.Value.SelectToken("county");
string county = Convert.ToString(_county);
// cont.
}
}
This looked really promising, except for three things..
I don't want to parse results[1]. You'll notice in the json response, that the second results instance has a lower accuracy score. And when I don't change the lat/lng values to hide my personal address, these two instances are different with the 2nd being much less accurate.
While I successfully got the value for the county above, I can't get a response for "formatted_address", as well as the value resets each time through the foreach loop.
In the "fields" section, there are multiple objects with the same name. For example..
JToken _county = property.Value.SelectToken("name");
How do I select which "name" I'm looking for? school district, timezone, congressional district, etc..
Again, I'm sorry for such a long post. I've been working on this all week, and just when I thought I had it figured out, one stupid address has to return no results and break everything!! I really appreciate the help of people much smarter than me ... the downside of working from home, no other brains to pick :)
If you look at the data that broke your code:
{
{
"input": {
..
},
"formatted_address": "123 E Main St, Mesa, AZ 85209"
},
"results": []
}
You have results defined as an empty array. In other words it contains zero elements. Thus trying to access the first element (at index 0) in this array results in the error that you are getting.
Instead of the test that you are doing:
if (array.results[0] != null)
{
// cont.
}
you should do:
if (array.Length != 0)
{
// cont.
}
this is because the 'results' object exists, but it is empty (length is zero).

How to get state="completed" PayPal Payments

I've received this JSON after execute a payment but the state remains "pending" how can i solve this in order to obtain "completed".
I've tried several things in order to make the payment but unsuccessfully
{
"id": "PAY-2NU51454E4492922YKPZRNBA",
"create_time": "2014-08-19T09:19:00Z",
"update_time": "2014-08-19T09:19:32Z",
"intent": "sale",
"payer": {
"payment_method": "paypal",
"payer_info": {
"email": "severiano.testes#gmail.com",
"first_name": "Diogo",
"last_name": "Severiano",
"payer_id": "MSQ6UB55W52N6",
"shipping_address": {
"line1": "1 Main Terrace",
"line2": "",
"city": "Wolverhampton",
"country_code": "GB",
"postal_code": "W12 4LQ",
"state": "West Midlands"
}
}
},
"transactions": [
{
"amount": {
"currency": "EUR",
"total": "54.00",
"details": {
"subtotal": "54.00"
}
},
"description": "Transaction Description",
"item_list": {
"items": [
{
"quantity": "1",
"name": "Project Submission (featured)",
"price": "54.00",
"currency": "EUR",
"sku": "27365"
}
],
"shipping_address": {
"recipient_name": "Diogo Severiano",
"line1": "1 Main Terrace",
"line2": "",
"city": "Wolverhampton",
"country_code": "GB",
"postal_code": "W12 4LQ",
"state": "West Midlands"
}
},
"related_resources": [
{
"sale": {
"id": "1BJ06026CY7370157",
"create_time": "2014-08-19T09:19:00Z",
"update_time": "2014-08-19T09:19:32Z",
"amount": {
"currency": "EUR",
"total": "54.00"
},
"state": "pending",
"parent_payment": "PAY-2NU51454E4492922YKPZRNBA",
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/sale/1BJ06026CY7370157",
"rel": "self",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/sale/1BJ06026CY7370157/refund",
"rel": "refund",
"method": "POST"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-2NU51454E4492922YKPZRNBA",
"rel": "parent_payment",
"method": "GET"
}
]
}
}
]
}
],
"state": "approved",
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-2NU51454E4492922YKPZRNBA",
"rel": "self",
"method": "GET"
}
]
}
I'm using C# to make this:
after using this the result is above.
var data = JsonConvert.DeserializeObject<Rootobject>(context.Session["RespostaJson"].ToString());
pymnt = new Payment();
pymnt.id = data.id;
PaymentExecution pymntExecution = new PaymentExecution();
pymntExecution.payer_id = context.Request.Params["PayerID"];
Payment executedPayment = pymnt.Execute(apiContext, pymntExecution);
context.Response.Write(JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
The receiver account (info.severiano-facilitator#gmail.com) has the primary currency set
to USD but your transaction currency is in the EUR . Whenever you receive the payment in
the currency that your account doesn't hold , you need to manually accept the transaction
by logging to the account . Once you accept the payment PayPal will prompt you to either :
1. Deny the payment
2. Or accept in the new currency and open the balance in the new currency
3. Or accept the payment and convert the payment into your primary currency .
For now I have accepted the EUR currency( second choice 2.) for your sandbox account .
Now you should be fine with your next payment and you will receive the Payment status
as "completed ".

Categories

Resources