Cloudfront UpdateDistribution operation failing with ServiceUnavailable - aws-cloudformation

I am trying to add Origin and Behaviors to an exiting CloudFront distribution using Boto3 but it fails with below error, also added retries. I tried with a standalone script and through CloudFormation custom resource but both fail. The same issue previously reported here: https://github.com/aws/aws-cdk/issues/15891#issuecomment-1243756855, any work around available for this?
Traceback (most recent call last):
File "/Users/test/Desktop/cf_test/test.py", line 194, in <module>
create_origin_and_behavior(config)
File "/Users/test/Desktop/cf_test/test.py", line 159, in create_origin_and_behavior
cloudfront.update_distribution(
File "/usr/local/lib/python3.10/site-packages/botocore/client.py", line 514, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/local/lib/python3.10/site-packages/botocore/client.py", line 938, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ServiceUnavailable) when calling the UpdateDistribution operation (reached max retries: 4): CloudFront encountered an internal error. Please try again.
Here is the script:
#!/usr/bin/python
import boto3
cloudfront = boto3.client('cloudfront')
response_data = {}
def create_origin_and_behavior(config):
distribution_config_response = cloudfront.get_distribution_config(Id=config['DistributionId'])
distribution_config = distribution_config_response['DistributionConfig']
distribution_etag = distribution_config_response['ETag']
origin = {
# 'Id': config['StackName'],
'Id': "new-test",
# 'DomainName': config['MediaPackageEgressHlsDomainName'],
'DomainName': '3423434234.mediapackage.us-west-2.amazonaws.com',
'OriginPath': '',
'CustomOriginConfig': {
'HTTPPort': 80,
'HTTPSPort': 443,
'OriginProtocolPolicy': 'match-viewer',
'OriginReadTimeout': 30,
'OriginSslProtocols': {
'Quantity': 1,
'Items': [
'TLSv1.2'
]
},
'OriginKeepaliveTimeout': 5
},
'CustomHeaders': {
'Quantity': 1,
'Items': [
{
'HeaderName': "X-MediaPackage-CDNIdentifier",
# 'HeaderValue': config['MediaPackageCDNIdentifier']
'HeaderValue': '23423-3242'
}
]
}
}
distribution_config['Origins']['Items'].append(origin)
distribution_config['Origins']['Quantity'] += 1
vtt_path_behavior = {
# 'PathPattern': config['MediaPackageEgressHlsPath'].replace("index.m3u8", "*.vtt"),
'PathPattern': "out/v1/test/*.vtt",
# 'TargetOriginId': config['StackName'],
'TargetOriginId': 'new-test',
'Compress': False,
'ViewerProtocolPolicy': 'redirect-to-https',
'SmoothStreaming': False,
'AllowedMethods': {
'Quantity': 2,
'Items': [
'GET', 'HEAD'
],
'CachedMethods': {
'Quantity': 2,
'Items': [
'GET', 'HEAD'
],
}
},
'TrustedSigners': {
'Enabled': True,
'Quantity': 1,
'Items': [
# config['Account']
'2343243242'
]
},
'ForwardedValues': {
'Headers': {
'Quantity': 3,
'Items': [
'Origin', 'Access-Control-Request-Method', 'Access-Control-Request-Headers'
]
},
'QueryString': True,
'QueryStringCacheKeys': {
'Quantity': 3,
'Items': [
"m", "start", "end"
]
},
'Cookies': {
'Forward': 'none'
}
},
'MinTTL': 0,
'DefaultTTL': 86400,
'MaxTTL': 31536000,
# 'ResponseHeadersPolicyId': config['ResponseHeadersPolicyId'],
'ResponseHeadersPolicyId': '2423423',
'LambdaFunctionAssociations': {
'Quantity': 1,
'Items': [
{
# 'LambdaFunctionARN': config['OriginResponseEdgeFunctionARN'],
'LambdaFunctionARN': 'arn:aws:lambda:us-east-1:2345235235:function:test:1',
'EventType': 'origin-response'
}
]
},
'FieldLevelEncryptionId': ""
}
if distribution_config['CacheBehaviors']['Quantity'] == 0:
distribution_config['CacheBehaviors']['Items'] = []
distribution_config['CacheBehaviors']['Items'].append(vtt_path_behavior)
distribution_config['CacheBehaviors']['Quantity'] += 1
cloudfront.update_distribution(
DistributionConfig=distribution_config,
Id=config['DistributionId'],
IfMatch=distribution_etag)
print('Mediapackage Egress Cloudfront input create completed for stack {} '.format(config['StackName']))
# response_data['DistributionId'] = config['DistributionId']
# response_data['StackName'] = config['StackName']
response_data['DistributionId'] = 'test'
response_data['StackName'] = 'new-test'
return response_data

Related

ipycytoscape, draw subgraph

I'm noob in ipycytoscape and Jupyter and seems need help. I'm trying to find a sutable way to show/draw subgraph after I click by node.
For example.
I have graph with node1---node2---node3 . I click by node1 and want to show
node1 --- node2.1 - node2.2 node2.3 --- node3.
Don't know how to make this. Tried to find in Google but coudn't find any suitable approach.
This is my simplest code for this. I no idea how to show and aftger hide (expand and collapse) subgraph. This code don't have this part.
I heard something about layouts but couldn't find sutable example for ipycytoscape.
Any ideas are welcome.
import ipycytoscape
import ipywidgets as widgets
import networkx as nx
counter = 0 # need to make new nodes with uniq id
data = {
'nodes': [
{ 'data': { 'id': 'desktop', 'name': 'Cytoscape', 'href': 'http://cytoscape.org' } },
{ 'data': { 'id': 'a', 'name': 'Grid', 'href': 'http://cytoscape.org', 'parent': 'Cola' } },
{ 'data': { 'id': 'c', 'name': 'Popper', 'href': 'http://cytoscape.org', 'parent': 'Cola' } },
{ 'data': { 'id': 'b', 'name': 'Cola', 'href': 'http://cytoscape.org' } },
{ 'data': { 'id': 'js', 'name': 'Cytoscape.js', 'href': 'http://js.cytoscape.org' } }
],
'edges': [
{'data': { 'source': 'desktop', 'target': 'js' }},
{'data': { 'source': 'a', 'target': 'b' }},
{'data': { 'source': 'a', 'target': 'c' }},
{'data': { 'source': 'b', 'target': 'c' }},
{'data': { 'source': 'js', 'target': 'b' }}
]
}
custom_inherited = ipycytoscape.CytoscapeWidget()
custom_inherited.graph.add_graph_from_json(data)
custom_inherited.set_style([{
'selector': 'node',
'css': {
'content': 'data(name)',
'text-valign': 'center',
'color': 'white',
'text-outline-width': 2,
'text-outline-color': 'green',
'background-color': 'green'
}
},
{
'selector': 'node[classes = "collapsed-childS"]',
'css': {
'background-color': 'red',
'line-color': 'blue',
'target-arrow-color': 'red',
'source-arrow-color': 'red',
'text-outline-color': 'red'
},
}
])
# When I click to node by mouse I add some nodes. I made this because don't know how to show and hide subgraph. The question in this place.
def paint_blue(event):
global counter
for node in cytoscapeobj.graph.nodes:
if node.data['id'] == event['data']['id']:
auxNode = node
auxNode.data['classes'] = "collapsed-childS"
station_NUR = ipycytoscape.Node()
station_NUR.data['id'] = "NUR" + str(counter)
station_NUR.data['name'] = station_NUR.data['id']
station_NUR.data['classes'] = "collapsed-childS"
station_FRA = ipycytoscape.Node()
station_FRA.data['id'] = "FRA" + str(counter)
station_FRA.data['name'] = station_FRA.data['id']
station_FRA.data['classes'] = "collapsed-childS"
new_edge1 = ipycytoscape.Edge()
new_edge1.data['id'] = "line6" + str(counter)
new_edge1.data['source'] = station_NUR.data['id']
new_edge1.data['target'] = station_FRA.data['id']
new_edge2 = ipycytoscape.Edge()
new_edge2.data['id'] = "line7" + str(counter)
new_edge2.data['source'] = station_NUR.data['id']
new_edge2.data['target'] = auxNode.data['id']
custom_inherited.graph.add_node(station_NUR)
custom_inherited.graph.add_node(station_FRA)
custom_inherited.graph.add_edges([new_edge1,new_edge2])
counter = counter + 1
custom_inherited.on('node', 'click', paint_blue)
custom_inherited

How to unwind/merge arrays from hierarchical document structure?

I have a nested document structure and I am able to filter it with pluck to show the relevant parts:
Is there an elegant way to merge all entries of the last level to a single array?
Expected result (entries are not unique on purpose):
[
'3425b91f-f019-4db3-ad56-c336bf55279b',
'3d07946e-183d-4992-9acd-676f5122e1b1',
'3425b91f-f019-4db3-ad56-c336bf55279b',
'3d07946e-183d-4992-9acd-676f5122e1b1',
'2cd652a6-4dcd-4920-9592-d4cdc5a034bf',
'70fe1812-e1de-447b-ac4f-d89fead4756d',
'2cd652a6-4dcd-4920-9592-d4cdc5a034bf',
'70fe1812-e1de-447b-ac4f-d89fead4756d'
]
I tried to use
r.table('periods')['regions']['sites']['plants']['product']['process']['technologies'].run()
but it gives the error "Cannot perform bracket on a sequence of sequences".
=> Is there some alternative operator to get a merged sequence instead a "sequence of sequences" for each step?
Something like
r.table('periods').unwind('regions.sites.plants.product.process.technologies')
Here is some python code to create example data:
from rethinkdb import RethinkDB
r = RethinkDB()
r.connect({}).repl()
r.table_create("periods")
def uniqueid():
return r.uuid().run()
periodid_first = uniqueid()
periodid_second = uniqueid()
companyid_2000 = uniqueid()
companyid_2001 = uniqueid()
technologyid_2000_first = uniqueid()
technologyid_2000_second = uniqueid()
technologyid_2001_first = uniqueid()
technologyid_2001_second = uniqueid()
energy_carrierid_2000_first = uniqueid()
energy_carrierid_2000_second = uniqueid()
energy_carrierid_2001_first = uniqueid()
energy_carrierid_2001_second = uniqueid()
periods = [
{
'id': periodid_first,
'start': 2000,
'end': 2000,
# 'sub_periods': [],
'regions': [
{
'id': 'DE',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_germany',
'company': companyid_2000, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2000_first, # => verweist auf periods => technologies
technologyid_2000_second
]
}
}
}
]
}
]
},
{
'id': 'FR',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_france',
'company': companyid_2000, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2000_first, # => verweist auf periods => technologies
technologyid_2000_second
]
}
}
}
]
}
]
}
],
'companies': [
{
'id': companyid_2000,
'name': 'international_company'
}
],
'technologies': [
{
'id': technologyid_2000_first,
'name': 'SMR',
'specific_cost_per_year': 123,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2000_first,
'specific_consumption': 5555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2000_second,
'energy_consumption': 2333
}
]
},
{
'id': technologyid_2000_second,
'name': 'HB',
'specific_cost_per_year': 1234,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2000_first,
'specific_consumption': 555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2000_second,
'energy_consumption': 233
}
]
}
],
'energy_carriers': [
{
'id': energy_carrierid_2000_first,
'name': 'oil',
'group': 'fuel'
},
{
'id': energy_carrierid_2000_second,
'name': 'gas',
'group': 'fuel'
},
{
'id': uniqueid(),
'name': 'conventional',
'group': 'electricity'
},
{
'id': uniqueid(),
'name': 'green',
'group': 'electricity'
}
],
'networks': [
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
},
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
}
]
},
{
'id': periodid_second,
'start': 2001,
'end': 2001,
# 'sub_periods': [],
'regions': [
{
'id': 'DE',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_germany',
'company': companyid_2001, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2001_first, # => verweist auf periods => technologies
technologyid_2001_second
]
}
}
}
]
}
]
},
{
'id': 'FR',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_france',
'company': companyid_2001, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2001_first, # => verweist auf periods => technologies
technologyid_2001_second
]
}
}
}
]
}
]
}
],
'companies': [
{
'id': companyid_2001,
'name': 'international_company'
}
],
'technologies': [
{
'id': technologyid_2001_first,
'name': 'SMR',
'specific_cost_per_year': 123,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2001_first,
'specific_consumption': 5555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2001_second,
'energy_consumption': 2333
}
]
},
{
'id': technologyid_2001_second,
'name': 'HB',
'specific_cost_per_year': 1234,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2001_first,
'specific_consumption': 555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2001_second,
'energy_consumption': 233
}
]
}
],
'energy_carrieriers': [
{
'id': energy_carrierid_2001_first,
'name': 'oil',
'group': 'fuel'
},
{
'id': energy_carrierid_2001_second,
'name': 'gas',
'group': 'fuel'
},
{
'id': uniqueid(),
'name': 'conventional',
'group': 'electricity'
},
{
'id': uniqueid(),
'name': 'green',
'group': 'electricity'
}
],
'networks': [
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
},
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
}
]
}
]
r.table('periods') \
.insert(periods) \
.run()
Related:
RethinkDB: RqlRuntimeError: Cannot perform bracket on a sequence of sequences
Nested concat_map in combination with r.row operator and bracket drill down does the trick:
r.table('periods') \
.concat_map(r.row['regions']) \
.concat_map(r.row['sites']) \
.concat_map(r.row['plants'])['product']['process'] \
.concat_map(r.row['technologies']) \
.run()

In Slick Grid inline edit I can't able to get the entire object

I am using angular slickgrid for showing my data. When I am trying to edit the slick grid record, I will get the changed fields only I need the entire object. I have given the sample data.
Columndefinition :
this.columnDefinitions = [
{
id: 'title', name: 'Title', field: 'title', width: 220, cssClass: 'cell-title',
filterable: true, sortable: true,
queryFieldSorter: 'id', type: FieldType.string,
formatter: Formatters.tree,
editor: {
model: Editors.longText,
required: true,
},
},
{ id: 'duration', name: 'Duration', field: 'duration', minWidth: 90, filterable: true },
{
id: 'child.0.percentComplete', name: '% Complete', field: 'child.0.percentComplete', minWidth: 120, maxWidth: 200,
sortable: true, filterable: true, filter: { model: Filters.slider, operator: '>=' },
formatter: Formatters.percentCompleteBar, type: FieldType.number,
editor: {
model: Editors.slider,
minValue: 0,
maxValue: 100,
params: { hideSliderNumber: false },
},
},
];
SlickGrid input data set structure:
const data = [
{
'id': 0,
'indent': 0,
'parentId': null,
'title': 'Task 0',
'duration': '5 days',
'percentComplete': 73,
'start': '2003-03-21T18:30:00.000Z',
'finish': '2003-04-21T18:30:00.000Z',
'effortDriven': true,
'child' : [{
'id': 2,
'indent': 0,
'parentId': 1,
'title': 'Task 0',
'duration': '5 days',
'percentComplete': 73,
'start': '2003-03-21T18:30:00.000Z',
'finish': '2003-04-21T18:30:00.000Z',
'effortDriven': true
}]
},
{
'id': 1,
'indent': 0,
'parentId': null,
'title': 'Task 1',
'duration': '5 days',
'percentComplete': 4,
'start': '2004-04-24T18:30:00.000Z',
'finish': '2004-05-24T18:30:00.000Z',
'effortDriven': false
}
];
When I start to change the employee field oncellchanged called and I got arg.Item
Current behaviour
onCellChanged(e, args) {
this.angularGrid.gridService.updateItemById(args.item['id'], args.item);
console.log(args.item);
}
Log
{
"id": 0,
"indent": 0,
"parentId": null,
"title": "Task 0",
"duration": "5 days",
"percentComplete": 73,
"start": "2003-03-21T18:30:00.000Z",
"finish": "2003-04-21T18:30:00.000Z",
"effortDriven": true,
"child": {
"0": {
"percentComplete": 25
}
}
}
Expected output:
{
"id": 0,
"indent": 0,
"parentId": null,
"title": "Task 0",
"duration": "5 days",
"percentComplete": 73,
"start": "2003-03-21T18:30:00.000Z",
"finish": "2003-04-21T18:30:00.000Z",
"effortDriven": true,
"child": [
{
"id": 2,
"indent": 0,
"parentId": 1,
"title": "Task 0",
"duration": "5 days",
"percentComplete": 25,
"start": "2003-03-21T18:30:00.000Z",
"finish": "2003-04-21T18:30:00.000Z",
"effortDriven": true
}
]
}
Software versions
Angular : 7.3.5
Angular-Slickgrid : 2.17.10
TypeScript : 3.1.6
Node : 10.16.3
The issue due to the utils files used in angular slickgrid library. If you want to fix this issue, have two solutions.
The library itself handle the function logic.
Need to implement custom editor based on your requirement.
Issue area
In each editor, applyValue method sets the object value to respective path. In the method, the array value not parsed properly. You can extend the editor class and override the applyValue method. Here I shared the sample code for your reference. Especially, go through the setDeepValue method which I have mentioned below.
import { EditorArguments, InputEditor } from 'angular-slickgrid';
export class CustomInputEditor extends InputEditor {
constructor(protected readonly args: EditorArguments, inputType: string) {
super(args, inputType);
}
applyValue(item: any, state: any) {
const fieldName = this.columnDef && this.columnDef.field;
if (fieldName !== undefined) {
const isComplexObject = fieldName?.indexOf('.') > 0; // is the field a complex object, "address.streetNumber"
// is the field a complex object having array value you need to specify the index position in path (Here I used 0th index), "address.0.streetNumber"
// validate the value before applying it (if not valid we'll set an empty string)
const validation = this.validate(state);
const newValue = validation?.valid ? state : '';
// set the new value to the item datacontext
if (isComplexObject) {
// when it's a complex object, user could override the object path (where the editable object is located)
// else we use the path provided in the Field Column Definition
const objectPath =
this.columnEditor?.complexObjectPath ?? fieldName ?? '';
this.setDeepValue(item, objectPath, newValue);
} else if (fieldName) {
item[fieldName] = newValue;
}
}
}
setDeepValue<T = any>(obj: T, path: string | string[], value: any) { // Customized the set value method to handle the array data
if (typeof path === 'string') {
path = path.split('.');
}
if (path.length > 1) {
const e = path.shift();
if (obj && e !== undefined) {
let innerObject;
if (!Array.isArray(obj[e]) && typeof obj[e] != 'object') {
obj[e] = {};
}
this.setDeepValue(obj[e], path, value);
}
} else if (obj && path[0]) {
(obj as any)[(path as any)[0]] = value;
}
}
}
I hope this may helpful for you.
Kind information to the library author, If possible update the setDeepValue method in latest release.

Why are the panels in my Grafana dashboard overlapping?

I am attempting to create a Grafana Scripted Dashboard consisting of panels that indicate whether a server is UP or not. The reason for this is that we constantly have a list of agents being added and making a new panel every time is becoming repetitive.
Currently, I have this as my script (Note my JavaScript/JQuery skills are abysmal..):
'use strict';
// accessible variables in this scope
var window, document, ARGS, $, jQuery, moment, kbn;
return function(callback) {
// Setup some variables
var dashboard;
// Initialize a skeleton with nothing but a rows array and service object
dashboard = {
annotations: {
list: [
{
builtIn: 1,
datasource: "-- Grafana --",
enable: true,
hide: false,
iconColor: "rgba(0, 211, 255, 1)",
name: "Annotations & Alerts",
type: "dashboard"
}
]
},
editable: true,
gnetId: null,
graphTooltip: 0,
id: 15,
links: [],
panels : [],
refresh: false,
schemaVersion: 16,
style: "dark",
tags: [],
templating: {
list: []
},
time: {
from: "now-5m",
to: "now"
},
timepicker: {
refresh_intervals: [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
time_options: [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
timezone: "",
title: "My Agents",
//uid: "000000019",
version: 2
};
// Set a title
dashboard.title = 'Scripted dash';
// Set default time
// time can be overridden in the url using from/to parameters, but this is
// handled automatically in grafana core during dashboard initialization
dashboard.time = {
from: "now-6h",
to: "now"
};
var rows = 1;
var seriesName = 'argName';
if(!_.isUndefined(ARGS.rows)) {
rows = parseInt(ARGS.rows, 10);
}
if(!_.isUndefined(ARGS.name)) {
seriesName = ARGS.name;
}
$.ajax({
method: 'GET',
url: 'http://my_server/api/my_rest_call_to_get_agents'
})
.done(function(result) {
//console.log(JSON.stringify(result));
var x = 0;
var y = 0;
var id = 0;
$.each(result.data.result, function(index, value) {
//console.log(value.metric.instance);
var panel = {
clusterName: "My Agent",
colorMode: "Panel",
colors: {
crit: "rgba(245, 54, 54, 0.9)",
disable: "rgba(128, 128, 128, 0.9)",
ok: "rgba(50, 128, 45, 0.9)",
warn: "rgba(237, 129, 40, 0.9)"
},
cornerRadius: 0,
//datasource: "Prometheus",
displayName: "Agent_Name",
flipCard: true,
flipTime: "2",
fontFormat: "Bold",
gridPos: {
h: 3,
w: 2,
x: x,
y: y
},
id: id,
isGrayOnNoData: true,
isHideAlertsOnDisable: false,
isIgnoreOKColors: false,
links: [],
targets: [
{
aggregation: "Last",
alias: value.metric.instance,
crit: 0,
decimals: 2,
displayAliasType: "Warning / Critical",
displayType: "Regular",
displayValueWithAlias: "Never",
expr: 'expression_to_query_service',
format: "time_series",
instant: true,
intervalFactor: 1,
legendFormat: value.metric.instance,
refId: "A",
units: "short",
valueHandler: "Number Threshold"
}
],
title: value.metric.instance,
transparent: true,
type: "vonage-status-panel"
}
dashboard.panels.push(panel);
x += 2;
});
callback(dashboard);
});
}
The strangest part about all of the panels being overlapping is that every panel has different coordinates if I look at each panel's JSON.
Any help with this would be appreciated!

jqGrid - cant select rows - Cannot call method 'indexOf' of undefined

Thanks to Oleg, my jqGrid now looks like this, and works fine. (my problem after the code)
var columnModel = [{ name: 'ID', index: 'ID', sortable: true, summaryType:'count', summaryTpl:'<b>{0} Item(s)</b>' },
{ name: 'FirstName', index: 'FirstName', sortable: true},
{ name: 'LastName', index: 'LastName', sortable: true }
];
var columnNames = ['Id', 'First Name', 'Last Name'];
myGrid.jqGrid({
url: './WebService.asmx/ViewNQueryData',
datatype: 'json',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj.d.rows; },
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; }
},
colModel: columnModel,
colNames: columnNames,
rowNum: 10,
rowList: [10, 20, 300],
sortname: 'ID',
sortorder: "asc",
sortable: true,
pager: "#ViewNQueryPager",
viewrecords: true,
gridview: true,
height: 250,
shrinkToFit: true,
grouping: true,
groupingView: {
groupField: ['ID'],
groupColumnShow: [false],
groupText: ['<b>{0} - {1} Item(s)</b>'],
groupSummary: [true],
groupOrder: ['asc'],
groupDataSorted: true,
showSummaryOnHide: true
},
footerrow: true,
userDataOnFooter: true,
gridComplete: function () {
$('#totalRecordsFound').html(myGrid.jqGrid('getGridParam', 'records') + " Customers");
},
onSelectRow: function () { alert("selected"); }
}).jqGrid('navGrid', '#ViewNQueryPager',
{ edit: false, add: false, del: false, search: true, view: true },//option
{}, // use default settings for edit
{}, // use default settings for add
{}, // delete instead that del:false we need this
{multipleSearch: true, multipleGroup: true, showQuery: true, onSearch: function (response) { showQueryDetails(); } },
{height: 250, jqModal: false, closeOnEscape: true} // view options
);
myGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true });
For some odd reason i can select any row (evrything else works fine) and i get in the browser this exception:
This happens only in chrome, firefox works fine.
Uncaught TypeError: Cannot call method 'indexOf' of undefined
$.jgrid.extend.setSelection
e.extend.eachjquery-1.6.2.min.js:16
e.fn.e.eachjquery-1.6.2.min.js:16
$.jgrid.extend.setSelection
$.fn.jqGrid
$.fn.jqGrid.each.$.before.click.bind.ts.p.datatype
f.event.handlejquery-1.6.2.min.js:17
f.event.add.i.handle.k
I need some new eyes to please help me and see what i did wrong... this is really driving me crazy..
Thanks in advance.
EDIT
My JSON data is like:
{"d":{"__type":"JqGridData","total":3,"page":1,"records":24,"rows":[{"id":1,"cell":["1","Prabir","Shrestha"]},{"id":2,"cell":["2","Scott","Gu"]},{"id":3,"cell":["3","Scott","Gu"]},{"id":4,"cell":["4","Bill","Gates"]},{"id":5,"cell":["5","Steve","Ballmer"]},{"id":1,"cell":["1","Prabir","Shrestha"]},{"id":2,"cell":["2","Scott","Gu"]},{"id":3,"cell":["3","Scott","Hanselman"]},{"id":4,"cell":["4","Bill","Hanselman"]},{"id":5,"cell":["5","Steve","Ballmer"]}]}}
The reason of your problem is the inconsistent JSON data which you use:
{
"d": {
"__type": "JqGridData",
"total": 3,
"page": 1,
"records": 24,
"rows": [
{"id": 1, "cell": ["1", "Prabir", "Shrestha"]},
{"id": 2, "cell": ["2", "Scott", "Gu"]},
{"id": 3, "cell": ["3", "Scott", "Gu"]},
{"id": 4, "cell": ["4", "Bill", "Gates"]},
{"id": 5, "cell": ["5", "Steve", "Ballmer"]},
{"id": 1, "cell": ["1", "Prabir", "Shrestha"]},
{"id": 2, "cell": ["2", "Scott", "Gu"]},
{"id": 3, "cell": ["3", "Scott", "Hanselman"]},
{"id": 4, "cell": ["4", "Bill", "Hanselman"]},
{"id": 5, "cell": ["5", "Steve", "Ballmer"]}
]
}
}
The id filed will be used as the value of id attribute of rows of the grid (<tr> elements). Corresponds to HTML/XHTML specification ids must be unique on the page.