Parse JSON Facebook Conversations XCODE - xcode

I need your help. I can parse correctly the graph.facebook.com/me/feed JSON, but i can't do it with graph.facebook.com/me/conversations. Can you please help me? this is how i get the last message from feed
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:nil];
NSLog(#"json %#", json);
NSDictionary *items = [json objectForKey:#"data"];
// NSDictionary *item = [items objectAtIndex:1];
NSLog(#"items %#", items);
NSMutableArray *story = [NSMutableArray array];
for (NSDictionary *item in items )
{
if([item objectForKey:#"message"] || [item objectForKey:#"message"] != nil || [[item objectForKey:#"message"] length]>0)
{
[story addObject:[item objectForKey:#"message"]];
}
else{
NSLog(#"no message");
}
}
NSLog(#"story %#", story);
NSString *lastMessage = [story objectAtIndex:0];
NSLog(#"lastmessage received is %#", lastMessage);
Can you please help me? Thanks
EDIT: I get this error in NSString *lastMessage = [story objectAtIndex:0];
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for
empty array'
* First throw call stack: (0x341fc2a3 0x3aede97f 0x34147b75 0xc3a1d 0x3add2d91 0x3c22c11f 0x3c22fecf 0x3c22fdc1 0x3c23091d 0x3c230ac1
0x3ae54a11 0x3ae548a4) libc++abi.dylib: terminate called throwing an
exception
NSLog from "items" is the following:
(
{
"can_reply" = 1;
id = "t_id.xx5719286166414";
"is_subscribed" = 1;
link = "http://www.facebook.com/messages/?action=read&tid=id.xx5719286166414";
"message_count" = 4;
messages = {
data = (
{
"created_time" = "2012-11-30T17:53:00+0000";
from = {
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
};
id = "m_msg.fe83b318fa94e6bbcc90a9a52fa4645b01";
message = "Questo \U00e8 un messaggio";
tags = {
data = (
{
name = inbox;
},
{
name = messenger;
},
{
name = read;
},
{
name = "source:mobile";
}
);
};
to = {
data = (
{
email = "100004765716168#facebook.com";
id = 100004765716168;
name = "AccountDevelopment Development";
},
{
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
}
);
};
},
{
"created_time" = "2012-11-29T11:49:00+0000";
from = {
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
};
id = "m_id.128631660627297";
message = "funziona?";
tags = {
data = (
{
name = inbox;
},
{
name = read;
},
{
name = "source:web";
}
);
};
to = {
data = (
{
email = "100004765716168#facebook.com";
id = 100004765716168;
name = "AccountDevelopment Development";
},
{
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
}
);
};
},
{
"created_time" = "2012-11-28T18:05:57+0000";
from = {
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
};
id = "m_id.141590452655798";
message = "prova messaggio";
tags = {
data = (
{
name = inbox;
},
{
name = read;
},
{
name = "source:web";
}
);
};
to = {
data = (
{
email = "100004765716168#facebook.com";
id = 100004765716168;
name = "AccountDevelopment Development";
},
{
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
}
);
};
},
{
"created_time" = "2012-11-28T18:04:50+0000";
from = {
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
};
id = "m_id.xx5719286166414";
message = "Ciao Francesco, come stai?";
tags = {
data = (
{
name = inbox;
},
{
name = read;
},
{
name = "source:web";
}
);
};
to = {
data = (
{
email = "100004765716168#facebook.com";
id = 100004765716168;
name = "AccountDevelopment Development";
},
{
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
}
);
};
}
);
paging = {
next = "https://graph.facebook.com/t_id.xx5719286166414/messages?access_token=BAABlotMxL1MBACbrnuvICOwBKjkw68ZBaqLOY2MVE6tga8xPmiF9VWH7RZAZCoZBDeSD29KWTzuze3xpjP7xb1kmfyw7VYtvGZC0E1gwgJthpZAoKoFXAYanGcBMb1qzO7SBAI3WPLcLAq7yAUpyF9NiHY0vIpsiGJZASx3eZCA83Lm18hpjmo0K97ZBSOiAoYeZCm2vYDgqq4S8jqOvZCvGZCZByNeg4ElNiSwZA1hHqdA6qrFAZDZD&limit=25&until=1354125890&__paging_token=m_id.xx5719286166414";
previous = "https://graph.facebook.com/t_id.xx5719286166414/messages?access_token=BAABlotMxL1MBACbrnuvICOwBKjkw68ZBaqLOY2MVE6tga8xPmiF9VWH7RZAZCoZBDeSD29KWTzuze3xpjP7xb1kmfyw7VYtvGZC0E1gwgJthpZAoKoFXAYanGcBMb1qzO7SBAI3WPLcLAq7yAUpyF9NiHY0vIpsiGJZASx3eZCA83Lm18hpjmo0K97ZBSOiAoYeZCm2vYDgqq4S8jqOvZCvGZCZByNeg4ElNiSwZA1hHqdA6qrFAZDZD&limit=25&since=1354297980&__paging_token=m_msg.fe83b318fa94e6bbcc90a9a52fa4645b01&__previous=1";
};
};
participants = {
data = (
{
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
},
{
email = "100004765716168#facebook.com";
id = 100004765716168;
name = "AccountDevelopment Development";
}
);
};
senders = {
data = (
{
email = "1367741936#facebook.com";
id = 1367741936;
name = " xxx xxx";
}
);
};
snippet = "Questo \U00e8 un messaggio";
tags = {
data = (
{
name = inbox;
},
{
name = read;
},
{
name = seen;
},
{
name = "source:web";
}
);
};
"updated_time" = "2012-11-30T17:53:00+0000";
}
)

You are missing a level in your accessors. The top level item in the JSON is messages, and that contains data. And then data is an array, not a dictionary. So you should change the first lines to this...
NSArray *messageGroups = [json objectForKey:#"data"];
NSDictionary* firstMessageGroup = [messageGroups objectAtIndex:0];
NSDictionary *messages = [firstMessageGroup objectForKey:#"messages"];
NSArray* items = [messages objectForKey#"data"];

Related

Multiple People Picker Columns (fields) on one form

SharePoint Online: I have multiple people picker columns and enter in a number of places people. I get the people OK but it won't update. It says it the entry is undefined. I thought maybe separating each out would work but obviously not. I hope I get some help on this one. What I want to do is to allow users to enter names into where the div entries are and as a people picker. I accomplished that but when you submit the form it says that any entry other than the first is undefined.
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" > < /script>
<script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
<script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
<script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript" src="/_layouts/15/autofill.js"></script>
<script type="text/javascript" src="/_layouts/15/1033/sts_strings.js"></script>
<script type="text/javascript">
var prim5 = 0;var sec4 = 0;var auth5 = 0;
var EorB25 = "";var BorE25 = "";var BorE35 = "";var siteUrl = "https://sp-cloud.kp.org/sites/MedicaidRepository";var cat25 = "";var regimpact = "";var regimpact1 = "";var prim25="";var sec25="";
var auth25="";var s1 = "";var soxD1 = "";var k1 = 'No';var com2 = "";var sDate1 = "";var sSever = "";var kDate1 = "";var finalusersP = [];var finalusers22 = [];var finalusersK = [];var user22 = [];var userK = [];var userP = [];var users22 = [];var usersK = [];var usersP = [];var userPemail = "";var userKemail = "";var user22email = "";
var tDay = new Date();
var dd = tDay.getDate();
var mm = tDay.getMonth()+1;
var yy = tDay.getFullYear();
var sDate = mm+ '/' +dd+ '/' +yy;
$(document).ready(function() {
prim5 = 1;
initializePeoplePickerP('peoplePickerDivP');
registerPPOnChangeEventP($('#peoplePickerDivP'));
});
$(document).ready(function() {
sec5 = 1;
initializePeoplePickerS('peoplePickerDivS');
registerPPOnChangeEventS($('#peoplePickerDivS'));
});
$(document).ready(function() {
auth5 = 1;
initializePeoplePickerK('peoplePickerDivK');
registerPPOnChangeEventK($('#peoplePickerDivK'));
});
function initializePeoplePickerP(peoplePickerElementIdP, UsersP) {
if (typeof(UsersP) == 'undefined') UsersP = null;
console.log('UsersP: ' +UsersP);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdP, null, schema);
}
function initializePeoplePickerS(peoplePickerElementIdS, Users22) {
if (typeof(Users22) == 'undefined') Users22 = null;
console.log('Users22: ' +Users22);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdS, null, schema);
}
function initializePeoplePickerK(peoplePickerElementIdK, UsersK) {
if (typeof(UsersK) == 'undefined') UsersK = null;
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdK, null, schema);
}
function registerPPOnChangeEventP(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
//var ppidTest = picker.toString();
console.log("picker: " +picker);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoP();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventS(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers22').html("");
$('#user22Keys').html("");
$('#user22ProfileProperties').html("");
$('#user22ID').html("");
} else {
setTimeout(function () {
getUserInfoS();
},
100);
}
picker.oldChanged();
}
} else {
//setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventK(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoK();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
// Query the picker for user information.
var userPropertyP = "";
var userPropertyS = "";
var userPropertyK ="";
var userPemail = "";
var i = 0;
var j = 0;
var m = 0;
var keysP = "";
var keysS = "";
var keysK = "";
function getUserInfoP() {
// Get the people picker object from the page.
var peoplePickerP = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivP_TopSpan;
// Get information about all users.
var usersP = peoplePickerP.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersP = new Array();
console.log('Users: ' +usersP);
var ownerP = usersP[0];
for(i = 0; i < usersP.length; i++){
userPemail = usersP[i];
}
console.log('Owner: ' +ownerP);
$("#siteOwenerEmail").val(ownerP.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerP.Key);
$("#siteOwnerName").val(ownerP.DisplayText);
$("#siteOwnerLogin").val(ownerP.Description);console.log('Get People Picker NameP: ' +ownerP.DisplayText);
var userInfo = '';
if(prim5 > 0){
for (var i = 0; i < usersP.length; i++) {
userP = usersP[i];
if(userP !== null){
//userPemail = userP.EntityData.Email;
userPemail = ownerP.DisplayText;
}
console.log("userPemail: " +userPemail);
return userPemail;
console.log('i= ' +i+ 'User= ' +userP);
for (userPropertyP in userP) {
prim25 += userPropertyP + ': ' + userP[userPropertyP] + '<br>';
}
}
$('#resolvedUsers').html(prim25);
// Get user keys.
keysP = peoplePickerP.GetAllUserKeys();
$('#userKeys').html(keysP);
// Get the first user's ID by using the login name.
getUserIdP(usersP[0].Key);
console.log('Initial: ' +prim25);
}
}
function getUserInfoS() {
// Get the people picker object from the page.
var peoplePickerS = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivS_TopSpan;
// Get information about all users.
users22 = peoplePickerS.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersS = new Array();
console.log('Users: ' + users22);
var ownerS = users22[0];
/*for(i = 0; i < usersS.length; j++){
userSemail = usersS[i];
}*/
console.log('Owner: ' +ownerS);
$("#siteOwenerEmail").val(ownerS.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerS.Key);
$("#siteOwnerName").val(ownerS.DisplayText);
$("#siteOwnerLogin").val(ownerS.Description);console.log('Get People Picker NameS: ' +ownerS.DisplayText);
var userInfo = '';
if(sec4 > 0){
for (j = 0; j < users22.length; j++) {
user22 = users22[j];
if(user22 !== null){
//userPemail = userP.EntityData.Email;
user22email = ownerS.DisplayText;
}
for (userPropertyS in user22) {
sec25 += userPropertyS + ': ' + user22[userPropertyS] + '<br>';
}
}
$('#resolvedUsers').html(sec25);
// Get user keys.
keysS = peoplePickerS.GetAllUserKeys();
$('#user22Keys').html(keysS);
// Get the first user's ID by using the login name.
getUserIdS( users22[0].Key);
}
}
function getUserInfoK() {
// Get the people picker object from the page.
var peoplePickerK = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivK_TopSpan;
// Get information about all users.
usersK = peoplePickerK.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersK = new Array();
console.log('Users: ' +usersK);
var ownerK = usersK[0];
/*for(i = 0; i < usersK.length; i++){
userKemail = usersK[i];
}*/
console.log('Owner: ' +ownerK);
$("#siteOwenerEmail").val(ownerK.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerK.Key);
$("#siteOwnerName").val(ownerK.DisplayText);
$("#siteOwnerLogin").val(ownerK.Description);console.log('Get People Picker NameK: ' +ownerK.DisplayText);
var userInfo = '';
if(auth5 > 0){
for (m = 0; m < usersK.length; m++) {
userK = usersK[m];
if(userK !== null){
//userPemail = userP.EntityData.Email;
userKemail = ownerK.DisplayText;
}
for (userPropertyK in userK) {
auth25 += userPropertyK + ': ' + userK[userPropertyK] + '<br>';
}
}
$('#resolvedUsers').html(auth25);
// Get user keys.
keysK = peoplePickerK.GetAllUserKeys();
$('#userKeys').html(keysK);
// Get the first user's ID by using the login name.
getUserIdK(usersK[0].Key);
}
}
// Get the user ID.
function getUserIdP(loginName) {
console.log('Get User ID-P');
var context = new SP.ClientContext.get_current();
this.userP = context.get_web().ensureUser(loginName);
context.load(this.userP);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessP),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessP() {
$('#userId').html(this.userP.get_id());
$("#siteOwenerId").val(this.userP.get_id());
userP = $("#siteOwenerId").val(this.userP.get_id());
}
function getUserIdS(loginName) {
console.log("Get User ID-S");
var context = new SP.ClientContext.get_current();
this.user22 = context.get_web().ensureUser(loginName);
context.load(this.user22);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessS),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessS() {
$('#userId').html(this.user22.get_id());
$("#siteOwenerId").val(this.user22.get_id());
userS = $("#siteOwenerId").val(this.user22.get_id());
}
function getUserIdK(loginName) {
console.log('Get User ID-K');
var context = new SP.ClientContext.get_current();
this.userK = context.get_web().ensureUser(loginName);
context.load(this.userK);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessK),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessK() {
$('#userId').html(this.userK.get_id());
$("#siteOwenerId").val(this.userK.get_id());
userK = $("#siteOwenerId").val(this.userK.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}
function addNewIntake(){
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',updateListItem1);
}
function updateListItem1() {
finalusersP.push(SP.FieldUserValue.fromUser(userP.Key));
finalusers22.push(SP.FieldUserValue.fromUser(user22.Key));
finalusersK.push(SP.FieldUserValue.fromUser(userK.Key));
var clientContext = new SP.ClientContext(siteUrl);
var oList =
clientContext.get_web().get_lists().getByTitle('Issue_Tracker_List');
this.oListItem = oList.addItem();
//console.log('primary person info: ' + finalusersP);
oListItem.set_item('MainContact2',finalusersP);
if(finalusers22 !== ""){
//console.log('secondary person info: ' +finalusers22);
oListItem.set_item('AdditionalContact_x0028_s_x0029_',finalusersS);
}
if(finalusersK !== ""){
oListItem.set_item('ITSupportOwner',finalusersK);
}
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
document.getElementById('main12').style.display="none";
document.getElementById('main22').style.display="block";
setTimeout(CloseDlg, 2000);
}
function CloseDlg() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

add ActionLink "Details" "Edit" "Delete" to a ajax list mvc 5

I want to have ActionLink "Details", "Edit" and "Delete" according to ID with an Ajax list, I managed to get my list out with datatable without having my columns in the script as you can see in my code, I would like to add the 3 links at the end of my table.
This is my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
var QueryString = HttpContext.Request.QueryString;
var orderBy = QueryString.Get("order[0][column]");
var orderByDir = QueryString.Get("order[0][dir]");
var search = QueryString.Get("search[value]");
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null) {
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{orderBy}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "1_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "1_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "2_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "2_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "0_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = lstData
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
This is my ajax call:
$(document).ready(function ()
{
$("#registrationTable").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
}
});
});
And this is my html for the table:
<table id="registrationTable" class="table table-striped dt-responsive display datatable dtr-inline" role="grid" aria-describedby="example-1_info">
<thead>
<tr>
<th>
ID
</th>
<th>
#Resource.FullName
</th>
<th>
#Resource.Email
</th>
<th class="sorting_desc_disabled sorting_asc_disabled">
#Resource.BirthDate
</th>
#*<th>
Edit
</th>
<th>
Delete
</th>*#
</tr>
</thead>
</table>
I found the solution, my controller changes a little bit, so here is my new code:
In my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
string orderByDir, search;
int orderByIdx;
List<string> cols = ExtractDataSortAndFilter(out orderByIdx, out orderByDir, out search);
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null)
{
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{cols[orderByIdx]}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "FullName_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "FullName_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "Email_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "Email_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "ID_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = new List<RegistrationsList>();
if (length > -1)
{
data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
}
else
{
data = query.Skip((int)start).ToList<RegistrationsList>();
}
/*var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}*/
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = data
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
private List<string> ExtractDataSortAndFilter(out int orderByIdx, out string orderByDir, out string search)
{
List<string> cols;
var QueryString = HttpContext.Request.QueryString;
cols = new List<string>();
string colName = null, colNamePath = "";
int colIdx = 0;
do
{
colNamePath = "columns[" + colIdx + "][data]";
colName = QueryString.Get(colNamePath);
cols.Add(colName);
colIdx++;
} while (colName != null);
string orderBy = QueryString.Get("order[0][column]");
orderByDir = QueryString.Get("order[0][dir]");
search = QueryString.Get("search[value]");
orderByIdx = orderBy == null ? 0 : int.Parse(orderBy);
orderByDir = orderByDir == null ? "asc" : orderByDir;
search = search == null ? "" : search;
return cols;
}
and this is my script:
$(document).ready(function () {
$("#registrationTable").DataTable({
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
},
"columns": [
{
data: null,
title: "<input type=\"checkbox\" id=\"btnSelAllStudents\">",
render: function (data, type, row, meta) {
return '<input type="checkbox" id="cbxRegStudent_' + row.ID + '" value="' + row.ID + '">';
},
targets: "no-sort",
orderable: false
},
{ data: "ID", title: "ID" },
{ data: "FullName", title: "#Resource.FullName" },
{ data: "Email", title: "#Resource.Email" },
{ data: "BirthDate", title: "#Resource.BirthDate" },
{
data: null, title: "Actions",
render: function (data, type, row, meta) {
/*return '<input type="button" class="btn-print printrec" id="' + row.ID + '" value="Print"/>';*/
return '#Resource.Profile | #Resource.Edit';
},
targets: "no-sort",
orderable: false
}
],
order: [],
});
$("#btnSelAllStudents").on("change", function (e) {
$("input[id^='cbxRegStudent_']").prop("checked", $(this).prop("checked"));
});
$('#registrationTable').on('processing.dt', function (e, settings, processing) {
$("#btnSelAllStudents").prop("checked", false);
}).dataTable();
});

Convert Lambda Expression into an Expression tree

I have that lambda:
var Ids = profileExample.CostCenters
.Where(CostCentre => CostCentre != null)
.Select(CostCentre => CostCentre.Id);
Then i convert to that expression tree
static IEnumerable<Int64> AboveLambdaConvertedToExpressionTree(Profile profileExample)
{
//Begin var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
var property = profileExample.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name != "Id").First();
var collection = ((IEnumerable)property.GetValue(profileExample, null)).AsQueryable();
var collectionType = property.PropertyType.GetGenericArguments()[0];
var collectionTypeName = collectionType.Name;
var keyType = typeof(Int64);
var keyName = "Id";
//BeginWhere
var parameter = Expression.Parameter(collectionType, collectionTypeName);
var profileExampleWhere = Expression.Lambda(
Expression.NotEqual(parameter, Expression.Constant(null)),
parameter);
var profileExampleWhereCall = Expression.Call(typeof(Enumerable),
"Where",
new Type[] { collectionType },
collection.Expression,
profileExampleWhere);
//EndWhere
//BeginSelect
var profileExampleSelect = Expression.Lambda(Expression.PropertyOrField(parameter, keyName),
parameter);
var profileExampleSelectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { collectionType, keyType },
profileExampleWhereCall,
profileExampleSelect);
var Ids = Expression.Lambda(profileExampleSelectCall).Compile().DynamicInvoke();
//EndSelect
//End var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
return ((IEnumerable)Ids).Cast<Int64>();
}
Now i want to do the same with bellow lambda
var result = Set.AsQueryable()
.Where(Profile => Profile.CostCenters.Select(CostCentre => CostCentre.Id)
.Any(Id => Ids.Contains(Id))).ToList();
But i stuck in .Any(Id => Ids.Contains(Id))....
var id = Expression.Parameter(typeof(long), "Id");
var costCentre = Expression.Parameter(typeof(CostCentre), "CostCentre");
var profile = Expression.Parameter(typeof(Profile), "Profile");
var selectLambda = Expression.Lambda(Expression.PropertyOrField(costCentre, "Id"), costCentre);
var selectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { typeof(CostCentre), typeof(long) },
Expression.PropertyOrField(profile, "CostCenters"),
selectLambda);
How can i call Any from selectCall and call Ids.Contains...
Full code to run as console application bellow:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace ExpressionTrees
{
class Program
{
static void Main(string[] args)
{
var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
Ids = AboveLambdaConvertedToExpressionTree(profileExample);
var result = Set.AsQueryable().Where(Profile => Profile.CostCenters.Select(CostCentre => CostCentre.Id).Any(Id => Ids.Contains(Id))).ToList();
//Expression<Func<Profile, bool>> lambda = (Profile) => Profile.CostCenters.Select(CostCentre => CostCentre.Id).Any(Id => Ids.Contains(Id));
var id = Expression.Parameter(typeof(long), "Id");
var costCentre = Expression.Parameter(typeof(CostCentre), "CostCentre");
var profile = Expression.Parameter(typeof(Profile), "Profile");
var selectLambda = Expression.Lambda(Expression.PropertyOrField(costCentre, "Id"), costCentre);
var selectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { typeof(CostCentre), typeof(long) },
Expression.PropertyOrField(profile, "CostCenters"),
selectLambda);
}
static IEnumerable<Int64> AboveLambdaConvertedToExpressionTree(Profile profileExample)
{
// I show that as example of what i need to do
var keyType = typeof(Int64);
var keyName = "Id";
//Begin var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
var property = profileExample.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name != keyName).First();
var collection = ((IEnumerable)property.GetValue(profileExample, null)).AsQueryable();
var collectionType = property.PropertyType.GetGenericArguments()[0];
var collectionTypeName = collectionType.Name;
//BeginWhere
var parameter = Expression.Parameter(collectionType, collectionTypeName);
var profileExampleWhere = Expression.Lambda(
Expression.NotEqual(parameter, Expression.Constant(null)),
parameter);
var profileExampleWhereCall = Expression.Call(typeof(Enumerable),
"Where",
new Type[] { collectionType },
collection.Expression,
profileExampleWhere);
//EndWhere
//BeginSelect
var profileExampleSelect = Expression.Lambda(Expression.PropertyOrField(parameter, keyName),
parameter);
var profileExampleSelectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { collectionType, keyType },
profileExampleWhereCall,
profileExampleSelect);
var Ids = Expression.Lambda(profileExampleSelectCall).Compile().DynamicInvoke();
//EndSelect
//End var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
return ((IEnumerable)Ids).Cast<Int64>();
}
public partial class Profile
{
public virtual Int64 Id { get; set; }
public virtual ICollection<CostCentre> CostCenters { get; set; }
}
public partial class CostCentre
{
public virtual Int64 Id { get; set; }
}
public static Profile profileExample
{
get
{
return new Profile()
{
Id = 1,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 2 } }
};
}
}
public static IList<Profile> Set
{
get
{
return new List<Profile>() { new Profile() { Id = 1,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 1 },
new CostCentre() { Id = 2 } }
},
new Profile() { Id = 2,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 2 },
new CostCentre() { Id = 3 } }
},
new Profile() { Id = 3,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 3 } }
} };
}
}
}
}
Since Any is a Generic Method you need to create it for a specific type. The method below gets the Any<T> method from the Enumerable type.
public static MethodInfo GetAnyExtensionMethod(Type forType)
{
MethodInfo method =
typeof(Enumerable).GetMethods()
.First(m => m.Name.Equals("Any") &&
m.GetParameters().Count() == 2);
return method.MakeGenericMethod(new[] { forType });
}
Its solved with help of Mads from MS
class Program
{
static void Main(string[] args)
{
//var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
var Ids = AboveLambdaConvertedToExpressionTree(profileExample);
//var result = Set.AsQueryable().Where(Profile => Profile.CostCenters.Select(CostCentre => CostCentre.Id).Any(Id => Ids.Contains(Id))).ToList();
var id = Expression.Parameter(typeof(long), "Id");
var costCentre = Expression.Parameter(typeof(CostCentre), "CostCentre");
var profile = Expression.Parameter(typeof(Profile), "Profile");
var selectLambda = Expression.Lambda(Expression.PropertyOrField(costCentre, "Id"), costCentre);
var selectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { typeof(CostCentre), typeof(long) },
Expression.PropertyOrField(profile, "CostCenters"),
selectLambda);
//var id2 = Expression.Parameter(typeof(long), "Id");
var containsCall = Expression.Call(typeof(Enumerable),
"Contains",
new Type[] { typeof(long) },
Expression.Constant(Ids),
id);
var anyLambda = Expression.Lambda(containsCall, id);
var anyCall = Expression.Call(typeof(Enumerable),
"Any",
new Type[] { typeof(long) },
selectCall,
anyLambda);
var whereLambda = Expression.Lambda(anyCall, profile);
var callExpression = Expression.Call(typeof(Queryable),
"Where",
new Type[] { typeof(Profile) },
Set.AsQueryable().Expression,
whereLambda);
var result = Expression.Lambda(callExpression).Compile().DynamicInvoke();
}

Parsing JSON with RestKit .20

Did some searching and was unable to find any suitable answers. Thanks in advance for helping me solve my probably trivial problem.
Here is the Json in question:
{
"User":{
"UserEvents":[
],
"Vendor":null,
"UserId":7,
"CreatedDate":"1900-01-01T00:00:00",
"UserName":"jasondboland#gmail.com",
"LoginCount":0,
"LastLogin":null,
"CurrentEventId":6,
"Company":null,
"FirstName":"Wedding Pro",
"LastName":"Boland",
"Gender":"female",
"Country":null,
"FacebookLink":null,
"FacebookData":null,
"PaymentToken":"",
"BillingAddress":null,
"ShippingAddress":null,
"ShipToPreference":1,
"ReferralId":null,
"BulkLicenseUpgrade":false,
"DisplayName":"Wedding Pro Boland",
"ImpersonateUser":null,
"VendorInd":false,
"AvailableLicenses":0
},
"Theme":{
"ThemeId":2,
"Name":"Tropical Beach 1",
"ThumbnailImage":"~/images/themes/tropical_beach_registry_t.jpg",
"LargeImage":"~/images/themes/tropical_beach_registry.jpg",
"Type":1,
"AccessLevel":1,
"StyleName":"tropic-beach",
"ActiveInd":true
},
"RegistryItems":[
],
"Organizers":[
{
"OrganizerId":11,
"CreatedDate":"2013-04-25T20:35:40.687",
"Address":null,
"OrganizerType":1,
"FirstName":"Jason",
"LastName":"Boland",
"Email":"jasondboland#gmail.com",
"Phone":"7143922631",
"FacebookId":null,
"PrimaryAccountInd":true,
"VerifiedInd":true,
"ActiveInd":true
},
{
"OrganizerId":12,
"CreatedDate":"2013-04-25T20:35:40.75",
"Address":null,
"OrganizerType":0,
"FirstName":"Ezzy",
"LastName":"Castillo",
"Email":null,
"Phone":null,
"FacebookId":null,
"PrimaryAccountInd":false,
"VerifiedInd":false,
"ActiveInd":true
}
],
"Attendees":[
],
"Schedules":[
{
"ScheduleId":11,
"CreatedDate":"2013-04-25T20:35:40.763",
"ScheduleType":2,
"Name":"Reception",
"Description":"Sea Cliff Country Club",
"DateStart":"2013-06-22T16:00:00",
"DateEnd":null,
"Address":null,
"ShowOnline":false,
"ActiveInd":true
},
{
"ScheduleId":12,
"CreatedDate":"2013-04-25T20:35:40.763",
"ScheduleType":1,
"Name":"Ceremony",
"Description":"Sea Cliff Country Club",
"DateStart":"2013-06-22T15:30:00",
"DateEnd":null,
"Address":null,
"ShowOnline":false,
"ActiveInd":true
}
],
"EventImages":[
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/aff69cb6-930b-4982-86e0-143d43a91da9_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/62b9c7e3-9ef8-41aa-b008-40847eb2eb18_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/b7281259-793d-4a7e-a2c7-466e2748a049_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/37cecb6b-0819-4a5e-aa21-475dfdad28c3_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/8f51398e-2cdf-47d2-a9bb-4fc32698ec18_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/a0e5f5c5-43f1-40db-b6cb-893bdf8d318e_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/17edaee6-8bdb-4988-847c-8977779c9000_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/0d460b63-9b65-4078-9660-a066c5390957_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/63536715-01ad-473f-b213-ba46f2f8a7d0_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
},
{
"ImageID":"00000000-0000-0000-0000-000000000000",
"Container":null,
"ImageName":null,
"ImageDesc":null,
"ThumbURL":null,
"MediumURL":null,
"LargeURL":"https://jjcompanies.blob.core.windows.net/eventimages/91f0675a-5df1-4c68-ae1f-e7db0c322e33_l",
"ImageType":0,
"SortOrder":0.0,
"UserEvents":null,
"RegistryItems":null
}
],
"UserEventId":6,
"CreatedDate":"2013-04-25T20:35:40.56",
"EventType":0,
"Name":"Jason Boland and Ezzy Castillo's Wedding",
"Description":"We can't wait to start out our lives together with a once in a lifetime trip to the south pacific.",
"Date":"2013-06-22T00:00:00",
"PaymentType":1,
"CurrencyType":1,
"EventLevel":1,
"RequestAddresses":true,
"ReferralCode":null,
"EventURL":"JasonAndEzzy",
"PublishedInd":true,
"PublishedDate":"2013-07-17T16:31:02.687",
"GalleryPurchasedInd":true,
"GalleryPurchasedDate":"2013-05-16T20:02:36.757",
"RequirePasswordOnGallery":false,
"EventPassword":"",
"BudgetPurchasedInd":true,
"BudgetPurchasedDate":"2013-05-16T20:02:36.757",
"GuestlistPurchasedInd":true,
"GuestlistPurchasedDate":"2013-05-16T20:02:36.757",
"GuestListInfoRequestsSent":null,
"GuestListInfoRequestsMessage":null,
"SampleInd":false,
"ActiveInd":true,
"DaysUntilWedding":"-25.13:43:16.6650000",
"PrimaryOrganizer":{
"OrganizerId":11,
"CreatedDate":"2013-04-25T20:35:40.687",
"Address":null,
"OrganizerType":1,
"FirstName":"Jason",
"LastName":"Boland",
"Email":"jasondboland#gmail.com",
"Phone":"7143922631",
"FacebookId":null,
"PrimaryAccountInd":true,
"VerifiedInd":true,
"ActiveInd":true
},
"CeremonySchedule":{
"ScheduleId":12,
"CreatedDate":"2013-04-25T20:35:40.763",
"ScheduleType":1,
"Name":"Ceremony",
"Description":"Sea Cliff Country Club",
"DateStart":"2013-06-22T15:30:00",
"DateEnd":null,
"Address":null,
"ShowOnline":false,
"ActiveInd":true
},
"ReceptionSchedule":{
"ScheduleId":11,
"CreatedDate":"2013-04-25T20:35:40.763",
"ScheduleType":2,
"Name":"Reception",
"Description":"Sea Cliff Country Club",
"DateStart":"2013-06-22T16:00:00",
"DateEnd":null,
"Address":null,
"ShowOnline":false,
"ActiveInd":true
}
}
Object:
#interface RKImage : NSObject
#property (nonatomic, copy) NSString *LargeURL;
#property (nonatomic, copy) NSString *ImageID;
#end
Attempted Code:
RKObjectMapping* wMapping = [RKObjectMapping mappingForClass:[RKImage class]];
[wMapping addAttributeMappingsFromDictionary:#{
//#"ImageID": #"ImageID",
#"LargeURL": #"LargeURL"
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:wMapping pathPattern:nil keyPath:#"EventImages" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
NSURL *URL = [NSURL URLWithString:#"http://myurl.cloudapp.net/api/mobilegallery/1"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[ responseDescriptor ]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(#"Load collection of Articles: %#", mappingResult.array);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
[objectRequestOperation start];
I'm getting the error:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<RKImage 0xa25b240> valueForUndefinedKey:]: this class is not key value coding-compliant for the key LargeURL.'
Edit: Error with logging enabled
2013-07-17 16:04:43.168 SimplyTieGallery[1002:c07] I
restkit.network:RKObjectRequestOperation.m:174 GET
'http://4451cfc5be9c49f4896a2dd6eeec96c9.cloudapp.net/api/mobilegallery/1'
2013-07-17 16:04:44.927 SimplyTieGallery[1002:4103] D
restkit.object_mapping:RKMapperOperation.m:390 Executing mapping
operation for representation: {
ActiveInd = 1;
Attendees = (
);
BudgetPurchasedDate = "";
BudgetPurchasedInd = 0;
CeremonySchedule = {
ActiveInd = 1;
Address = "";
CreatedDate = "2013-04-11T13:11:16.803";
DateEnd = "2013-10-08T13:11:16";
DateStart = "2013-10-08T13:11:16";
Description = "Falkirk Estate and Country Club";
Name = Ceremony;
ScheduleId = 2;
ScheduleType = 1;
ShowOnline = 1;
};
CreatedDate = "2013-04-11T13:11:13.93";
CurrencyType = 1;
Date = "2013-10-08T00:00:00";
DaysUntilWedding = "82.00:55:14.3863200";
Description = "We will soon be Mr. and Ms. Jones and just can't wait! While everyone is recovering from the massive party (our
wedding) we will be boarding a plane to Bora Bora to start our lives
together in grand fashion! We are lucky to be blessed with a fully
stocked home so we have decided to use SimplyTie to help us create the
most amazing honeymoon we could think of. We can\U2019t thank
everyone enough for all your love, support and generosity! Thank you
so much! John and Judy Jones";
EventImages = (
{
Container = "";
ImageDesc = "";
ImageID = "00000000-0000-0000-0000-000000000000";
ImageName = "";
ImageType = 0;
LargeURL = "https://jjcompanies.blob.core.windows.net/eventimages/c4d56b3d-840e-4093-bdc8-8369cf05da34_l";
MediumURL = "";
RegistryItems = "";
SortOrder = 0;
ThumbURL = "";
UserEvents = "";
},
{
Container = "";
ImageDesc = "";
ImageID = "00000000-0000-0000-0000-000000000000";
ImageName = "";
ImageType = 0;
LargeURL = "https://jjcompanies.blob.core.windows.net/eventimages/cd22c262-8cbc-480b-b0ee-a4b33e248b70_l";
MediumURL = "";
RegistryItems = "";
SortOrder = 0;
ThumbURL = "";
UserEvents = "";
}
);
EventLevel = 1;
EventPassword = "";
EventType = 0;
EventURL = BoraBoraSample;
GalleryPurchasedDate = "2013-04-26T00:11:45.427";
GalleryPurchasedInd = 1;
GuestListInfoRequestsMessage = "";
GuestListInfoRequestsSent = "";
GuestlistPurchasedDate = "";
GuestlistPurchasedInd = 0;
Name = "John and Judy's Wedding";
Organizers = (
{
ActiveInd = 1;
Address = "";
CreatedDate = "2013-04-11T13:11:16.32";
Email = "JudyMcGride#SimplyTie.com";
FacebookId = "";
FirstName = Judy;
LastName = McBride;
OrganizerId = 1;
OrganizerType = 0;
Phone = "";
PrimaryAccountInd = 1;
VerifiedInd = 1;
},
{
ActiveInd = 1;
Address = "";
CreatedDate = "2013-04-11T13:11:16.323";
Email = "JohnJones#SimplyTie.com";
FacebookId = "";
FirstName = John;
LastName = Jones;
OrganizerId = 2;
OrganizerType = 1;
Phone = "";
PrimaryAccountInd = 0;
VerifiedInd = 1;
}
);
PaymentType = 1;
PrimaryOrganizer = {
ActiveInd = 1;
Address = "";
CreatedDate = "2013-04-11T13:11:16.32";
Email = "JudyMcGride#SimplyTie.com";
FacebookId = "";
FirstName = Judy;
LastName = McBride;
OrganizerId = 1;
OrganizerType = 0;
Phone = "";
PrimaryAccountInd = 1;
VerifiedInd = 1;
};
PublishedDate = "2013-04-11T13:11:13.93";
PublishedInd = 1;
ReceptionSchedule = {
ActiveInd = 1;
Address = "";
CreatedDate = "2013-04-11T13:11:16.803";
DateEnd = "2013-10-08T13:11:16";
DateStart = "2013-10-08T13:11:16";
Description = "Falkirk Estate and Country Club";
Name = Reception;
ScheduleId = 1;
ScheduleType = 2;
ShowOnline = 1;
};
ReferralCode = "";
RegistryItems = (
);
RequestAddresses = 1;
RequirePasswordOnGallery = 0;
SampleInd = 1;
Schedules = (
{
ActiveInd = 1;
Address = "";
CreatedDate = "2013-04-11T13:11:16.803";
DateEnd = "2013-10-08T13:11:16";
DateStart = "2013-10-08T13:11:16";
Description = "Falkirk Estate and Country Club";
Name = Reception;
ScheduleId = 1;
ScheduleType = 2;
ShowOnline = 1;
},
{
ActiveInd = 1;
Address = "";
CreatedDate = "2013-04-11T13:11:16.803";
DateEnd = "2013-10-08T13:11:16";
DateStart = "2013-10-08T13:11:16";
Description = "Falkirk Estate and Country Club";
Name = Ceremony;
ScheduleId = 2;
ScheduleType = 1;
ShowOnline = 1;
}
);
Theme = {
AccessLevel = 1;
ActiveInd = 1;
LargeImage = "~/images/themes/tropical_beach_registry.jpg";
Name = "Tropical Beach 1";
StyleName = "tropic-beach";
ThemeId = 2;
ThumbnailImage = "~/images/themes/tropical_beach_registry_t.jpg";
Type = 1;
};
User = {
AvailableLicenses = 0;
BillingAddress = "";
BulkLicenseUpgrade = 0;
Company = "";
Country = "";
CreatedDate = "1900-01-01T00:00:00";
CurrentEventId = 1;
DisplayName = "John Sample";
FacebookData = "";
FacebookLink = "";
FirstName = John;
Gender = Male;
ImpersonateUser = "";
LastLogin = "";
LastName = Sample;
LoginCount = 0;
PaymentToken = "";
ReferralId = "";
ShipToPreference = 2;
ShippingAddress = "";
UserEvents = (
);
UserId = 1;
UserName = "boraborasample#simplytie.com";
Vendor = "";
VendorInd = 0;
};
UserEventId = 1; } and targetObject: (null) 2013-07-17 16:04:44.930 SimplyTieGallery[1002:4103] T
restkit.object_mapping:RKMapperOperation.m:333 Examining keyPath
'EventImages' for mappable content... 2013-07-17 16:04:44.930
SimplyTieGallery[1002:4103] D
restkit.object_mapping:RKMapperOperation.m:310 Found mappable
collection at keyPath 'EventImages': (
{
Container = "";
ImageDesc = "";
ImageID = "00000000-0000-0000-0000-000000000000";
ImageName = "";
ImageType = 0;
LargeURL = "https://jjcompanies.blob.core.windows.net/eventimages/c4d56b3d-840e-4093-bdc8-8369cf05da34_l";
MediumURL = "";
RegistryItems = "";
SortOrder = 0;
ThumbURL = "";
UserEvents = "";
},
{
Container = "";
ImageDesc = "";
ImageID = "00000000-0000-0000-0000-000000000000";
ImageName = "";
ImageType = 0;
LargeURL = "https://jjcompanies.blob.core.windows.net/eventimages/cd22c262-8cbc-480b-b0ee-a4b33e248b70_l";
MediumURL = "";
RegistryItems = "";
SortOrder = 0;
ThumbURL = "";
UserEvents = "";
} ) 2013-07-17 16:04:44.931 SimplyTieGallery[1002:4103] D restkit.object_mapping:RKMapperOperation.m:244 Asked to map source
object {
Container = "";
ImageDesc = "";
ImageID = "00000000-0000-0000-0000-000000000000";
ImageName = "";
ImageType = 0;
LargeURL = "https://jjcompanies.blob.core.windows.net/eventimages/c4d56b3d-840e-4093-bdc8-8369cf05da34_l";
MediumURL = "";
RegistryItems = "";
SortOrder = 0;
ThumbURL = "";
UserEvents = ""; } with mapping LargeURL>" )> 2013-07-17 16:04:44.931 SimplyTieGallery[1002:4103] D
restkit.object_mapping:RKMappingOperation.m:912 Starting mapping
operation... 2013-07-17 16:04:44.932 SimplyTieGallery[1002:4103] T
restkit.object_mapping:RKMappingOperation.m:913 Performing mapping
operation: for 'RKImage' object.
Mapping values from object {
Container = "";
ImageDesc = "";
ImageID = "00000000-0000-0000-0000-000000000000";
ImageName = "";
ImageType = 0;
LargeURL = "https://jjcompanies.blob.core.windows.net/eventimages/c4d56b3d-840e-4093-bdc8-8369cf05da34_l";
MediumURL = "";
RegistryItems = "";
SortOrder = 0;
ThumbURL = "";
UserEvents = ""; } to object with object mapping (null) 2013-07-17 16:04:44.932
SimplyTieGallery[1002:4103] T
restkit.object_mapping:RKMappingOperation.m:515 Mapping attribute
value keyPath 'LargeURL' to 'LargeURL' 2013-07-17 16:04:44.933
SimplyTieGallery[1002:1703] D
restkit.object_mapping:RKPropertyInspector.m:126 Cached property
inspection for Class 'RKImage': {
ImageID = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = ImageID;
};
LargeURL = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = LargeURL;
}; } 2013-07-17 16:04:44.933 SimplyTieGallery[1002:4103] * Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[ valueForUndefinedKey:]: this class is
not key value coding-compliant for the key LargeURL.'
* First throw call stack: (0x1e68012 0x1c8de7e 0x1ef0fb1 0x1962d1d 0x18cf00b 0x18cefbd 0x18ed247 0xa3561 0xa4a92 0xa5e39 0xad45d
0x18ef453 0x18ef164 0x9bb79 0x9b018 0x1e61e7c 0x1e61a16 0x1e61925
0x9accb 0x9cbff 0x9d657 0x9e021 0x18ef453 0x18ef164 0x8c850 0x8a955
0x18ef453 0x18ef164 0x197ba31 0x254b53f 0x255d014 0x254e2e8 0x254e450
0x91453e72 0x9143bd2a) libc++abi.dylib: terminate called throwing an
exception (lldb)
Tried messing with keyPaths and I'm just getting nowhere fast. Thanks!

how to use jstree ondemand with mvc3 razor

I have to display a treeview .But it will take much time, that's why I want to load this treeview on demand.At the first I want just display first level, and repeating that level by level.
This is the view
$("#onflycheckboxes").jstree({
json_data: {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = ""
if (node == -1) {
url = "/TreeView/GetCollectionWS/source";
}
else {
nodeId = node.attr('id');
url = "/TreeView/GetCollectionWS/" + nodeId;
}
return url;
},
"type": "POST",
"dataType": "json",
"contentType": "application/json charset=utf-8"
}
},
checkbox: {
real_checkboxes: true,
checked_parent_open: true
},
plugins: ["themes", "json_data", "ui", "checkbox"]
});
this is the controller
public virtual ActionResult GetCollectionWS(string root)
{
int? nodeId = (root == source) ? (int?)null : Convert.ToInt32(root);
Object[] liste = new Object[100];
liste = DSClient.Views.Traitement.getTop(nodeId);
List<TreeViewNode> nodes = new List<TreeViewNode>();
for (int i = 0; (i < liste.Length && liste.ElementAt(i) != null);i++ )
{
bool leaf = false;
nodes.Add(new TreeViewNode()
{
id = Convert.ToString(DSClient.Views.Traitement.GetNodeId(liste.ElementAt(i))),
text = liste.ElementAt(i).Handle,
classes = leaf ? "file" : "folder",
hasChildren = !leaf
});
}
return Json(nodes);
}
when I try a breakpoint on the line return Json(nodes); I remarque that nodes contains
at the first {id=0,text=Collection-10,classes=folder,haChildren=false}
the view display nothing.Please, can any one help me??
public virtual string GetCollectionWS(string id)
{
Object[] liste = new Object[100];
client = new DSServiceClient();
if (id == "source")
{
Collection[] _top = new Collection[100];
client.Open();
_top = client.GetTopCollections();
client.Close();
for (int i = 0; i < _top.Length; i++)
{
DSClient.Controllers.Object obji = new DSClient.Controllers.Object();
obji.Handle = _top[i].Handle;
obji.Name = _top[i].Title;
liste[i] = obji;
}
}
else
{
client = new DSServiceClient();
client.Open();
Tree tree = client.GetTreeView(id);
client.Close();
liste = tree.listObjects;
}
var recursiveObjects = FillRecursive(liste);
string myjsonmodel = new JavaScriptSerializer().Serialize(recursiveObjects);
return myjsonmodel;
}
private static List<RecursiveObject> FillRecursive(Object[] flatObjects)
{
List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();
for (int i = 0; (i < flatObjects.Length && flatObjects.ElementAt(i) != null); i++)
{
recursiveObjects.Add(new RecursiveObject()
{
data = flatObjects.ElementAt(i).Name,
id = flatObjects.ElementAt(i).Handle,
attr = new FlatTreeAttribute { id = flatObjects.ElementAt(i).Handle, selected = false },
children = null,
state = "closed"
});
}
return recursiveObjects;
}
Now I want to send the text and Id of nodes selected to my controller.
<script type="text/javascript">
var divId = [];
var divText = [];
$('#idjstree').value=function GetIDs() {
divId = [];
divText = [];
$("#onflycheckboxes").jstree("get_checked", null, true).each
(function () {
divId.push(this.id);
divText.push($(this).children('a').text());
});
return (divId);
}</script
and this is in the view
#:<div id="onflycheckboxes"></div>
#:<input type="hidden" id="idjstree" name="idjstree" value="" />
but always I get idjstree="" when I do a breakpoint on the post of create.But the function GetIDs() is correct.
What can I do please?

Resources