Error 500 in Angularjs $http.post and webservice asmx - angularjs

I try to make a validatión with a webservice and $http from angular, the problem is an error 500 when i try to send data, if i call webservice without data works perfectly, the code:
Angularjs
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post('/CloudMobile/gpvdata.asmx/validausuario', {username: username, password: password}).success(function(data, status, headers, config) {
$rootScope.datos = data[0];
console.log($rootScope.datos.grupo);
callback({success: true});
}).error(function(data, status, headers, config) {
console.log('Falla la validación en el asmx');
});
Webservice
[WebMethod]
public void validausuario(string usuario, string password)
{
TGlobalOpClases g = miGlobal(usuario, password);
t1ValidacionSistema val = new t1ValidacionSistema(g);
Resultado_BD ResBD = val.Valida("SYSTEM_GPV", "DEMO", DateTime.Now);
g.idUsuarioConsola = val.Datos.idUsuario;
if (ResBD.ok)
{
t1Usuario user = new t1Usuario(g);
Entrada_OPBD x = new Entrada_OPBD();
x.PonLanzarEx();
user.FichaCarga(x,g.idUsuarioConsola);
user.GruposPertenece_Carga(x);
string jsn = Json.Encode(user.GruposPertenece);
HttpContext.Current.Response.Write(jsn);
}
else {
HttpContext.Current.Response.Write("Fallo la conexión");
}
}
public TGlobalOpClases miGlobal(string usuario, string password)
//public TGlobalOpClases miGlobal()
{
ExEngine_Client.TGlobalOpClases global = new TGlobalOpClases();
global.miParIniOP.password = password;
global.miParIniOP.Usuario = usuario;
global.Server = "192.168.0.16\\sql";
global.DataBase = "Desarrollo";
global.Conecta();
return global;
}
Thanks.

Related

How to post form-data IFormFile to API from Controller?

received null in api IFormFile.
Javascript:
var archivo = _('inputCargar').files[0];
const form = new FormData();
form.append("files", archivo);
const config = {
headers: {
'content-type': 'multipart/form-data'}}
await axios.post(`${data.urlUtil}Insert_FileAzure`, form, config);
The form file arrive to the controller but cant arrive to the api
Controller in Front:
public async Task<JsonResult> Insert_FileAzure([FromForm] ICollection<IFormFile> files)
{
var result = await _apiUtil.PostAsync<ICollection<IFormFile>> ("File/UploadAzure", files);
return Json(result);
}
API:
[HttpPost]
public async Task<ActionResult<RespuestaUpload>> UploadAzure([FromForm(Name = "files")] ICollection<IFormFile> files)
{
if (files == null || files.Count == 0)
return Content("file not selected");
var respuestaUpload = await _utiles.UploadFilesAzure(files);
return Ok(respuestaUpload);
}
Use MultipartFormDataContent as httpContent like below:
var Client = new HttpClient();
var multipartFormDataContent = new MultipartFormDataContent();
foreach (IFormFile file in files)
{
byte[] fileData;
using (var reader = new BinaryReader(file.OpenReadStream()))
{
fileData = reader.ReadBytes((int)file.OpenReadStream().Length);
}
var fileContent = new ByteArrayContent(fileData);
multipartFormDataContent.Add(fileContent, "files", file.FileName);
}
var response = await Client.PostAsync(requestUrl, multipartFormDataContent);

Angularjs $http get not working

I am trying to access REST web service from angularjs. I am not able to call it successfully.
AngularJs Code
var singleOrderUrl = "/singleOrder/retrieve";
function getSingleOrderDetails(userName,singleOrderUrl,$http,$q) {
var fd = new FormData();
var deffered = $q.defer();
fd.append('USERNAME', 'test123');
//fd.append();
//fd.append();
console.log("inside service"+userName+"singleOrderUrl:::"+singleOrderUrl);
return $http.get(singleOrderUrl, fd, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined,
}
}).success(function(response) {
console.log(response);
responseData = response.data.toString();;
deffered.resolve(response);
return responseData;
}).error(function(error) {
alert("error");
deffered.reject(error);
return "failed";
});
};
Rest Service code
#RestController
public class SingleOrderHistoryController {
private static final Logger logger = LoggerFactory.getLogger(SingleOrderHistoryController.class.getName());
#RequestMapping(value = "/singleOrder/retrieve", method=RequestMethod.GET, produces="application/json")
public List<SingleHistoryRecord> getSingleOrderDetails(#RequestParam(value = Constants.USER_NAME, required = true) String userName, HttpServletRequest request,HttpServletResponse response) throws Exception {
logger.debug("inside SingleOrderHistoryController ");
List<SingleHistoryRecord> singleOrderHistoryList = new ArrayList<SingleHistoryRecord>();
SingleHistoryRecord record1 = new SingleHistoryRecord();
SingleHistoryRecord record2 = new SingleHistoryRecord();
record1.setClientIdentifier(userName);
record1.setSubmitDate("01/05/2017");
record1.setStatus("Complete");
record1.setReferenceID("1234555");
record1.setOrderID("test123");
record2.setClientIdentifier(userName);
record2.setSubmitDate("01/05/2017");
record2.setStatus("Complete");
record2.setReferenceID("1234555");
record2.setOrderID("test123");
singleOrderHistoryList.add(record1);
singleOrderHistoryList.add(record2);
return singleOrderHistoryList;
}
Can anyone please advise what I am doing wrong here, It is getting the source code of the page in response instead of getting the list.

Not able to expose the custom headers from WebAPI to client

I have written a program to download the pdf, word or txt file returned by web api and it's working fine. On server side I have used WebApi and client side AngularJs. Now the problem is, I also need the file name from api as well and for that I need to read the headers returned by api. But reponse.headers doesn't contains all the headers info. Below is my code:
[HttpGet]
[Authorize]
public HttpResponseMessage GetTranscript(string key, int format)
{
var badRequest = Request.CreateResponse(HttpStatusCode.OK, "Not a valid input."); //ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, "Not a valid input."));
if (string.IsNullOrWhiteSpace(jiraTaskKey))
{
return badRequest;
}
string transcript = _mediaCaptionService.GetTranscript(UserId, key);
string fileName = "transcript";
var response = new HttpResponseMessage(HttpStatusCode.OK);
if (format == (int)TranscriptFormat.PDF)
{
byte[] byteInfo = GeneratePDFTranscript(transcript);
response.Content = new ByteArrayContent(byteInfo);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileName = fileName + ".pdf";
}
else if (format == (int)TranscriptFormat.TXT)
{
response.Content = new StringContent(transcript, System.Text.Encoding.UTF8, "text/plain");
fileName = fileName + ".txt";
}
else if (format == (int)TranscriptFormat.WORD)
{
string transcriptFontName = "Arial";
byte[] byteInfo = GenerateWordTranscript(transcript, transcriptFontName);
response.Content = new ByteArrayContent(byteInfo);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileName = fileName + ".doc";
}
else
{
return badRequest;
}
response.Content.Headers.Add("x-filename", fileName);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = fileName
};
//response.Content.Headers.ContentDisposition.FileName = fileName;
return response; //ResponseMessage(response);
}
and in client side
function getTranscriptResult(method, apiUrl, data) {
var deferred = $q.defer();
$http({
method: method,
url: apiUrl,
data: data,
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
debugger;
var results = [];
results.data = data;
results.headers = headers();
results.status = status;
results.config = config;
deferred.resolve(results);
}).error(function (error, status, headers, config) {
deferred.reject(error);
});
return deferred.promise;
}
But when I put the break point in above code, I get this:
Can you please tell me where is the problem in my code that I am not able to get the file name? Also please let me know if you need more information.
After adding below lines has solved my problem.
// Add a custom header for filename and expose it to be consumed by JavaScript.
response.Content.Headers.Add("Filename", zipFileName);
response.Content.Headers.Add("Access-Control-Expose-Headers", "Filename");
So basically adding Access-Control-Expose-Headers helped me to expose the custom headers to client. For more information on this please follow this link

sending HashMap by angularjs $http.get in spring mvc

I want to send and retrieve HashMap through angularjs and receive it in springmvc controller. I have successfully send and received List but unable to send HashMap.
My code is.
$scope.addskill = function(skills){
// $scope.list = [];
// $scope.list.push(skills.skillName, skills.expMonth, skills.expYear, skills.experties);
var map = {};
map['name'] = skills.skillName;
map['month'] = skills.expMonth;
map['year'] = skills.expYear;
map['experties'] = skills.experties;
alert(map['name']);
var response = $http.get('/JobSearch/user/addskill/?map=' +map);
// var response = $http.get('/JobSearch/user/addskill/?list=' +$scope.list);
response.success(function(data, status, headers, config){
$scope.skills = null;
$timeout($scope.refreshskill,1000);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
};
My mvc Controller is :
#RequestMapping(value = "/addskill", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(#RequestBody HashMap<String,String> map){
System.out.println(map.get("name"));
/*
* public void addStudentSkill(#RequestParam("list") List list){
try{
StudentSkills skills = new StudentSkills();
skills.setSkillName(list[0]);
skills.setExpMonth(Integer.parseInt(list[1]));
skills.setExpYear(Integer.parseInt(list[2]));
skills.setExperties(list[3]);
skills.setStudent(studentService.getStudent(getStudentName()));
studentService.addStudentSkill(skills);
}catch(Exception e){};
*/
}
Commented code works when i send and receive List. I want to use key to retrieve data. If there is any better way please suggest.
The error is cannot convert java.lang.string to hashmap
You're sending the map as a request parameter. And you're trying to read it in the request body. That can't possibly work. And GET requests don't have a body anyway.
Here's how you should do it:
var parameters = {};
parameters.name = skills.skillName;
parameters.month = skills.expMonth;
parameters.year = skills.expYear;
parameters.experties = skills.experties;
var promise = $http.get('/JobSearch/user/addskill', {
params: parameters
});
And in the Spring controller:
#RequestMapping(value = "/addskill", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(#RequestParam("name") String name,
#RequestParam("name") String month,
#RequestParam("name") String year,
#RequestParam("name") String experties) {
...
}
That said, given the name of the method addStudentSkill, and the fact that it doesn't return anything, it seems this method is not used to get data from the server, but instead to create data on the server. So this method should be mapped to a POST request, and the data should be sent as the body:
var data = {};
data.name = skills.skillName;
data.month = skills.expMonth;
data.year = skills.expYear;
data.experties = skills.experties;
var promise = $http.post('/JobSearch/user/addskill', params);
and in the controller:
#RequestMapping(value = "/addskill", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.CREATED)
public void addStudentSkill(#RequestBody Map<String, String> data) {
...
}

How to properly retrieve a record by ID

In my Angular/WebAPI app I'm struggling with retrieving a specific record by its id.
On the Front-End I have a controller and a data service. The controller calls a method on the data service, and the data service makes $http call to a WebAPI.
In my controller I'm passing the OID of the desired record to the getServiceRequestById method of the data service. Once of my issues is, that the actual value of that OID comes out as :1 instead of just 1.
My other issue is, that when the data service makes a call to WebAPI, the WebAPI perceives the request, as if it caries no ID in it, and passes that request onto its Get() method, instead of Get(int Id).
Here is my Front-End controller:
angular.module('frontEndApp').controller('EditServiceRequestCtrl',['$scope', 'requestsRepository','$routeParams',
function ($scope, requestsRepository,$routeParams) {
console.log("This is EditServiceRequestCtrl ; $routeParams: " + $routeParams);
//First we make a call to the data service, to fetch our ServiceRequest by its OID
//Then, in the callback function, we populate the $scope models below with the data of our retreived ServiceRequest
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
var Id = getCleanId();
//var cleanId = id.substring(0, 2);
console.log('getCleanId Id: ' + Id);
requestsRepository.getServiceRequestById(Id, function (request) {
$scope.OID = request.OID;
$scope.RequestorName = request.RequestorName;
$scope.RequestorBusinessUnit = request.RequestorBusinessUnit;
$scope.CustomerName = request.CustomerName;
$scope.CscContactPerson = request.CscContactPerson;
$scope.IsWbsCodeAvailable = request.IsWbsCodeAvailable;
$scope.SalesforceIdNumber = request.SalesforceIdNumber;
$scope.ProjectCtv = request.ProjectCtv;
$scope.RequestedCompletionDate = request.RequestedCompletionDate;
$scope.ToBeUsedForCloudMigration = request.ToBeUsedForCloudMigration;
$scope.ToBeUsedForDatacenterMove = request.ToBeUsedForDatacenterMove;
$scope.ToBeUsedForServerRefresh = request.toBeUsedForServerRefresh;
$scope.DataRequirements = request.DataRequirements;
$scope.DataProtectionRequirements = request.DataProtectionRequirements;
$scope.ProjectedDataAvailability = request.ProjectedDataAvailability;
$scope.DiscoveryLeadName = request.DiscoveryLeadName;
$scope.SelectedCountries = request.SelectedCountries;
$scope.ManualDiscovery = request.ManualDiscovery;
$scope.AutomatedDiscovery = request.AutomatedDiscovery;
$scope.DataLoadUsingMasterTemplate = request.DataLoadUsingMasterTemplate;
$scope.DataLoadUsingAutomatedInterface = request.DataLoadUsingAutomatedInterface;
$scope.DataLoaderRequiresSitizenship = request.DataLoaderRequiresSitizenship;
$scope.countries = [
{
name: "US", checked: false
},
{
name: "UK", checked: false
},
{
name: "France", checked: false
},
{
name: "Germany", checked: false
},
{
name: "Sweden", checked: false
},
{
name: "Danmark", checked: false
}
];
var list = [];
$scope.checkit = function () {
for (var p in $scope.countries) {
if ($scope.countries[p].checked) {
list.push($scope.countries[p].name);
console.log("selected country: " + $scope.countries[p].name + " " + $scope.ProjectedDataAvailability);
}
} return list;
}
console.log('EditServiceRequestCtrl $scope.RequestorName : ' + $scope.RequestorName);
});
$scope.updateServiceRequest = function () {
var ServiceRequest = {
requestorName: $scope.RequestorName,
requestorBusinessUnit: $scope.RequestorBusinessUnit,
customerName: $scope.CustomerName,
cscContactPerson: $scope.CscContactPerson,
isWbsCodeAvailable: $scope.IsWbsCodeAvailable,
salesforceIdNumber: $scope.SalesforceIdNumber,
projectCtv: $scope.ProjectCtv,
requestedCompletionDate: $scope.RequestedCompletionDate,
projectedDataAvailability: $scope.ProjectedDataAvailability,
toBeUsedForCloudMigration: $scope.ToBeUsedForCloudMigration,
toBeUsedForDatacenterMove: $scope.ToBeUsedForDatacenterMove,
toBeUsedForServerRefresh: $scope.ToBeUsedForServerRefresh,
dataRequirements: $scope.DataRequirements,
dataProtectionRequirements: $scope.DataProtectionRequirements,
selectedCountries:
list.filter(function (itm, i, a) {
return i == a.indexOf(itm);
}).toString(),
projectedDataAvailability: $scope.ProjectedDataAvailability,
discoveryLeadName: $scope.DiscoveryLeadName,
manualDiscovery: $scope.ManualDiscovery,
automatedDiscovery: $scope.AutomatedDiscovery,
dataLoadUsingMasterTemplate: $scope.DataLoadUsingMasterTemplate,
dataLoadUsingAutomatedInterface: $scope.DataLoadUsingAutomatedInterface,
dataLoaderRequiresSitizenship: $scope.DataLoaderRequiresSitizenship
};
requestsRepository.updateServiceRequest(ServiceRequest);
}
}]);
Here is my Front-End data service:
frontEndApp.factory('requestsRepository',function ($http) {
var createServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "POST", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("createServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("createServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var updateServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "PUT", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("updateServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("updatetServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var getServiceRequests = function (successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
}).success(function (data, status, headers, config) {
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
var getServiceRequestById = function (Id,successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests/' + Id
}).success(function (data, status, headers, config) {
console.log("getServiceRequestById, data: " + data);
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
return {
createServiceRequest: createServiceRequest, getServiceRequests: getServiceRequests,
updateServiceRequest: updateServiceRequest, getServiceRequestById: getServiceRequestById
};
});
And here is my Back-End WebAPI:
public HttpResponseMessage Get()
{
var requestList = from req in new XPQuery<DummyRequest>(uow) select req;
List<AccountViewServiceRequest> dataList = new List<AccountViewServiceRequest>();
foreach(var item in requestList)
{
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
dataList.Add(sr);
}
var response = Request.CreateResponse(HttpStatusCode.OK, dataList.ToList());
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
public HttpResponseMessage Get(int Oid)
{
var item = (from req in new XPQuery<DummyRequest>(uow) where req.Oid == Convert.ToInt32(Oid) select req).First();
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
var response = Request.CreateResponse(HttpStatusCode.OK, sr);
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
Which part should I correct to successfully retrieve a single e record based on its OID?
Since it appears that your first issue is related to this routine:
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
Change the substring starting position to 1 to remove the prepended colon.
var getCleanId = function () {
return $routeParams.OID.substring(1, 2)
};
That in turn should fix the issue with not getting a single record out of the web api. The web api is trying to find a matching function signature in the controller on the web server. The only parameter can't convert to an integer, so it uses the Get() instead of the Get(int Oid).

Resources