Kendo UI Grid Fires CRUD Operations multiple times - grid

I've seen this problem in many places but I can't seem to find a solution. So I have defined a Kendo grid with CRUD operations the thing is that the previous fired operations get fired again.
Say you delete entry X and then you add entry Y, the create operation fires and after that the delete operation (for X - which has been deleted) fires again. Same thing if you first create an element and then edit another, it edits the 2nd element and then it re-fires the 1st create statement and inserts a duplicate for the 1st inserted element. If you go on an on with several operations a nightmare happens with all the other previous operations being fired and sent to the controller.
My grid is:
function InitializeIPAddressesGrid(userID) {
selectedUserID = userID;
$(".ipAddresses").kendoGrid({
dataSource: IPAdressesDataSource,
sortable: {
mode: "single",
allowUnsort: false
},
remove: function (e) {
this.refresh();
var canDelete = confirm("Are you sure you want to delete this record?");
if (!canDelete) {
e.preventDefault();
}
},
height: 420,
resizable: true,
pageable: {
refresh: true,
pageSize: 10
},
selectable: "row",
toolbar: ["create"],
editable:{mode: "inline", confirmation:false} ,
columns: [{
field: "IpAddress",
title: "IP Address"
},
{
field: "Status",
title: "Status"
},
{
field: "LockedUntil",
title: "Locked until",
template: "#=kendo.toString(LockedUntil, 'yyyy/MM/dd' )#"
},
{ command: ["edit", "destroy"], title: " ", width: "180px" }
]
});
}
var IPAdressesDataSource = new kendo.data.DataSource({
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
//scrollable:false,
transport: {
read: {
url: websiteRootUrl + '/PortalAuthorization/GetIPAddressesList',
},
update: {
url: websiteRootUrl + "/PortalAuthorization/UpdateIP",
dataType: "json",
type: 'POST',
complete: function (e) {
if (e.status != 200) {
alert(eval('(' + e.responseText + ')').Message);
}
}
},
create: {
url: websiteRootUrl + "/PortalAuthorization/CreateIP",
dataType: "json",
type: 'POST',
complete: function (e) {
if (e.status != 200) {
alert(eval('(' + e.responseText + ')').Message);
}
}
},
destroy: {
url: websiteRootUrl + "/PortalAuthorization/DeleteIP",
dataType: "json",
type: 'DELETE',
complete: function (e) {
if (e.status != 200) {
alert(eval('(' + e.responseText + ')').Message);
}
}
},
parameterMap: function (options, operation) {
if (operation == "update" && options) {
return {ipAddress: options.IpAddress ,
status: options.Status ,
lockedUntil: kendo.toString(options.LockedUntil, 'yyyy/MM/dd' ),
pkey: options.ID,
databaseID: selectedDatabaseID };
}
else
if (operation == "destroy" && options)
{
return {
databaseID: selectedDatabaseID,
pkey: options.ID,
userIDParam: selectedUserID
};
}
else
if (operation == "create" && options) {
return {ipAddress: options.IpAddress ,
status: options.Status ,
lockedUntil: kendo.toString(options.LockedUntil, 'yyyy/MM/dd' ),
pkey: options.ID,
userIDParam: selectedUserID,
databaseID: selectedDatabaseID };
}
else
{
options.databaseID = selectedDatabaseID;
options.userID = selectedUserID;
return options;
}
}
},
schema: {
model: {
id: "ID",
fields: {
IpAddress: { type: "string" },
Status: { type: "string" },
LockedUntil: { type: "date" }
}
},
data: function (data) {
return data.Items;
},
total: function (data) {
return data.TotalCount;
}
}
});
My controllers are:
public object UpdateIP(int databaseID, long pkey, string status, string lockedUntil, string ipAddress)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = "...";
repository.ExecuteNonQuery(query);
return new HttpResponseMessage(HttpStatusCode.OK);
}
public object DeleteIP(int databaseID, long pkey, int? userIDParam)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = "...";
repository.ExecuteNonQuery(query);
return new HttpResponseMessage(HttpStatusCode.OK);
}
public object CreateIP(int databaseID, long? pkey, string status, string lockedUntil, string ipAddress, int? userIDParam)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = "...";
repository.ExecuteNonQuery(query);
return new HttpResponseMessage(HttpStatusCode.OK);
}
Do you have any ideea? where I've done something wrong? thanks in advance. P.S. the queries in the controllers work fine.

I fixed the problem, followed OnaBai's suggestion of returning the Updated/Created entity, and in the case of a Delete I returned the ID of the deleted entry.
public object UpdateIP(int databaseID, long pkey, string status, string lockedUntil, string ipAddress)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = [...];
IPList updatedIP = new IPList { ID = pkey, IpAddress = ipAddress, Status = status, LockedUntil = DateTime.Today };
return Json(updatedIP, JsonRequestBehavior.AllowGet);
// return new HttpResponseMessage(HttpStatusCode.OK);
}
Only one mention: in the case of a CREATE, the method didn't seem to work so what I did is in the .complete event of the CREATE operation I did a ipGrid.dataSource.read();
ipGrid.refresh(); - so the operation doesn't repeat itself. ( I read that in this case there might be problem with the model definition - setting the ID field - but I did set that one). Many thanks to OnaBai

Related

Can SimpleSchema express "object with custom keys and specific schema for values"?

I want to make a SimpleSchema for documents with the the following format:
{
...,
permissions: {
foo: {allow: ["user1", "user2"]},
bar: {allow: ["admin"]},
}
}
If foo and bar were well-known strings in the schema, I would just do this:
const PermissionsSchema = new SimpleSchema({
allow: {type: [String]},
});
new SimpleSchema({
...,
'permissions.foo': {
type: PermissionSchema,
},
'permissions.bar': {
type: PermissionSchema,
},
})
However, in this case, there can be arbitrary string keys, not just foo and bar. The values must always match PermissionsSchema. Is there a way to express this?
Custom validators to the rescue!
import { ValidationError } from 'mdg:validation-error';
function permissionsValidator(keyRegEx) {
if (!(keyRegEx instanceof RegExp)) {
throw new Error('must pass a regular expression');
}
return function() {
// https://github.com/aldeed/meteor-simple-schema#custom-validation
const value = this.value;
for (let key in value) {
if (value.hasOwnProperty(key)) {
if (!keyRegEx.test(key)) {
return 'regEx';
}
try {
PermissionSchema.validate(value[key]);
} catch (ex) {
if (ex instanceof ValidationError) {
return ex.error;
}
}
}
}
};
}
new SimpleSchema({
...,
permissions: {
type: Object,
custom: permissionsValidator(/^.*$/),
blackbox: true,
optional: true,
defaultValue: {},
},
});
The error messages that come out are rubbish, though. Improvements or better strategies still welcome.

How do I write an item to a DynamoDb with the AWS DynamoDB DocumentClient?

I'm having trouble with the AWS DynamoDb JS SDK v2.4.9. I want to use the DocumentClient class as opposed to the lower level DynamoDb class, but can't get it working.
This works:
function testPutItem( callback ) {
var tableName = 'todos';
var params = {
TableName: tableName,
Item: {
user_id: { S : userId },
id: { N : msFromEpoch }, // ms from epoch
title: { S : makeRandomStringWithLength(16) },
completed: { BOOL: false }
}
};
var dynamodb = new AWS.DynamoDB();
dynamodb.putItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data); // successful response
if (callback) callback(data);
}
});
}
This does not work and gives the error InvalidParameterType: Expected params.Item[attribute] to be a structure for each attribute--as if DocumentClient is expecting the same input as DynamoDb:
function testPutItem( callback ) {
var tableName = 'todos';
var params = {
TableName: tableName,
Item: {
user_id: userId,
id: msFromEpoch,
title: makeRandomStringWithLength(16),
completed: false
}
};
console.log(params);
var docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
docClient.put(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data); // successful response
if (callback) callback(data);
}
});
}
Does anyone have any idea what I am doing wrong?
I used to have the same issue,
please try with a simple object first, cause it's due to some special characters in your attributes, see my example :
this generates the error
InvalidParameterType: Expected params.Item[attribute] to be a structure
var Item = {
domain: "knewtone.com",
categorie: "<some HTML Object stuff>",
title: "<some HTML stuff>",
html: "<some HTML stuff>""
};
but when i replace the HTML stuff with a formated Html, simple characters , it works
var Item = {
domain: "knewtone.com",
categorie: $(categorie).html(),
title: $(title).html(),
html: $(html).html()
};

How to validate an update against SimpleSchema before updating a document in collection

I'm trying to validate my data against a SimpleSchema before it gets submitted to the collection but for some reason I'm not able to do so with this error.
Exception while invoking method 'createVendorCategory' { stack: 'TypeError: Cannot call method \'simpleSchema\' of undefined
I have one collections with two SimpleSchemas as follows.
Vendors = new Mongo.Collection('vendors'); //Define the collection.
VendorCategoriesSchema = new SimpleSchema({
name: {
type: String,
label: "Category"
},
slug: {
type: String,
label: "Slug"
},
createdAt : {
type: Date,
label: "Created At",
autoValue: function(){
return new Date()//return the current date timestamp to the schema
}
}
});
VendorSchema = new SimpleSchema({
name: {
type: String,
label: "Name"
},
phone: {
type: String,
label: "Phone"
},
vendorCategories:{
type: [VendorCategoriesSchema],
optional: true
}
});
Vendors.attachSchema(VendorSchema);
The vendorCategory will be added after the Vendor document is created by the user.
Here is what my client side looks like.
Template.addCategory.events({
'click #app-vendor-category-submit': function(e,t){
var category = {
vendorID: Session.get("currentViewingVendor"),
name: $.trim(t.find('#app-cat-name').value),
slug: $.trim(t.find('#app-cat-slug').value),
};
Meteor.call('createVendorCategory', category, function(error) {
//Server-side validation
if (error) {
alert(error);
}
});
}
});
And here is what my server side Meteor.methods look like
createVendorCategory: function(category)
{
var vendorID = Vendors.findOne(category.vendorID);
if(!vendorID){
throw new Meteor.Error(403, 'This Vendor is not found!');
}
//build the arr to be passed to collection
var vendorCategories = {
name: category.name,
slug: category.slug
}
var isValid = check( vendorCategories, VendorSchema.vendorCategories.simpleSchema());//This is not working?
if(isValid){
Vendors.update(VendorID, vendorCategories);
// return vendorReview;
console.log(vendorCategories);
}
else{
throw new Meteor.Error(403, 'Data is not valid');
}
}
I'm guessing this is where the error is coming from.
var isValid = check( vendorCategories, VendorSchema.vendorCategories.simpleSchema());//This is not working?
Any help would be greatly appreciated.
Since you've already defined a sub-schema for the sub-object you can directly check against that:
check(vendorCategories,VendorCategoriesSchema)

Import/Use XrmServiceToolkit on Microsoft CRM 2013

how I use XrmServiceToolkit? Where I import this solution on Microsoft CRM 2013?
Hope this helps you. This is having all information related to xrmservicetoolkit.
https://xrmservicetoolkit.codeplex.com/
http://sumedha8.blogspot.in/2014/03/rest-functions-from-xrmservicetoolkit.html
Add the libraryto your CRM form:
Sample code to use the library:
function Retrieve() {
var re;
XrmServiceToolkit.Rest.Retrieve(
"{EE81D2A9-E28E-E311-96DF-D89D6765B238}",
"AccountSet",
null, null,
function (result) {
re = result;
alert("success");
},
function (error) {
alert("failed");
},
false
);
//debugger;
alert(re.Name);
alert(re.AccountId);
}
function Delete() {
XrmServiceToolkit.Rest.Delete(
"{32815A55-19AF-E311-BF0E-D89D6765B238}",
"AccountSet",
function () {
alert("successfully deleted");
},
function (error) {
alert("failed to delete");
},
false
);
}
function Update() {
var account = {};
account.Name = "SO and Company A1";
account.Address1_AddressTypeCode = { Value: 3 }; //Address 1: Address Type = Primary
account.Address1_City = "Wentworthville";
account.Address1_Line1 = "153 Dunmore Stret";
XrmServiceToolkit.Rest.Update(
"{EE81D2A9-E28E-E311-96DF-D89D6765B238}",
account,
"AccountSet",
function () {
alert("successfully Updated");
},
function (error) {
alert("failed to Update");
},
false
)
}
function Create() {
var account = {};
account.Name = "SO and Company B1";
account.Address1_AddressTypeCode = { Value: 3 }; //Address 1: Address Type = Primary
account.Address1_City = "Wentworthville B";
account.Address1_Line1 = "153 Dunmore Stret B";
XrmServiceToolkit.Rest.Create(
account,
"AccountSet",
function (result) {
accountId = result.AccountId;
alert("successfully Created. Acc ID : " + result.AccountId);
},
function (error) {
alert("failed to Create Account");
},
false
);
}

jqGrid postdata sends null values (mvc3 asp/net)

jqGrid doesn't send postdata to my controller. I tried all provided solutions on stackoverflow, buy apparently I'm making error(s) somewhere. So here is the code:
function refreshGrid() {
alert('CompanyNamePart=' + $("#CompanyNamePart").val()); // to check if this is correct value
$("#list").trigger('reloadGrid');
return false;
}
$(function () {
var grid = jQuery("#list").jqGrid({
datatype: 'json',
caption: 'Transaction Log',
postdata: {
CompanyNamePart: function () { return $("#CompanyNamePart").val(); },
UsernamePart: function () { return $("#UsernamePart").val(); },
},
url: '#Url.Action("GetTransactionLogData")',
mtype: 'GET',
colNames: ['Ref.', 'TradeDate', 'Status'],
colModel: [
{ name: 'Reference', index: 'Reference', width: '60' },
{ name: 'TradeDate', index: 'TradeDate', width: '70' },
{ name: 'Status', index: 'Status', width: '80' }
],
pager: $('#pager'),
rowNum: 10,
height: '100%'
});
});
On Controller side I have simple code:
[HttpGet]
public ActionResult GetTransactionLogData(string sidx, string sord, int page, int rows, string CompanyNamePart, string UsernamePart)
{ return Json(null); }
and in Debugging mode when I call refreshGrid() by clicking a button I get one alert to confirm me that it reads correctly value of textfield, and after that it refreshes the grid. I receive call of controller, but values for CompanyNamePart and UsernamePart variables are all null, even though I filled them.
I tried another solution for postdata section with another approach, first I created functions that return needed values and put them in postdata section of grid:
function getCompanyNamePartVal() {
return $("#CompanyNamePart").val();
}
function getUsernamePartVal() {
return $("#UsernamePart").val();
}
... in jqgrid definition
postdata: {
CompanyNamePart: getCompanyNamePartVal(),
UsernamePart: getUsernamePartVal(),
},
but with no success.
When I checked Firebug, I could see that jqGrid is not sending postdata values:
Get Parameters caught by Firebug
_ 1340696638960
_search false
nd 1340696638955
page 1
rows 10
sidx
sord asc
What am I doing wrong?
The parameter is called postData, not postdata. Don't forget that javascript is a case sensitive language. So try like this:
postData: {
CompanyNamePart: function () { return $("#CompanyNamePart").val(); },
UsernamePart: function () { return $("#UsernamePart").val(); }
}
Also notice that I removed a trailing comma after the UsernamePart function that you had in your code and which produces invalid javascript. Some more sensitive browsers might not accept it.
$("#grid").jqGrid({
url: "/DocumentoBalanza/GetBalanzaEmpresaMes",
//postData: JSON.stringify(formDataParam),
postData : {
id: function () { return formDataParam.id; },
strDate: function () { return formDataParam.strDate; },
},
datatype: 'json',
mtype: 'GET',
public JsonResult GetBalanzaEmpresaMes(string sidx, string sord, int page, int rows, int id, string strDate)
Code OK.

Resources