Related
//lightning controller- Here I am capturing the signature in a hidden canvas and extracting the base64 data from it , and sending it to the server side apex
var tCtx = document.getElementById('textCanvas').getContext('2d'),
imageElem = document.getElementById('Signimage');
tCtx.canvas.width = 720;
tCtx.canvas.height= 100;
tCtx.font = "italic 30px monospace";
var theSignature = n; // name of person - the text that is to be converted to an img
tCtx.fillText(theSignature,10, 50);
imageElem.src = tCtx.canvas.toDataURL();
var base64Canvas = tCtx.canvas.toDataURL().split(';base64,')[1];
component.set('{!v.storeApplicantSign}',base64Canvas);
//lightning helper
uploadonSubmit: function(component,event,helper) {
// call the apex method 'saveChunk'
var action = component.get("c.saveChunk");
action.setParams({
parentId: component.get("v.recordId"),
base64Data: component.get("v.storeApplicantSign"), // contains the base64 data
});
// set call back
action.setCallback(this, function(response) {
// store the response / Attachment Id
var result = response.getReturnValue();
var state = response.getState();
if (state === "SUCCESS") {
alert("Success");
// this.showtheToast();
} else if (state === "INCOMPLETE") {
alert("From server: " + response.getReturnValue());
} else if (state === "ERROR") {
var errors = response.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " + errors[0].message);
}
} else {
console.log("Unknown error");
}
}
});
// enqueue the action
$A.enqueueAction(action);
},
// apex class
//Here decoding the data from the lightning and creating content version
#AuraEnabled
public static Id saveChunk(Id parentId,String base64Data) {
String fileId = saveTheFile(parentId,base64Data,'Signature.png');
return Id.valueOf(fileId);
}
public static Id saveTheFile(Id parentId,String base64Data,String fileName) {
base64Data = EncodingUtil.urlDecode(base64Data,'UTF-8');
ContentVersion contentVersion = new ContentVersion(
versionData = EncodingUtil.base64Decode(base64Data),
title = fileName,
pathOnClient = 'Signature'+'.'+'png',
ContentLocation='S',
FirstPublishLocationId = parentId);
system.debug('contentversion data=> '+contentVersion+'version data ----> '+contentVersion.VersionData);
insert contentVersion;
return contentVersion.Id;
}
// File is being created but it's empty that is image is not there / can't be opened as img
The issue was in apex side :
just removed the line :
`base64Data = EncodingUtil.urlDecode(base64Data,'UTF-8'); // this wasn't required
removing the above line solved it .
I tried to display the output of this data into a list but it can't
this is my data output
{activity: {"project":" Distributions","code":2000,"code_name":"OpenProcessSnapshot","activity":{"id_process_snapshot":988,"name":"Android Process"}}, created_at: 2019-06-20 08:58:48.492885+07, id: 1, id_user: 1}
{activity: {"project":"Distributions","code":2000,"code_name":"OpenProcessSnapshot","activity":{"id_process_snapshot":988,"name":"Android Process"}}, created_at: 2019-06-20 08:58:48.492885+07, id: 1, id_user: 1}
{activity: {"project":" Distributions","code":2000,"code_name":"OpenProcessSnapshot","activity":{"id_process_snapshot":988,"name":"Android Process"}}, created_at: 2019-06-20 08:58:48.492885+07, id: 1, id_user: 1}
and this is my code
FutureBuilder(
future: UserController.getActivity(_selectedUser),
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data.toString());
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data.toString()),
],
);
} else {
return Center(
child: Text("No data displayed"),
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
what if I want to display created_at and project?
You can use jsonDecode to get that specific element.
Documentation Link
For your case you have to create a new widget function and return it:
//put this method before your widget build function
Widget _mapJsonDataToText(String data){
Map<String, List<dynamic>> jsonData = jsonDecode(data);
Map<String, dynamic> jsonDataInner = jsonDecode(jsonData['activity']);
return Text(jsonDataInner['created_at']);
//do the same for project
}
children: <Widget>[
//gets the method that returns the text widget
_mapJsonDataToText(snapshot.data.toString()),
],
I have a different method, this will add up the data into the list. Not using future builder, just making use of my common sense to display the data logically into the list.
Assuming you know about http of flutter, if you don't then this is the link for you: Fetch data from the internet
Suppose you have a data[], in which activity{} are being displayed in your JSON output.
List<String> project = [];
List<String> createdAt = [];
void initState(){
super.initState();
//this will run this method on call of this page, everytime
this.fetchData();
}
Future<void> fetchData() async{
List<String> _project = [];
List<String> _createdAt = [];
final response =
await http.get('your_api_url');
//looping through the array of activity object
(response['data'] as list).forEach((item){
//check if the data comes correct
print(item['activity']['project']);
print(item['created_at']);
_project.add(item['activity']['project']);
_createdAt.add(item['created_at']);
});
setState((){
this.project = _project;
this.createdAt = _createdAt;
});
}
//In order to show them in the list of project, call ListView()
List<Widget> projectWidget(){
List<Widget> _widget = [];
this.project.forEach((item){
_widget.add(item);
});
return _widget;
}
//In order to show them in the list of createdAt, call ListView()
List<Widget> createdAtWidget(){
List<Widget> _anotherWidget = [];
this.createdAt.forEach((item){
_anotherWidget.add(item);
});
return _anotherWidget;
}
Display the data as you want in your UI. Let me if it works for you. Thanks :)
I am going to use a real json. First of all, I should run the project that is written in Flask, then use the local host to achieve data.
Here is the real Json I`m using
{
"devices":[
{
"device_desc":"cooler",
"device_title":"cooler",
"functions":[
{
"device_id":1,
"function_desc":"pomp",
"function_title":"pomp",
"status":1
},
{
"device_id":1,
"function_desc":"less",
"function_title":"less",
"status":1
},
{
"device_id":1,
"function_desc":"up",
"function_title":"up",
"status":1
}
],
"image_path":"fdfdfsf",
"status_id":1,
"statuss":{
"status_desc":"device is on",
"status_title":"on"
}
},
{
"device_desc":"panke",
"device_title":"panke",
"functions":[
{
"device_id":2,
"function_desc":"less",
"function_title":"pomp",
"status":2
},
{
"device_id":2,
"function_desc":"less",
"function_title":"less",
"status":2
}
],
"image_path":"vfx",
"status_id":2,
"statuss":{
"status_desc":"device is off",
"status_title":"off"
}
}
]
}
This is my code:
these are data models for defining json properties:
class Base{
//the type of our object is the array
List<Device> _devices;
Base(this._devices);
List<Device> get devices => _devices;
set devices(List<Device> value) {
_devices = value;
}
}
class Device {
String _device_desc,_device_title,_image_path;
int _status_id;
List<function> _functions;
List<Status> _statuss ;
Device(this._device_desc, this._device_title, this._image_path,
this._status_id, this._functions, this._statuss);
List<Status> get statuss => _statuss;
set statuss(List<Status> value) {
_statuss = value;
}
List<function> get functions => _functions;
set functions(List<function> value) {
_functions = value;
}
int get status_id => _status_id;
set status_id(int value) {
_status_id = value;
}
get image_path => _image_path;
set image_path(value) {
_image_path = value;
}
get device_title => _device_title;
set device_title(value) {
_device_title = value;
}
String get device_desc => _device_desc;
set device_desc(String value) {
_device_desc = value;
}
}
class Status {
String _status_desc, _status_title;
Status(this._status_desc, this._status_title);
get status_title => _status_title;
set status_title(value) {
_status_title = value;
}
String get status_desc => _status_desc;
set status_desc(String value) {
_status_desc = value;
}}
class function {
String _function_desc, _function_title;
int _device_id, _status;
function(this._function_desc, this._function_title, this._device_id,
this._status);
get status => _status;
set status(value) {
_status = value;
}
int get device_id => _device_id;
set device_id(int value) {
_device_id = value;
}
get function_title => _function_title;
set function_title(value) {
_function_title = value;
}
String get function_desc => _function_desc;
set function_desc(String value) {
_function_desc = value;
}}
and this is the stateful class :
class MyHomePage extends StatefulWidget {
var title;
MyHomePage({Key key, this.title}) : super(key: key);
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<Base> _getBase() async {
var data = await http.get(Uri.encodeFull("http://192.168.1.111:5000/mobile-home"));
var jsonData = json.decode(data.body);
Base base = Base(jsonData);
return Base(jsonData[0]);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Container(
child: FutureBuilder(
future: _getBase(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.devices.length,
itemBuilder: (BuildContext context, int index) {
snapshot.data.devices.map<Widget>((devices){
return ListTile(
subtitle: Text(devices[index].device_desc.toString()),
title: Text(devices[index].device_title),
/*leading: CircleAvatar(
// ignore: argument_type_not_assignable
backgroundImage: NetworkImage(snapshot.data[index].thumbnailUrl),
)*/
);
}
);
},
);
}
},
),
),
);
}
}
I got an error when while debugging:
"type 'List<dynamic>' is not a subtype of type 'List<Device>'"
I can not get the data from json.
There was no question in your question, but I assume the question is:
My Json code is not working - How do I efficiently parse and encode complex json objects in my
flutter program.
For complex JSON you may want to consider using code generation to reduce the boiler plate you have to write. The flutter page has a good example using JsonSerializable. Here the basic instructions for your example:
Add dependencies to pubspec.yaml and run flutter pub get in the command line:
dependencies:
json_annotation: ^1.2.0
dev_dependencies:
build_runner: ^1.0.0
json_serializable: ^1.5.1
Create the basic Object model (similar to what you have done). Except for the following differences:
You don't have a List of Status for the field statuss, but a single Status object.
Don't use private fields.
To enable json boiler plate code generation do the following three steps:
add the json-annotations to each class,
add a factory .fromJson method on each class and
add a .toJson method on each class:
#JsonSerializable()
class Base {
List<Device> devices;
Base({this.devices});
factory Base.fromJson(Map<String, dynamic> json) => _$BaseFromJson(json);
Map<String, dynamic> toJson() => _$BaseToJson(this);
}
#JsonSerializable()
class Device {
String device_desc,device_title,image_path;
int status_id;
List<function> functions;
Status statuss ;
Device(this.device_desc, this.device_title, this.image_path,
this.status_id, this.functions, this.statuss);
factory Device.fromJson(Map<String, dynamic> json) => _$DeviceFromJson(json);
Map<String, dynamic> toJson() => _$DeviceToJson(this);
}
#JsonSerializable()
class Status {
String status_desc, status_title;
Status(this.status_desc, this.status_title);
factory Status.fromJson(Map<String, dynamic> json) => _$StatusFromJson(json);
Map<String, dynamic> toJson() => _$StatusToJson(this);
}
#JsonSerializable()
class function {
String function_desc, function_title;
int device_id, status;
function(this.function_desc, this.function_title, this.device_id,
this.status);
factory function.fromJson(Map<String, dynamic> json) => _$functionFromJson(json);
Map<String, dynamic> toJson() => _$functionToJson(this);
}
Run the command line to start code generation in the project root folder:
flutter packages pub run build_runner watch
Now an additional source file appears with your generated boiler plate code. Add this file to your own source file using the part keyword, for example if your source file is main.dart add the following line:
part 'main.g.dart';
And you are done - This is all you need to test your encoding / decoding. For example with the following code:
import 'dart:convert';
void main() => (){
var jsonExample = '{"devices": [{"device_desc": "cooler", "device_title": "cooler", "functions": [{"device_id": 1, "function_desc": "pomp", "function_title": "pomp", "status": 1}, {"device_id": 1, "function_desc": "less", "function_title": "less", "status": 1}, {"device_id": 1, "function_desc": "up", "function_title": "up", "status": 1}], "image_path": "fdfdfsf", "status_id": 1, "statuss": {"status_desc": "device is on", "status_title": "on"}}, {"device_desc": "panke", "device_title": "panke", "functions": [{"device_id": 2, "function_desc": "less", "function_title": "pomp", "status": 2}, {"device_id": 2, "function_desc": "less", "function_title": "less", "status": 2}], "image_path": "vfx", "status_id": 2, "statuss": {"status_desc": "device is off", "status_title": "off"}}]}';
Map base_example = json.decode(jsonExample);
Base base_example_parsed = Base.fromJson(base_example);
var numberDevices = base_example_parsed.devices.length;
var numberFuncs = base_example_parsed.devices[0].functions.length;
print('$base_example_parsed has $numberDevices devices and the first device has $numberFuncs functions');
var base_example_encoded_again = json.encode(base_example_parsed);
print('$base_example_encoded_again');
};
For more information please refer to:
1. the official example.
2. this blog.
There's a very good article about how to parse complex JSON in Flutter. Here's a quick summary...
Simple Stuff:
{
"id":"487349",
"name":"Pooja Bhaumik",
"score" : 1000
}
becomes...
class Student{
String studentId;
String studentName;
int studentScores;
Student({
this.studentId,
this.studentName,
this.studentScores
});
factory Student.fromJson(Map<String, dynamic> parsedJson){
return Student(
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : parsedJson ['score']
);
}
}
You create a new Student object like Student.fromJson(your_parsed_json).
Sub-objects work in a similar way. For each object inside the parent object you make a new Dart object, each with it's own parser for fromJson. Then inside the parent factory you call that fromJson method (like so)... This also works for lists of objects.
factory Student.fromJson(Map<String, dynamic> parsedJson){
return Student(
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : Teacher.fromJson(parsedJson['teacher'])
);
I have the big problem. I want to display this json, but returning undefined value.
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
I use this code in service.ts
public getHomeboxPById(id: string): Observable<HomeboxP> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('home_id', id);
urlSearchParams.append('token', this.auth.getCurrentUser().token);
let body = urlSearchParams.toString();
return this.http.post(Api.getUrl(Api.URLS.getHomeboxPById), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return new HomeboxP(res.StatusDescription[0]);
} else if (res.StatusCode === 1) {
this.auth.logout();
} else {
return new HomeboxP(null);
}
});
}
In ts code I call this method getHomeboxPById, like this
editHomeboxPForm: FormGroup;
homeboxp: HomeboxP;
this.editHomeboxPForm = this.fb.group({
'homebox_id': new FormControl('', Validators.required)
});
}
populateFormHomeboxP() {
this.activatedRoute.params.subscribe(
params => {
this.ws.getHomeboxPById(params['id']).subscribe(
homeboxp => {
console.log(homeboxp); // display undefined
this.homeboxp = homeboxp;
this.editHomeboxPForm.controls['homebox_id'].setValue(homeboxp.homebox_id);
}
);
}
);
}
Please, can you help me, why doesn't work?
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
If this is the response of
this.http.post(Api.getUrl(Api.URLS.getHomeboxPById)
Then issue is res.StatusDescription[0] , it should be res.StatusDescription like :
new HomeboxP(res.StatusDescription);
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.