as3 socket with multi thread or background process in as3 socket - multithreading

my project using flex mobile 4.5 using socket .. receive huge data stream..
and ui application like hang... in minute before all process data complete
and how to do with multi thread in socket in as3 ? any axamples ?
any trick? to make background process
bellow my code
private var workQueue:Array = new Array();
/**************** VARIABLES ************************/
[Bindable]public var defauldSocketIP:String ="119.99.67.168";
[Bindable]public var defauldPort:Number = 9090;
[Bindable]public var heartbeatTime:Number = 1000 * 60;
[Bindable]public var limitLivetrade:Number = 30;
[Bindable]public var sessionid:String;
[Bindable]public var userid:String;
[Bindable]public var password:String;
[Bindable]public var msgdata:String;
[Bindable]public var busyIndicator:Boolean = false;
[Bindable]public var livetradeData:ArrayCollection = new ArrayCollection();
[Bindable]public var IndicesSectoralData:ArrayCollection = new ArrayCollection();
[Bindable]public var topGainerBrokerData:ArrayCollection = new ArrayCollection();
[Bindable]public var brokerData:ArrayCollection = new ArrayCollection();
[Bindable]public var stockData:ArrayCollection = new ArrayCollection();
[Bindable]public var marketChartData:ArrayCollection = new ArrayCollection();
/* best Quote */
[Bindable]public var bestQuoteDataA:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteDataB:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteBID:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteOFFER:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteTFREQ:ArrayCollection = new ArrayCollection();
[Bindable]public var stockSummarayData:ArrayCollection = new ArrayCollection();
/* end of best Quote */
[Bindable]public var tempDataSocket:ByteArray = new ByteArray();
[Bindable]public var sTemp:int = new int();
[Bindable]public var db:ArrayCollection = new ArrayCollection();
[Bindable]public var curentCode:String;//current code for unscribe
/**************** Socket ********************/
private var buffer:ByteArray = new ByteArray();
public var _data:ByteArray;
[Bindable]public var websocketData:String;
[Bindable]public var isLogin:Boolean = false;
public var flipTrans:FlipViewTransition = new FlipViewTransition();
\
/* socket connection */
public var socket : Socket;
public function init() : void {
//navigator.defaultPushTransition = new FlipViewTransition();
socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onSocketClose);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onSEC_ERRORError );
/****************** INTERVAL FOR PING SERVER *************/
var myInterval:uint = setInterval (heartbeat, heartbeatTime);
//clearInterval(myInterval);
if(isLogin){
flipTrans.duration = 1000;
flipTrans.mode = FlipViewTransitionMode.CARD;
flipTrans.direction = ViewTransitionDirection.RIGHT;
mainview.pushView(MainView,null,null,flipTrans);
}
/****************** Database setup *************/
initDB();
if(db.length == 0){ createDefauldConfig(); }
}
/**************** menus ********************/
/**************** alert information box *********************/
protected function alertSoketError():void
{
Alert.show(this, Alert.IC_INFO, "Information", "Sorry cannot connect to server please contact administrator.");
}
/**************** inquotes database ********************/
public var sqlConnection:SQLConnection;
public function onSEC_ERRORError( errorEvent:SecurityErrorEvent ):void
{
busyIndicator = false;
isLogin = false;
mainview.pushView(login);
trace( "onSEC_ERRORError: " + errorEvent );
alertSoketError();
}
public function onSocketClose(e:Event,reconect:Boolean = true):void{ resetData();
socket.close();
mainview.pushView(login);
trace("socket Closed");
if(reconect){
reconnect();
}
}
public function onIOError( errorEvent:IOErrorEvent ):void
{
busyIndicator = false;
isLogin = false;
mainview.pushView(login);
trace( "IOError: " + errorEvent.text );
alertSoketError();
}
public function onConnect(event : Event) : void {
trace("login|"+userid+"|"+(MD5.hash(password)));
sendData("login|"+userid+"|"+(MD5.hash(password)));
}
public function getFormattedTime(t:int):String
{
var s:String = new String();
var hour:String = t.toString().substr(0,2);
var minute:String = t.toString().substr(2,2);
var scn:String = t.toString().substr(4,5);
return s =hour+":"+minute+":"+scn;
}
public function checkTipe(data:String):void{
var split:Array = spliter.doSplit(data,"|");
/*Login */
if(split[0]=="login" && split[1]=="ok" && isLogin == false){
trace("split[0]"+split[0]+"-split[1]"+split[1]+"isLogin =="+isLogin);
sessionid = new String();
sessionid = split[2];
isLogin = true;
flipTrans.duration = 1000;
flipTrans.mode = FlipViewTransitionMode.CARD;
flipTrans.direction = ViewTransitionDirection.RIGHT;
mainview.pushView(MainView,null,null,flipTrans);
sendData("subscribe|"+sessionid+"|4|0");
sendData("subscribe|"+sessionid+"|3|0");
sendData("subscribe|"+sessionid+"|5|0");
}
/*Login fail*/
if(split[0]=="login" && split[1]!="ok"){
sessionid = new String();
Alert.show(this, Alert.IC_INFO, "Login", "Sorry Fail.. check your user name or password");
}
/*live trade */
if(split[1]=="2"){
curentCode = "2";
var change:Number = split[17] == 0 ? 0 : split[6] - split[17];
var obj:Object = new Object();
obj.header = split[0];
obj.type = split[1];
obj.seqno = split[2];
obj.time = FormatTime.getFormattedTime(split[3]);
obj.stock = split[4];
obj.board = split[5];
obj.last = split[6];
obj.lot = split[7];
obj.buyer = split[8];
obj.buy = split[9];
obj.seller = split[10];
obj.sell = split[11];
obj.bestbid = split[12];
obj.bestbidlot = split[13];
obj.bestoffer = split[14];
obj.bestofferlot = split[15];
obj.tradeno = split[16];
obj.previous = split[17];
obj.change = change;
obj.percent = Number((change * 100 ) / split[17]).toFixed(1);
if(livetradeData.length < limitLivetrade){
livetradeData.addItem(obj);
}else{
livetradeData.removeItemAt(livetradeData.length-1);
livetradeData.addItemAt(obj,0);
}
livetradeData.refresh();
}
if(split[1]=="6"){
curentCode = "6" ;
IndicesSectoralData = IndicesSectoral.setIndicesSectoral(split,IndicesSectoralData);
IndicesSectoralData.refresh();
}
if(split[1]=="TSBB"){
curentCode = "TSBB";
var obj:Object = new Object();
obj.header = split[0];
obj.type = split[1];
obj.seqno = split[2];
obj.min1 = split[3];
obj.min2 = split[4];
obj.BrokerID = split[5];
obj.min3 = split[6];
obj.BuyAvg = split[7];
obj.SellAvg = split[8];
obj.BuyVol = split[9];
obj.BuyVal = formater.formatMoneyUnit(Number(split[10]));
obj.BuyFreq = split[11];
obj.SellVol = split[12];
obj.SellVal = formater.formatMoneyUnit(split[13]);
obj.SellFreq = formater.formatMoneyUnit(split[14]);
obj.ValNet = formater.formatMoneyUnit((Number(split[10]) -
Number(split[13])));
obj.TotalVal = formater.formatMoneyUnit((Number(split[10]) +
Number(split[13])));
obj.TotalVol = formater.formatMoneyUnit((Number(split[9]) +
Number(split[12])));
obj.FreqTotal = formater.formatMoneyUnit((Number(split[11]) +
Number(split[14])));
/*header|type|seqno|-|-|BrokerID|-|BuyAvg|SellAvg|BuyVol|BuyVal|BuyFreq|SellVol|SellVal|SellFreq
ValNet = BuyVal - SellVal
TotalVal = BuyVal + SellVal
TotalVol = BuyVol + SellVol
FreqTotal = BuyFreq + SellFreq
Diurut Berdasarkan TotalVal*/
var brokerIndex:int = find.findIndex(brokerData,"BrokerID", split[5]);
if(brokerIndex != -1){
obj.BrokerName = brokerData.getItemAt(brokerIndex).BrokerName;
}
var idx:int = find.findIndex(topGainerBrokerData,"BrokerID", split[5]);
//trace("BrokerID:"+idx+"arr[5]"+arr[5]);
if(idx == -1){
topGainerBrokerData.addItem(obj);
}else{
topGainerBrokerData.removeItemAt(idx);
topGainerBrokerData.addItemAt(obj,idx);
}
ArrayCollection. */
//topGainerBrokerData.sort = numericDataSort;
topGainerBrokerData.refresh();
}
/*broker */
if(split[1]=="4"){
curentCode = "4";
brokerData = Broker.setBroker(split,brokerData);
brokerData.refresh();
}
/*Stock */
if(split[1]=="3"){
curentCode = "3";
var objStock:Object = new Object();
objStock.header = split[0];
objStock.type = split[1];
objStock.seqno = split[2];
objStock.stockcode = split[3];
objStock.stockname = split[4];
objStock.status = split[5];
objStock.stocktype = split[6];
objStock.sector = split[7];
objStock.ipoprice = split[8];
objStock.baseprice = split[9];
objStock.listedshares = split[10];
objStock.tradelistedshares = split[11];
objStock.shareperlot = split[12];
var idStock:int = find.findIndex(stockData,"stockcode", split[3]);
//trace("BrokerID:"+idx+"arr[5]"+arr[5]);
if(idStock == -1){
stockData.addItem(objStock);
}else{
stockData.removeItemAt(idStock);
stockData.addItemAt(objStock,idStock);
}
}
if(split[1]=="1"){
curentCode = "1" ;
trace("best Quote A:"+data+"\n");
/* best quote bid */
var XB:Array = spliter.doSplit(data,"<");
var bLotBid:String = XB[1].toString().substring(1,XB[1].toString().indexOf("]")-1);
trace("bLotBid:"+bLotBid);
if(bLotBid != ""){
bLotBid = bLotBid.substring(1,bLotBid.length);
var bLotBidArr:Array = spliter.doSplit(bLotBid,">");
var bInt:int;
for(bInt = 0; bInt < 10;bInt++){
if(bLotBidArr[bInt] != undefined){
trace("dipotong :"+bLotBidArr[bInt]);
var bBidDAT:Array = spliter.doSplit(bLotBidArr[bInt],"|");
var obLotBid:Object = new Object();
obLotBid.freq = formater.formatNumber(bBidDAT[0]);
obLotBid.lot = formater.formatNumber(bBidDAT[1]);
obLotBid.bid = formater.formatNumber(bBidDAT[2]);
bestQuoteBID.addItem(obLotBid);
}
}
}
/* best quote bid */
/* offer */
var bOFF:String =
XB[1].toString().substring(XB[1].toString().indexOf("O[")+2,XB[1].toString().indexOf("]L"));
trace("bOFF:"+bOFF);
var boffArr:Array = spliter.doSplit(bOFF,">");
var bIof:int;
for(bIof = 0; bIof < 10;bIof++){
if(boffArr[bIof] != undefined && boffArr[bIof] != ""){
trace("dipotong offer :"+boffArr[bIof]);
var boofDAT:Array = spliter.doSplit(boffArr[bIof],"|");
var obLotBidOFF:Object = new Object();
obLotBidOFF.offer = formater.formatNumber(boofDAT[0]);
obLotBidOFF.lot = formater.formatNumber(boofDAT[1]);
obLotBidOFF.o = formater.formatNumber(boofDAT[2]);
bestQuoteOFFER.addItem(obLotBidOFF);
}
}
}
// best Quote B //
if(split[1]=="TP"){
curentCode = "TP";
trace("best Quote TP:"+data+"\n");
//header|type|seqno|stock|board|price|T.Lot|T.Freq
var objTp:Object = new Object();
objTp.header = split[0];
objTp.type = split[1];
objTp.seqno = split[2];
objTp.stock = split[3];
objTp.board = split[4];
objTp.price = formater.formatNumber(split[5]);
objTp.Tlot = formater.formatNumber(split[6]);
objTp.Tfreq = formater.formatNumber(split[7]);
bestQuoteTFREQ.addItem(objTp);
}
/* stock summary */
if(split[1]=="5"){
//curentCode = "5" ;
var objStcSum:Object = new Object();
objStcSum.header = split[0];
objStcSum.type = split[1];
objStcSum.seqno = split[2];
objStcSum.code = split[3];
objStcSum.board = split[4];
objStcSum.remarks = split[5];
objStcSum.previous = split[6];
objStcSum.highest = split[7];
objStcSum.lowest = split[8];
objStcSum.closing = split[9];
objStcSum.change = split[10];
objStcSum.tradedvolume = split[11];
objStcSum.tradedvalue = split[12];
objStcSum.tradedfrequency = split[13];
objStcSum.individualindices = split[14];
objStcSum.foreigner = split[15];
objStcSum.opening = split[16];
objStcSum.bestbid = split[17];
objStcSum.bestbidvolume = split[18];
objStcSum.bestoffer = split[19];
objStcSum.bestoffervolume = split[20];
stockSummarayData.addItem(objStcSum);
var idStockSum:int = find.findIndex(stockSummarayData,"code", split[3]);
if(idStockSum == -1){
stockSummarayData.addItem(objStcSum);
}else{
stockSummarayData.removeItemAt(idStockSum);
stockSummarayData.addItemAt(objStcSum,idStock);
}
}
/* market chart */
//trace("COMPOSITE-->"+split[1]);
if(split[0]=="CHI" && split[1]=="COMPOSITE"){
curentCode = "COMPOSITE";
//trace("split[1]:"+split[1]+"split[2]:"+split[2]+"split[3]:"+split[3]+"split[4]:"+split[4]);
var mrc:Array = spliter.doSplit(split.toString(),"\n");
if(split[2]!= null){
var o:int;
for(o = 0;o < (mrc.length -1);o++){
var dtmrc:Array = spliter.doSplit(mrc[o],",");
var objMcht:Object = new Object();
if(o == 0){
objMcht.time = FormatTime.getFormattedTime(dtmrc[2]);
objMcht.timeUnformat = dtmrc[2];
objMcht.type = dtmrc[3];
objMcht.value = dtmrc[4];
trace("mrc[o]"+mrc[o]+"== dtmrc:"+dtmrc[0]);
trace("dtmrc[2]"+dtmrc[2]);
trace("MARKET CHART time 0-->"+FormatTime.getFormattedTime(dtmrc[2]));
}else{
objMcht.time = FormatTime.getFormattedTime(dtmrc[0]);
objMcht.timeUnformat = dtmrc[0];
objMcht.type = dtmrc[1];
objMcht.value = dtmrc[2];
//trace("dtmrc[0]"+dtmrc[0]);
//trace("MARKET CHART time1-->"+FormatTime.getFormattedTime(dtmrc[0]))+"-->value-->"+dtmrc[2];
}
marketChartData.addItem(objMcht);
}
//time|type|value
}
marketChartData.refresh();
}
}
public function onSocketData(event : ProgressEvent) : void {
busyIndicator = true;
var msgdataTemp:String = new String();
var n:int = socket.bytesAvailable;
var bArray:ByteArray = new ByteArray();
try{
//trace("n "+n.toString());
while(n > 0){
var p:int = socket.bytesAvailable;
var s:int = new int();
if(sTemp == 0){
if(p > 0)
p = socket.bytesAvailable;
try{
s = socket.readInt();//total
}catch(e:EOFError){
trace("err :"+e);
break;
}
p = socket.bytesAvailable;
//trace("bArray"+bArray.toString()+" s:"+s.toString()+" "+p);
if(s > p){
var bytex:ByteArray = new ByteArray();
socket.readBytes(bytex,0,p);
tempDataSocket.writeBytes(bytex,0,bytex.length);
sTemp = s;
break;
}
socket.readBytes(bArray,0,s);
bArray.uncompress(CompressionAlgorithm.ZLIB);
checkTipe(bArray.toString());
n = n-( 4+ s);
}else{
if(sTemp > p){
//bArray.writeBytes(tempDataSocket,0,bArray.length);
socket.readBytes(bArray,0,p);
tempDataSocket.writeBytes(bArray,0,bArray.length);
// trace("sTemp > p sTemp :"+sTemp+" S :"+s+" p:"+p+" n:"+n+" "+tempDataSocket.length);
sTemp = sTemp +s;
if(sTemp == tempDataSocket.length){
tempDataSocket.uncompress(CompressionAlgorithm.ZLIB);
checkTipe(tempDataSocket.toString());
}
break;
}
//trace("sTemp :"+sTemp+" S :"+s+" p:"+p+" n:"+n+" tempDataSocket :"+tempDataSocket.length+" bArray.length:"+bArray.length);
var bnew:ByteArray = new ByteArray();
if(socket.bytesAvailable > 0){
socket.readBytes(bArray,0,(sTemp - tempDataSocket.length));
}
//tempDataSocket.writeBytes(bArray,tempDataSocket.length,bArray.length);
//bnew.writeBytes(bArray,sTemp
bnew.writeBytes(tempDataSocket,0,tempDataSocket.length);
bnew.writeBytes(bArray,0,bArray.length);
bnew.uncompress(CompressionAlgorithm.ZLIB);
//trace("bnew:"+bnew.toString());
checkTipe(bnew.toString());
tempDataSocket = new ByteArray();
n = socket.bytesAvailable;
sTemp = 0;
}
p = socket.bytesAvailable;
if(p>0){
}
}
}catch(ev:Error){
trace("socket_error:"+ev.getStackTrace());
}finally{
}
}
public function resetData():void{
sessionid = "";
msgdata = "";
busyIndicator = false;
livetradeData = new ArrayCollection();
IndicesSectoralData = new ArrayCollection();
topGainerBrokerData = new ArrayCollection();
brokerData = new ArrayCollection();
stockData = new ArrayCollection();
marketChartData = new ArrayCollection();
bestQuoteDataA = new ArrayCollection();
bestQuoteDataB = new ArrayCollection();
bestQuoteBID = new ArrayCollection();
bestQuoteOFFER = new ArrayCollection();
bestQuoteTFREQ = new ArrayCollection();
stockSummarayData = new ArrayCollection();
tempDataSocket = new ByteArray();
sTemp = new int();
curentCode = "";//current code for unscribe
buffer = new ByteArray();
_data = new ByteArray();
websocketData = "";
isLogin = false;
}
public function trim( s:String ):String
{
return s.replace( /^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2" );
}
private function removeBufferBefore(pos:int):void {
if (pos == 0) return;
var nextBuffer:ByteArray = new ByteArray();
buffer.position = pos;
buffer.readBytes(nextBuffer);
buffer = nextBuffer;
}
public function unSubscribe():void{
if(curentCode != null && sessionid != null && curentCode != ""){
try{
socket.writeMultiByte("unsubscribe|"+sessionid+"|"+curentCode,"iso-8859-1");
socket.writeByte(0xff);
socket.flush();
}catch(e:flash.events.ErrorEvent){
Alert.show(this, Alert.IC_INFO, "Sorry..", e.text);
}
}
}
public function sendData(data:String):void{
busyIndicator = true;
unSubscribe();
socket.writeMultiByte(data,"iso-8859-1");
socket.writeByte(0xff);
socket.flush();
trace("sendData:"+data);
}
public function connect(useridx:String,passwordx:String) : void {
busyIndicator = true;
userid = useridx;
password = passwordx;
trace("userid:"+userid);
trace("password:"+password);
socket.connect(db.getItemAt(0).defauldIpAdress, db.getItemAt(0).defauldPort);
//threadedSocket();
}
]]>
</fx:Script>
<s:ViewNavigator label="Main" backgroundColor="0x000" id="mainview" width="100%" height="100%"
firstView="views.login" icon="#Embed('assets/home.png')"/>
<s:ViewNavigator label="Menu" backgroundColor="0x000" width="100%" height="100%" firstView="views.MenuView"
icon="#Embed('assets/menu.png')"/>
<s:ViewNavigator label="about" backgroundColor="0x000" width="100%" height="100%" firstView="views.aboutView"
icon="#Embed('assets/info.png')"/>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
<!--<mx:NumberFormatter
decimalSeparatorFrom="."
decimalSeparatorTo="."
precision="-1"
rounding="none|up|down|nearest"
thousandsSeparatorFrom=","
thousandsSeparatorTo=","
useNegativeSign="true|false"
useThousandsSeparator="true|false"/>-->
<mx:NumberFormatter id="fortmar1" precision="6"
rounding="none"
decimalSeparatorFrom="."
decimalSeparatorTo="."
thousandsSeparatorTo=","
thousandsSeparatorFrom=","
useThousandsSeparator="true"
useNegativeSign="true"
/>
</fx:Declarations>
</s:TabbedViewNavigatorApplication>

If you are stuck with an old version of the flash player, you need to search google for "Green Threads in AS3".
If you are using a newer version of the player, or Adobe AIR for desktop and devices, multithreading, via "actionscript workers", is available.

Related

Script works in Greasemonkey but not Tampermonkey

I've found a script that works within Greasemonkey on Firefox but doesn't work on Tampermonkey in Chrome. The only thing i've found online to try is changing "unsafewindow" to "window" as it doesnt work in chrome, which didnt work. Beyond that i have no idea and i'd really appreciate some help.
And i've gotta try and fill the wordcount because it wont let me post.
// ==UserScript==
// #name Haggler
// #version 1.1.0
// #namespace Shinzan
// #Description Neopets autohaggler
// #Match http://www.neopets.com/haggle.phtml*
// #Match http://www.neopets.com/haggle.phtml
// #include http://www.neopets.com/objects.phtml?obj_type=*&type=shop
// #include http://www.neopets.com/objects.phtml?type=shop&obj_type=*
// #require https://raw.githubusercontent.com/hectorvazc/jsfun/master/jsfun.min.js
// ==/UserScript==
var url = document.URL;
var OCR = true;
var return_ab = true;
var haggle_type = 1;
function solve_captcha(url, callback) {
var captcha = new Image();
captcha.src = url;
captcha.onload = function(){
var width = captcha.width;
var height = captcha.height;
var canvas = unsafeWindow.document.createElement('canvas');
canvas.width = width;
canvas.height = width;
canvas.getContext("2d").drawImage(captcha, 0, 0);
var imgData = canvas.getContext("2d").getImageData(0, 0, width, height);
var lowy = 999;
var lowx = 999;
var low = 999;
for (var x = 0; x < imgData.width; x++){
for (var y = 0; y < imgData.height; y++){
var i = x*4+y*4*imgData.width;
var avg = Math.floor((imgData.data[i]+imgData.data[i+1]+imgData.data[i+2])/3);
if (avg < low){
low = avg;
lowx = x;
lowy = y;
}
}
}
callback(lowx, lowy);
};
}
function smart_haggle(haggle_price){
var val = new Array(2);
val[0] = haggle_price.substr(0,1);
val[1] = haggle_price.substr(1,1);
var x = 0;
var end_price = "";
for(x=0; x<haggle_price.length; x++){
end_price += val[(x%2)];
}
return end_price;
}
function pctr_haggle(haggle_price){
var randomPer = (Math.floor(((Math.random()*10) + 90))/ 100);
return Math.floor(parseInt(haggle_price) * randomPer);
}
if(url === 'http://www.neopets.com/haggle.phtml'){
if(return_ab) js().getNode('input[type="submit"]')[1].click();
}else if(url.includes('objects.phtml')){
var content = js().getNode('table[align="center"][cellpadding="4"][border="0"]');
js().here(content).find('tr').each(function(tr){
js().here(tr).find('td').each(function(td){
var a = js().here(td).find('a').detach()[0];
js(a).removeAttribute('onclick');
js(td).insertFirst(a);
});
});
}else if(url.includes('haggle.phtml')){
var src = js().here('div[align=center]').getNode('img[width="450"][height="150"]');
var haggle_price = js().getNode('font')[2];
haggle_price = js().here(haggle_price).getNode('b')[3].innerHTML;
haggle_price = (haggle_price.match("([0-9-,]+)")[0]).replace(",", "");
var value = (haggle_type) == 1 ? smart_haggle(haggle_price) : pctr_haggle(haggle_price);
js().find('input[name=current_offer]').val(value);
if(OCR){
solve_captcha(document.querySelector('input[type="image"]').src, function(x, y) {
setTimeout(function(){
var haggleform = document.querySelector('form[name="haggleform"]');
var newInput = document.createElement("input");
var newInput2 = document.createElement("input");
newInput.type="hidden";
newInput.name="x";
newInput.value=x;
haggleform.appendChild(newInput);
newInput2.type="hidden";
newInput2.name="y";
newInput2.value=y;
haggleform.appendChild(newInput2);
haggleform.submit();
}, 500);
});
}
}

Add dimension between link and element

i am tried to find the link wall face,but when i use the reference to create a new dimension , i will get result about 'invaild number of references'. i cant trans link face to active face.
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;
var rf1 = uidoc.Selection.PickObject(ObjectType.PointOnElement, "select");
var element1 = doc.GetElement(rf1);
var location = element1.Location as LocationPoint;
var point = location.Point;
var rf2 = uidoc.Selection.PickObject(ObjectType.LinkedElement, "select");
var linkElement = doc.GetElement(rf2) as RevitLinkInstance;
var linkDoc = linkElement.GetLinkDocument();
var linkWall = linkDoc.GetElement(rf2.LinkedElementId) as Wall;
var wallLocation = linkWall.Location as LocationCurve;
var curve = wallLocation.Curve;
var cRf = curve.Reference;
var solid = BIMTools.Geometry.GetSolid(linkWall);
Face face = null;
foreach (var solidFace in solid.Faces)
{
XYZ normal = ((Face)solidFace).ComputeNormal(new UV(0, 0));
if (normal.Y < 0)
{
face = solidFace as Face;
break;
}
}
var viewLevel = uidoc.ActiveView.GenLevel.Elevation;
var tPoint = new XYZ(point.X,(face as PlanarFace).Origin.Y, viewLevel);
point = new XYZ(point.X, point.Y, viewLevel);
var line = Line.CreateBound(point, tPoint);
var references = new ReferenceArray();
references.Append(rf1);
references.Append(face.Reference);
using (Transaction trans = new Transaction(doc,"create"))
{
trans.Start();
var dimension = doc.Create.NewDimension(uidoc.ActiveView, line, references);
trans.Commit();
}
return Result.Succeeded;
}
The Building Coder provides a whole list of articles on creating dimensioning.

Acumatica - Where is the method that writes to CRRelation?

Can anyone help me find where in the code Acumatica writes to the CRRelation table when createing a Sales Order from an Opportunity? I've done a search for all instances of "CRRelation" but none of them seem to be doing the actual writing to the table.
It is done in the DoCreateSalesOrder(CreateSalesOrderFilter param) method which is called in the CreateSalesOrder action:
public PXAction<CROpportunity> createSalesOrder;
[PXUIField(DisplayName = Messages.CreateSalesOrder, MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Select)]
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
public virtual IEnumerable CreateSalesOrder(PXAdapter adapter)
{
foreach (CROpportunity opportunity in adapter.Get())
{
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>
.SelectSingleBound(this, new object[] { opportunity });
if (customer == null)
{
throw new PXException(Messages.ProspectNotCustomer);
}
var products = Products.View.SelectMultiBound(new object[] { opportunity }).RowCast<CROpportunityProducts>();
if (products.Any(_ => _.InventoryID == null) && !products.Any(_ => _.InventoryID != null))
{
throw new PXException(Messages.SalesOrderHasOnlyNonInventoryLines);
}
if (CreateOrderParams.AskExtFullyValid((graph, viewName) => { }, DialogAnswerType.Positive))
{
Save.Press();
PXLongOperation.StartOperation(this, delegate()
{
var grapph = PXGraph.CreateInstance<OpportunityMaint>();
grapph.Opportunity.Current = opportunity;
grapph.CreateOrderParams.Current = CreateOrderParams.Current;
grapph.DoCreateSalesOrder(CreateOrderParams.Current);
});
}
yield return opportunity;
}
}
if we look in that method we can find the following lines which are creating the relation:
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
You can find the full code of that method below:
protected virtual void DoCreateSalesOrder(CreateSalesOrderFilter param)
{
bool recalcAny = param.RecalculatePrices == true ||
param.RecalculateDiscounts == true ||
param.OverrideManualDiscounts == true ||
param.OverrideManualDocGroupDiscounts == true ||
param.OverrideManualPrices == true;
var opportunity = this.Opportunity.Current;
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>.Select(this);
SOOrderEntry docgraph = PXGraph.CreateInstance<SOOrderEntry>();
CurrencyInfo info = PXSelect<CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Current<CROpportunity.curyInfoID>>>>.Select(this);
info.CuryInfoID = null;
info = CurrencyInfo.GetEX(docgraph.currencyinfo.Insert(info.GetCM()));
SOOrder doc = new SOOrder();
doc.OrderType = CreateOrderParams.Current.OrderType ?? SOOrderTypeConstants.SalesOrder;
doc = docgraph.Document.Insert(doc);
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Search<SOOrder.orderNbr>(doc.OrderNbr));
doc.CuryInfoID = info.CuryInfoID;
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Update(doc));
doc.CuryID = info.CuryID;
doc.OrderDate = Accessinfo.BusinessDate;
doc.OrderDesc = opportunity.Subject;
doc.TermsID = customer.TermsID;
doc.CustomerID = opportunity.BAccountID;
doc.CustomerLocationID = opportunity.LocationID ?? customer.DefLocationID;
if (opportunity.TaxZoneID != null)
{
doc.TaxZoneID = opportunity.TaxZoneID;
if (!recalcAny)
{
SOTaxAttribute.SetTaxCalc<SOLine.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
SOTaxAttribute.SetTaxCalc<SOOrder.freightTaxCategoryID>(docgraph.Document.Cache, null,
TaxCalc.ManualCalc);
}
}
doc.ProjectID = opportunity.ProjectID;
doc.BranchID = opportunity.BranchID;
doc = docgraph.Document.Update(doc);
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
bool failed = false;
foreach (CROpportunityProducts product in SelectProducts(opportunity.QuoteNoteID))
{
if (product.SiteID == null)
{
InventoryItem item = (InventoryItem)PXSelectorAttribute.Select<CROpportunityProducts.inventoryID>(Products.Cache, product);
if (item != null && item.NonStockShip == true)
{
Products.Cache.RaiseExceptionHandling<CROpportunityProducts.siteID>(product, null,
new PXSetPropertyException(ErrorMessages.FieldIsEmpty, typeof(CROpportunityProducts.siteID).Name));
failed = true;
}
}
SOLine tran = new SOLine();
tran = docgraph.Transactions.Insert(tran);
if (tran != null)
{
tran.InventoryID = product.InventoryID;
tran.SubItemID = product.SubItemID;
tran.TranDesc = product.Descr;
tran.OrderQty = product.Quantity;
tran.UOM = product.UOM;
tran.CuryUnitPrice = product.CuryUnitPrice;
tran.TaxCategoryID = product.TaxCategoryID;
tran.SiteID = product.SiteID;
tran.IsFree = product.IsFree;
tran.ProjectID = product.ProjectID;
tran.TaskID = product.TaskID;
tran.CostCodeID = product.CostCodeID;
tran.ManualPrice = true;
tran.ManualDisc = true;
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
tran.POCreate = product.POCreate;
tran.VendorID = product.VendorID;
if (param.RecalculatePrices != true)
{
tran.ManualPrice = true;
}
else
{
if (param.OverrideManualPrices != true)
tran.ManualPrice = product.ManualPrice;
else
tran.ManualPrice = false;
}
if (param.RecalculateDiscounts != true)
{
tran.ManualDisc = true;
}
else
{
if (param.OverrideManualDiscounts != true)
tran.ManualDisc = product.ManualDisc;
else
tran.ManualDisc = false;
}
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
}
tran = docgraph.Transactions.Update(tran);
PXNoteAttribute.CopyNoteAndFiles(Products.Cache, product, docgraph.Transactions.Cache, tran,
Setup.Current);
}
PXNoteAttribute.CopyNoteAndFiles(Opportunity.Cache, opportunity, docgraph.Document.Cache, doc, Setup.Current);
if (failed)
throw new PXException(Messages.SiteNotDefined);
//Skip all customer dicounts
if (param.RecalculateDiscounts != true && param.OverrideManualDiscounts != true)
{
var discounts = new Dictionary<string, SOOrderDiscountDetail>();
foreach (SOOrderDiscountDetail discountDetail in docgraph.DiscountDetails.Select())
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(discountDetail, true);
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
discounts.Add(key, discountDetail);
}
Discount ext = this.GetExtension<Discount>();
foreach (CROpportunityDiscountDetail discountDetail in ext.DiscountDetails.Select())
{
SOOrderDiscountDetail detail;
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
if (discounts.TryGetValue(key, out detail))
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(detail, false);
if (discountDetail.IsManual == true && discountDetail.Type == DiscountType.Document)
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.extDiscCode>(detail, discountDetail.ExtDiscCode);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.description>(detail, discountDetail.Description);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.isManual>(detail, discountDetail.IsManual);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.curyDiscountAmt>(detail, discountDetail.CuryDiscountAmt);
}
}
else
{
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.CreateInstance();
detail.Type = discountDetail.Type;
detail.DiscountID = discountDetail.DiscountID;
detail.DiscountSequenceID = discountDetail.DiscountSequenceID;
detail.ExtDiscCode = discountDetail.ExtDiscCode;
detail.Description = discountDetail.Description;
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.Insert(detail);
if (discountDetail.IsManual == true && (discountDetail.Type == DiscountType.Document || discountDetail.Type == DiscountType.ExternalDocument))
{
detail.CuryDiscountAmt = discountDetail.CuryDiscountAmt;
detail.IsManual = discountDetail.IsManual;
docgraph.DiscountDetails.Cache.Update(detail);
}
}
}
SOOrder old_row = PXCache<SOOrder>.CreateCopy(docgraph.Document.Current);
docgraph.Document.Cache.SetValueExt<SOOrder.curyDiscTot>(docgraph.Document.Current, DiscountEngineProvider.GetEngineFor<SOLine, SOOrderDiscountDetail>().GetTotalGroupAndDocumentDiscount(docgraph.DiscountDetails));
docgraph.Document.Cache.RaiseRowUpdated(docgraph.Document.Current, old_row);
}
doc = docgraph.Document.Update(doc);
if (opportunity.TaxZoneID != null && !recalcAny)
{
foreach (CRTaxTran tax in PXSelect<CRTaxTran, Where<CRTaxTran.quoteID, Equal<Current<CROpportunity.quoteNoteID>>>>.Select(this))
{
SOTaxTran newtax = new SOTaxTran();
newtax.LineNbr = int.MaxValue;
newtax.TaxID = tax.TaxID;
newtax = docgraph.Taxes.Insert(newtax);
if (newtax != null)
{
newtax = PXCache<SOTaxTran>.CreateCopy(newtax);
newtax.TaxRate = tax.TaxRate;
newtax.CuryTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnshippedTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnshippedTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnbilledTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnbilledTaxAmt = tax.CuryTaxAmt;
newtax = docgraph.Taxes.Update(newtax);
}
}
}
if (opportunity.AllowOverrideContactAddress == true)
{
CRContact _CRContact = Opportunity_Contact.SelectSingle();
CRAddress _CRAddress = Opportunity_Address.SelectSingle();
// Insert
if (_CRContact != null)
{
SOBillingContact _billingContact = docgraph.Billing_Contact.Select();
if (_billingContact != null)
{
_billingContact.FullName = _CRContact.FullName;
_billingContact.Salutation = _CRContact.Salutation;
_billingContact.Phone1 = _CRContact.Phone1;
_billingContact.Email = _CRContact.Email;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
_billingContact.IsDefaultContact = false;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
}
}
if (_CRAddress != null)
{
SOBillingAddress _billingAddress = docgraph.Billing_Address.Select();
if (_billingAddress != null)
{
_billingAddress.AddressLine1 = _CRAddress.AddressLine1;
_billingAddress.AddressLine2 = _CRAddress.AddressLine2;
_billingAddress.City = _CRAddress.City;
_billingAddress.CountryID = _CRAddress.CountryID;
_billingAddress.State = _CRAddress.State;
_billingAddress.PostalCode = _CRAddress.PostalCode;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
_billingAddress.IsDefaultAddress = false;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
}
}
}
if (recalcAny)
{
docgraph.recalcdiscountsfilter.Current.OverrideManualPrices = param.OverrideManualPrices == true;
docgraph.recalcdiscountsfilter.Current.RecalcDiscounts = param.RecalculateDiscounts == true;
docgraph.recalcdiscountsfilter.Current.RecalcUnitPrices = param.RecalculatePrices == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDiscounts = param.OverrideManualDiscounts == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDocGroupDiscounts = param.OverrideManualDocGroupDiscounts == true;
docgraph.Actions[nameof(Discount.RecalculateDiscountsAction)].Press();
}
if (!this.IsContractBasedAPI)
throw new PXRedirectRequiredException(docgraph, "");
docgraph.Save.Press();
}
NOTE: you can find most part of the sources by the following path in the Acumatica's server folder App_Data\CodeRepository\PX.Objects,App_Data\CodeRepository\PX.Data,App_Data\CodeRepository\PX.Objects.FS

Error #1069: Property Pertanyaan0 not found on String and there is no default value

I stuck here please help, i'm new in flash, using adobe flash cs5.5
Here's the code :
import flash.net.URLLoaderDataFormat;
import flash.events.DataEvent;
stop();
alert_mc.visible = false;
alert_mc.ok_btn.visible = false;
var score:Number = 0;
var jawaban;
var nextQst:Number = 0;
var i:Number = 0;
a_btn.addEventListener(MouseEvent.CLICK,btna);
function btna(ev:MouseEvent):void
{
cekJawaban("a");
}
b_btn.addEventListener(MouseEvent.CLICK,btnb);
function btnb(ev:MouseEvent):void
{
cekJawaban("b");
}
c_btn.addEventListener(MouseEvent.CLICK,btnc);
function btnc(ev:MouseEvent):void
{
cekJawaban("c");
}
d_btn.addEventListener(MouseEvent.CLICK,btnd);
function btnd(ev:MouseEvent):void
{
cekJawaban("d");
}
var qvar_lv:URLLoader = new URLLoader();
qvar_lv.dataFormat = URLLoaderDataFormat.TEXT;// Step 1
qvar_lv.load(new URLRequest("DaftarSoal.txt")); // Step 2
qvar_lv.addEventListener(Event.COMPLETE, onComplete); // Step 3
function onComplete (event:Event):void // Step 4
{
var faq:String = event.target.data; // Step 5
trace("Success"+faq);
if (faq["Pertanyaan"+i] != undefined) {
no_txt.text = "PERTANYAAN KE-"+i;
soal_txt.text = faq["Pertanyaan"+i]; ja_txt.text = faq["a"+i];
jb_txt.text = faq["b"+i];
jc_txt.text = faq["c"+i];
jd_txt.text = faq["d"+i];
jawaban =faq["benar"+i];
} else {
gotoAndStop(3);
skor_txt.text = score+"";
teks_txt.text = "Score akhir kamu :";
}
}
function cekJawaban(val) {
alert_mc.visible = true;
if (val != jawaban) {
alert_mc.alert_txt.text = "jawaban kamu salah, score anda berkurang 50 points";
score = score-50;
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok);
function btnok(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
} else {
score = score+100;
alert_mc.alert_txt.text = "jawaban kamu benar, score anda bertambah 100 points";
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok2);
function btnok2(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
trace(score);
}
}
Error #1069:
Property Pertanyaan0 not found on String and there is no default value.
at revisi_fla::Symbol5_68/onComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()

trigger is called in beginning

I have a sound that gets triggered with OnTriggerEnter, and picking up whether sound is playing to turn sprite renderer on/off.
For some reason, when I start the game, the sound starts playing (which should only be getting called by the trigger).
I checked the trigger with the players tag and debug.log to console, and found that the trigger method isn't being called at the start. But, for some reason, the sound is getting played at the start and when I hit the trigger(but not turning the sprite renderer back on).
FlagScript
#pragma strict
var Sprite2 : Sprite; //second sprite to renderer
var sr : SpriteRenderer;
var hasBeenHit : boolean = false;
var flagCollisionSounderies: AudioSource;
var flagCollisionSound : AudioClip = null;
private var applauseRef: ApplauseScript;
private var go: GameObject;
var count : int = 0;
function Start () {
//access the spriteRenderer
flagCollisionSound = flagCollisionSounderies.clip;
sr = GetComponent(SpriteRenderer);
go = GameObject.Find("ClapMaster");
applauseRef = go.GetComponent(typeof(ApplauseScript));
//Debug.Log("bool: "+flagCollisionSounderies.isPlaying); //true already
}
function OnTriggerEnter2D(coll: Collider2D){
//Debug.Log("flagtriggered");
//change the flag to other flag
sr.sprite = Sprite2;
if (coll.gameObject.tag == "Player"){
Debug.Log("poos");
if (hasBeenHit == false){
GameMaster.setFlags(GameMaster.getFlags()-1);
GameMaster.addPointsToScore(100);
if (flagCollisionSound != null){
flagCollisionSounderies.PlayClipAtPoint(flagCollisionSound, transform.position);
//Debug.Log("bool:" + flagCollisionSounderies.isPlaying);
applauseRef.animRenderer.enabled = true;
}
}
}
hasBeenHit = true;
}
function Update(){
if(!flagCollisionSounderies.isPlaying){
applauseRef.animRenderer.enabled = false;
//applauseRef.playApplauseAnim = false;
}else{
//Debug.Log("sounderies detecteddFsdlfkjsdlfksjdflksdjflkj1123123");
applauseRef.animRenderer.enabled = true;
//applauseRef.playApplauseAnim = true;
}
}
Applause Script
#pragma strict
var SpriteLoad: Sprite[];
static var animSprites : Sprite[];
static var playerScriptRef: newplayer;
static var animRenderer: SpriteRenderer;
//private static var i : int = 7;
private static var frame : int = 3;
private static var Ymove: float = 0f;
private static var goingUp: boolean = false;
static var playApplauseAnim: boolean;
function Start(){
animRenderer = GetComponent(SpriteRenderer);
animSprites = SpriteLoad;
playerScriptRef = GameObject.Find("Player 1").GetComponent(newplayer);
//animRenderer.enabled = false;
//playApplauseAnim = false;
}
function Update(){
PicMover();
frame = (frame +1 ) % 4;
animRenderer.sprite = animSprites[frame];
}
static function PicMover(){
if(Ymove < 20 && goingUp){
Ymove++;
}else if(Ymove > -20 && !goingUp){
Ymove--;
}else if(Ymove == 20){
goingUp = false;
}else if(Ymove == -20){
goingUp = true;
}
animRenderer.transform.position = new Vector2(10,10);
}

Resources