I have developed web API with this method and I test it with Advanced Rest Client in my machine and everything is alright, but after deploy to server the result is omitted by the server and not recognize as valid JSON text and not parse correctly.
[Route("[action]")]
[HttpGet]
public async Task<JsonResult> GetAllCityEvent(string apiKey)
{
List<CityMapMarker> availableMapMarkers = new List<CityMapMarker>();
PersianUtilCore.Api.MethodResult result = new PersianUtilCore.Api.MethodResult();
List<PersianUtilCore.Api.MethodError> errors = new List<PersianUtilCore.Api.MethodError>();
ApiBO apiBO = new ApiBO(AggregateService);
bool isValidKey = apiBO.IsValidKey(apiKey);
if (!isValidKey)
{
result.IsSuccess = false;
errors.Add(new PersianUtilCore.Api.MethodError(300, "your key is not valid!"));
}
else
{
JunctionBO junctionBO = new JunctionBO(AggregateService);
StreetBO streetBO = new StreetBO(AggregateService);
HighwayBO highwayBO = new HighwayBO(AggregateService);
SightBO sightBO = new SightBO(AggregateService);
TrafficLightBO trafficLightBO = new TrafficLightBO(AggregateService);
CameraBO cameraBO = new CameraBO(AggregateService);
TransportationStationBO bussStationBO = new TransportationStationBO(AggregateService);
TrafficBO trafficBO = new TrafficBO(AggregateService);
CityEventBO cityEventBO = new CityEventBO(AggregateService);
//availableMapMarkers.AddRange(junctionBO.CityMapMarkers());
//availableMapMarkers.AddRange(streetBO.CityMapMarkers());
//availableMapMarkers.AddRange(highwayBO.CityMapMarkers());
//availableMapMarkers.AddRange(sightBO.CityMapMarkers());
//availableMapMarkers.AddRange(trafficLightBO.CityMapMarkers());
//availableMapMarkers.AddRange(trafficBO.CityMapMarkers());
//availableMapMarkers.AddRange(cameraBO.CityMapMarkers());
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.Bus));
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.Train));
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.BRT));
availableMapMarkers.AddRange(cityEventBO.CityMapMarkers());
result.Result = availableMapMarkers;
result.IsSuccess = true;
}
result.Errors = errors;
result.Result = availableMapMarkers;
result.IsSuccess = errors.Count <= 0;
var logHistoryResult = apiBO.LogHistory(apiKey, nameof(this.GetAllCityEvent));
return Json(result);
}
I couldn't find any way to change JsonResult max length like with I did in Asp.net MVC4 or Asp.net Webforms
How can I increase JsonResult maxlength in MVC Core?
Why there is different in IIS publish or local machine when I try to get result from my web API?
Related
I'm using Asp.Net MVC Core3.1 "code first" : i have issue with "JsonResult" : JsonResult: doesn't recognize so what the solution ?
The error say : Error CS1729 'JsonResult' does not contain a constructor that takes 0 arguments Attendance
public JsonResult GetEvents()
{
using (MyDbContext dc = new MyDbContext())
{
var events = dc.rotation.ToList();
return new JsonResult(){ Data = events , JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
The right answer is replace :
return new JsonResult(){ Data = events , JsonRequestBehavior = JsonRequestBehavior.AllowGet };
to
return Json(events)
Clicking a certain Ajax ActionLink in this app I just inherited produces a POST request AND a GET request (POST and then a GET immediately after). The first request hits the HttpPost method on the server, but the second request (the GET) throws a "404 (Not Found)" error in the browser. How do I stop the unwanted GET request? Where is it coming from?
If I change the method from POST to GET, the reverse occurs with the POST throwing the error instead of the GET.
I searched the application for similar requests to the same HttpPost method that were configured as GETs and there are none.
I searched for custom JavaScript that was attaching an extra click event to all links and there were no instances of that. Could there be other events that would produce the same result in this instance?
Chrome DevTools Screenshot
In DocumentManagementController.cs:
[HttpPost]
public ActionResult OpenPopup(string ntgLoadId) { ... }
In _GridLoadsAddendum.cshtml:
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "DetailedGrid_" + Model.LoadId;
settings.Width = Unit.Percentage(100);
settings.Settings.ShowFilterRow = false;
settings.Settings.ShowGroupPanel = false;
settings.Settings.ShowFooter = false;
settings.Settings.ShowColumnHeaders = false;
settings.KeyFieldName = "NtgLoadId";
settings.Columns.Add(column =>
{
column.FieldName = "Status";
column.Caption = "Status";
column.Width = Unit.Pixel(83);
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Ajax.ActionLink(
DataBinder.Eval(c.DataItem, "Status").ToString(),
"OpenPopup",
"DocumentManagement",
new
{
ntgLoadId = c.KeyValue.ToString()
},
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ModalContainer",
AllowCache = false
},
new
{
#class = "status-link",
data_Toggle = "modal",
data_Target = "#ModalContainer",
data_backdrop = "static",
data_Keyboard = "false"
}).ToHtmlString());
});
});
settings.Styles.Table.CssClass = "MVCxGridViewTable";
settings.Styles.Header.CssClass = "MVCxGridViewHeader";
settings.Styles.Cell.CssClass = "MVCxGridViewCell addendum";
settings.Styles.CommandColumnItem.CssClass = "MVCxGridViewCell";
settings.Styles.AlternatingRow.CssClass = "MVCxGridViewAlternatingRow addendum";
settings.Styles.PagerBottomPanel.CssClass = "MVCxGridViewPagerBottomPanel";
settings.Settings.ShowFooter = false;
settings.ClientSideEvents.BeginCallback = "initechPortal.carrierPaymentStatusHelper.gridResultsHelper.beginCallback";
settings.CallbackRouteValues = new
{
Controller = "CarrierPaymentController",
Action = "GridLoadsAddendum",
Id = Model.LoadId
};
settings.DataBound = (sender, e) =>
{
MVCxGridView gv = sender as MVCxGridView;
gv.Visible = gv.VisibleRowCount > 0;
};
}).BindToLINQ(
string.Empty,
string.Empty,
new EventHandler<DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs>(
(s, e) =>
{
e.QueryableSource = Model.CarrierPaymentResultData;
e.KeyExpression = "ntgLoadId";
})).GetHtml();
I've down Method GET with HttpClient, but i dont know how to get data with param (id) or by method POST, anyone help me.
this is a code GET with HttpClient i use before, hope method POST same it.
public async void getreponse()
{
var postrequest = (HttpWebRequest)WebRequest.Create("http://210.86.239.156/PIXA/app_truyenhay/api/list_story");
postrequest.Method = "GET";
postrequest.CookieContainer = new CookieContainer();
HttpWebResponse postresponse = (HttpWebResponse)await postrequest.GetResponseAsync();
string response = String.Empty;
if (postresponse != null)
{
var postResponseStream = postresponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
response = await postStreamReader.ReadToEndAsync();
}
ListStory liststory = Newtonsoft.Json.JsonConvert.DeserializeObject<ListStory>(response);
/*foreach (var blog in liststory.items)
blog.storyImage = "http://a.wattpad.com/cover/30539421-256-k910647.jpg";
//LBTruyen.ItemsSource = liststory.items; */
}
I haven't been able to find anything that will clearly explain how to use google compute engine through the .net API (specifically c#). Is there anyone that can point me to anything?
P.S. I know about the API reference (https://developers.google.com/resources/api-libraries/documentation/compute/v1/csharp/latest/annotated.html)
I could not find any detailed tutorial with code samples, but official documentation is available at [1] includes a code sample.
There is a tutorial with C# sample specific for Google Drive at [2].
For your reference APIs documentation is available at [3] and the annotated library reference is available at [4].
Link:
[1] - https://developers.google.com/api-client-library/dotnet/get_started#examples
[2] - http://conficient.wordpress.com/2014/06/18/using-google-drive-api-with-c-part-1/
[3] - https://developers.google.com/compute/docs/reference/latest/
[4] - https://developers.google.com/resources/api-libraries/documentation/compute/v1/csharp/latest/annotated.html
A list of steps you need to follow:
Specifically you can modify and use the following code to Create the vmInstance of Google Compute Engine
Here is the c# (using Google api SDK) functions that can create instances
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "ClientId",
ClientSecret = "ClientSecret"
},
new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform },
"user",
CancellationToken.None, null);
`ComputeService service = new ComputeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ApplicationName",
ApiKey = "ApiKey"
});
public IEnumerable<CreateInstanceResult> CreateInstances(params CreateInstanceRequest[] instances)
{
IList<Instance> vmInstances = new List<Instance>();
ComputeService service = assign GoogleComputeServiceObject;
if (instances != null)
{
foreach (CreateInstanceRequest requestInstance in instances)
{
#region Meatadata Setting
Metadata metaData = new Metadata();
metaData.Items = new List<Metadata.ItemsData>();
Metadata.ItemsData itemData = new Metadata.ItemsData();
itemData.Key = "Expiration";
itemData.Value = requestInstance.Expiration.ToString();
metaData.Items.Add(itemData);
itemData = new Metadata.ItemsData();
itemData.Key = "AccountId";
itemData.Value = requestInstance.AccountId;
metaData.Items.Add(itemData);
if (requestInstance.Data != null)
{
foreach (KeyValuePair<string, string> keyValue in requestInstance.Data)
{
Metadata.ItemsData otherItemData = new Metadata.ItemsData();
otherItemData.Key = keyValue.Key;
otherItemData.Value = keyValue.Value;
metaData.Items.Add(otherItemData);
}
}
#endregion Meatadata Setting
#region DiskSetting
IList<AttachedDisk> attachedDisks = new List<AttachedDisk>();
AttachedDisk attachedDisk = new AttachedDisk();
AttachedDiskInitializeParams attachedDiskInitializeParams = new AttachedDiskInitializeParams();
attachedDiskInitializeParams.DiskSizeGb = googleCloudServerSetting.DiskSize;
attachedDiskInitializeParams.DiskType = service.BaseUri + "Your_ProjectId" + "/zones/" + "specifyZone" + "/diskTypes/" + "specify_DiskType";
// for example
attachedDiskInitializeParams.SourceImage = service.BaseUri + "/debian-cloud/global/images/specify_imagesourceImage";
attachedDisk.AutoDelete = true;
attachedDisk.Boot = true;
attachedDisk.Interface__ = "SCSI";//for example
attachedDisk.InitializeParams = attachedDiskInitializeParams;
attachedDisks.Add(attachedDisk);
IList<NetworkInterface> networkInterfaces = new List<NetworkInterface>();
NetworkInterface networkInterface = new NetworkInterface();
networkInterface.Network = service.BaseUri + ProjectId + "/global/networks/default";
networkInterfaces.Add(networkInterface);
Tags tags = new Tags();
IList<string> stringList = new List<string>();
tags.Items = new List<string>();
tags.Items.Add("http-server");
tags.Items.Add("https-server");
#endregion DiskSetting
#region Creating Instance object
Instance instance = new Instance()
{
MachineType = requestInstance.SizeId ?? service.BaseUri + "ProjectId" + "/zones/" + "specify_Zone" + "/machineTypes/" + "specify_machineType",
Metadata = metaData,
Name = "InstanceName",
Tags = tags,
NetworkInterfaces = networkInterfaces,
Disks = attachedDisks
};
#endregion Creating Instance object
vmInstances.Add(instance);
}
var batchRequest = new BatchRequest(service);
foreach (Instance instance in instances)
{
batchRequest.Queue<Instance>(service.Instances.Insert(instance, ProjectId, Zone),
(content, error, i, message) =>
{
});
}
await batchRequest.ExecuteAsync();
}
else
{
throw new Exception("null");
}
}
Bit stuck on another one i'm afraid, i am trying to write a unit test for a bulk APEX class.
The class has a calllout to the google api, so i have created a static resource which i am feeding in via a mock, so i can complete testing of processing the JSON that is returned. However for some reason the response is always empty.
Now the very odd thing is that if i use exactly the same callout/JSON code, and the same mock code on a previous #future call, then it does return fine.
Here is the class:
global class mileage_bulk implements Database.Batchable<sObject>,
Database.AllowsCallouts
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String query = 'SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c,Shipping_Postcode_2__c FROM Opportunity WHERE R2_Shipping_Post_Code__c != null';
return Database.getQueryLocator(query);
//system.debug('Executing'+query);
}
global void execute(Database.BatchableContext BC, List<Opportunity> scope)
{
system.debug(scope);
for(Opportunity a : scope)
{
String startPostcode = null;
startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');
String endPostcode = null;
String endPostcodeEncoded = null;
if (a.R2_Shipping_Post_Code__c != null){
endPostcode = a.R2_Shipping_Post_Code__c;
Pattern nonWordChar = Pattern.compile('[^\\w]');
endPostcode = nonWordChar.matcher(endPostcode).replaceAll('');
endPostcodeEncoded = EncodingUtil.urlEncode(endPostcode, 'UTF-8');
}
Double totalDistanceMeter = null;
Integer totalDistanceMile = null;
String responseBody = null;
Boolean firstRecord = false;
String ukPrefix = 'UKH';
if (a.R2_Job_Ref__c != null){
if ((a.R2_Job_Ref__c).toLowerCase().contains(ukPrefix.toLowerCase())){
system.debug('Is Hemel Job');
startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');
} else {
system.debug('Is Bromsgrove Job');
startPostcode = EncodingUtil.urlEncode('B604AD', 'UTF-8');
}
}
// build callout
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://maps.googleapis.com/maps/api/directions/json?origin='+startPostcode+'&destination='+endPostcodeEncoded+'&units=imperial&sensor=false');
req.setMethod('GET');
req.setTimeout(60000);
system.debug('request follows');
system.debug(req);
try{
// callout
HttpResponse res = h.send(req);
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
responseBody = res.getBody();
system.debug(responseBody);
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'distance')){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
//system.debug(parser.nextToken());
//system.debug(txt);
if (firstRecord == false){
//if (txt == 'text'){
//totalDistanceMile = parser.getText();
system.debug(parser.getText());
//}
if (txt == 'value'){
totalDistanceMeter = parser.getDoubleValue();
double inches = totalDistanceMeter*39.3701;
totalDistanceMile = (integer)inches/63360;
system.debug(parser.getText());
firstRecord = true;
}
}
}
}
}
} catch (Exception e) {
}
//system.debug(accountId);
system.debug(a);
system.debug(endPostcodeEncoded);
system.debug(totalDistanceMeter);
system.debug(totalDistanceMile);
// update coordinates if we get back
if (totalDistanceMile != null){
system.debug('Entering Function to Update Object');
a.DistanceM__c = totalDistanceMile;
a.Shipping_Postcode_2__c = a.R2_Shipping_Post_Code__c;
//update a;
}
}
update scope;
}
global void finish(Database.BatchableContext BC)
{
}
}
and here is the test class;
#isTest
private class mileage_bulk_tests{
static testMethod void myUnitTest() {
Opportunity opp1 = new Opportunity(name = 'Google Test Opportunity',R2_Job_Ref__c = 'UKH12345',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());
insert opp1;
Opportunity opp2 = new Opportunity(name = 'Google Test Opportunity 2',StageName = 'qualified',CloseDate = Date.today());
insert opp2;
Opportunity opp3 = new Opportunity(name = 'Google Test Opportunity 3',R2_Job_Ref__c = 'UKB56789',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());
insert opp3;
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('googleMapsJSON');
mock.setStatusCode(200); // Or other appropriate HTTP status code
mock.setHeader('Content-Type', 'application/json'); // Or other appropriate MIME type like application/xml
//Set the mock callout mode
Test.setMock(HttpCalloutMock.class, mock);
system.debug(opp1);
system.debug(opp1.id);
//Call the method that performs the callout
Test.startTest();
mileage_bulk b = new mileage_bulk();
database.executeBatch((b), 10);
Test.stopTest();
}
}
Help greatly appreciated!
Thanks
Gareth
Not certain what 'googleMapsJSON' looks like, perhaps you could post for us.
Assuming your mock resource is well formatted, make sure the file extension is ".json" and was saved with UTF-8 encoding.
If #2 does not work, you should try saving your resource as .txt - I've run in to this before where it needed a plain text resource but expected application/json content type
Be certain that the resource name string you are providing has the same casing as the name of the resource. It is case sensitive.
Are you developing on a namespaced package environment? Try adding the namespace to the resource name if so.
Otherwise, your code looks pretty good at first glance.