I received an C# DLL to access an API and another C# to invoke the DLL.
I'm trying to make an ABL program to INVOKE the DLL.
Ive tried the USING, also run it as an EXTERNAL but no luck.
Never used C#, but it looks like a very simple program can't find how to instatiate the DLL from ABL.
Thanks in advance,
Hugo
Here is the C# code, will appreciate any help
Code:
using System;
using System.Windows.Forms;
namespace CayanConnectSample
{
public partial class MainFrm : Form
{
public MainFrm()
{
InitializeComponent();
}
private string merchantName = "Test Dynamic Payments";
private string merchantSiteId = "2Q5JSJH3";
private string merchantKey = "GQPXT-GTJTP-66A1Y-RWT5G-CNULU";
private string terminalIPAddress = "192.168.1.32"; //ip address in CDI Technologies
private int requestTimeout = 60;
private void btnCreateTransaction_Click(object sender, EventArgs e)
{
decimal amount = Convert.ToDecimal(0.09);
string clerkId = "MIKE";
//only transactionType used are sale & refund
CayanConnect.CreateTransaction.Request request = new CayanConnect.CreateTransaction.Request()
{
MerchantName = merchantName,
MerchantSiteId = merchantSiteId,
MerchantKey = merchantKey,
TransactionType = CayanConnect.CreateTransaction.TransactionTypeEnum.SALE,
ClerkId = clerkId,
Dba = merchantName,
Amount = amount,
//[Amount] is always positive. TransactionType has the sign. Sale or Refund
OrderNumber = "1234"
};
CayanConnect.CreateTransaction createTrx = new CayanConnect.CreateTransaction();
CayanConnect.CreateTransaction.Response ctr = createTrx.Process(request, CayanConnect.ThemeEnum.None);
if (ctr.Success)
{
CayanConnect.InitiateTransaction it = new CayanConnect.InitiateTransaction(terminalIPAddress, ctr.TransportKey, null, CayanConnect.ThemeEnum.None, "Waiting for customer...");
CayanConnect.InitiateTransaction.Response response = it.Process(requestTimeout, true);
string emvDetail = response.EMVDetail;
bool approved = false;
if (response.Success)
{
//THERE IS NO TIMEOUT OR ERROR CALLING THE SERVICE
if (response.Status.ToUpper() == "APPROVED")
{
//AN AMOUNT HAS BEEN APPROVED
if (Convert.ToDecimal(Math.Abs(amount)) == response.AmountApproved)
{
//FULL AMOUNT APPROVED
approved = true;
txtResponse.Text = "Good to go!!";
}
else
{
//PARTIALLY APPROVED, HAS TO VOID THIS
string v = this.VoidApprovedTransaction(response.Token);
string em = v.IsEmpty() ? "Transaction was voided succesfully." : v;
txtResponse.Text = $"Invalid approved amount.{Environment.NewLine}Amount: {amount.ToString("C")}{Environment.NewLine}Approved Amount: {response.AmountApproved.ToString("c")}{em}";
}
}
else
{
//AMOUNT WAS DECLINED
txtResponse.Text = response.DeclinedMessage(amount);
}
}
else
{
//THERE WAS A PROBLEM CALLING THE SERVICE
txtResponse.Text = response.ErrorMessage;
}
}
else
{
//THERE WAS A PROBLEM CALLING THE SERVICE
txtResponse.Text = ctr.ErrorMessage;
}
}
private string GetStatus()
{
string rt = string.Empty;
CayanConnect.GetStatus status = new CayanConnect.GetStatus(this.terminalIPAddress, null, CayanConnect.ThemeEnum.None, "Verifying terminal status...");
CayanConnect.GetStatus.Response statusResponse = status.Process(this.requestTimeout);
rt = statusResponse.ToXml();
return rt;
}
private string VoidApprovedTransaction(string token)
{
string rt = string.Empty;
CayanConnect.Void _void = new CayanConnect.Void();
CayanConnect.Void.Request request = new CayanConnect.Void.Request()
{
MerchantName = this.merchantName,
MerchantKey = this.merchantKey,
MerchantSiteId = this.merchantSiteId,
Token = token,
Timeout = this.requestTimeout
};
CayanConnect.Void.Response response = _void.Process(request, CayanConnect.ThemeEnum.None);
if (!response.Success)
{
rt = $"Error voiding transaction.{Environment.NewLine}{Environment.NewLine}{response.ErrorMessage}";
}
return rt;
}
private void btnIsOnLine_Click(object sender, EventArgs e)
{
txtResponse.Text = GetStatus();
}
}
}
============================================================================
You don't need to 'invoke' the DLL. I have found that the DLL's doc is very important to read - you'll need to know things like who's in charge (ABL or the DLL) of memory allocation and deallocation, structure sizes etc. Also, the AVM is not re-entrant (so cannot be registered as a callback for any DLL).
For an example of calling DLL/SO functions from within an ABL class, take a look in the repo at https://github.com/PeterJudge-PSC/abl_odbc_api .
You'll need to create function prototypes (see an example at https://github.com/PeterJudge-PSC/abl_odbc_api/blob/master/src/OpenEdge/Data/ODBC/ODBCConnectionProto.i ) and you can then call those functions from within a method . Take a look at https://github.com/PeterJudge-PSC/abl_odbc_api/blob/master/src/OpenEdge/Data/ODBC/SqlCommonFunctions.cls for examples.
Related
When I check in my website using Paypal it gives me this message: "Checkout Error - Amount total mismatch" I used Microsoft tutorial to implement PayPal:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/checkout-and-payment-with-paypal
I did exactly what it said I even did twice but somehow keep getting this error Appreciate your help Thanks
public partial class CheckoutReview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
NVPAPICaller payPalCaller = new NVPAPICaller();
string retMsg = "";
string token = "";
string PayerID = "";
NVPCodec decoder = new NVPCodec();
token = Session["token"].ToString();
bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
if (ret)
{
Session["payerId"] = PayerID;
var myOrder = new Order();
myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
myOrder.Username = User.Identity.Name;
myOrder.FirstName = decoder["FIRSTNAME"].ToString();
myOrder.LastName = decoder["LASTNAME"].ToString();
myOrder.Address = decoder["SHIPTOSTREET"].ToString();
myOrder.City = decoder["SHIPTOCITY"].ToString();
myOrder.State = decoder["SHIPTOSTATE"].ToString();
myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
myOrder.Country = decoder["SHIPTOCOUNTRYCODE"].ToString();
myOrder.Email = decoder["EMAIL"].ToString();
myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());
// Verify total payment amount as set on CheckoutStart.aspx.
try
{
decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
{
Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
}
}
catch (Exception)
{
Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
}
// Get DB context.
ProductContext _db = new ProductContext();
// Add order to DB.
_db.Orders.Add(myOrder);
_db.SaveChanges();
// Get the shopping cart items and process them.
using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
{
List<CartItem> myOrderList = usersShoppingCart.GetCartItems();
// Add OrderDetail information to the DB for each product purchased.
for (int i = 0; i < myOrderList.Count; i++)
{
// Create a new OrderDetail object.
var myOrderDetail = new OrderDetail();
myOrderDetail.OrderId = myOrder.OrderId;
myOrderDetail.Username = User.Identity.Name;
myOrderDetail.ProductId = myOrderList[i].ProductId;
myOrderDetail.Quantity = myOrderList[i].Quantity;
myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;
// Add OrderDetail to DB.
_db.OrderDetails.Add(myOrderDetail);
_db.SaveChanges();
}
// Set OrderId.
Session["currentOrderId"] = myOrder.OrderId;
// Display Order information.
List<Order> orderList = new List<Order>();
orderList.Add(myOrder);
ShipInfo.DataSource = orderList;
ShipInfo.DataBind();
// Display OrderDetails.
OrderItemList.DataSource = myOrderList;
OrderItemList.DataBind();
}
}
else
{
Response.Redirect("CheckoutError.aspx?" + retMsg);
}
}
}
protected void CheckoutConfirm_Click(object sender, EventArgs e)
{
Session["userCheckoutCompleted"] = "true";
Response.Redirect("~/Checkout/CheckoutComplete.aspx");
}
}
I encountered the same problem while doing the tutorial, so here is my solution in case someone encounters it as well.
The main problem here is that Asp.NET displays the string versions of the amounts as XX,XX instead of XX.XX. This is because the .ToString()-function displays decimals as they are written in the current region.
To solve this problem, every .ToString() and Convert.ToDecimal() should be called with an extra parameter called CultureInfo.InvariantCulture, which ensures that the string amounts are stored in memory in the XX.XX-format.
I hope this helps someone in the future.
I'm trying to access Amazon MWS API from my .Net application, using Products API Section Client Library - C# (https://developer.amazonservices.com/doc/products/products/v20111001/cSharp.html/138-8219342-3408216)
Everything works fine, except for GetMyFeesEstimate calls.
I use this method from example:
public GetMyFeesEstimateResponse InvokeGetMyFeesEstimate()
{
// Create a request.
GetMyFeesEstimateRequest request = new GetMyFeesEstimateRequest();
string sellerId = "example";
request.SellerId = sellerId;
string mwsAuthToken = "example";
request.MWSAuthToken = mwsAuthToken;
FeesEstimateRequestList feesEstimateRequestList = new FeesEstimateRequestList();
request.FeesEstimateRequestList = feesEstimateRequestList;
return this.client.GetMyFeesEstimate(request);
}
And I add item to FeesEstimateRequestList like this:
feesEstimateRequestList.FeesEstimateRequest.Add(new FeesEstimateRequest
{
MarketplaceId = marketplaceId,
IdType = "ASIN",
IdValue = "B0078LENZC",
PriceToEstimateFees = new PriceToEstimateFees { ListingPrice = new MoneyType { Amount = 30.49M, CurrencyCode = "GBP" }, Shipping = new MoneyType { Amount = 3.5M, CurrencyCode = "GBP" }, Points = new Points { PointsNumber = 0 } },
Identifier = "request_" + Guid.NewGuid().ToString(),
IsAmazonFulfilled = false
});
But constantly get MalformedInput error with no message describing what is wrong:
<ErrorResponse
xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<Error>
<Type>Sender</Type>
<Code>MalformedInput</Code>
</Error>
<RequestId>f79b9147-90d7-4ea2-b51c-d6c37c6a1bd0</RequestId>
</ErrorResponse>
Have someone any ideas how to make it work?
I have found solution:
Due to my OS regional settings, decimal separator in price had being set to comma, instead of dot when converting parameters to string.
I have to modify method putValue of MwsAQCall class like this:
private void putValue(object value)
{
if (value==null)
{
return;
}
if (value is IMwsObject)
{
parameterPrefix.Append('.');
(value as IMwsObject).WriteFragmentTo(this);
return;
}
string name = parameterPrefix.ToString();
if (value is DateTime)
{
parameters.Add(name, MwsUtil.GetFormattedTimestamp((DateTime)value));
return;
}
string valueStr = value.ToString();
if (value is decimal)
{
valueStr = valueStr.Replace(",", ".");
}
if (valueStr==null || valueStr.Length==0)
{
return;
}
if (value is bool)
{
valueStr = valueStr.ToLower();
}
parameters.Add(name, valueStr);
}
Scenario
One windows service polls a url every two minutes to retrieve certain data.
If any data has been added since the previous call, the data is retrieved and stored otherwise the loop carries on.
Issue
Sometimes a request takes more than two minutes to return a response.
When this happens, the next request is still made and finds new data, since the previous request hasn't return a response yet
This results in duplicate entries when the data is stored.
What I've tried
I tried to handle that by using a boolean like so:
Boolean InProgress = true;
foreach (var item in Lists)
{
\\Make a request and return new data (if any)
InProgress = false;
if (InProgress = false)
{
\\Store new data
}
}
This doesn't solve the issue. I believe I'm using the boolean in wrong place, but I'm not sure where it should.
This is the loop that makes the request and store the data
void serviceTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
Data getCredentials = new Data();
DataTable credentials = getCredentials.loadCredentials();
Boolean InProgress = true;
for (int i = 0; i < credentials.Rows.Count; i++)
{
if (credentials != null)
{
var PBranchID = (int)credentials.Rows[i]["PortalBranchID"];
var negRef = (int)credentials.Rows[i]["NegotiatorRef"];
var Username = credentials.Rows[i]["Username"].ToString();
var Password = credentials.Rows[i]["Password"].ToString();
var Domain = credentials.Rows[i]["Domain"].ToString();
var FooCompanyBaseUrl = "https://" + Domain + ".FooCompany.com/";
Data getCalls = new Data();
DataTable calls = getCalls.loadCalls(PBranchID);
//If it's not the first call
if (calls != null && calls.Rows.Count > 0)
{
//Makes a call
DateTime CreatedSince = DateTime.SpecifyKind((DateTime)calls.Rows[0]["LastSuccessOn"], DateTimeKind.Local);
string IssueListUrl = FooCompany.WebApi.V2.URLs.Issues(BaseUrl, null, CreatedSince.ToUniversalTime(), null);
FooCompany.WebApi.V2.DTO.PrevNextPagedList resultIssueList;
resultIssueList = FooCompany.WebApi.Client.Helper.Utils.Getter<Foocompany.WebApi.V2.DTO.PrevNextPagedList>(IssueListUrl, Username, Password);
InProgress = false;
if (InProgress == false)
{
if (resultIssueList.Items.Count > 0)
{
//If call returns new issues, save call
Data saveCalls = new Data();
saveCalls.saveCalls(PBranchID);
foreach (var item in resultIssueList.Items)
{
var Issue = FooCompany.WebApi.Client.Helper.Utils.Getter<FooCompany.WebApi.V2.DTO.Issue>(item, Username, Password);
string TenantSurname = Issue.Surname;
string TenantEmail = Issue.EmailAddress;
Data tenants = new Data();
int tenantPropRef = Convert.ToInt32(tenants.loadTenantPropRef(PBranchID, TenantSurname, TenantEmail));
Data Properties = new Data();
DataTable propAddress = Properties.loadPropAddress(PBranchID, tenantPropRef);
var Address1 = propAddress.Rows[0]["Address1"];
var Address2 = propAddress.Rows[0]["Address2"];
var AddressFolder = Address1 + "," + Address2;
if (!Directory.Exists("path"))
{
Directory.CreateDirectory("path");
}
string ReportPDFDestination = "path";
if (File.Exists(ReportPDFDestination))
{
File.Delete(ReportPDFDestination);
}
FooCompany.WebApi.Client.Helper.Utils.DownloadFileAuthenticated(FooCompany.WebApi.V2.URLs.IssueReport(BaseUrl, Issue.Id), Username, Password, ReportPDFDestination);
//Store data
}
IssueListUrl = resultIssueList.NextURL;
}
}
}
else
{
continue;
}
}
}
catch (Exception ex)
{
//write to log
}
}
Question
I'm sure there is a better way than a boolean.
Could anyone advice a different method to handle the issue properly?
Thanks.
Solution
I ended up using a combination of both Thomas and Mason suggestions. I wrapped a lock statement around the main function of my windows service and used a boolean inside the function section that makes the call to the remote server.
Tested many times and it's error free.
You seems to have a problem of synchronisation, just surround the code that iterate though the List with a lock, and you will be fine.
public class MyClass{
private readonly object internalLock= new object();
private bool AlreadyRunning { get; set; }
void serviceTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if(AlreadyRunning){
return;
}
try{
lock(internalLock){
Thread.MemoryBarrier();
if(AlreadyRunning){
return;
}
AlreadyRunning = true;
...Do all the things...
}
}
catch(Exception e){
..Exception handling
}
finally
{
AlreadyRunning = false;
}
}
bool InProgress=false;
void serviceTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if(!InProgress)
{
InProgress=true;
//retrieve data
InProgress=false;
}
}
Your InProgress variable needs to be declared outside the event handler. When you enter the method, check to see if it's already running. If it is, then we do nothing. If it's not running, then we say it's running, retrieve our data, then reset our flag to say we've finished running.
You'll probably need to add appropriate locks for thread safety, similar to Thomas's answer.
Previously there the bing translator was easily accessible with the SOAP interface. Now it has been migrated to Windows Azure. I have registered in the Azure marketplace for 10000 letters per month (free). How can I translate text through the translator api, for windows phone in C#? Please help. I am not sure how to use the BeginExecute and EndExecute for queries.
I have downloaded and added the TranslatorContainer.cs to my project. For now I am just trying to get the Languages with the GetLanguagesForTranslation method. This is the code which I have written.
public partial class PhonePage1 : PhoneApplicationPage
{
public PhonePage1()
{
InitializeComponent();
Translator transInstance = new Translator();
}
class Translator
{
private Uri service_root;
private TranslatorContainer context;
public Translator()
{
service_root = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/");
context = new TranslatorContainer(service_root);
context.Credentials = new NetworkCredential("ID","...........");
var query = context.GetLanguagesForTranslation();
query.BeginExecute(OnQueryComplete, query);
}
public void OnQueryComplete(IAsyncResult result)
{
var query = result as DataServiceQuery<Language>;
string langstring = "";
foreach (Language lang in query.EndExecute(result))
{
langstring += lang.Code + "\n";
}
MessageBox.Show(langstring);
}
}
}
In OnQueryComplete() the query is null even after the assignment. The result has the Properties IsCompleted as true, and statusCode is OK.
I am not able to figure out how to go about this. Please help.
Thank you
With help from Bing Translator team I got it working in my Silverlight Application:
UseDefaultCredentials needs to be turned off on the proxy
On the async callback, you were casting the result to a DSQ, but it’s the result’s AsyncState that needs to be casted. See below.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var serviceUri = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/");
var accountKey = "**********************"; //
var tcode = new Microsoft.TranslatorContainer(serviceUri);
tcode.Credentials = new NetworkCredential(accountKey, accountKey);
tcode.UseDefaultCredentials = false;
var query = tcode.GetLanguagesForTranslation();
query.BeginExecute(OnQueryComplete, query);
}
public void OnQueryComplete(IAsyncResult result)
{
var query = (DataServiceQuery<Microsoft.Language>)result.AsyncState;
var enumerableLanguages = query.EndExecute(result);
string langstring = "";
foreach (Microsoft.Language lang in enumerableLanguages)
{
langstring += lang.Code + "\n";
}
MessageBox.Show(langstring);
}
This way you can use BeginExecute() and BeginEnd() to get Async results.
I had exact same problem and I was suggested that the issue may be related with the how the Async results are return internally when calling GetLanguagesForTranslation, however I did not dig further and just used Execute() to get the list of Language as below:
var serviceUri = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/");
var accountKey = "***********************"; //
var tcode = new TranslatorContainer(serviceUri);
tcode.Credentials = new NetworkCredential(accountKey, accountKey);
var languages = tcode.GetLanguagesForTranslation().Execute().ToArray();
foreach (var i in languages)
{
Console.WriteLine(i.Code);
}
Not sure if that is what you are looking for but it worked in my case well.
I'm working on a flash MMO with a c# server. I have a simple messaging protocol for the sockets. When a client joins he sends out this:
"%|clientId|need"
And positions are updated like this:
"$|clientId|xPosition|yPosition"
For some reason this isn't working. I store all the avatars in an array, the avatar class simply extends movieclip. This should add all clients into the room but it isn't working. Any ideas?
Edit: The error is probably in the client-side code above, I think it's with how I store the Avatars in an array.
Here is my code:
id.text = String(Math.random());
import flash.net.Socket;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
var avatars:Array = new Array();
var _socket:Socket = new Socket();
_socket.addEventListener(ProgressEvent.SOCKET_DATA,socketData);
_socket.addEventListener(Event.CONNECT,socketConnected);
_socket.addEventListener(IOErrorEvent.IO_ERROR,socketError);
_socket.connect("192.168.1.4",8000);
function sendText(msg:String):void {
if (_socket.connected) {
_socket.writeUTFBytes(msg);
_socket.flush();
} else {
}
}
function socketConnected(e:Event):void {
chat.appendText("Connected. \n");
sendText("%|" + id.text + "|need");
//chat.scrollV = chat.maxScrollV;
}
function socketError(e:IOErrorEvent):void {
chat.appendText("SYSTEM MSG:"+e.text+"\n");
//chat.scrollV = chat.maxScrollV;
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
//var xml:XML = new XML(str);
chat.appendText(str + "\n");
//[pos]|50|334
if(str.search("$")){
var positionArray = str.split("|");
avatars[str[1]].x = str[2];
avatars[str[1]].x = str[3];
}
if(str.search("%")){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
dump.text = miniArray[1];
}
}
me.addEventListener(MouseEvent.MOUSE_DOWN, drag);
me.addEventListener(MouseEvent.MOUSE_UP, sDrag);
var timing:Boolean = false;
var t:Timer = new Timer(1);
t.addEventListener(TimerEvent.TIMER, tick);
function tick(e:TimerEvent){
if(timing){
sendText('$|'+id.text+'|'+me.x+'|'+me.y);
}
else{
}
}
t.start();
function drag(e:MouseEvent){
me.startDrag();
timing = true;
}
function sDrag(e:MouseEvent){
me.stopDrag();
timing = false;
}
Edit: Changing answer based on additional information.
You had a few problems after addressing the code. First was your use of if(str.search)... The $ and % can be parsed as a regular expression. Additionally since your chars were at an index of 0 these if's could fail to be true. Lastly your were using str[1] instead of positionArray[1] etc. Below is the working code with some hacking to test without the use of a socket server. Might show you some tricks on how to do some focused testing when you run into issues like this.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
public class TestSocket extends Sprite
{
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.Dictionary;
import flash.utils.Timer;
[Embed(source="assets/avatar.png")]
private var Avatar:Class;
private var avatars:Array = new Array();
function TestSocket():void
{
socketSimulator(10);
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
if(str.indexOf("$") >= 0){
var positionArray = str.split("|");
avatars[positionArray[1]].x = positionArray[2];
avatars[positionArray[1]].x = positionArray[3];
}
if(str.indexOf("%") >= 0){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
}
}
/** Test Code **/
private var _numClients;
private function socketSimulator(numClients:int):void
{
_numClients = numClients;
var msg:String;
while(--numClients >= 0)
{
msg = "%|" + numClients + "|need";
sendFakeData(msg);
}
var timer:Timer = new Timer(500, 9999);
timer.addEventListener(TimerEvent.TIMER, sendFakeMovement);
timer.start();
}
private function sendFakeMovement(e:TimerEvent):void
{
var id:uint = Math.random() * _numClients;
var x:Number = Math.random() * 1000;
var y:Number = Math.random() * 1000;
var msg:String = "$|"+id+"|"+x+"|"+y;
sendFakeData(msg);
}
//This is just hacked test code, don't do this in production
private function sendFakeData(msg:String):void
{
var e:MyProgressEvent = new MyProgressEvent(ProgressEvent.SOCKET_DATA);
e.currentTarget = {
readUTFBytes: function(bytes:int = 0):String
{
return msg;
}
}
socketData(e);
}
}
}
import flash.events.ProgressEvent;
class MyProgressEvent extends ProgressEvent
{
private var _currentTarget:Object;
public function set currentTarget(val:Object):void
{
_currentTarget = val;
}
override public function get currentTarget():Object
{
return _currentTarget;
}
function MyProgressEvent(type:String):void
{
super(type);
}
}
Before you test log in/log off/position, make sure that your architecture supports sending and receiving data in the first place, I mean, send a string ("some data") on the front-end and check if you're really receiving ("some data") on the back-end. I am afraid the byte endianness that you're sending on the client is different from that on the server and so the server will mis-understand the incoming data. If so you need to convert the incoming messages to the suitable endianness before trying to process them.