Trying to Create Order through Order API - nopcommerce

I am getting this error when attempting to create an order
"order placement": [
"Order GUID is not generated"
]
I have looked through the code for API and this error is not generated in that project.
I attempted this and it didnt work either
[JsonProperty("order_guid")]
public Guid OrderGuid { get; set; }
This is the section in the CreateOrder Endpoint where the error is generated
var placeOrderResult = PlaceOrder(newOrder, customer);
if (!placeOrderResult.Success)
{
foreach (var error in placeOrderResult.Errors)
{
ModelState.AddModelError("order placement", error);
}
return Error(HttpStatusCode.BadRequest);
}
Seems like the error is being thrown in the nopCommerce not the API
Can I get some help around this?

Related

Create custom response in .NET Core 5 with OData 8 controller

I'm using OData 8 in .NET Core 5 with the [EnableQuery] attribute. Problem is when I want to return Problem() or BadRequest("Some message"), the API always returns some default OData BadRequest and never the message I wanted (only when [EnableQuery] attribute is there).
Example:
[HttpGet]
[EnableQuery(EnsureStableOrdering = false )]
public IActionResult GetList(ODataQueryOptions<List> queryOptions)
{
if (queryOptions.Filter == null)
{
return BadRequest( "Filter is required for this endpoind!" );
}
try
{
queryOptions.Filter.Validator = new OdataCustomFilterValidator();
this.BaseValidateQueryOptions(queryOptions);
}
catch (ODataException ex)
{
return this.BadRequest(ex.Message);
}
IQueryable<List> list = this._service.GetList();
return this.Ok(list);
}
So in the above example, if the code gets to the first IF, i do not recieve this message but ALWAYS the same Odata error:
{
"error": {
"code": "",
"message": "The query specified in the URI is not valid. The requested resource is not a collection. Query options $filter, $orderby, $count, $skip, and $top can be applied only on collections.",
"details": [],
Hi you ran into this bug which was fixed in OData/WebApi https://github.com/OData/WebApi/issues/2511 but it seems like it has not yet been migrated to AspNetCoreOData, A pull request exists which when merged and published should allow you to continue with your use case which is valid.

Put method in web api (EF)

I am using a web api put method. I need to update two columns in the database. But I'm having an issue on updating both column.
I've got an error stated below
System.NullReferenceException: 'Object reference not set to an
instance of an object.'
emp was null.
This is my current code;
public class EmployeeController : ApiController
{
public HttpResponseMessage Put(int id, [FromBody] Employee emp)
{
try
{
using (EmpDBContext dbContext = new EmpDBContext())
{
var entity = dbContext.Employees.FirstOrDefault(e => e.Index == id);
if (entity != null)
{
entity.Name = emp.Name;
entity.EmpNum = emp.EmpNum;
dbContext.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Employee with Id " + id.ToString() + " not found to update");
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
Need some advice regarding this issue.
When you try to use any value in c# which is null then you will get 'Object reference error'. You need to see the API calling method to check why emp is coming null.
Below are the possibility -
Passing parameter name from calling method should exactly same as the name in parameter of the API, in your case it should be emp.
Check your Employee Model if it matching with your calling method properties.
You can check this info from Network tab of your browser.

Trying to query "traces" in Application Insights via the REST API

I am attempting to query the Application Insights "traces" data via the API by using the C# example given on the API Quickstart page (https://dev.applicationinsights.io/quickstart) and I think I am having an issue understanding the path to make the call work.
The following was taken from the Quickstart page...
public class QueryAppInsights
{
private const string URL = "https://api.applicationinsights.io/v1/apps/{0}/{1}/{2}?{3}";
public static string GetTelemetry(string appid, string apikey, string queryType, string queryPath, string parameterString)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-key", apikey);
var req = string.Format(URL, appid, queryType, queryPath, parameterString);
HttpResponseMessage response = client.GetAsync(req).Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine(response.StatusCode);
return response.Content.ReadAsStringAsync().Result;
}
else
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine(response.StatusCode);
return response.ReasonPhrase;
}
}
}
When I call it using the following parameters I get the following error.
{"error":{"message":"The requested path does not exist","code":"PathNotFoundError"}}
NotFound
public class TestSuite
{
public void CallTest()
{
QueryAppInsights.GetTelemetry("My Application ID", "My API Key", "query", "traces", "timespan=P7D&query=traces%7C%20where%20message%20contains%20%1111a11aa1-1111-11aa-1a1a-11aa11a1a11a%22");
}
}
When I call it replacing the "query" param with "events" I get over 500 rows returned with the following at the top
{"#odata.context":"https://api.applicationinsights.io/v1/apps/GUID PLACE HOLDER/events/$metadata#traces","#ai.messages":[{"code":"AddedLimitToQuery","message":"The query was limited to 500 rows"}
public class TestSuite
{
public void CallTest()
{
QueryAppInsights.GetTelemetry("My Application ID", "My API Key", "events", "traces", "timespan=P7D&query=traces%7C%20where%20message%20contains%20%1111a11aa1-1111-11aa-1a1a-11aa11a1a11a%22");
}
}
When I call it replacing the "events" param with "metrics" I get the following error:
{"error":{"message":"The requested item was not found","code":"ItemNotFoundError","innererror":{"code":"MetricNotFoundError","message":"Metric traces does not exist"}}}
NotFound
public class TestSuite
{
public void CallTest()
{
QueryAppInsights.GetTelemetry("My Application ID", "My API Key", "metrics", "traces", "timespan=P7D&query=traces%7C%20where%20message%20contains%20%1111a11aa1-1111-11aa-1a1a-11aa11a1a11a%22");
}
}
So I don't know if the way I am passing the query is incorrect or if I am trying something that is not possible. The query was taken from the API Explorer page (https://dev.applicationinsights.io/apiexplorer/query) in the "Query" > "GET /query" section and it does work as expected returning the correct row:
traces
| where message contains "1111a11aa1-1111-11aa-1a1a-11aa11a1a11a" (I've replaced the real GUID's with made up ones)
Just in case anyone ever comes across this I wanted to share how I did it successfully. Basically, I was using the wrong URL constant provided by the example on the quickstart (https://dev.applicationinsights.io/quickstart) page. I had to modify it in order to query Traces:
The given example on the quickstart:
private const string URL = "https://api.applicationinsights.io/v1/apps/{0}/{1}/{2}?{3}";
My implementation:
private const string URL = "https://api.applicationinsights.io/v1/apps/{0}/{1}?{2}{3}";
essentially moving the query string params to match what the GET/query API Explorer (https://dev.applicationinsights.io/apiexplorer/query) does when sending a query.

WebApi and Swagger

I am using asp.net webapi and using swagger to create a RestApi within a WPF app via AutoRest.
I am having problem figuring out how to consume the returned data if there is an error.
My controller is as follows;
// POST: api/Personnel
//[SwaggerResponse(HttpStatusCode.InternalServerError ,Type = typeof(HttpError))]
[SwaggerOperation("AddEditContract")]
[SwaggerResponse(HttpStatusCode.OK, Description = "Add/Edit a Contract", Type =typeof(int))]
public IHttpActionResult Post(ContractDto value)
{
try
{
var _contractsService = new Business.ContractsService();
var contractToSave = _contractsService.GetContractsById(value.CC_Id);
if (contractToSave == null)
{
return NotFound();
}
var ret = _contractsService.SaveContract(value);
if (ret > 0)
{
return Ok(ret);
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
I happened to have an error appear within the WebApi based on an error with AutoMapper but it was getting swallowed up. It is returning an error message in the response, which is great.
Here is the current AutoRest code for this call.
public static int? AddEditContract(this IBuxtedConAPI operations, ContractDto value)
{
return Task.Factory.StartNew(s => ((IBuxtedConAPI)s).AddEditContractAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
As you can see its expecting an int. If I uncomment the
//[SwaggerResponse(HttpStatusCode.InternalServerError ,Type = typeof(HttpError))]
The int return type turns to object.
So the real question.
Here is my service call from WPF to the WebApi
public async Task<int> SaveContract(ContractDto entity)
{
using (var db = new BuxtedConAPI())
{
var ret = await db.AddEditContractAsync(entity);
return (int)ret;
}
}
If an object is returned how do I pick up if an error has occurred or if the simple int (with a success) is just returned.
Thanks in advance.
Scott
Can you post the swagger file that you're generating and passing to AutoRest?
The reason return type turns to object (or whatever common base class is shared between all the possible responses), is because AutoRest treats explicitly defined responses as return values. Exceptions are used only for the default response.
We're investigating ways to specify multiple error responses that will generate the appropriate exceptions.

How to retrieve docs using Google Drive SDK in Asp.Net

I am working on a project that retrieve Google Drive docs list using ASP.NET, but I'm getting an error:
An error occurred: Google.Apis.Requests.RequestError Daily Limit for
Unauthenticated Use Exceeded. Continued use requires signup. [403]
This is my site (getting error on this link) : http://www.netdesklive.com/
I am trying DrEdit code for this, but not working proper.
I set all the credential as per https://developers.google.com/drive/examples/dotnet but still i m getting an error
So Please, Suggest me
Code :
-> I am getting null value in state and code
public ActionResult Index(string state, string code)
{
try
{
IAuthenticator authenticator = Utils.GetCredentials(code, state);
// Store the authenticator and the authorized service in session
Session["authenticator"] = authenticator;
Session["service"] = Utils.BuildService(authenticator);
}
catch (CodeExchangeException)
{
if (Session["service"] == null || Session["authenticator"] == null)
{
Response.Redirect(Utils.GetAuthorizationUrl("", state));
}
}
catch (NoRefreshTokenException e)
{
Response.Redirect(e.AuthorizationUrl);
}
DriveState driveState = new DriveState();
if (!string.IsNullOrEmpty(state))
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
driveState = jsonSerializer.Deserialize<DriveState>(state);
}
if (driveState.action == "open")
{
return OpenWith(driveState);
}
else
{
return CreateNew(driveState);
}
}
Your error message suggests that your requests are not authorized. You should authorize them using Oauth2 :
Authorizing Drive requests
Google Oauth2 documentation

Resources