AngularJs, FileSaver Export To Excel with Turkish Chars? - angularjs

I can export to Excel with FileSaver in my solution. Here my sources:
tapuController.cs:
[Route("Tapu/tcKimlikNoIleToEcel")]
public void tcKimlikNoIleToEcel(string tcKimlikNo)
{
List<TapuZeminModel> zeminler = new List<TapuZeminModel>();
zeminler = TapuModule.GetZeminListFromTcNo(tcKimlikNo);
List<TapuZeminViewModel> zeminList = new List<TapuZeminViewModel>();
foreach (var zemin in zeminler)
{
foreach (var hisse in zemin.Hisseler)
{
TapuZeminViewModel ze = new TapuZeminViewModel();
ze.Ad = hisse.Kisi.Ad;
ze.AdaNo = zemin.AdaNo;
if (zemin.KatMulkiyeti != null)
{
ze.ArsaPay = zemin.KatMulkiyeti.ArsaPay;
ze.ArsaPayda = zemin.KatMulkiyeti.ArsaPayda;
ze.BagimsizBolumNo = zemin.KatMulkiyeti.BagimsizBolumNo;
ze.Blok = zemin.KatMulkiyeti.Blok;
ze.Giris = zemin.KatMulkiyeti.Giris;
}
ze.Cilt = zemin.CiltNo;
ze.EdinmeSebep = hisse.EdinmeSebep;
ze.HisseId = hisse.TapuKod;
ze.HissePay = hisse.HissePay;
ze.HissePayda = hisse.HissePayda;
ze.Il = zemin.Il.Ad;
ze.Ilce = zemin.Ilce.Ad;
ze.KisiId = hisse.Kisi.TapuKod;
ze.ParselNo = zemin.ParselNo;
ze.Sayfa = zemin.SayfaNo;
ze.Kurum = zemin.Kurum.Ad;
ze.ZeminId = zemin.TapuKod;
ze.ZeminTip = zemin.ZeminTip.Ad;
ze.Mahalle = zemin.Mahalle.Ad;
ze.Nitelik = zemin.AnaTasinmaz.Nitelik;
ze.Mevkii = zemin.AnaTasinmaz.Mevkii;
if (hisse.Kisi.GercekKisi != null)
{
ze.SoyAd = hisse.Kisi.GercekKisi.SoyAd;
ze.TcKimlikNo = hisse.Kisi.GercekKisi.TcKimlikNo;
}
if (hisse.Kisi.TuzelKisi != null)
{
ze.TuzelKisiAd = hisse.Kisi.TuzelKisi.Ad;
ze.VergiNo = hisse.Kisi.TuzelKisi.VergiNo;
ze.SicilNo = hisse.Kisi.TuzelKisi.SicilNo;
}
zeminList.Add(ze);
}
}
StringBuilder dosyaAdi = new StringBuilder();
dosyaAdi.Append(DateTime.Now.ToString("dd.MM.yyyy HH.mm"));
dosyaAdi.Append("-" + tcKimlikNo);
dosyaAdi.Append(".xls");
GridView gv = new GridView();
gv.DataSource = zeminList;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + dosyaAdi.ToString());
Response.ContentType = "application/ms-excel=utf-8";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
tapuControllerService.js:
angular.module('TapuAppModule')
.factory('TapuControllerService', function TapuIlApiFactory($http) {
return {
adaParselSorguToExcel: function (zeminArg) {
return $http({ method: "GET", url: "Tapu/ExportToExcel", params: { ada: zeminArg.Ada, ilceId: zeminArg.IlceId, mahId: zeminArg.MahalleId, parsel: zeminArg.Parsel } });
},
tcKimlikNoIleToEcel: function (manuelTcKimlikNo) {
return $http({ method: "GET", url: "Tapu/tcKimlikNoIleToEcel", params: { tcKimlikNo: manuelTcKimlikNo } });
},
kurumIdIleToEcel: function (manuelKurumId) {
return $http({ method: "GET", url: "Tapu/kurumIdIleToEcel", params: { kurumId: manuelKurumId } });
}
}
});
tapuController.js:
$scope.exportToExcel = function () {
$scope.ZeminArg = {
Ada: $scope.selectedAdaNo,
Parsel: $scope.selectedParselNo,
MahalleId: $scope.selectedMahalle,
IlceId: $scope.selectedIlce
};
if (document.getElementById('adaparsel').className == "tab-pane fade active in") {
var fileName = "MahalleId-" + $scope.ZeminArg.MahalleId + "_IlceId-" + $scope.ZeminArg.IlceId + "_AdaNo-" + $scope.ZeminArg.Ada + "_ParselNo-" + $scope.ZeminArg.Parsel;
TapuControllerService.adaParselSorguToExcel($scope.ZeminArg)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
if (document.getElementById("tckimlikno").className == "tab-pane fade active in") {
var fileName = "TcNo-" + $scope.manuelTcKimlikNo;
TapuControllerService.tcKimlikNoIleToEcel($scope.manuelTcKimlikNo)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
if (document.getElementById("kurum").className == "tab-pane fade active in") {
var fileName = "kurum-" + $scope.manuelKurumId;
TapuControllerService.kurumIdIleToEcel($scope.manuelKurumId)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
};
And i'm using FileSaver. Here filesaver Url
Everything is ok. It's working. But i can't use Turkish chars. I tried some encoding but not worked. Here is my error's pic:
For example first SoyAd is : FERİKOĞLU
Second row Ad is : ALATTİN
etc. What should i do for output Excel with Turkish Chars??

Related

How to query Salesforce from NetSuite SuiteScript 2.0?

How would you go about querying Salesforce from a NetSuite suitescript?
Here is an example of querying Users from Salesforce in SuiteScript 2.0.
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(['N/https', 'N/record'],
function (https, record)
{
//handle the bs if its being created
function afterSubmit(context)
{
var body;
var response;
var recordData = {};
var queryURL;
body = loginSalesforceNLAP(); //login to SF
//error check the login
if(body.access_token == undefined || body.access_token == "")
{
log.debug("afterSubmit","Could not access SF");
return;
}
//check this email exists in SF
response = _HTTPS.get({
url: getURL(body) + "/query/?q=SELECT Id FROM User WHERE Username = user",
body: recordData,
headers: {"Authorization": "OAuth " + body.access_token,"Content-Type": "application/json"}
});
if(response.code != 200)
{
log.debug('afterSubmit', 'Could not query SF ' + response.code + ' ');
return;
}
//Check results (only 1 should be returned)
var b = JSON.parse(response.body);
if (b.totalSize == 1)
{
SFID = b.records[0].Id;
log.debug('afterSubmit', 'Found user in SF with ID ' + SFID);
}
else
{
log.debug('afterSubmit', 'No SF user with username user was found in SF');
return;
}
}
return {afterSubmit: afterSubmit};
});
//get URL of max version of SF
function getURL(body)
{
var max;
var arr;
var header = {"Authorization": "OAuth " + body.access_token };
var recordData = {};
var url = body.instance_url + "/services/data/";
response = _HTTPS.get({
url: url,
body: recordData,
headers: header
});
if(response.code == 200 || response.code == 204)
{
arr = JSON.parse(response.body);
for(var i = 0; i < arr.length; i++)
{
if(!max || parseInt(arr[i]["version"]) > parseInt(max["version"]))
max = arr[i];
}
return body.instance_url + max.url;
}
else
return "";
}
//Connect to Salesforce instance and obtain the Access Token used for subsequent Salesforce calls this session
function loginSalesforceNLAP() {
//production
var clientID = "432432432432432432432432ncK7FyfTUgxH2YNHvR6QPoVXpDE";
var clientSecret = "732323213210608985";
var securityToken = "N0bx9d323231aO321igJ6";
var username = "login#login.com";
var password = "password";
var loginURL = "https://login.salesforce.com/services/oauth2/token";
var header = [];
header['Content-Type'] = 'application/json;charset=UTF-8';
var recordData = {};
var url = loginURL + "?grant_type=password&client_id=" + clientID + "&client_secret=" + clientSecret + "&username=" + username + "&password=" + password + securityToken;
try
{
response = _HTTPS.post({
url: url,
body: recordData,
headers: header
});
response = JSON.parse(JSON.stringify(response));
if (response.code == 200 || response.code == 204)
return JSON.parse(response.body);
}
catch (er02)
{
log.error('ERROR:loginSalesforceNLAP', er02);
}
return "";
}
To find your security token, clientId, and client Secret follow the steps in these links:
https://success.salesforce.com/answers?id=90630000000glADAAY
https://developer.salesforce.com/forums/?id=906F0000000AfcgIAC

how do i display base 64 encoded string as image in ionic app in offline

my code in here
here $scope.student_photo is my variable to get encoded string
first i get it in ajax and stored in local db
$http.post(mData.url+'getStudentDetails/',{student_id : student_id} ).success(function(data){
//$scope.student_pic = data.student_details[0].student_pic;
//$scope.student_photo = data.student_details[0].student_photo;
$scope.myImage=data.student_details[0].student_photo;
//alert($scope.myImage);
// var image_stu = data.student_details[0].student_photo;
// localStorage.setItem("imageData", image_stu);
// document.getElementById("img_stu").src='data:image/png;base64,' + image_stu;
//alert("DONE");
var events = data.student_details
var l = events.length;
//alert(l);
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM dashboard ', [], function(tx, results){
if (results.rows.length == 0)
{
tx.executeSql("INSERT INTO dashboard(dashboard_id, stu_name,clas,sec,student_image) VALUES(?,?,?,?,?)", [ student_id,data.student_details[0].student_name, data.student_details[0].class_name, data.student_details[0].section_name,data.student_details[0].student_photo], function(tx, res) {
$scope.dashboardDetails();
//alert('INSERTED');
}, function(e) {
//alert('ERROR: ' + e.message);
});
}
});
});
});
$scope.showScreen = function(screen) {
$state.go('app.'+screen);
}
$scope.printDashboard = function()
{
//alert('ss');
db.transaction(function (tx) {
// tx.executeSql('SELECT * FROM dashboard', [], function (tx, dtresult) {
//alert("dtresult.rows.length" + dtresult.rows.length);
// console.log("dtresult.rows.length" + dtresult.rows.length);
// $scope.totalrecords = dtresult.rows.length;
// });
tx.executeSql('SELECT * FROM dashboard', [], function (tx, dresult) {
console.log("dresult.rows.length" + dresult.rows.length);
dataset = dresult.rows;
console.log(dresult.rows);
for (var i = 0, item = null; i < dresult.rows.length; i++) {
item = dataset.item(i);
$scope.dashboarditems.push({stu_name: item['stu_name'],stu_class: item['clas'],stu_sec: item['Sec'],stu_img: item['student_image']});
//$scope.items.push({id: item['notice_title'], notice:item['notice'], event_date: item['event_date']});
console.log($scope.dashboarditems[0]);
}
$state.go('app.dashboard');
});
});
}
$scope.dashboardDetails = function()
{
var citems = [];
syncWithServer(function(syncSuccess){
$scope.printDashboard();
}, false);
}
Question:
How to display my base64 string to image formate.
If your base64 string is present inside the $scope.student_photo
try the following img tag to display the image in view
<img ng-src="{{'data:image/png;base64,'+student_photo}}">

Angular ng-file-upload Get Byte Array and FormData in Asp.net MVC

I am trying to use ng-file-upload to upload files using Angular. I need the byte array to store in our database (I cannot store the uploaded file on the server), but I also need the FormData as well. My problem is that I can only seem to get one or the other (either the byte array or the formdata) but not both.
Here is my Angular code:
$scope.uploadPic = function (file) {
$scope.emrDetailID = 7;
file.upload = Upload.upload({
url: '/SSQV4/SSQV5/api/Document/UploadEMRDocument',
method: 'POST',
data: { file: file, 'emrdetail': $scope.emrDetailID}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
$scope.imageID = file.result;
});
});
};
Using the code below, I can get the byte array and store it in my database:
public async Task<IHttpActionResult> UploadDocument()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
string ClientIP = IPNetworking.GetIP4Address();
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var extension = Path.GetExtension(filename).TrimStart('.');
var buffer = await f.ReadAsByteArrayAsync();
FileImageParameterModel pm = new FileImageParameterModel();
pm.binFileImage = buffer;
//pm.CompanyID = UserInfo.intMajorID;
pm.CompanyID = 10707;
pm.dteDocumentDate = Convert.ToDateTime("4/4/2016");
pm.dteExpiration = Convert.ToDateTime("4/4/2017");
pm.vchUserIP = ClientIP;
pm.vchUploadedbyUserName = UserInfo.Username;
pm.vchFileExtension = extension;
CommonClient = new CommonWebApiClient();
CommonClient.AuthorizationToken = UserInfo.AccessToken;
int imageID = await CommonClient.InsertNewFileImage(pm);
return Json(imageID);
}
else
{
return BadRequest("Attachment failed to upload");
}
}
Using the code below I can get the FormData
var provider = new MultipartFormDataStreamProvider(workingFolder);
await Request.Content.ReadAsMultipartAsync(provider);
var emr = provider.FormData["emrdetail"];
but then I can't get the byte array as using MultipartFormDataStreamProvider wants a folder to store the file.
There's got to be a way to get both. I have been searching the internet for 2 days and all I can find are the two solutions above neither of which solves my issue.
Any assistance is greatly appreciated!
You are thinking way to complicated. Here is some of my code which I used for file upload in AngularJS with .NET
Angular:
function uploadFileToUrl(file) {
var formData = new FormData(); // Notice the FormData!!!
formData.append('uploadedFile', file);
return $http({
url: uploadUrl,
method: 'POST',
data: formData,
headers: {
'Content-Type': undefined
}
}).then(resolve, reject);
function resolve(data) {
$log.debug('data : ', data);
return data;
}
function reject(e) {
$log.warn('error in uploadFileToUrl : ', e);
return $q.reject(e);
}
}
Server:
public Task HandleAsync([NotNull] UploadFilesCommand command)
{
return wrapper.InvokeOnChannel(async client =>
{
// init command
command.Output = new Dictionary<string, int>();
try
{
foreach (var file in command.Files)
{
var request = new UploadFileRequest
{
FileName = file.Name,
FileStream = file.Stream
};
UploadFileResponse response = await client.UploadFileAsync(request);
command.Output.Add(file.Name, response.Id);
}
}
finally
{
// dispose streams
foreach (var file in command.Files)
{
if (file.Stream != null)
{
file.Stream.Dispose();
}
}
}
});
}

AngularJS extend model

I had in my old project this bit of code for an API:
.factory('Api', ['$resource', 'apiUrl', function ($resource, api) {
var Api = $resource(api + ':path', {
path: '#path'
});
return Api;
}])
and then I had an Order model which extended this factory class like this:
.factory('Order', ['$filter', 'Api', function ($filter, api) {
var Order = api;
angular.extend(Order.prototype, {
getDescription: function () {
var rolls = 0,
cuts = 0,
skus = [],
lines = $filter('orderBy')(this.lines, 'sku');
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
switch (line.type) {
case 0: // cut
cuts++;
break;
case 1: // roll
rolls++
break;
}
if (skus.indexOf(line.sku) == -1) {
skus.push(line.sku);
}
}
var description = '';
description += cuts > 0 ? cuts > 1 ? cuts + ' x cuts' : cuts + ' x cut' : '';
description += rolls > 0 && description.length > 0 ? ', ' : '';
description += rolls > 0 ? rolls > 1 ? rolls + ' x rolls' : rolls + ' x roll' : '';
description += skus.length == 1 ? ' of ' + skus[0] : '';
return description;
},
getStatus: function () {
var lines = this.lines,
status = lines[0].status;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (status !== line.status)
return 'Multiple';
}
return status;
},
getDeliveryDate: function () {
var lines = this.lines,
date = lines[0].dates.delivery;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (date !== line.dates.delivery)
return 'Multiple';
}
date = new Date(date);
return date;
},
getDispatchDate: function () {
var lines = this.lines,
date = lines[0].orderDate;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (date !== lines.orderDate)
return 'Multiple';
}
date = new Date(date);
return date;
}
});
return Order;
}]);
Now, I have recently changed my API factory to this:
// ---
// CONSTANTS.
// ---
.constant('apiUrl', 'http://localhost:54326/')
//.constant('apiUrl', 'http://localhost:81/')
// ---
// SERVICES.
// ---
.service('Api', ['$http', 'HttpHandler', 'apiUrl', function ($http, handler, apiUrl) {
// Private function to build our request
var buildRequest = function (url, method, data, params) {
var model = {
method: method,
url: apiUrl + url,
data: data,
params: params
};
return $http(model);
}
// GET
this.get = function (url, params) {
return handler.loadData(buildRequest(url, 'GET', null, params));
}
// POST
this.post = function (url, data) {
return handler.loadData(buildRequest(url, 'POST', data));
}
// PUT
this.put = function (url, data) {
return handler.loadData(buildRequest(url, 'PUT', data));
}
// DELETE
this.delete = function (url, data) {
return handler.loadData(buildRequest(url, 'DELETE', data));
}
}])
When I did this, my order model no longer works. I get an error stating:
Cannot read property '$$hashKey' of undefined
Is there a way I can get my Order model to use the new API factory? Specifically I want to attach functions each object returned by the API.

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