Hi I'm a newbie in web development and I'm having some trouble in inserting new data in my database.
First, there's an error in dbcontext.Tbl_Articles.Add(adto);
It says, cannot convert WebAPI.Models.Articles to WebAPI.DataLayer.Tbl_Articles
Another thing is, whenever I run my Web API, it says something like this - {"Message":"The requested resource does not support http method 'GET'."}
script file:
$scope.AddArticle = function ()
{
var data =
{
Category: $scope.Category,
IsCarousel: $scope.IsCarousel,
IsImportant: $scope.IsImportant,
HeaderImage: $scope.HeaderImage,
Title: $scope.Title,
ByLine: $scope.ByLine,
Content: $scope.Content,
Author: $scope.Author,
PublishStartDate: $scope.PublishStartDate_date + " " + $scope.PublishStartDate_time + $scope.PublishStartDate_time_ext,
PublishEndDate: $scope.PublishEndDate_date + " " + $scope.PublishEndDate_time + $scope.PublishEndDate_time_ext
};
$http(
{
method: 'POST',
url: 'http://project-aphrodite-uat-service.azurewebsites.net/api/articles/createarticle',
data: JSON.stringify(data)
})
.then(function successCallback(response)
{
console.log(response);
},
function errorCallback(response)
{
console.log("error" + response);
});
};
ArticlesController.cs:
[HttpPost]
[Route("api/articles/createarticle")]
public Articles CreateArticle(Articles obj)
{
DataLayer.DataLayer dl = new DataLayer.DataLayer();
dl.CreateArticle(obj);
return obj;
}
DataLayer.cs:
public string CreateArticle(Articles obj)
{
var adto = new Articles();
adto.Category = obj.Category;
adto.IsCarousel = obj.IsCarousel;
adto.IsImportant = obj.IsImportant;
adto.HeaderImage = obj.HeaderImage;
adto.Title = obj.Title;
adto.ByLine = obj.ByLine;
adto.Content = obj.Content;
adto.Author = obj.Author;
adto.PublishStartDate = obj.PublishStartDate;
adto.PublishEndDate = obj.PublishEndDate;
using (ArticleEntities dbcontext = new ArticleEntities())
{
dbcontext.Tbl_Articles.Add(adto);
dbcontext.SaveChanges();
return "test";
}
}
I hope someone could help me fix these. Thankie so much!
Related
I'm having some problems passing the data from my razor page to the server. It is passing NULL value from my abp.ajax({. Is there anything I'm missing from my ajax or the server-side code:
I'm using RAZOR PAGES ABP Framework 5.3
MY AJAX:
$("#frmDistrict").on("submit",
function (event) {
event.preventDefault();
const Url = $(this).attr("action");
const formData = $(this).serialize();
abp.ajax({
type: 'POST',
url: url,
data: JSON.stringify(formData)
}).then(function (result) {
if (data.isValid) {
if (data.IsNew) {
abp.notify.success(data.retmsg);
window.location.href = data.returl;
} else {
}
abp.notify.success(data.retmsg);
} else {
DisplayModelStateErrors(data.retmsg);
}
}).catch(function () {
alert("request failed :(");
});
});
MY SERVER CODE:
public async Task<JsonResult> OnPostAsync()
{
var rt = await Mediator.Send(new CreateDistrictCommand
{
District = district
});
if (rt.Failed) return new JsonResult(new { isValid = false, IsNew = true, retmsg =
rt.Message, sdata = rt.Data });
var retmsg = "District " + rt.Data.Name + " Created successfully.";
var returl = "/Districts/";
return new JsonResult(new { isValid = true, IsNew = true, retmsg, returl });
}
MY FORM
<form method="post" id="frmDistrict" >
<partial name="_AddEditDistrict" model="Model.District" />
</form>
If I use the standard ajax call
``$.ajax({ it works fine
but abp.ajax({ doesn't work
Many thanks
Zak
I have a class
public class Customer
{
private int _Id;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
private String _Name;
public String Name
{
get { return _Name; }
set { _Name = value; }
}
private String _Address;
public String Address
{
get { return _Address; }
set { _Address = value; }
}
}
I need to save data using this class. I need to know how to call this class in data function
$scope.Save = function () {
var httpreq = {
method: 'POST',
url: 'ajs.aspx/Save',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'dataType': 'json'
},
data: { //** Here How to call assign object value for my customer class **// }
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
How to create class object and assign value for my customer class in this data section.
In my web method
[System.Web.Services.WebMethod()]
public static void Save(Customer objcsr)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "insert into customer (Name, Address) values (#Name, #Address);";
cmd.Parameters.AddWithValue("#Name", objcsr.Name);
cmd.Parameters.AddWithValue("#Address", objcsr.Address);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
You need pass the json format data with the class properties, Try this below code
Var objcsr={Id:"1",Name:"Donald Trump",Address:"Alien Planet"}
$scope.Save = function () {
var httpreq = {
method: 'POST',
url: 'ajs.aspx/Save',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'dataType': 'json'
},
data: objcsr
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
When you are sending data from client to server, according to the best practices, the data should be sent either in the form of XML or JSON.
Hence, the JSON of your class object could be something like
var obj = {
"id" : "YOUR ID",
"name" : "YOUR NAME",
"address" : "YOUR ADDRESS"
}
Moreover, according to the best practices, the http requests should be made using a factory or service.
So your factory should be something like
angular.module("YOUR_MODULE").factory('YOUR_SERVICE',function($http,$q){
var obj = {};
obj.saveObject = function(data){
var defer = $q.defer();
$http.post("YOUR URL",data).then(function(response){
defer.resolve(response);
},function(error){
defer.reject(error);
});
return defer.promise;
}
return obj;
});
And thus you can make a controller call as
$scope.Save = function (data) {
YOUR_SERVICE.saveObject(data);
}
and that can be called like
var obj = {
"id" : "YOUR ID",
"name" : "YOUR NAME",
"address" : "YOUR ADDRESS"
}
$scope.Save(obj);
If your getting it from form elements then you should be using it like
$scope.Save = function () {
var customerObject={
"Id": $scope.customerId,
"Name": $scope.customerName,
"Address":$scope.customerAddress
};
var httpreq = {
method: 'POST',
url: 'ajs.aspx/Save',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
data: { customerObject }
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
Also Note that, the objectName and their respective properties that your are passing should match with that of the objectName in webmethod. For example
Your properties are
your corresponding json object must have the same properties
Id: $scope.Id
Name: $scope.Name
Address: $scope.Address
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();
}
}
}
});
}
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).
var store = new FMP.AspNetJsonStore({
fields: [
{ name: 'AssetID' },
{ name: 'AssociationID' },
{ name: 'Image' },
{ name: 'StatusName' },
{ name: 'ModelName' },
{ name: 'IPAddress' },
{ name: 'InScope', type: 'boolean' },
{ name: 'ServicePlanName' },
{ name: 'PricePlanName' },
{ name: 'PricePlanDescription' },
{ name: 'Program' },
{ name: 'ServicePlanID' },
{ name: 'Customer' },
{ name: 'Black', type: 'float' },
{ name: 'Cyan', type: 'float' },
{ name: 'Magenta', type: 'float' },
{ name: 'Yellow', type: 'float' },
{ name: 'BlackPct' },
{ name: 'CyanPct' },
{ name: 'MagentaPct' },
{ name: 'YellowPct' },
{ name: 'PrinterMarkerSupplies' },
{ name: 'PageCount' },
{ name: 'BlackImpressions' },
{ name: 'ColorImpressions' },
{ name: 'PricePlanID' },
{ name: 'ResponsibilityForAction' },
{ name: 'PrinterSerialNumber' }
],
totalProperty: "TotalCount",
autoLoad: { params: { start: 0, limit: myPageSize} },
//autoLoad: true,
proxy: new Ext.data.HttpProxy({
// Call web service method using GET syntax
url: 'GetPrintersGrid.asmx/buildGrid',
// Ask for Json response
headers: { 'Content-type': 'application/json' },
method: "GET"
}),
remoteSort: true,
//sortInfo: { field: 'PageCount', direction: "DESC" },
groupField: 'Customer',
root: 'Records'
});
store.setDefaultSort('PageCount', 'DESC');
I am using a webservice to sort this.
I am getting an error
{"Message":"Invalid JSON primitive: DESC.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext context, JavaScriptSerializer serializer, WebServiceMethodData methodData)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
Can anyone help me in this issue
I am using Ext.ux.AspWebServiceProxy class and used this proxy class in the store.Also defined the webservice in the user control in scriptmanager proxy
Iam getting an error saying GetPrintersGrid is undefined.Iam using the follwing example for reference.
http://osman.in/aspnet/using-extjs-grid-with-aspnet-ajax-wcf-webservices-c/
Can you please help me in this issue.
/// <reference path="ExtJS/ext-all.js" />
Ext.namespace('Ext.ux');
Ext.ux.AspWebServiceProxy = function(conn)
{
Ext.ux.AspWebServiceProxy.superclass.constructor.call(this);
Ext.apply(this, conn);
};
Ext.extend(Ext.ux.AspWebServiceProxy, Ext.data.DataProxy,
{
load : function (params, reader, callback, scope, arg)
{
var userContext = {
callback: callback,
reader: reader,
arg: arg,
scope: scope
};
var proxyWrapper = this;
//Handles the response we get back from the web service call
var webServiceCallback = function(response, context, methodName)
{
proxyWrapper.loadResponse(response, userContext, methodName);
}
var serviceParams = [];
//Convert the params into an array of values so that they can be used in the call (note assumes that the properties on the object are in the correct order)
for (var property in params)
{
serviceParams.push(params[property]);
}
//Add the webservice callback handlers
serviceParams.push(webServiceCallback);
serviceParams.push(this.handleErrorResponse);
//Make the actual ASP.Net web service call
this.webServiceProxyMethod.apply(this.webServiceProxy, serviceParams);
},
handleErrorResponse : function(response, userContext, methodName)
{
alert("Error while calling method: " + methodName + "\n" + response.get_message());
},
loadResponse : function (response, userContext, methodName)
{
var result = userContext.reader.readRecords(response);
userContext.callback.call(userContext.scope, result, userContext.arg, true);
}
});
var dataStore = new Ext.data.Store(
{
//Note that I have renamed the web service proxy class
proxy: new Ext.ux.AspWebServiceProxy(
{
webServiceProxy: GetPrintersGrid,
webServiceProxyMethod: GetPrintersGrid.buildGrid
}),
remoteSort: true
});
<asp:ScriptManagerProxy ID="PageScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~/GetPrintersGrid.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Path="~/Ext.ux.AspWebServiceProxy.js" />
</Scripts>
</asp:ScriptManagerProxy>
This is the souce code i ussed
FMP.AspNetJsonReader = Ext.extend(Ext.data.JsonReader, {
read: function(response) {
// Assuming ASP.NET encoding - Data is stored as
var json = response.responseText;
var o = Ext.decode(json);
if (!o) {
throw { message: "AspNetJsonReader.read: Json object not found" };
}
if (!o.d) {
throw { message: "AspNetJsonReader.read: Root element d not found" };
}
return this.readRecords(o.d);
}
});
FMP.AspNetJsonStore = Ext.extend(Ext.data.GroupingStore, {
/**
* #cfg {Ext.data.DataReader} reader #hide
*/
constructor: function(config) {
FMP.AspNetJsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new FMP.AspNetJsonReader(config)
}));
}
});
Iam using AS.NET for server side
Here is my webservice
public PagedResult buildGrid(int start, int limit, string sortfield, string dir)
{
var a=5;
Guid AccountID = (Guid)Session["AccountID"];
//string sortdir;
//if( dir == "DESC")
//{
// sortdir = dir.Substring(0, 4).Trim().ToUpper();
//}
//else
//{
// sortdir = dir.Substring(0, 3).Trim().ToUpper();
//}
string SortExpression = sortfield + " " + (!String.IsNullOrEmpty(dir) ? dir : String.Empty);
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' order by a.PageCount = '" + + "'";
string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' Order By a."+SortExpression;
//string whereClause = "SELECT value a , ROW_NUMBER() OVER(ORDER BY" + " " + SortExpression + ") As RowNumber FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "'";
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "'";
List<FMPAsset> fmpAssets = new List<FMPAsset>();
using (XSPAssetModel.XSPAssetEntities assetEntities = new XSPAssetEntities(b.BuildEntityConnectionString1("XSMDSN")))
{
ObjectQuery<XSP_AssetList_V> assets = new ObjectQuery<XSP_AssetList_V>(whereClause, assetEntities);
//var assetOrder = assets.OrderBy(x => x.StatusName).ToList();
var assetPage = assets.Skip(start).Take(limit);
//var totalAssetCount = assets.Count();
currentAssets = assetPage.ToList();
int currentAssetsCount = currentAssets.Count;
string imgprefix = System.Configuration.ConfigurationManager.AppSettings["ImgPrefix"];
char[] separators = { '/' };
string appname = "";
int lastloc = imgprefix.Substring(0, imgprefix.Length - 1).LastIndexOfAny(separators);
if (lastloc > 6)
{
appname = imgprefix.Substring(lastloc + 1);
}
FMPAsset asset = new FMPAsset();
//StreamWriter sw = new StreamWriter("C:\\test.txt");
XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities markerCtx = new XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities(b.BuildEntityConnectionString1("XSMDSN"));
for (int x = 0; x < currentAssetsCount; x++)
{
asset = new FMPAsset();
asset.AssetID = currentAssets[x].AssetID.ToString();
asset.PricePlanID = currentAssets[x].PricePlanID.ToString();
asset.AssociationID = currentAssets[x].AssociationID;
asset.ModelName = currentAssets[x].ModelName;
asset.ResponsibilityForAction = currentAssets[x].ResponsibilityForAction;
asset.IPAddress = (String.IsNullOrEmpty(currentAssets[x].PrinterIPAddress)) ? "No IP" : currentAssets[x].PrinterIPAddress; ;
if (currentAssets[x].InScope)
{
asset.InScope = b.GetString("SDE_YES");
}
else
{
asset.InScope = b.GetString("SDE_NO");
}
asset = SetStatus(appname, asset, x);
asset.PricePlanName = currentAssets[x].Program;
asset.PricePlanDescription = currentAssets[x].PricePlanDescription;
asset.ServicePlanName = currentAssets[x].ServicePlanName;
if (currentAssets[x].PrinterSerialNumber != null)
{
asset.PrinterSerialNumber = currentAssets[x].PrinterSerialNumber;
}
else
{
asset.PrinterSerialNumber = "-";
}
//sw.WriteLine("ChargebackDescription: " + DateTime.Now.Millisecond);
if (this.b.UseChargebackDescription && !String.IsNullOrEmpty(currentAssets[x].CustomerChargebackDescription) && currentAssets[x].CustomerChargebackDescription != "Generated by OUT Integration")
{
asset.Customer = currentAssets[x].CustomerChargebackDescription;
if (asset.Customer.IndexOf(Environment.NewLine) > -1)
{
asset.Customer = asset.Customer.Substring(0, asset.Customer.IndexOf(Environment.NewLine));
}
}
else
{
asset.Customer = currentAssets[x].CustomerChargeBackEntryName;
}
if (this.b.UsePricePlanDescription && !String.IsNullOrEmpty(currentAssets[x].PricePlanDescription))
{
asset.Program = currentAssets[x].PricePlanDescription;
if (asset.Program.IndexOf(Environment.NewLine) > -1)
{
asset.Program = asset.Program.Substring(0, asset.Program.IndexOf(Environment.NewLine));
}
}
else
{
asset.Program = currentAssets[x].Program;
}
asset.BlackPct = -3;
asset.CyanPct = -3;
asset.MagentaPct = -3;
asset.YellowPct = -3;
Guid id = currentAssets[x].AssetID;
asset = SetCMYKvalues(asset, x);
BuilldImpressionsValues(currentAssets[x], ref asset);
fmpAssets.Add(asset);
}
var totalAssetCount = assets.Count();
var y = new PagedResult<FMPAsset>();
y.Records = fmpAssets;
y.TotalCount = totalAssetCount;
return y;
// CommonGrid1.BindDataSource(SortByStatusName(fmpAssets));
}
}
This error is happening when your store is making the call to your web service. Whatever JSON is being sent is not valid for some reason (or .NET does not think it is), hence the server error when ASP.NET is trying to deserialize the data into a valid argument list for your method. I would first look in Firebug to see exactly what JSON is being passed to the server -- that might give you a clue as to what the issue is. If the JSON being sent is not valid then it's a client/Ext issue -- if it is valid, then it's a .NET issue.