var store = new FMP.AspNetJsonStore({
fields: [
{ name: 'AssetID' },
{ name: 'AssociationID' },
{ name: 'Image' },
{ name: 'StatusName' },
{ name: 'ModelName' },
{ name: 'IPAddress' },
{ name: 'InScope', type: 'boolean' },
{ name: 'ServicePlanName' },
{ name: 'PricePlanName' },
{ name: 'PricePlanDescription' },
{ name: 'Program' },
{ name: 'ServicePlanID' },
{ name: 'Customer' },
{ name: 'Black', type: 'float' },
{ name: 'Cyan', type: 'float' },
{ name: 'Magenta', type: 'float' },
{ name: 'Yellow', type: 'float' },
{ name: 'BlackPct' },
{ name: 'CyanPct' },
{ name: 'MagentaPct' },
{ name: 'YellowPct' },
{ name: 'PrinterMarkerSupplies' },
{ name: 'PageCount' },
{ name: 'BlackImpressions' },
{ name: 'ColorImpressions' },
{ name: 'PricePlanID' },
{ name: 'ResponsibilityForAction' },
{ name: 'PrinterSerialNumber' }
],
totalProperty: "TotalCount",
autoLoad: { params: { start: 0, limit: myPageSize} },
//autoLoad: true,
proxy: new Ext.data.HttpProxy({
// Call web service method using GET syntax
url: 'GetPrintersGrid.asmx/buildGrid',
// Ask for Json response
headers: { 'Content-type': 'application/json' },
method: "GET"
}),
remoteSort: true,
//sortInfo: { field: 'PageCount', direction: "DESC" },
groupField: 'Customer',
root: 'Records'
});
store.setDefaultSort('PageCount', 'DESC');
I am using a webservice to sort this.
I am getting an error
{"Message":"Invalid JSON primitive: DESC.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext context, JavaScriptSerializer serializer, WebServiceMethodData methodData)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
Can anyone help me in this issue
I am using Ext.ux.AspWebServiceProxy class and used this proxy class in the store.Also defined the webservice in the user control in scriptmanager proxy
Iam getting an error saying GetPrintersGrid is undefined.Iam using the follwing example for reference.
http://osman.in/aspnet/using-extjs-grid-with-aspnet-ajax-wcf-webservices-c/
Can you please help me in this issue.
/// <reference path="ExtJS/ext-all.js" />
Ext.namespace('Ext.ux');
Ext.ux.AspWebServiceProxy = function(conn)
{
Ext.ux.AspWebServiceProxy.superclass.constructor.call(this);
Ext.apply(this, conn);
};
Ext.extend(Ext.ux.AspWebServiceProxy, Ext.data.DataProxy,
{
load : function (params, reader, callback, scope, arg)
{
var userContext = {
callback: callback,
reader: reader,
arg: arg,
scope: scope
};
var proxyWrapper = this;
//Handles the response we get back from the web service call
var webServiceCallback = function(response, context, methodName)
{
proxyWrapper.loadResponse(response, userContext, methodName);
}
var serviceParams = [];
//Convert the params into an array of values so that they can be used in the call (note assumes that the properties on the object are in the correct order)
for (var property in params)
{
serviceParams.push(params[property]);
}
//Add the webservice callback handlers
serviceParams.push(webServiceCallback);
serviceParams.push(this.handleErrorResponse);
//Make the actual ASP.Net web service call
this.webServiceProxyMethod.apply(this.webServiceProxy, serviceParams);
},
handleErrorResponse : function(response, userContext, methodName)
{
alert("Error while calling method: " + methodName + "\n" + response.get_message());
},
loadResponse : function (response, userContext, methodName)
{
var result = userContext.reader.readRecords(response);
userContext.callback.call(userContext.scope, result, userContext.arg, true);
}
});
var dataStore = new Ext.data.Store(
{
//Note that I have renamed the web service proxy class
proxy: new Ext.ux.AspWebServiceProxy(
{
webServiceProxy: GetPrintersGrid,
webServiceProxyMethod: GetPrintersGrid.buildGrid
}),
remoteSort: true
});
<asp:ScriptManagerProxy ID="PageScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~/GetPrintersGrid.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Path="~/Ext.ux.AspWebServiceProxy.js" />
</Scripts>
</asp:ScriptManagerProxy>
This is the souce code i ussed
FMP.AspNetJsonReader = Ext.extend(Ext.data.JsonReader, {
read: function(response) {
// Assuming ASP.NET encoding - Data is stored as
var json = response.responseText;
var o = Ext.decode(json);
if (!o) {
throw { message: "AspNetJsonReader.read: Json object not found" };
}
if (!o.d) {
throw { message: "AspNetJsonReader.read: Root element d not found" };
}
return this.readRecords(o.d);
}
});
FMP.AspNetJsonStore = Ext.extend(Ext.data.GroupingStore, {
/**
* #cfg {Ext.data.DataReader} reader #hide
*/
constructor: function(config) {
FMP.AspNetJsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new FMP.AspNetJsonReader(config)
}));
}
});
Iam using AS.NET for server side
Here is my webservice
public PagedResult buildGrid(int start, int limit, string sortfield, string dir)
{
var a=5;
Guid AccountID = (Guid)Session["AccountID"];
//string sortdir;
//if( dir == "DESC")
//{
// sortdir = dir.Substring(0, 4).Trim().ToUpper();
//}
//else
//{
// sortdir = dir.Substring(0, 3).Trim().ToUpper();
//}
string SortExpression = sortfield + " " + (!String.IsNullOrEmpty(dir) ? dir : String.Empty);
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' order by a.PageCount = '" + + "'";
string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' Order By a."+SortExpression;
//string whereClause = "SELECT value a , ROW_NUMBER() OVER(ORDER BY" + " " + SortExpression + ") As RowNumber FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "'";
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "'";
List<FMPAsset> fmpAssets = new List<FMPAsset>();
using (XSPAssetModel.XSPAssetEntities assetEntities = new XSPAssetEntities(b.BuildEntityConnectionString1("XSMDSN")))
{
ObjectQuery<XSP_AssetList_V> assets = new ObjectQuery<XSP_AssetList_V>(whereClause, assetEntities);
//var assetOrder = assets.OrderBy(x => x.StatusName).ToList();
var assetPage = assets.Skip(start).Take(limit);
//var totalAssetCount = assets.Count();
currentAssets = assetPage.ToList();
int currentAssetsCount = currentAssets.Count;
string imgprefix = System.Configuration.ConfigurationManager.AppSettings["ImgPrefix"];
char[] separators = { '/' };
string appname = "";
int lastloc = imgprefix.Substring(0, imgprefix.Length - 1).LastIndexOfAny(separators);
if (lastloc > 6)
{
appname = imgprefix.Substring(lastloc + 1);
}
FMPAsset asset = new FMPAsset();
//StreamWriter sw = new StreamWriter("C:\\test.txt");
XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities markerCtx = new XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities(b.BuildEntityConnectionString1("XSMDSN"));
for (int x = 0; x < currentAssetsCount; x++)
{
asset = new FMPAsset();
asset.AssetID = currentAssets[x].AssetID.ToString();
asset.PricePlanID = currentAssets[x].PricePlanID.ToString();
asset.AssociationID = currentAssets[x].AssociationID;
asset.ModelName = currentAssets[x].ModelName;
asset.ResponsibilityForAction = currentAssets[x].ResponsibilityForAction;
asset.IPAddress = (String.IsNullOrEmpty(currentAssets[x].PrinterIPAddress)) ? "No IP" : currentAssets[x].PrinterIPAddress; ;
if (currentAssets[x].InScope)
{
asset.InScope = b.GetString("SDE_YES");
}
else
{
asset.InScope = b.GetString("SDE_NO");
}
asset = SetStatus(appname, asset, x);
asset.PricePlanName = currentAssets[x].Program;
asset.PricePlanDescription = currentAssets[x].PricePlanDescription;
asset.ServicePlanName = currentAssets[x].ServicePlanName;
if (currentAssets[x].PrinterSerialNumber != null)
{
asset.PrinterSerialNumber = currentAssets[x].PrinterSerialNumber;
}
else
{
asset.PrinterSerialNumber = "-";
}
//sw.WriteLine("ChargebackDescription: " + DateTime.Now.Millisecond);
if (this.b.UseChargebackDescription && !String.IsNullOrEmpty(currentAssets[x].CustomerChargebackDescription) && currentAssets[x].CustomerChargebackDescription != "Generated by OUT Integration")
{
asset.Customer = currentAssets[x].CustomerChargebackDescription;
if (asset.Customer.IndexOf(Environment.NewLine) > -1)
{
asset.Customer = asset.Customer.Substring(0, asset.Customer.IndexOf(Environment.NewLine));
}
}
else
{
asset.Customer = currentAssets[x].CustomerChargeBackEntryName;
}
if (this.b.UsePricePlanDescription && !String.IsNullOrEmpty(currentAssets[x].PricePlanDescription))
{
asset.Program = currentAssets[x].PricePlanDescription;
if (asset.Program.IndexOf(Environment.NewLine) > -1)
{
asset.Program = asset.Program.Substring(0, asset.Program.IndexOf(Environment.NewLine));
}
}
else
{
asset.Program = currentAssets[x].Program;
}
asset.BlackPct = -3;
asset.CyanPct = -3;
asset.MagentaPct = -3;
asset.YellowPct = -3;
Guid id = currentAssets[x].AssetID;
asset = SetCMYKvalues(asset, x);
BuilldImpressionsValues(currentAssets[x], ref asset);
fmpAssets.Add(asset);
}
var totalAssetCount = assets.Count();
var y = new PagedResult<FMPAsset>();
y.Records = fmpAssets;
y.TotalCount = totalAssetCount;
return y;
// CommonGrid1.BindDataSource(SortByStatusName(fmpAssets));
}
}
This error is happening when your store is making the call to your web service. Whatever JSON is being sent is not valid for some reason (or .NET does not think it is), hence the server error when ASP.NET is trying to deserialize the data into a valid argument list for your method. I would first look in Firebug to see exactly what JSON is being passed to the server -- that might give you a clue as to what the issue is. If the JSON being sent is not valid then it's a client/Ext issue -- if it is valid, then it's a .NET issue.
Related
I would like to create a JSON object with the following structure:
var exec_log = {
total_correct: 0,
total_error: 0,
[exec_detail: {
timestamp: "1a",
script: "New Deal",
type: "Bot",
id: "2a",
pair: "3a",
status: "4a",
message: "5a"
},
exec_detail: {
timestamp: "1a",
script: "New Deal",
type: "Bot",
id: "2a",
pair: "3a",
status: "4a",
message: "5a"
},
...]
}
However I don't know how to create an array of objects inside an object or how to access them to populate them correctly.
Current code:
So far I have achieved this but I'm sure the array is not defined correctly and I suspect that I have to create an external array and push it inside the exec_log object.. Should I define 2 separated objects and push one inside the other?
function StartNewDeal(filterAPC){
var exec_log = {
total_correct: 0,
total_error: 0,
exec_detail: {
timestamp: "",
script: "New Deal",
type: "Bot",
id: "",
pair: "",
status: "",
message: ""
}
}
for(var i = 0; i < filterAPC.length; i++){
Logger.log("Passing botID: " + filterAPC[i][1])
var new_deal = StartDeal(filterAPC[i][1]);
var currentDate = Utilities.formatDate(new Date(), "PST", "yyyy-MM-dd HH:mm");
exec_log.exec_detail[timestamp[i]] = currentDate;
exec.log.exec_detail[id[i]] = filterAPC[i][1];
exec_log.exec_detail[pair[i]] = new_deal.pair;
if(new_deal.valid == false){
exec_log.exec_detail[status[i]] = "Error";
exec_log.exec_detail[message[i]] = new_deal.json;
exec.log.total_error = exec.log.total_error + 1;
}else{
exec_log.exec_detail[status[i]] = "Completed";
exec_log.exec_detail[message[i]] = "Completed";
exec.log.total_correct = exec.log.total_correct + 1;
}
}
return exec_log;
}
function createObject() {
let obj={property1:'value1',property2:'value2',property3:[],property4:[],property5:'value5',property6:'value6'};
for(let i=0;i<2;i++) {
let iObj={};
for(let j=0;j<5;j++) {
iObj['item'+j]='donkey'+j;
}
obj.property3.push(iObj);
obj.property4.push(iObj);
}
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput('<textarea>' + JSON.stringify(obj) + '</textarea>'), "Making an object with no parts");
}
Try this:
function StartNewDeal(filterAPC){
var exec_log = {
total_correct: 0,
total_error: 0,
exec_details_list: [] // an array to store your exect_details objects
}
for(var i = 0; i < filterAPC.length; i++) {
Logger.log("Passing botID: " + filterAPC[i][1])
var new_deal = StartDeal(filterAPC[i][1]);
var timestamp = Utilities.formatDate(new Date(), "PST", "yyyy-MM-dd HH:mm");
var id = filterAPC[i][1];
var pair = new_deal.pair;
var status;
var message;
var script; // doesn't seem like you're using this
if (new_deal.valid == false){
status = "Error";
message = new_deal.json;
exec.log.total_error = exec.log.total_error + 1;
} else{
status = "Completed";
message = "Completed";
exec.log.total_correct = exec.log.total_correct + 1;
}
exec_log.exec_details_list.push(new ExecDetailObject(timestamp, script, type, id, pair, status, message));
}
return exec_log;
}
// A function to create new exec_detail objects
// from your code you don't seem to be using the script property. Not sure if that's intentional
function ExecDetailObject(timestamp, script, type, id, pair, status, message) {
this.timestampt = timestamp;
this.script = script;
this.type = type;
this.id = id;
this.pair = pair;
this.status = status;
this.message = message;
}
Hi I'm a newbie in web development and I'm having some trouble in inserting new data in my database.
First, there's an error in dbcontext.Tbl_Articles.Add(adto);
It says, cannot convert WebAPI.Models.Articles to WebAPI.DataLayer.Tbl_Articles
Another thing is, whenever I run my Web API, it says something like this - {"Message":"The requested resource does not support http method 'GET'."}
script file:
$scope.AddArticle = function ()
{
var data =
{
Category: $scope.Category,
IsCarousel: $scope.IsCarousel,
IsImportant: $scope.IsImportant,
HeaderImage: $scope.HeaderImage,
Title: $scope.Title,
ByLine: $scope.ByLine,
Content: $scope.Content,
Author: $scope.Author,
PublishStartDate: $scope.PublishStartDate_date + " " + $scope.PublishStartDate_time + $scope.PublishStartDate_time_ext,
PublishEndDate: $scope.PublishEndDate_date + " " + $scope.PublishEndDate_time + $scope.PublishEndDate_time_ext
};
$http(
{
method: 'POST',
url: 'http://project-aphrodite-uat-service.azurewebsites.net/api/articles/createarticle',
data: JSON.stringify(data)
})
.then(function successCallback(response)
{
console.log(response);
},
function errorCallback(response)
{
console.log("error" + response);
});
};
ArticlesController.cs:
[HttpPost]
[Route("api/articles/createarticle")]
public Articles CreateArticle(Articles obj)
{
DataLayer.DataLayer dl = new DataLayer.DataLayer();
dl.CreateArticle(obj);
return obj;
}
DataLayer.cs:
public string CreateArticle(Articles obj)
{
var adto = new Articles();
adto.Category = obj.Category;
adto.IsCarousel = obj.IsCarousel;
adto.IsImportant = obj.IsImportant;
adto.HeaderImage = obj.HeaderImage;
adto.Title = obj.Title;
adto.ByLine = obj.ByLine;
adto.Content = obj.Content;
adto.Author = obj.Author;
adto.PublishStartDate = obj.PublishStartDate;
adto.PublishEndDate = obj.PublishEndDate;
using (ArticleEntities dbcontext = new ArticleEntities())
{
dbcontext.Tbl_Articles.Add(adto);
dbcontext.SaveChanges();
return "test";
}
}
I hope someone could help me fix these. Thankie so much!
my code in here
here $scope.student_photo is my variable to get encoded string
first i get it in ajax and stored in local db
$http.post(mData.url+'getStudentDetails/',{student_id : student_id} ).success(function(data){
//$scope.student_pic = data.student_details[0].student_pic;
//$scope.student_photo = data.student_details[0].student_photo;
$scope.myImage=data.student_details[0].student_photo;
//alert($scope.myImage);
// var image_stu = data.student_details[0].student_photo;
// localStorage.setItem("imageData", image_stu);
// document.getElementById("img_stu").src='data:image/png;base64,' + image_stu;
//alert("DONE");
var events = data.student_details
var l = events.length;
//alert(l);
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM dashboard ', [], function(tx, results){
if (results.rows.length == 0)
{
tx.executeSql("INSERT INTO dashboard(dashboard_id, stu_name,clas,sec,student_image) VALUES(?,?,?,?,?)", [ student_id,data.student_details[0].student_name, data.student_details[0].class_name, data.student_details[0].section_name,data.student_details[0].student_photo], function(tx, res) {
$scope.dashboardDetails();
//alert('INSERTED');
}, function(e) {
//alert('ERROR: ' + e.message);
});
}
});
});
});
$scope.showScreen = function(screen) {
$state.go('app.'+screen);
}
$scope.printDashboard = function()
{
//alert('ss');
db.transaction(function (tx) {
// tx.executeSql('SELECT * FROM dashboard', [], function (tx, dtresult) {
//alert("dtresult.rows.length" + dtresult.rows.length);
// console.log("dtresult.rows.length" + dtresult.rows.length);
// $scope.totalrecords = dtresult.rows.length;
// });
tx.executeSql('SELECT * FROM dashboard', [], function (tx, dresult) {
console.log("dresult.rows.length" + dresult.rows.length);
dataset = dresult.rows;
console.log(dresult.rows);
for (var i = 0, item = null; i < dresult.rows.length; i++) {
item = dataset.item(i);
$scope.dashboarditems.push({stu_name: item['stu_name'],stu_class: item['clas'],stu_sec: item['Sec'],stu_img: item['student_image']});
//$scope.items.push({id: item['notice_title'], notice:item['notice'], event_date: item['event_date']});
console.log($scope.dashboarditems[0]);
}
$state.go('app.dashboard');
});
});
}
$scope.dashboardDetails = function()
{
var citems = [];
syncWithServer(function(syncSuccess){
$scope.printDashboard();
}, false);
}
Question:
How to display my base64 string to image formate.
If your base64 string is present inside the $scope.student_photo
try the following img tag to display the image in view
<img ng-src="{{'data:image/png;base64,'+student_photo}}">
I am learning AngularJS and I have a conventional JS Script that I wrote a while ago and I would like to use it inside my new Angular app.
Can I literally just dump the entire script in side the directive or do I need to change some things like the keyword this to element etc...?
directive.directive("skillLevel", ['$timeout', function($timeout) {
return{
link: function(scope, el, atts){
// CAN I PASTE MY SCRIPT HERE??
}
}]);
I have this 'quite length some' script that I want to use. How would I go about effectivly using this inside my directive?
(function ($) {
'use strict';
var RSS = function (target, url, options, callback) {
this.target = target;
this.url = url;
this.html = [];
this.effectQueue = [];
this.options = $.extend({
ssl: false,
host: 'www.feedrapp.info',
limit: null,
key: null,
layoutTemplate: '<ul>{entries}</ul>',
entryTemplate: '<li>[{author}#{date}] {title}<br/>{shortBodyPlain}</li>',
tokens: {},
outputMode: 'json',
dateFormat: 'dddd MMM Do',
dateLocale: 'en',
effect: 'show',
offsetStart: false,
offsetEnd: false,
error: function () {
console.log('jQuery RSS: url doesn\'t link to RSS-Feed');
},
onData: function () {},
success: function () {}
}, options || {});
// The current SSL certificate is only valid for *.herokuapp.com
if (this.options.ssl && (this.options.host === 'www.feedrapp.info')) {
this.options.host = 'feedrapp.herokuapp.com';
}
this.callback = callback || this.options.success;
};
RSS.htmlTags = [
'doctype', 'html', 'head', 'title', 'base', 'link', 'meta', 'style', 'script', 'noscript',
'body', 'article', 'nav', 'aside', 'section', 'header', 'footer', 'h1-h6', 'hgroup', 'address',
'p', 'hr', 'pre', 'blockquote', 'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'figure', 'figcaption',
'div', 'table', 'caption', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'col', 'colgroup',
'form', 'fieldset', 'legend', 'label', 'input', 'button', 'select', 'datalist', 'optgroup',
'option', 'textarea', 'keygen', 'output', 'progress', 'meter', 'details', 'summary', 'command',
'menu', 'del', 'ins', 'img', 'iframe', 'embed', 'object', 'param', 'video', 'audio', 'source',
'canvas', 'track', 'map', 'area', 'a', 'em', 'strong', 'i', 'b', 'u', 's', 'small', 'abbr', 'q',
'cite', 'dfn', 'sub', 'sup', 'time', 'code', 'kbd', 'samp', 'var', 'mark', 'bdi', 'bdo', 'ruby',
'rt', 'rp', 'span', 'br', 'wbr'
];
RSS.prototype.load = function (callback) {
var apiProtocol = 'http' + (this.options.ssl ? 's' : '');
var apiHost = apiProtocol + '://' + this.options.host;
var apiUrl = apiHost + '?callback=?&q=' + encodeURIComponent(this.url);
// set limit to offsetEnd if offset has been set
if (this.options.offsetStart && this.options.offsetEnd) {
this.options.limit = this.options.offsetEnd;
}
if (this.options.limit !== null) {
apiUrl += '&num=' + this.options.limit;
}
if (this.options.key !== null) {
apiUrl += '&key=' + this.options.key;
}
$.getJSON(apiUrl, callback);
};
RSS.prototype.render = function () {
var self = this;
this.load(function (data) {
try {
self.feed = data.responseData.feed;
self.entries = data.responseData.feed.entries;
} catch (e) {
self.entries = [];
self.feed = null;
return self.options.error.call(self);
}
var html = self.generateHTMLForEntries();
self.target.append(html.layout);
if (html.entries.length !== 0) {
if ($.isFunction(self.options.onData)) {
self.options.onData.call(self);
}
self.appendEntriesAndApplyEffects($('entries', html.layout), html.entries);
}
if (self.effectQueue.length > 0) {
self.executeEffectQueue(self.callback);
} else if ($.isFunction(self.callback)) {
self.callback.call(self);
}
});
};
RSS.prototype.appendEntriesAndApplyEffects = function (target, entries) {
var self = this;
$.each(entries, function (idx, entry) {
var $html = self.wrapContent(entry);
if (self.options.effect === 'show') {
target.before($html);
} else {
$html.css({ display: 'none' });
target.before($html);
self.applyEffect($html, self.options.effect);
}
});
target.remove();
};
RSS.prototype.generateHTMLForEntries = function () {
var self = this;
var result = { entries: [], layout: null };
$(this.entries).each(function () {
var entry = this;
var offsetStart = self.options.offsetStart;
var offsetEnd = self.options.offsetEnd;
var evaluatedString;
// offset required
if (offsetStart && offsetEnd) {
if (index >= offsetStart && index <= offsetEnd) {
if (self.isRelevant(entry, result.entries)) {
evaluatedString = self.evaluateStringForEntry(
self.options.entryTemplate, entry
);
result.entries.push(evaluatedString);
}
}
} else {
// no offset
if (self.isRelevant(entry, result.entries)) {
evaluatedString = self.evaluateStringForEntry(
self.options.entryTemplate, entry
);
result.entries.push(evaluatedString);
}
}
});
if (!!this.options.entryTemplate) {
// we have an entryTemplate
result.layout = this.wrapContent(
this.options.layoutTemplate.replace('{entries}', '<entries></entries>')
);
} else {
// no entryTemplate available
result.layout = this.wrapContent('<div><entries></entries></div>');
}
return result;
};
RSS.prototype.wrapContent = function (content) {
if ($.trim(content).indexOf('<') !== 0) {
// the content has no html => create a surrounding div
return $('<div>' + content + '</div>');
} else {
// the content has html => don't touch it
return $(content);
}
};
RSS.prototype.applyEffect = function ($element, effect, callback) {
var self = this;
switch (effect) {
case 'slide':
$element.slideDown('slow', callback);
break;
case 'slideFast':
$element.slideDown(callback);
break;
case 'slideSynced':
self.effectQueue.push({ element: $element, effect: 'slide' });
break;
case 'slideFastSynced':
self.effectQueue.push({ element: $element, effect: 'slideFast' });
break;
}
};
RSS.prototype.executeEffectQueue = function (callback) {
var self = this;
this.effectQueue.reverse();
var executeEffectQueueItem = function () {
var item = self.effectQueue.pop();
if (item) {
self.applyEffect(item.element, item.effect, executeEffectQueueItem);
} else if (callback) {
callback();
}
};
executeEffectQueueItem();
};
RSS.prototype.evaluateStringForEntry = function (string, entry) {
var result = string;
var self = this;
$(string.match(/(\{.*?\})/g)).each(function () {
var token = this.toString();
result = result.replace(token, self.getValueForToken(token, entry));
});
return result;
};
RSS.prototype.isRelevant = function (entry, entries) {
var tokenMap = this.getTokenMap(entry);
if (this.options.filter) {
if (this.options.filterLimit && (this.options.filterLimit === entries.length)) {
return false;
} else {
return this.options.filter(entry, tokenMap);
}
} else {
return true;
}
};
RSS.prototype.getFormattedDate = function (dateString) {
// If a custom formatting function is provided, use that.
if (this.options.dateFormatFunction) {
return this.options.dateFormatFunction(dateString);
} else if (typeof moment !== 'undefined') {
// If moment.js is available and dateFormatFunction is not overriding it,
// use it to format the date.
var date = moment(new Date(dateString));
if (date.locale) {
date = date.locale(this.options.dateLocale);
} else {
date = date.lang(this.options.dateLocale);
}
return date.format(this.options.dateFormat);
} else {
// If all else fails, just use the date as-is.
return dateString;
}
};
RSS.prototype.getTokenMap = function (entry) {
if (!this.feedTokens) {
var feed = JSON.parse(JSON.stringify(this.feed));
delete feed.entries;
this.feedTokens = feed;
}
return $.extend({
feed: this.feedTokens,
url: entry.link,
author: entry.author,
date: this.getFormattedDate(entry.publishedDate),
title: entry.title,
body: entry.content,
shortBody: entry.contentSnippet,
bodyPlain: (function (entry) {
var result = entry.content
.replace(/<script[\\r\\\s\S]*<\/script>/mgi, '')
.replace(/<\/?[^>]+>/gi, '');
for (var i = 0; i < RSS.htmlTags.length; i++) {
result = result.replace(new RegExp('<' + RSS.htmlTags[i], 'gi'), '');
}
return result;
})(entry),
shortBodyPlain: entry.contentSnippet.replace(/<\/?[^>]+>/gi, ''),
index: $.inArray(entry, this.entries),
totalEntries: this.entries.length,
teaserImage: (function (entry) {
try {
return entry.content.match(/(<img.*?>)/gi)[0];
}
catch (e) {
return '';
}
})(entry),
teaserImageUrl: (function (entry) {
try {
return entry.content.match(/(<img.*?>)/gi)[0].match(/src="(.*?)"/)[1];
}
catch (e) {
return '';
}
})(entry)
}, this.options.tokens);
};
RSS.prototype.getValueForToken = function (_token, entry) {
var tokenMap = this.getTokenMap(entry);
var token = _token.replace(/[\{\}]/g, '');
var result = tokenMap[token];
if (typeof result !== 'undefined') {
return ((typeof result === 'function') ? result(entry, tokenMap) : result);
} else {
throw new Error('Unknown token: ' + _token + ', url:' + this.url);
}
};
$.fn.rss = function (url, options, callback) {
new RSS(this, url, options, callback).render();
return this; // Implement chaining
};
})(jQuery);
I think a better way would be to wrap that script in an angular module and load that module as a dependancy in your main app and use it anywhere you see fit.
Using ExtJs 4.2 with MVC pattern
I am trying to make a custom model, store, proxy, reader, writer but am having problems getting it to work in the MVC pattern. I followed this example to extend a model and I can see it working only if it is not used in the MVC way.
My store refers to a model such as Contacts defined in the model property, then Contacts refers to custom model WakandaModel using the model property. But when I create my store which refers to Contacts none of the model properties or proxy defined in the custom WakandaModel is brought over to the stores model.
Here is my code, I have left comments in so you can see what I have attempted to try. Thanks for any help!
App Code
Ext.Loader.setConfig({
enabled : true,
paths : {
'Ext.ux' : "lib/extux",
'Wakanda' : "lib/extux/wakanda"
}
});
Ext.application({
name : 'SimplyFundraising',
autoCreateViewport : true,
requires : ['Ext.ux.Router', // Require the UX
'Ext.window.MessageBox'],
controllers : ['Contacts'],
});
Custom Model
Ext.define('Wakanda.Model', {
extend: 'Ext.data.Model',
idProperty: '__KEY',
stampProperty: '__STAMP',
defaultProxyType: 'wakanda',
onClassExtended: function(cls, data) {
// debugger;
// cls.apply(this)
// var parts = data.$className.split('.');
// var entity = parts[2]
// var catalog = this.prototype.getCatalog(entity),
// attributes = catalog.attributes;
// for (var i = 0, l = attributes.length; i < l; i++) {
// if (attributes[i].name === 'ID') {
// attributes[i].persist = false;
// }
// }
// attributes.push({name: this.prototype.idProperty});
// attributes.push({name: this.prototype.stampProperty});
// // data.fields = attributes;
// // debugger;
// //this.setFields(data.fields)
// // var mymodel = Ext.ModelManager.getModel(data.$className);
// debugger;
// Ext.appy(this);
// //this.superclass.superclass.$onExtended.apply(this, arguments);
},
getCatalog: function(className) {
var catalog;
Ext.Ajax.request({
async: false,
url: 'http://127.0.0.1:8081/cors/$catalog/' + className,
success: function(response) {
catalog = Ext.decode(response.responseText);
}
});
return catalog;
}
});
Custom proxy
Ext.define('Wakanda.Proxy', {
extend: 'Ext.data.proxy.Rest',
// alternateClassName: 'SimplyFundraising.data.WakandaProxy',
alias : 'proxy.wakanda',
sortParam: '$orderby',
filterParam: '$filter',
startParam: '$skip',
limitParam: '$top',
// groupersParam: '$group',
reader: 'wakanda',
writer: 'wakanda',
actionMethods: {
create : 'POST',
read : 'GET',
update : 'POST',
destroy: 'POST'
},
buildUrl: function(request) {
debugger;
var modelName = this.model.modelName,
operation = request.operation,
records = operation.records || [],
record = records[0],
id = record ? record.getId() : operation.id,
url = '/cors/' + modelName,
action = request.action;
if (this.appendId && id && (action === 'read' || action === 'destroy')) {
url += '(' + id + ')';
}
request.url = url;
// console.log("buildUrl", this, arguments, request.url);
if (action !== 'read') {
if (action === 'create') action = 'update';
else if (action === 'destroy') action = 'delete';
url = Ext.urlAppend(url, '$method=' + action);
}
if (this.noCache) {
url = Ext.urlAppend(url, Ext.String.format("{0}={1}", this.cacheString, Ext.Date.now()));
}
return url;
},
encodeSorters: function(sorters) {
var min = [],
length = sorters.length,
i = 0, sort = '';
for (; i < length; i++) {
sort += sorters[i].property + ' ' + sorters[i].direction + ' ';
}
return sort;
},
encodeFilters: function(filters) {
var min = [],
length = filters.length,
i = 0, filter = '';
for (; i < length; i++) {
filter += filters[i].property + ' eq ' + filters[i].value + '# ';
}
return filter;
}
});
Custom reader
Ext.define('Wakanda.reader', {
extend: 'Ext.data.reader.Json',
//alternateClassName: 'SimplyFundraising.data.WakandaReader',
alias : 'reader.wakanda',
root: '__ENTITIES',
totalProperty: '__COUNT',
getData: function(data) {
if (Ext.isObject(data) && !data[this.root]) {
data = [data];
}
return data;
}
});
Custom writer
Ext.define('Wakanda.writer', {
extend: 'Ext.data.writer.Json',
// alternateClassName: 'SimplyFundraising.data.WakandaWriter',
alias: 'writer.wakanda',
writeAllFields: false,
getRecordData: function(record) {
var isPhantom = record.phantom === true,
writeAll = this.writeAllFields || isPhantom,
nameProperty = this.nameProperty,
fields = record.fields,
data = {},
changes,
name,
field,
key;
if (writeAll) {
// console.log("getRecordData1", this, arguments);
fields.each(function(field){
if (field.persist) {
name = field[nameProperty] || field.name;
data[name] = record.get(field.name);
} else {
}
});
} else {
changes = record.getChanges();
// console.log("getRecordData2", this, arguments, changes);
for (key in changes) {
if (changes.hasOwnProperty(key)) {
field = fields.get(key);
name = field[nameProperty] || field.name;
data[name] = changes[key];
}
}
if (!isPhantom) {
data[record.idProperty] = record.getId();
data[record.stampProperty] = record.get(record.stampProperty);
}
}
return {'__ENTITIES': [data]};
}
});
Contacts Model
Ext.define('SimplyFundraising.model.Contact', {
extend : 'Wakanda.Model' ,
//constructor: function() {
//alert(“Going to call parent’s overriden constructor…”);
// this.callParent(arguments);
// return this;
// }
});
Contacts Store
Ext.define('SimplyFundraising.store.Contacts', {
extend : 'Ext.data.Store',
model : 'SimplyFundraising.model.Contact',
autoLoad : true,
autoSync : true,
// constructor: function() {
// this.model = Ext.create('SimplyFundraising.model.Contact')
//alert(“Going to call parent’s overriden constructor…”);
// this.callParent(arguments);
return this;
// }
});
Contacts Controller
Ext.define('SimplyFundraising.controller.Contacts', {
extend : 'Ext.app.Controller',
models : ['Contact'],
views : ['contacts.List', 'contacts.Edit'],
init : function() {
this.control({
'contactslist' : {
itemdblclick : this.editContact,
removeitem : this.removeContact
},
'contactslist > toolbar > button[action=create]' : {
click : this.onCreateContact
},
// 'contactsadd button[action=save]': {
// click: this.doCreateContact
// },
'contactsedit button[action=save]' : {
click : this.updateContact
}
});
},
list : function() {
// var mystore = Ext.StoreMgr.lookup('Contacts');
// var myContact = this.getModel('Contact')
// var User = this.getModel('User');
//debugger;
// var mystore = Ext.create('SimplyFundraising.store.Contacts')
// var myContact = this.getModel('Contact').create()
// var bb = myContact.create()
// var rr = Ext.create('SimplyFundraising.model.Contact')
var mystore = Ext.create('SimplyFundraising.store.Contacts')
debugger;
// mystore.proxy.api.read = users.proxy.api.read + '(17)'
//mystore.proxy.extraParams = { $expand: 'ContactType'};
mystore.load();
//var test = Ext.ModelManager.getModel('Contact');
// //var User = this.getContactModel();
// User.load(258, {
// success: function(user) {
// console.log("Loaded user 258: " + user.get('lastName'));
// }
// });
},
editContact : function(grid, record) {
var view = Ext.widget('contactsedit');
view.down('form').loadRecord(record);
this.addnew = false
},
removeContact : function(Contact) {
Ext.Msg.confirm('Remove Contact ' + Contact.data.lastName, 'Are you sure?', function(button) {
if (button == 'yes') {
this.getContactsStore().remove(Contact);
}
}, this);
},
onCreateContact : function() {
var view = Ext.widget('contactsedit');
this.addnew = true
},
// doCreateContact: function (button) {
// var win = button.up('window'),
// form = win.down('form'),
// values = form.getValues(),
// store = this.getContactsStore();
// if (form.getForm().isValid()) {
// store.add(values);
// win.close();
// }
// },
updateContact : function(button) {
var win = button.up('window'), form = win.down('form'), record = form.getRecord(), values = form.getValues(), store = this.getContactsStore();
if (form.getForm().isValid()) {
if (this.addnew == true) {
store.add(values);
} else {
record.set(values);
}
win.close();
}
}
});
I got this working now:
It looks like my custom wakanda model,proxy,reader,writer where not loading. Still a bit confused on how MVC references classes and loads files and instantiates classes, which I asked in other question.
Any way the fix was to add a requires to the custom wakanda model and proxy
For the Wakanda model add requires: ['Wakanda.proxy'],
For Wakanda proxy add requires: ['Wakanda.reader', 'Wakanda.writer'],
now the inheritance is working as expected.