AS3 Client - C# Server Socket Connection fail, - c#

Hi I'm working on a flash application. I'm sockets from Flash in Action-script 3 (CS5). Server is C# . My functions are nicely and great work and connect server with socket, when i export as projector (.exe). But when i export as .swf my functions are nicely work again but socket.connected return "false".
i added crossdomain.xml but still same problem.
Could you help me ?
Note: i found this page but i not load any data a external page :( .
here is my code
Edit: i didnt send to server but when i run .swf flash send a data to server
"<policy-file-request/>"
Connection Error[SecurityErrorEvent type="securityError" bubbles=false
cancelable=false eventPhase=2 text="Error #2048"]
but root include crossdomain.xml and i added this as3 kod but still problem is not solved.
Security.allowDomain("*");
Security.loadPolicyFile("http://MY-IP-ADDRESS/crossdomain.xml");
--lastest code
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.DisplayObject;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldType;
import flash.text.TextFieldAutoSize;
import flash.display.BitmapData;
import flash.geom.ColorTransform;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.net.FileReference;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.Socket;
import flash.display.BitmapData;
import flash.utils.setInterval;
import flash.system.* ;
import PNGEncoder;
public class Main extends MovieClip
{
/* Variables */
var aktarilan:BitmapData = new BitmapData(600,290);
/* Pencil Tool shape, everything drawed with this tool and eraser is stored inside board.pencilDraw */
var pencilDraw:Shape = new Shape();
/* Text format */
var textformat:TextFormat = new TextFormat();
/* Colors */
var colorsBmd:BitmapData;
var pixelValue:uint;
var activeColor:uint = 0x000000;
/* Save dialog instance */
var saveDialog:SaveDialog;
/* Active var, to check wich tool is active */
var active:String;
private static var fl_socket:Socket;
/* Shape size color */
var ct:ColorTransform = new ColorTransform();
private function onConnect(e:Event){
if(fl_socket.connected){
durum_bilgisi.text = "Connected to Server";
}else{
durum_bilgisi.text = "Connection Error";
}
}
public function Main():void
{
Security.allowDomain("*");
Security.loadPolicyFile("http://MY-IP-ADDRESS/crossdomain.xml");
fl_socket = new Socket();
fl_socket.addEventListener(Event.CONNECT, onConnect);
try{
fl_socket.connect("MY-IP-ADDRESS", 1234);
trace('Socket connection error');
}
catch(e:Error){
trace('Socket connection error ' + e.message );
durum_bilgisi.text = "Connection Error" + e.message;
}
textformat.font = "Quicksand Bold Regular";
textformat.bold = true;
textformat.size = 16;
// Soket baglantisi
convertToBMD();
addListeners();
/* Hide tools highlights */
pencil.visible = false;
hideTools(eraser, txt);
}
/* Pencil Tool */
private function PencilTool(e:MouseEvent):void
{
/* Quit active tool */
quitActiveTool();
/* Set to Active */
active = "Pencil";
/* Listeners */
board.addEventListener(MouseEvent.MOUSE_DOWN, startPencilTool);
board.addEventListener(MouseEvent.MOUSE_UP, stopPencilTool);
/* Highlight */
highlightTool(pencil);
hideTools(eraser, txt);
ct.color = activeColor;
shapeSize.transform.colorTransform = ct;
}
private function startPencilTool(e:MouseEvent):void
{
pencilDraw = new Shape();
board.addChild(pencilDraw);
pencilDraw.graphics.moveTo(mouseX, mouseY);
pencilDraw.graphics.lineStyle(shapeSize.width, activeColor, 1.0,true,"normal","round");
pencilDraw.graphics.lineTo(mouseX+1, mouseY+1);
board.addEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool);
}
private function drawPencilTool(e:MouseEvent):void
{
pencilDraw.graphics.lineTo(mouseX, mouseY);
}
private function stopPencilTool(e:MouseEvent):void
{
board.removeEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool);
}
/* Eraser Tool */
private function EraserTool(e:MouseEvent):void
{
var bmd:BitmapData = new BitmapData(600, 290);
bmd.draw(board);
var ba:ByteArray = PNGEncoder.encode(bmd);
/* Quit active tool */
quitActiveTool();
/* Set to Active */
active = "Eraser";
/* Listeners */
board.addEventListener(MouseEvent.MOUSE_DOWN, startEraserTool);
board.addEventListener(MouseEvent.MOUSE_UP, stopEraserTool);
/* Highlight */
highlightTool(eraser);
hideTools(pencil, txt);
ct.color = 0x000000;
shapeSize.transform.colorTransform = ct;
}
private function startEraserTool(e:MouseEvent):void
{
pencilDraw = new Shape();
board.addChild(pencilDraw);
pencilDraw.graphics.moveTo(mouseX, mouseY);
pencilDraw.graphics.lineStyle(shapeSize.width, 0xFFFFFF);
board.addEventListener(MouseEvent.MOUSE_MOVE, drawEraserTool);
}
private function drawEraserTool(e:MouseEvent):void
{
pencilDraw.graphics.lineTo(mouseX, mouseY);
}
function stopEraserTool(e:MouseEvent):void
{
board.removeEventListener(MouseEvent.MOUSE_MOVE, drawEraserTool);
}
/* Text Tool */
private function TextTool(e:MouseEvent):void
{
/* Quit active tool */
quitActiveTool();
/* Set to Active */
active = "Text";
/* Listener */
board.addEventListener(MouseEvent.MOUSE_UP, writeText);
/* Highlight */
highlightTool(txt);
hideTools(pencil, eraser);
}
private function writeText(e:MouseEvent):void
{
var textfield = new TextField();
textfield.type = TextFieldType.INPUT;
textfield.autoSize = TextFieldAutoSize.LEFT;
textfield.selectable = false;
textfield.defaultTextFormat = textformat;
textfield.textColor = activeColor;
textfield.x = mouseX;
textfield.y = mouseY;
stage.focus = textfield;
board.addChild(textfield);
}
/* Clear Tool */
private function clearBoard(e:MouseEvent):void
{
/* Create a blank rectangle on top of everything but board */
var blank:Shape = new Shape();
blank.graphics.beginFill(0xFFFFFF);
blank.graphics.drawRect(0, 0, board.width, board.height);
blank.graphics.endFill();
board.addChild(blank);
}
/* Default colors function */
private function convertToBMD():void
{
colorsBmd = new BitmapData(colors.width,colors.height);
colorsBmd.draw(colors);
}
private function chooseColor(e:MouseEvent):void
{
pixelValue = colorsBmd.getPixel(colors.mouseX,colors.mouseY);
activeColor = pixelValue;//uint can be RGB!
ct.color = activeColor;
shapeSize.transform.colorTransform = ct;
}
/* Quit active function */
private function quitActiveTool():void
{
switch (active)
{
case "Pencil" :
board.removeEventListener(MouseEvent.MOUSE_DOWN, startPencilTool);
board.removeEventListener(MouseEvent.MOUSE_UP, stopPencilTool);
case "Eraser" :
board.removeEventListener(MouseEvent.MOUSE_DOWN, startEraserTool);
board.removeEventListener(MouseEvent.MOUSE_UP, stopEraserTool);
case "Text" :
board.removeEventListener(MouseEvent.MOUSE_UP, writeText);
default :
}
}
/* Highlight active Tool */
private function highlightTool(tool:DisplayObject):void
{
tool.visible=true;
}
private function hideTools(tool1:DisplayObject, tool2:DisplayObject):void
{
tool1.visible=false;
tool2.visible=false;
}
/* Change shape size */
private function changeShapeSize(e:MouseEvent):void
{
if (shapeSize.width >= 50)
{
shapeSize.width = 1;
shapeSize.height = 1;
/* TextFormat */
textformat.size = 16;
}
else
{
shapeSize.width += 5;
shapeSize.height=shapeSize.width;
/* TextFormat */
textformat.size+=5;
}
}
private function addListeners():void
{
pencilTool.addEventListener(MouseEvent.MOUSE_UP, PencilTool);
eraserTool.addEventListener(MouseEvent.MOUSE_UP, EraserTool);
textTool.addEventListener(MouseEvent.MOUSE_UP, TextTool);
clearTool.addEventListener(MouseEvent.MOUSE_UP, clearBoard);
colors.addEventListener(MouseEvent.MOUSE_UP, chooseColor);
sizePanel.addEventListener(MouseEvent.MOUSE_UP, changeShapeSize);
shapeSize.addEventListener(MouseEvent.MOUSE_UP, changeShapeSize);
}
}

The code as you posted will not run.
// remove the following lines
fl_socket = new Socket();
fl_socket.connect("MY-IP-ADDRESS", 1234);
if(fl_socket.connected){durum_bilgisi.text = "Connected to Server";} else {durum_bilgisi.text = "Connection Error";}
// in the main function add this
fl_socket = new Socket();
fl_socket.addEventListener(Event.CONNECT, onConnect);
try{
fl_socket.connect("MY-IP-ADDRESS", 1234);
}catch(e:Error){
trace('Socket connection error ' + e.message )
}
// and lastly add this function
private function onConnect(e:Event){
if(fl_socket.connected){
durum_bilgisi.text = "Connected to Server";
}else{
durum_bilgisi.text = "Connection Error";
}

Related

Translate from C# to PROGRESS OPENEDGE ABL

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.

How can I scan a document using ASP.net MVC 5 with the help of Twain

Please help me out by sharing the step by step procedure to achieve the scanning functionality using Twain in ASP.Net MVC5. Thank you
Solution is here:
In ASP.Net/Core Project you send message to call winform project:
var start = function () {
var i = 0;
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://localhost:8181/');
ws.onmessage = function (e) {
$('#submit').hide();
$('#scanBtn').hide();
$('.loader').show();
if (typeof e.data === "string") {
//IF Received Data is String
}
else if (e.data instanceof ArrayBuffer) {
//IF Received Data is ArrayBuffer
}
else if (e.data instanceof Blob) {
i++;
var f = e.data;
f.name = "File" + i;
storedFiles.push(f);
formdata.append(f.name, f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div class=\"col-sm-2 text-center\"
style=\"border: 1px solid black; margin-left: 2px;\"><img
height=\"200px\" width=\"200px\" src=\"" + e.target.result + "\"
data-file='" + f.name + "' class='selFile' title='Click to
remove'><br/>" + i + "</div>";
selDiv.append(html);
$('#submit').show();
$('#scanBtn').show();
$('.loader').hide();
}
reader.readAsDataURL(f);
}
};
ws.onopen = function () {
//Do whatever u want when connected succesfully
};
ws.onclose = function () {
$('.dalert').modal('show');
};
}
window.onload = start;
function scanImage() {
ws.send("1100");
};
https://javascript.info/websocket
In Winforms Project you scan document and send graphic data back to Asp.Net/Core project:
public partial class Form1 : Form
{
ImageCodecInfo _tiffCodecInfo;
TwainSession _twain;
bool _stopScan;
bool _loadingCaps;
List allSockets;
WebSocketServer server;
public Form1()
{
InitializeComponent();
if (NTwain.PlatformInfo.Current.IsApp64Bit)
{
Text = Text + " (64bit)";
}
else
{
Text = Text + " (32bit)";
}
foreach (var enc in ImageCodecInfo.GetImageEncoders())
{
if (enc.MimeType == "image/tiff") { _tiffCodecInfo = enc; break; }
}
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
allSockets = new List<IWebSocketConnection>();
server = new WebSocketServer("ws://0.0.0.0:8181");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
if (message == "1100")
{
this.Invoke(new Action(()=> {
this.WindowState = FormWindowState.Normal;
}));
}
};
});
}
Link to project.
https://github.com/mgriit/ScanAppForWeb
You can remake this project, as you want.
At this moment, none of the browsers support scanning out of the box. You need to use a third-party library (not part of Microsoft's .NET core components). Below example uses Scanner.js, which is a product offered by our company:
Enable Scanning from TWAIN Scanners to ASP.NET Pages: Step by Step
Below steps use Scanner.js as example; they may differ for other products.
1) Include the scanning library in your HTML code:
<script type="text/javascript" src="//asprise.azureedge.net/scannerjs/scanner.js"></script>
2) Add a button to trigger the scanning process:
function scanToJpg() {
scanner.scan(displayImagesOnPage,
{
"twain_cap_setting" : {
"ICAP_PIXELTYPE" : "TWPT_RGB", // Color
"ICAP_XRESOLUTION" : "100", // DPI: 100
"ICAP_YRESOLUTION" : "100",
"ICAP_SUPPORTEDSIZES" : "TWSS_USLETTER" // Paper size: TWSS_USLETTER, TWSS_A4, ...
},
"output_settings" :
[
{
"type" : "return-base64",
"format" : "jpg"
}
]
}
);
}
3) Handle the scan result - display, upload, etc.
Below code creates an img element for each image scanned to display on the current web page:
/** Processes the scan result */
function displayImagesOnPage(successful, mesg, response) {
var scannedImages = scanner.getScannedImage(response, true, false); // returns an array of ScannedImage
for(var i = 0; (scannedImages instanceof Array) && i < scannedImages.length; i++) {
var scannedImage = scannedImages[i];
processScannedImage(scannedImage);
}
}
/** Images scanned so far. */
var imagesScanned = [];
/** Processes a ScannedImage */
function processScannedImage(scannedImage) {
imagesScanned.push(scannedImage);
var elementImg = createDomElementFromModel( {
'name': 'img',
'attributes': {
'class': 'scanned',
'src': scannedImage.src
}
});
document.getElementById('images').appendChild(elementImg);
}
For examples of scanning into PDF formats and direct uploading, please visit the code repository: https://github.com/Asprise/scannerjs.javascript-scanner-access-in-browsers-chrome-ie.scanner.js

OWC gives error on publish website

I have develop web App. I do not have office on server and want to deploy my publish folder over there.
Is Microsoft office is madatory for OWC?
If yes is there any way we can use it without excel installed?
using System.Web;
using System.IO;
using OWC11;
namespace AspNetResources.Owc
{
public partial class _default : System.Web.UI.Page
{
// ------------------------------------------------------------------
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
BuildCharts ();
}
// ------------------------------------------------------------------
private void BuildCharts ()
{
string[] chartCategoriesArr = new string [] {"Accord Coupe", "Accord Sedan", "Civic Coupe", "Civic Sedan", "Civic Si"};
string[] chartValuesArr = new string []{"19400", "15900", "13710", "13010", "19070"};
string chartCategoriesStr = String.Join ("\t", chartCategoriesArr);
string chartValuesStr = String.Join ("\t", chartValuesArr);
OWC11.ChartSpaceClass oChartSpace = new OWC11.ChartSpaceClass ();
OWC11.ChartChartTypeEnum chartType;
/*--------------------------------------------------------------
* Try using different char types just for fun
* -------------------------------------------------------------
chartType = ChartChartTypeEnum.chChartTypeArea;
chartType = ChartChartTypeEnum.chChartTypeArea3D;
chartType = ChartChartTypeEnum.chChartTypeBarClustered;
chartType = ChartChartTypeEnum.chChartTypeBar3D;
chartType = ChartChartTypeEnum.chChartTypeColumnClustered;
chartType = ChartChartTypeEnum.chChartTypeColumn3D;
chartType = ChartChartTypeEnum.chChartTypeDoughnut;
chartType = ChartChartTypeEnum.chChartTypeLineStacked;
chartType = ChartChartTypeEnum.chChartTypeLine3D;
chartType = ChartChartTypeEnum.chChartTypeLineMarkers;
chartType = ChartChartTypeEnum.chChartTypePie;
chartType = ChartChartTypeEnum.chChartTypePie3D;
chartType = ChartChartTypeEnum.chChartTypeRadarSmoothLine;
chartType = ChartChartTypeEnum.chChartTypeSmoothLine;
*/
// ------------------------------------------------------------------------
// Give pie and doughnut charts a legend on the bottom. For the rest of
// them let the control figure it out on its own.
// ------------------------------------------------------------------------
chartType = ChartChartTypeEnum.chChartTypeColumn3D;
if (chartType == ChartChartTypeEnum.chChartTypePie ||
chartType == ChartChartTypeEnum.chChartTypePie3D ||
chartType == ChartChartTypeEnum.chChartTypeDoughnut)
{
oChartSpace.HasChartSpaceLegend = true;
oChartSpace.ChartSpaceLegend.Position = ChartLegendPositionEnum.chLegendPositionBottom;
}
oChartSpace.Border.Color = "white";
oChartSpace.Charts.Add(0);
oChartSpace.Charts[0].HasTitle = true;
oChartSpace.Charts[0].Type = chartType;
oChartSpace.Charts[0].ChartDepth = 125;
oChartSpace.Charts[0].AspectRatio = 80;
oChartSpace.Charts[0].Title.Caption = "Pricing Of 2004 Hondas";
oChartSpace.Charts[0].Title.Font.Bold = true;
oChartSpace.Charts[0].SeriesCollection.Add(0);
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection.Add ();
// ------------------------------------------------------------------------
// If you're charting a pie or a variation thereof percentages make a lot
// more sense than values...
// ------------------------------------------------------------------------
if (chartType == ChartChartTypeEnum.chChartTypePie ||
chartType == ChartChartTypeEnum.chChartTypePie3D ||
chartType == ChartChartTypeEnum.chChartTypeDoughnut)
{
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasPercentage = true;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasValue = false;
}
// ------------------------------------------------------------------------
// Not so for other chart types where values have more meaning than
// percentages.
// ------------------------------------------------------------------------
else
{
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasPercentage = false;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasValue = true;
}
// ------------------------------------------------------------------------
// Plug your own visual bells and whistles here
// ------------------------------------------------------------------------
oChartSpace.Charts[0].SeriesCollection[0].Caption = String.Empty;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Name = "verdana";
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Size = 10;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Bold = true;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Color = "white";
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Position = ChartDataLabelPositionEnum.chLabelPositionCenter;
oChartSpace.Charts[0].SeriesCollection[0].SetData (OWC11.ChartDimensionsEnum.chDimCategories,
Convert.ToInt32(OWC11.ChartSpecialDataSourcesEnum.chDataLiteral), chartCategoriesStr);
oChartSpace.Charts[0].SeriesCollection[0].SetData (OWC11.ChartDimensionsEnum.chDimValues,
Convert.ToInt32(OWC11.ChartSpecialDataSourcesEnum.chDataLiteral), chartValuesStr);
// ------------------------------------------------------------------------
// Pick your favorite image format
// ------------------------------------------------------------------------
byte[] byteArr = (byte[]) oChartSpace.GetPicture ("png", 500, 500);
// ------------------------------------------------------------------------
// Store the chart image in Session to be picked up by an HttpHandler later
// ------------------------------------------------------------------------
HttpContext ctx = HttpContext.Current;
string chartID = Guid.NewGuid ().ToString ();
ctx.Session [chartID] = byteArr;
imgHondaLineup.ImageUrl = string.Concat ("chart.ashx?", chartID);
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
}
}
It gives error that
Server Error in '/owc' Application.
Could not load file or assembly 'owc' or one of its dependencies. An attempt was made to load a program with an incorrect format.
The error message means that the file owc.dll or one of it's references is missing.
Check whether the file is either:
in the bin folder of your web project (after publishing);
in the GAC (C:\windows\assembly).
If it does exist there, you can use Reflector, or similar products to see what the references of owc.dll are and you have to check those references too.

array returned from a web service to an android text view prints anyTpe{String instead of the values only

I want to print the array returned from a web service to an android text view. But when it prints the array it displays the results as "anyType{string=Shean;string=Ya;string=Hey;} instead of printing it as Shean Ya Hey.. any idea what im doing wrong?
The android code is as follows:
package com.example.fp1_webservicedropdown;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;
import org.ksoap2.*;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.*;
public class MainActivity extends Activity {
TextView result;
Spinner spinnerC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerC = (Spinner) findViewById(R.id.spinner1);
result = (TextView) findViewById(R.id.textView2);
final String NAMESPACE = "http://sample.com/";
final String METHOD_NAME = "GetCustomerList";
final String SOAP_ACTION = "http://sample.com/GetCustomerList";
final String URL = "http://10.113.28.241/HelloWorldNew/Service1.asmx";
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
// Request.addProperty("a", "32");
// Request.addProperty("b", "12");
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
AndroidHttpTransport aht = new AndroidHttpTransport(URL);
try {
aht.call(SOAP_ACTION, soapEnvelope);
SoapObject response = (SoapObject) soapEnvelope.bodyIn;
int intPropertyCount = response.getPropertyCount();
for (int i = 0; i < intPropertyCount; i++) {
SoapObject responseChild = (SoapObject) response.getProperty(i);
result.setText(responseChild.toString());
// You can add all strings in a list and give
// ArrayAdapter<String> for Spinner
}
/*
* result.setText("The web service returned " +
* resultString.toString());
*/
// ---------- result To Spinner Code -----------------------//
/*
* String[] toSpinner = new String[] { resultString.toString() };
* ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
* android.R.layout.simple_spinner_item, toSpinner);
* adapter.setDropDownViewResource
* (android.R.layout.simple_spinner_dropdown_item);
* spinnerC.setAdapter(adapter);
*/
// ---------- result To Spinner Code ends here -----------------//
} catch (Exception e) {
e.printStackTrace();
}
}
}
The web method is as follows:
[WebMethod]
public string[] GetCustomerList()
{
//substitute code to actually populate the array with the dataset data
string[] personIds = { "Shean", "Ya", "Hey" };
return personIds;
}
Does this work?
for (int i = 0; i < intPropertyCount; i++) {
SoapObject responseChild = (SoapObject) response.getProperty(i);
for (int j = 0; j < lengthOfResponseChild; j++)
result[j].setText(responseChild[j].toString());
}
}
This is just rough code. You may need to clean up to get the right functions and variables.

AS3 Socket/Server MMO Communication

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.

Categories

Resources