My pattern is wrong, how do I make it DRY? - actionscript-3

So I got this TitleWindow based Flex application where these windows are called by static functions written in them.
This is how it looks like when an entity needs do be created or edited from a DataGrid:
private function incluir():void {
NavioForm.incluir(dg.dataProvider);
}
private function atualizar():void {
NavioForm.atualizar(dg.dataProvider, dg.selectedIndex);
}
It's working perfectly from this side.
But since I used static functions, the code is starting to get a bit repetitive, as we can see on the examples below:
[Script tag of a CRUD form(incluir == include, atualizar == update, excluir == delete)]
...
[Bindable] private var navio:Navio;
public static function incluir(dataList:IList):void {
var form:NavioForm = new NavioForm();
form.action = FormWindow.ACTION_NEW + Navio.name;
form.navio = new Navio();
form.navio.lastUpdate = new Date();
form.result = function():void {
PortoService.obj.persistirNavio(form.navio).result(function(navio:Navio):void {
dataList.addItem(navio);
form.close();
}).fault(function(event:FaultEvent):void {
if(event.fault.faultString == 'duplicate key') {
Util.showError("This vessel's IMO is already present in our database.");
} else throw event.fault;
});
};
PopUp.add(form);
}
public static function atualizar(dataList:IList, index:int):void {
var form:NavioForm = new NavioForm();
form.action = FormWindow.ACTION_UPDATE + Navio.name;
form.imoRecieved = true;
form.navio = dataList[index];
PortoService.obj.obter(Navio, form.navio.key).result(function(navio:Navio):void {
form.navio = navio;
form.navio.lastUpdate = new Date();
});
form.result = function():void {
PortoService.obj.persistir(form.navio).result(function(navio:Navio):void {
dataList[index] = navio;
form.close();
}).fault(function(event:FaultEvent):void {
if(event.fault.faultString == 'duplicate key') {
Util.showError("This vessel's IMO is already present in our database.");
} else throw event.fault;
});
};
PopUp.add(form);
}
...
Script tag of another CRUD form:
...
[Bindable] private var vesselType:VesselType;
public static function incluir(dataList:IList):void {
var form:VesselTypeForm = new VesselTypeForm();
form.action = FormWindow.ACTION_NEW + VesselType.name;
form.vesselType = new VesselType();
form.result = function():void {
CoreService.obj.persistir(form.vesselType).result(function(type:VesselType):void {
dataList.addItem(type);
form.close();
});
};
PopUp.add(form);
}
public static function atualizar(dataList:IList, index:int):void {
var form:VesselTypeForm = new VesselTypeForm();
form.action = FormWindow.ACTION_UPDATE + VesselType.name;
form.vesselType = Util.clone(dataList[index]);
form.result = function():void {
CoreService.obj.persistir(form.vesselType).result(function(type:VesselType):void {
dataList[index] = type;
form.close();
});
};
form.deleteClick = function():void {
CoreService.obj.excluir(form.vesselType.key).result(function():void {
dataList.removeItemAt(index);
form.close();
});
};
PopUp.add(form);
}
So, is there a design pattern or any other technique to make this work?

You could make a crud component that you instantiate with all of the dynamic stuff such as the data provider location and it broadcasts events (or signals) that you assign appropriate listeners to.

Related

Simple autocomplete with Ace Editor in AS3?

I'm working in XML and I'd like to provide autocomplete suggestions for the attributes for specific node types using AS3.
For example, if the user is has a cursor in the following node:
<s:Button label="Hello World"/>
I'd like autocomplete to show "width, height, x, y".
I'm trying to get the node name and namespace and then give the editor a list of attributes that should appear in autocomplete.
I found similar questions but those are using a service call and a few that are out dated. I may delete this question if it is a duplicate.
Ace Editor for AS3 here.
In my case, for AS3, it is a combination of items:
ace.setCompleters(null); // I'm removing existing autocomplete
ace.addCompleter(codeCompleter); // adding my own
public var autoCompleteErrorMessage:String = "Nothing available";
public function codeCompleter(editor:Object, session:Object, position:Object, prefix:String, callback:Function):void {
var row:int = position.row;
var column:int = position.column;
/*
if (prefix.length === 0) {
callback(null, []);
return;
}
*/
//var myList:Array = {value: "message", caption: "Caption to user", meta: "Type shown", score: "I don't know"};
var testing:Boolean = false;
if (testing) {
callback(autoCompleteErrorMessage, [{value:"addedToStage"},{value:"added"},{value:"adding"}]);
}
else {
callback(autoCompleteErrorMessage, attributes);
}
}
protected function cursorChangeHandler(event:Event):void {
var qname:QName = getQNameFromCursorPosition(ace.row, ace.column);
if (qname==null) {
if (attributes.length) {
attributes = [];
}
return;
}
if (qname) {
attributes = getSuggestionListFromObject(classObject);
autoCompleteErrorMessage = null;
lastSelectedQName = qname;
}
}
public static var XML_TAG_NAME:String = "meta.tag.tag-name.xml";
public static var XML_TAG_OPEN:String = "meta.tag.punctuation.tag-open.xml";
public static var XML_TAG_CLOSE:String = "meta.tag.punctuation.tag-close.xml";
public static var XML_ATTRIBUTE_NAME:String = "entity.other.attribute-name.xml";
public function getQNameFromCursorPosition(row:int, column:int):QName {
var token:Object;
var line:String;
var type:String;
var value:String;
var found:Boolean;
var qname:QName;
for (; row > -1; row--) {
line = ace.getLine(row);
column = line.length;
for (; column>-1; column--) {
token = ace.getTokenAt(row, column);
type = token ? token.type : "";
if (type==XML_TAG_NAME) {
value = token.value;
found = true;
}
}
if (found) break;
}
if (found) {
qname = new QName("", value);
}
return qname;
}
The getQNameFromCursorPosition() method is fragile and I'm looking into a new method using the jumpToMatching() method.

chrome cast on chrome not sending message

if (!chrome.cast || !chrome.cast.isAvailable) {
setTimeout(initializeCastApi, 1000);
}
function initializeCastApi() {
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
sessionListener,
receiverListener);
chrome.cast.initialize(apiConfig, onInitSuccess, onError);
};
function sessionListener(e) {
//this function doenot runs firsttime
appendMessage('New session ID:' + e.sessionId);
session = e;
session.addUpdateListener(sessionUpdateListener);
session.addMessageListener(namespace, receiverMessage);
console.log(receiverMessage);
}
sessionListener() function doenot gets called first time.when session get updaed it gets called.Why is it so?

How can I turn part of my casperjs script into a function so I can use it multiple times

Okay, so here is a part of my casperjs script below which works fine
if(casper.exists(ac1)){
var uel = "https://example.ws/send.html?f=1099817";
this.thenOpen(uel, function() {
casper.wait(10000, function() {
casper.then(function() {
this.evaluate(function() {
var amount = 0.29
var result = amount * 0.019
var result2 = result.toFixed(6);
var fresult = amount - result2;
var needed = fresult.toFixed(3);
document.getElementById('account').value = 'ydfg028';
document.getElementsByName('data')[0].value = needed;
});
this.click("input#sbt.button[type='submit']");
casper.wait(10000, function() {
casper.then(function() {
this.capture("filenadfgmedsfg.jpg");
var el2 = this.getHTML();
fs.write('results23.html', el2, 'w');
});
});
});
});
});
} else {
this.exit();
}
The problem I have is over 14 of the following statements
if(casper.exists()){
So what I am trying to do, is use the casperjs steps as a function. This is what I have tried below, but it just does nothing and casperjs ends when it reaches the function. Here's what I am trying
This is the casperjs function I have made
function casperstep(amount, user, location) {
var uel = "https://example.ws/send.html?f=" + location;
this.thenOpen(uel, function() {
casper.wait(10000, function() {
casper.then(function() {
this.evaluate(function() {
var result = amount * 0.019
var result2 = result.toFixed(6);
var fresult = amount - result2;
var needed = fresult.toFixed(3);
document.getElementById('account').value = user;
document.getElementsByName('data')[0].value = needed;
});
this.click("input#sbt.button[type='submit']");
casper.wait(10000, function() {
casper.then(function() {
this.capture("filenadfgmedsfg.jpg");
var el2 = this.getHTML();
fs.write('results23.html', el2, 'w');
});
});
});
});
});
}
Then when I try the following
if(casper.exists(ac1)){
casperstep(0.29, "username", "3245324");
}
it just does not work at all. The casper steps just do not fire. How can I fix this in theory? It should have worked.
What I have been trying with your answers...
My function
casper.captchaget = function (selector) {
var Loc = this.getHTML(selector, true).match(/src="(.*?)"/)[1];
var Ilocation = 'https://perfectmoney.is' + Loc;
var image = Loc;
var imagesplit = image.split ('?');
var split1 = imagesplit[1];
var string = split1 + ".jpg";
this.download(Ilocation, string);
}
and how I am trying to use it
casper.then(function(){
this.captchaget('img#cpt_img');//this.casperstep(0.29, "username", "3245324");
});
I tried the above to test out using casper extension.
Well, you want to add your own method to a casper object instance : http://casperjs.readthedocs.org/en/latest/extending.html
so :
casper.casperstep = function (amount, user, location) {
{your instructions....}
}
Then call it :
casper.start();
casper.then(function(){
if(casper.exists(ac1)){
casper.casperstep(0.29, "username", "3245324");//this.casperstep(0.29, "username", "3245324");
}
})
.run(function() {
test.done();
});
Old-monkey patching :)
To see other ways to do it : Custom casperjs modules

Decode/Encode .swf file

I have this .swf file: http://www.mediafire.com/download/hrr3c6c188jsgvd/upload.swf
I need to change something in this file, so I have this website http://www.showmycode.com/ decode the file and got those code:
if (!hasOwnProperty("_load05626E90")) {
_load05626E90 = true;
telltarget ("..") {
var copyright = function () {
telltarget ("..") {
geturl("http://www.google.com/search?q=PHP+Script+c-Image+Uploader+3.0", "_blank");
}
};
}
}
else {
// unexpected jump
}
var author = function () {
telltarget ("..") {
geturl("http://chiplove.biz", "_blank");
}
};
// unexpected jump
// unexpected jump
var uploadItem = function (num) {
telltarget ("..") {
var item = flash.net.FileReference(list[num]);
item.addlistener(listener2);
item.upload((((((((((("upload.php?watermark=" + watermark) + "&logo=") + logo) + "&resize=") + resize) + "&server=") + server) + "&q=") + q)+ "&account=") + account)+ "&password=") + password);
}
};
// unexpected jump
// unexpected jump
var FileChooser = function () {
telltarget ("..") {
var fileRef = new flash.net.FileReferenceList();
fileRef.addlistener(listener);
fileRef.browse(allTypes);
}
};
// unexpected jump
// unexpected jump
};
stop();
//---------------------------------------------------------------------- //Frame 1 //----------------------------------------------------------------------
this.menu = new contextmenu();
this.menu.hidebuiltinitems();
this.menu.customitems.push(new contextmenuitem("PHP Script - c-Image Uploader 3.0", copyright));
this.menu.customitems.push(new contextmenuitem("Powered by chiplove.9xpro", author));
//---------------------------------------------------------------------- //Symbol 3 Button //----------------------------------------------------------------------
on (press) {
var listener = new object();
var listener2 = new object();
var itemnum = 0;
var numfiles = 0;
delete _global.__resolve;
_global.__resolve = _global.__debugResolve;
if (list == undefined) {
var list = null;
}
var allTypes = new array();
var imageTypes = new object();
imageTypes.description = "Images (*.jpg; *.jpeg; *.jpe; *.gif; *.png;)";
imageTypes.extension = "*.jpg; *.JPG; *.jpeg; *.jpe; *.gif; *.png;";
allTypes.push(imageTypes);
listener.onselect = function (fileRefList) {
list = fileRefList.fileList; numfiles = list.length;
uploadItem(itemnum);
};
listener2.onOpen = function (file) { };
listener2.onProgress = function (file, bytesloaded, bytestotal) {
flash.external.ExternalInterface.call("loading");
};
listener2.onComplete = function (file) { };
listener2.onUploadCompleteData = function (file, data) {
var loadvars = new loadvars();
loadvars.decode(data);
flash.external.ExternalInterface.call("displaypic", file.name, loadvars.image);
itemnum = itemnum + 1;
if (itemnum < numfiles) {
uploadItem(itemnum);
}
else {
flash.external.ExternalInterface.call("responseStatus", "Done!");
}
};
flash.external.ExternalInterface.addCallBack("FileChooser", this, FileChooser);
flash.external.ExternalInterface.call("clearlist");
FileChooser();
}
I think this is Action Script code, so after make some little change I get flash builder to recompile it, however, flash builder show a lot of red underline (syntax error) in my code and can't build those code to .swf file again. I wonder if the code I got from showmycode.com is correct, or is it action script? If the code I got from showmycode.com is not correct, how can I decode, edit, then encode again that "upload.swf" file?

Client-Side Validation for entire model using MVC 3 (unobtrusive ajax)

I've got client-side validation working for individual properties, however, I would like to validate at the model level (2 or more properties) using client-side validation.
I'm using #Html.ValidationSummary(true) to display the validation error for the Model attribute that I created.
However, when the model error is generated, it doesn't display a message. It prevents the action from being made, but no error is displayed.
Anybody know why this would be the case?
My hunch is that it has something to do with client-side validation since server-side doesn't work in this case since I have to use an Ajax form.
Any advice would be appreciated!
Model Attribute
public class AuditDetailValidatorAttribute : ValidationAttribute, IClientValidatable
{
public AuditDetailValidatorAttribute()
{
ErrorMessage = "Must select an NCN level...";
}
public override bool IsValid(object value)
{
AuditRequirementDetail audit = value as AuditRequirementDetail;
if (audit == null || audit.AuditResult.Id == 0 || audit.AssessmentLevel.Id == 0)
{
return true;
}
else
{
return !(audit.AuditResult.Id == 4 && audit.AssessmentLevel.Id == 1);
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new List<ModelClientValidationRule>
{
new ModelClientValidationRule
{
ValidationType = "required",
ErrorMessage = this.ErrorMessage
}
};
}
}
Model Class
[AuditDetailValidator]
public class AuditRequirementDetail
{
// Constructor
public AuditRequirementDetail()
{
// instantiate the contained objects on AuditRequirementDetail creation
AssessmentLevel = new AssessmentLevel();
AuditResult = new AuditResult();
Requirement = new RequirementDetail();
Attachment = new Attachment();
Counter = 0;
}
/* rest of the code */
}
View
#model pdiqc.Models.AuditRequirement.AuditRequirementDetail
#{
var SuccessTarget = "success" + Model.DetailID;
var IsValidTarget = "IsValid" + Model.DetailID;
var PerformCompletedTarget = "PerformCompleted" + Model.DetailID;
var AuditResultTarget = "AuditResult_Id" + Model.DetailID;
var AssessmentLevelTarget = "AssessmentLevel_Id" + Model.DetailID;
var DesignatorTarget = "Designator_Id" + Model.DetailID;
var EvidenceTarget = "Evidence_Id" + Model.DetailID;
var AttachmentTarget = "Attachments_Id" + Model.DetailID;
var AuditResultReferral = "#" + AuditResultTarget;
var AssessmentLevelReferral = "#" + AssessmentLevelTarget;
var DesignatorReferral = "#" + DesignatorTarget;
var EvidenceReferral = "#" + EvidenceTarget;
var AttachmentReferral = "#" + AttachmentTarget;
}
#using (Ajax.BeginForm("PerformRequirement", "Audit", new AjaxOptions { HttpMethod = "POST", OnSuccess = "success" }, new {Class="PerformReqForm" }))
{
#Html.ValidationSummary(true)
if ((Model.AuditResult.Id == 1 && Model.AssessmentLevel.Id > 1) || Model.Evidence == string.Empty || Model.Evidence == null)
{
<input class="#IsValidTarget" name="IsValid" type="hidden" value=false />
}
else
{
<input class="#IsValidTarget" name="IsValid" type="hidden" value=true />
}
<p class="reqText">#Model.RequirementLabel.ConfigurableLabelDesc ##ViewBag.PerformCounter - #ModelMetadata.FromLambdaExpression(x => x.Requirement.Text, ViewData).SimpleDisplayText</p>
<div class="hide">
/* REST OF CODE */
}
I wrote a custom validator for a checkbox to make sure it was cheeked and had to do the following.
<script type="text/javascript">
$(function() {
$.validator.unobtrusive.adapters.addBool('requiredcheckbox', 'required');
}(jQuery));
</script>
Also include #Html.ValidationMessageFor(x=>x.yourProp)