What will cause a SecurityErrorEvent? - apache-flex

I'm executing the following command:
var chatRequest:URLRequest = new URLRequest("http://test.com/videophonetest/scripts/get_put_peerID.php?peerID=" + myID);
chatLoader = new URLLoader(chatRequest);
configureListenersChatLoader(chatLoader);
chatLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
chatLoader.load(chatRequest);
configureListenersChatLoader(chatLoader) and friends looks like:
private function configureListenersDeleteLoader(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandlerDeleteLoader);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandlerChatLoader(event:Event):void {
writeText("Completed Connection!");
var urlVariables:URLVariables = new URLVariables(chatLoader.data);
writeText("Your ID: " + myID);
theirID = urlVariables.peerID;
writeText("Their ID: " + theirID);
}
private function completeHandlerDeleteLoader(event:Event):void {
writeText("Deletion Complete!");
var urlVariables:URLVariables = new URLVariables(deleteLoader.data);
writeText("Deleted: " + urlVariables.deleted);
writeText("Getting New Chat...");
initNewChatSession();
}
private function openHandler(event:Event):void {
writeText("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
writeText("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
writeText("securityErrorHandler: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
writeText("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
writeText("ioErrorHandler: " + event);
}
The command works on my computer but when I try it on my roommates computer it returns an error:
httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=0 responseURL=null]
securityErrorHandler: [SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048"]
Any reason why this might be happening? It works on some computers but not others. Firewalls?

You will need to allow the location of the file on your friends' computer in this settings manager:
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html

Related

AtmosphereHandler - Chat: I get "undefined" when I send a message

I am having trouble with this example of chat: https://github.com/Atmosphere/atmosphere/wiki/Getting-Started-with-AtmosphereHandler,-WebSocket-and-Long-Polling
In this simple example is used an implemetation of AtmosphereHandler to create a chat application.
How you could see from the pic below, i don't see what i have wrote but only an "undefined" message. Why? Where is the error?
Thank you a lot.
web.xml:
<display-name>AtmoChat</display-name>
<description>Atmosphere Chat</description>
<servlet>
<description>AtmosphereServlet</description>
<servlet-name>AtmosphereServlet</servlet-name>
<servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
<!-- limit classpath scanning to speed up starting, not mandatory -->
<init-param>
<param-name>org.atmosphere.cpr.packages</param-name>
<param-value>org.atmosphere.samples</param-value>
</init-param>
<init-param>
<param-name>org.atmosphere.interceptor.HeartbeatInterceptor.clientHeartbeatFrequencyInSeconds</param-name>
<param-value>10</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>AtmosphereServlet</servlet-name>
<url-pattern>/chat/*</url-pattern>
</servlet-mapping>
application.js:
$(function () {
"use strict";
var header = $('#header');
var content = $('#content');
var input = $('#input');
var status = $('#status');
var myName = false;
var author = null;
var logged = false;
var socket = atmosphere;
var subSocket;
var transport = 'websocket';
// We are now ready to cut the request
var request = { url: 'http://myLink/' + 'chat',
contentType : "application/json",
logLevel : 'debug',
transport : transport ,
trackMessageLength : true,
reconnectInterval : 5000 };
request.onOpen = function(response) {
content.html($('<p>', { text: 'Atmosphere connected using ' + response.transport }));
input.removeAttr('disabled').focus();
status.text('Choose name:');
transport = response.transport;
// Carry the UUID. This is required if you want to call subscribe(request) again.
request.uuid = response.request.uuid;
};
request.onClientTimeout = function(r) {
content.html($('<p>', { text: 'Client closed the connection after a timeout. Reconnecting in ' + request.reconnectInterval }));
subSocket.push(atmosphere.util.stringifyJSON({ author: author, message: 'is inactive and closed the connection. Will reconnect in ' + request.reconnectInterval }));
input.attr('disabled', 'disabled');
setTimeout(function (){
subSocket = socket.subscribe(request);
}, request.reconnectInterval);
};
request.onReopen = function(response) {
input.removeAttr('disabled').focus();
content.html($('<p>', { text: 'Atmosphere re-connected using ' + response.transport }));
};
// For demonstration of how you can customize the fallbackTransport using the onTransportFailure function
request.onTransportFailure = function(errorMsg, request) {
atmosphere.util.info(errorMsg);
request.fallbackTransport = "long-polling";
header.html($('<h3>', { text: 'Atmosphere Chat. Default transport is WebSocket, fallback is ' + request.fallbackTransport }));
};
request.onMessage = function (response) {
var message = response.responseBody;
try {
var json = atmosphere.util.parseJSON(message);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message);
return;
}
input.removeAttr('disabled').focus();
if (!logged && myName) {
logged = true;
status.text(myName + ': ').css('color', 'blue');
} else {
var me = json.author == author;
var date = typeof(json.time) == 'string' ? parseInt(json.time) : json.time;
addMessage(json.author, json.message, me ? 'blue' : 'black', new Date(date));
}
};
request.onClose = function(response) {
content.html($('<p>', { text: 'Server closed the connection after a timeout' }));
if (subSocket) {
subSocket.push(atmosphere.util.stringifyJSON({ author: author, message: 'disconnecting' }));
}
input.attr('disabled', 'disabled');
};
request.onError = function(response) {
content.html($('<p>', { text: 'Sorry, but there\'s some problem with your '
+ 'socket or the server is down' }));
logged = false;
};
request.onReconnect = function(request, response) {
content.html($('<p>', { text: 'Connection lost, trying to reconnect. Trying to reconnect ' + request.reconnectInterval}));
input.attr('disabled', 'disabled');
};
subSocket = socket.subscribe(request);
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
// First message is always the author's name
if (author == null) {
author = msg;
}
subSocket.push(atmosphere.util.stringifyJSON({ author: author, message: msg }));
$(this).val('');
input.attr('disabled', 'disabled');
if (myName === false) {
myName = msg;
}
}
});
function addMessage(author, message, color, datetime) {
content.append('<p><span style="color:' + color + '">' + author + '</span> # ' +
+ (datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours()) + ':'
+ (datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes())
+ ': ' + message + '</p>');
}});
Ok. For now, I don't see any trouble about your "onMessage" method in your javascript code. Your javascript code is based on simple chat room from documentation of atmosphere-js. So, your code is correct.
I need to see your Java code for how you send object message to client app. I need also to see your class Java representing the model object message to send.
Maybe, the value of message attribute from object model class is null or empty. That's why you have "undefined" value in your message field.
Your model java class must be like :
public class ChatMessage {
private String message;
private String author;
private long time = System.currentTimeMillis();
public ChatMessage(){
this("","");
}
public ChatMessage(String author, String message) {
this.author = author;
this.message = message;
this.time = new Date().getTime();
}
public String getMessage(){
return message;
}
public String getAuthor(){
return author;
}
public void setAuthor(String author){
this.author = author;
}
public void setMessage(String message){
this.message = message;
}
public long getTime(){
return time;
}
public void setTime(long time){
this.time = time;
}
}
Here's an class Java to manage a chat application :
import java.io.IOException;
import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Message;
import org.atmosphere.config.service.PathParam;
import org.atmosphere.config.service.Ready;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple annotated class that demonstrate the power of Atmosphere. This class
* supports all transports, support message length guarantee, heart beat,
* message cache thanks to the #ManagedService.
*/
#ManagedService(path = "/chatRoom/{room_id}")
public final class ChatRoom {
private static final Logger logger = LoggerFactory.getLogger(ChatRoom.class);
#PathParam("room_id")
private String chatRoomId;
/**
* Invoked when the connection as been fully established and suspended, e.g
* ready for receiving messages.
*
* #param r
* the atmosphere resource
* #return
*/
#Ready
public final void onReady(final AtmosphereResource r) {
logger.info("Browser {} connected.", r.uuid());
}
/**
* Invoked when the client disconnect or when an unexpected closing of the
* underlying connection happens.
*
* #param event
* the event
* #throws IOException
*/
#Disconnect
public final void onDisconnect(final AtmosphereResourceEvent event) throws IOException {
if (event.isCancelled()) {
logger.info("Browser {} unexpectedly disconnected", event.getResource().uuid());
}
else if (event.isClosedByClient()) {
logger.info("Browser {} closed the connection", event.getResource().uuid());
}
}
/**
* Simple annotated class that demonstrate how
* {#link org.atmosphere.config.managed.Encoder} and {#link org.atmosphere.config.managed.Decoder
* can be used.
*
* #param message an instance of {#link ChatMessage }
* #return the chat message
*/
#Message(encoders = { ChatMessageEncoderDecoder.class }, decoders = { ChatMessageEncoderDecoder.class })
public final ChatMessage onMessage(final ChatMessage message) {
logger.info("{} just send {}", message.getAuthor(), message.getMessage());
return message;
}
}

Client side event is not calling for " Clients.Group(groupName).MessageReceived(UserName, message, groupName); "

Hub class
public void sendToAll(string UserName,string message,string grpId,string groupName,string UserId)
{
if (grpId == "3")
{
//This is working
Clients.All.MessageReceived(UserName, message, groupName);
}
if (grpId == "4")
{ //This is not working
Clients.Group(groupName).MessageReceived(UserName,message,groupName);
}
}
Client side:
$('#btnSendToAll').click(function () {
var GrpId = $(this).parent().attr('groupid');
var GrpName = $(this).parent().attr('groupname1');
chat.server.sendToAll($("#hdnUserName").val(), $('#txtMsg').val(), GrpId, GrpName, $("#hdnUserId").val());
$('#dvGroupChat', $(this).parent()).find('ul').append($('#txtMsg').val());
$('#message').val('').focus();
});
chat.client.messageReceived = function (name, message, groupType) {
$('div[groupname1=' + groupType + ']').find('ul').append('<ul>' + name + ': ' + message + '');
};

CometD Issues with Publishing Data to a Channel

I am new to cometd, I have planned to send a message to the server and get the message in my browser using cometd
If i send a message it is successfully send to the server but couldn't get it in the browser
private void testService() {
String channelName = "/service/out";
log.info("Channel Name = " + channelName);
log.info("bayeuxServer : " + (bayeuxServer == null ? "Is Null" : "Is Not Null"));
System.out.println("CHANNELS : " + bayeuxServer.getChannels().toString());
System.out.println("Subscribers on /service/in = "+bayeuxServer.getChannel("/service/in").getSubscribers().toString());
System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());
// convert to cometd format
Map<String, Object> data = new HashMap<String, Object>(4);
data.put("serverMsg", getDetails());
ServerChannel channel = bayeuxServer.getChannel(channelName);
subscribers = channel.getSubscribers().size();
log.info("Subscribers = " + subscribers);
log.info("channel = " + channel);
channel.publish(sender, data, null);
System.out.println("Session subscriptions :" + sender.getServerSession().getSubscriptions());
System.out.println("Listeners on /service/out = "+bayeuxServer.getChannel("/service/out").getListeners().toString());
System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());
}
But this one is not working
#Subscription("/service/out")
public void echo(Message message)
{
System.out.println("Echo service published " + message);
}
Logs:
1
7:48:18,775 INFO ClientHelloService [] Bayeux server =org.cometd.server.BayeuxServerImpl#1436088
17:48:18,775 INFO ClientHelloService [] Message = Hello world
17:48:18,775 INFO ClientHelloService [] remote Client Id = 3renjdwk25ercglzli36tudpl
17:48:18,776 INFO ClientHelloService [] Local session = L:_21w17u5f3mvvluvp71c27yaqvt
17:48:18,776 INFO ClientHelloService [] session = 3renjdwk25ercglzli36tudpl - last connect 1 ms ago
17:48:18,776 INFO ClientHelloService [] Channel Name = /service/out
17:48:18,776 INFO ClientHelloService [] bayeuxServer : Is Not Null
CHANNELS : [/service/out, /meta/subscribe, /service, /service/*, /meta, /meta/handshake, /meta/disconnect, /service/in, /meta/connect, /meta/unsubscribe]
Subscribers on /service/in = []
Subscribers on /service/out = []
17:48:18,777 INFO ClientHelloService [] msg = Hello world
17:48:18,777 INFO ClientHelloService [] Subscribers = 0
17:48:18,777 INFO ClientHelloService [] channel = /service/out
17:48:18,777 DEBUG 21192840 [] < {data={serverMsg=Hello world}, channel=/service/out}
17:48:18,777 INFO ClientHelloService [] publish the channel
Session subscriptions :[]
Listeners on /service/out = []
Subscribers on /service/out = []
Application.js
var sendChannel = '/service/in'; // Message from jsp
var receiveChannel = '/service/*'; // Message from server
/*var cometdServerURL = 'http://127.0.0.1:8080/cometd';*/
require(['dojox/cometd', 'dojo/dom', 'dojo/domReady!'], function(cometd, dom)
{ // // configuration object
// cometd.websocketEnabled = true;
// Open connection to CometD server
cometd.configure({
url: location.protocol + '//' + location.host + config.contextPath + '/cometd',
logLevel: 'debug'
});
cometd.addListener('/meta/*', function(message)
{
if (message.successful)
{
dom.byId('status').innerHTML += '<div>CometD handshake successful</div>';
cometd.subscribe(receiveChannel, function(message) {
dom.byId('results').innerHTML +=' Message from server ' + message.data;
dom.byId('results').innerHTML +=' Subscription to ' + receiveChannel;
});
}
else if(_connectionBroken()){
dom.byId('status').innerHTML += '<div>CometD Connection Broken</div>';
}
else
{
dom.byId('status').innerHTML += '<div>CometD handshake failed</div>';
}
});
dom.byId('greeter').onclick = function()
{
var text = dom.byId('msg').value;
cometd.publish(sendChannel, 'Hello world');
dom.byId('msg').value = "" ;
dom.byId('results').innerHTML +='Message send to server' ;
};
cometd.handshake();
});
There are several mistakes in your code, addressed below.
First, you don't want in your javascript to add a listener to /meta/* to handle subscriptions in the if (message.successful) branch. That branch will be executed for any meta message response, for example also for responses to subscriptions (that are sent over /meta/subscribe), executing the code multiple times when that is not the intention.
Change the listener to listen to /meta/handshake channel and perform the subscription in that listener.
Likewise you want to execute the if (_connectionBroken()) branch in a /meta/connect listener.
Please refer to the primer to build a proper skeleton of your application.
Also, follow the tutorials to better understand the roles of your listeners.
Second, it is not recommended that you subscribe, from the client, to service channels.
Have a read at the CometD concepts to understand the difference between a service channel and a broadcast channel, and about the difference between adding a listener and subscribing.
Third, when you have service channel, publish() is a local activity, so no message will be delivered to remote clients. The right API to use in this case is ServerSession.deliver(...), if you really want to use service channels.
Finally, your use case is covered by the tutorials, so I recommend you follow those and your application will work.
Hope that helped.
var sendChannel = '/service/in'; // Message from jsp
var receiveChannel = '/service/out'; // Message from server
/*var cometdServerURL = 'http://127.0.0.1:8080/cometd';*/
require(['dojox/cometd', 'dojo/dom', 'dojo/domReady!','dojo/_base/unload'], function(cometd, dom)
{ // // configuration object
// Open connection to CometD server
cometd.configure({
url: location.protocol + '//' + location.host + config.contextPath + '/cometd',
logLevel: 'debug'
});
cometd.addListener('/meta/connect', function(message) {
var wasConnected;
if(cometd.isDisconnected()) {
dom.byId('status').innerHTML +=' Disconnected from the server = ' + message;
} else{
/* dom.byId('status').innerHTML +=' Disconnected from the server = ' + message.data;*/
}
});
// listener for handshake
cometd.addListener('/meta/handshake', function(message)
{
if (message.successful)
{
dom.byId('status').innerHTML += '<div>CometD handshake successful</div>';
cometd.batch(function()
{
cometd.subscribe(receiveChannel, function(message) {
dom.byId('results').innerHTML +=' Message from server ' + message.data;
dom.byId('results').innerHTML +=' Subscription to ' + receiveChannel;
});
// cometd.publish('/service/in', { name: 'World' });
});
}
else if(_connectionBroken()){
dom.byId('status').innerHTML += '<div>CometD Connection Broken</div>';
}
else
{
dom.byId('status').innerHTML += '<div>CometD handshake failed</div>';
}
});
dom.byId('greeter').onclick = function()
{
var text = dom.byId('msg').value;
cometd.publish(sendChannel, 'Hello world');
dom.byId('msg').value = "" ;
dom.byId('results').innerHTML +='Message send to server' ;
};
cometd.handshake();
});
Now also couldnt publish to the channels
#Service
public class ClientHelloService {
static Logger log = Logger.getLogger(
ClientHelloService.class.getName());
String details;
#Inject
private BayeuxServer bayeuxServer;
#Session
private LocalSession sender;
#Session
private ClientSession bayeuxClient;
#Session
ServerSession session;
int subscribers;
// represent callback
#Listener("/service/in")
public void processClientHello(ServerSession session, ServerMessage message)
{
log.info("Bayeux server =" + bayeuxServer);
log.info("Message = " + message.getData());
log.info("remote Client Id = " + session.getId());
log.info("Local session = " + sender);
log.info("session = " + getSession());
// log.info("sender = " + sender);
details = (String) message.getData();
// session.deliver(sender,"/service/out",getDetails() , null);
testService();
}
private void testService() {
// Create the channel name using the symbol
String channelName = "/service/out";
log.info("Channel Name = " + channelName);
log.info("bayeuxServer : " + (bayeuxServer == null ? "Is Null" : "Is Not Null"));
// Initialize the channel, making it persistant
// new sendChannel
bayeuxServer.createIfAbsent(channelName, new ConfigurableServerChannel.Initializer() {
public void configureChannel(ConfigurableServerChannel channel) {
log.info("Configurable channel " + channel);
// channel exists even if it has no subscribers
channel.setPersistent(true);
channel.setLazy(true);
}
});
System.out.println("CHANNELS : " + bayeuxServer.getChannels().toString());
System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());
// convert to cometd format
Map<String, Object> data = new HashMap<String, Object>(4);
data.put("serverMsg", getDetails());
log.info("msg = " + data.get("serverMsg"));
// Publish the channel to all
ServerChannel channel = bayeuxServer.getChannel(channelName);
subscribers = channel.getSubscribers().size();
log.info("Subscribers = " + subscribers);
log.info("channel = " + channel);
// publish the message
try {
channel.publish(getSession(), data, null);
log.info("publish the channel");
}
catch (Exception e){
System.out.println(" Exception = " + e);
}
System.out.println("Session subscriptions :" + sender.getServerSession().getSubscriptions());
System.out.println("Listeners on /service/out = "+bayeuxServer.getChannel("/service/out").getListeners().toString());
System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());
publishData(data);
}
public ServerSession getSession() {
return session;
}
public void setSession(ServerSession session) {
this.session = session;
}
private void publishData(Map<String, Object> data) {
System.out.println("Published data = " + data);
}
/* #org.cometd.annotation.Subscription("/service/out")*/
#Subscription("/service/out")
public void echo(Message message)
{
System.out.println("Echo service published " + message);
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}

Invoke static method using Introspection in Flex

All,
While this is similar to another post, that post (does not indicate how to perform this (if it can be done) without instantiating an object. Also, without success I have tried multiple variations on the theme of:
class[method](arg)
class[method].call(arg)
method.apply(class, arg)
I am new to Flex, but have used Reflection in both C# and Java. BTW, the code that I am attempting to get to work in Flex is mirrored in both those languages and works as expected.
Any help is appreciated,
Thanks,
Todd
Non-functioning Flex Code:
private function ipMethodTester( ipMethodName:String,
shouldPass:Array, shouldFail:Array):void
{
var message:String;
var entry:String;
for each(entry in shouldPass)
{
message = ipMethodName + ": " + entry + " should pass";
try
{
Assert.assertTrue(message,
FieldValidator[ipMethodName](entry));
}
catch(e:Error)
{
Assert.fail(e.message + " " + message);
}
}
for each(entry in shouldFail)
{
message = ipMethodName + ": " + entry + " should fail";
try
{
Assert.assertFalse(message,
FieldValidator[ipMethodName](entry));
}
catch(e:Error)
{
Assert.fail(e.message + " " + message);
}
}
}
Java Code:
private void ipMethodTester(final String ipMethodName,
final String[] shouldPass, final String[] shouldFail)
{
Method method;
try
{
method = InetUtil.class.getDeclaredMethod(ipMethodName, String.class);
method.setAccessible(true);
for(String entry : shouldPass)
{
Object[] invokeArgs = { entry };
boolean passed = (Boolean)method.invoke(null, invokeArgs);
assertTrue(ipMethodName + ": " + entry + " should pass", passed);
}
for(String entry : shouldFail)
{
Object[] invokeArgs = { entry };
boolean passed = (Boolean)method.invoke(null, invokeArgs);
assertFalse(ipMethodName + ": " + entry + " should fail", passed);
}
}
catch (final Exception e)
{
fail(e.getClass().toString());
}
}
C# code:
private void ipMethodTester(string ipMethodName, string[] shouldPass, string[] shouldFail)
{
Type type = typeof (ValidateUtil);
BindingFlags bindingFlags = BindingFlags.InvokeMethod
| BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
MethodInfo method = type.GetMethod(ipMethodName, bindingFlags);
foreach(string entry in shouldPass)
{
object[] invokeArgs = { entry };
bool passed = (bool)method.Invoke(null, invokeArgs);
Assert.IsTrue(passed, ipMethodName + ": " + entry + " should pass");
}
foreach(string entry in shouldFail)
{
object[] invokeArgs = { entry };
bool passed = (bool)method.Invoke(null, invokeArgs);
Assert.IsFalse(passed, ipMethodName + ": " + entry + " should fail");
}
}
This works for me:
MyClass['myMethod']('arg1','arg2');
This also works:
MyClass['myMethod'].call(MyClass, 'arg1', 'arg2');
Note: the first argument of the 'call' method (MyClass in this case) just specifies which object is referenced when you use the 'this' keyword inside the function.

Passing objects to ASP :NET Webservice through JSON

Im trying to send a custom HTML object from my ASP 2.0 website to my webservice through jQuery ajax. But I cant get it to work.
Everything is parsed correct in my webservice when I drop the ObjectHTML part. But I get an error when I add the ObjectHTML part.
Is it possible to send custom javascript objects?
function SavePage() {
var rowCount = $('#pageArea div.object').length;
var i = 1;
var objects = "[";
$('.object').each(function(index) {
var objectHtml = new ObjectHTML($(this).html());
objects += "{'ObjectID': " + "'" + $(this).attr('objectid') + "', 'ObjectIndex': '" + $(this).attr('objectindex') + "', 'ObjectHTML': " + objectHtml + "}";
if (i == rowCount)
objects += ""
else
objects += ",";
i++;
});
objects += "]";
alert("{'objects': " + objects + "}");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Folder/ObjectService.asmx/SavePage",
data: "{'objects': " + objects + "}",
dataType: "json",
success:
function(msg) {
alert("Success!");
},
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error Occured: " + errorThrown);
}
});
}
function ObjectHTML(rawHtml) {
this.Html = rawHtml;
}
Webservice code:
[WebMethod(EnableSession = true)]
public string SavePage(List<PageObject> objects)
{
return "";
}
public class PageObject
{
private string _objectid, _objectindex;
private ObjectHTML _objectHtml;
public string ObjectID
{
get { return _objectid; }
set { _objectid = value; }
}
public string ObjectIndex
{
get { return _objectindex; }
set { _objectindex = value; }
}
public ObjectHTML ObjectHTML
{
get { return _objectHtml; }
set { _objectHtml = value; }
}
}
public class ObjectHTML
{
private string _Html;
public string Html
{
get { return _Html; }
set { _Html = value; }
}
}
It looks to me like you are getting a little confused between your C# classes on your server and the Javascript classes in your script.
One thing that you could do is encode your html for JSOn by using JSON.Stringify
var myObject = JSON.stringify({
ObjectId: $(this).attr('objectid'),
ObjectIndex: $(this).attr('objectIndex'),
ObjectHtml: $(this).html()
});
This will make sure that the html is encoded as valid JSON

Resources