Beispiel #1
0
        public override object ServiceMessage(IMessage message)
        {
            RemotingMessage     message2    = message as RemotingMessage;
            RemotingDestination destination = base.GetDestination(message) as RemotingDestination;

            return(destination.ServiceAdapter.Invoke(message));
        }
Beispiel #2
0
        public void Call <T>(string endpoint, string destination, string source, string operation, Responder <T> responder, params object[] arguments)
        {
            if (_netConnection.ObjectEncoding == ObjectEncoding.AMF0)
            {
                throw new NotSupportedException("AMF0 not supported for Flex RPC");
            }
            try {
                TypeHelper._Init();

                RemotingMessage remotingMessage = new RemotingMessage();
                remotingMessage.clientId    = Guid.NewGuid().ToString("D");
                remotingMessage.destination = destination;
                remotingMessage.messageId   = Guid.NewGuid().ToString("D");
                remotingMessage.timestamp   = 0;
                remotingMessage.timeToLive  = 0;
                remotingMessage.SetHeader(MessageBase.EndpointHeader, endpoint);
                remotingMessage.SetHeader(MessageBase.FlexClientIdHeader, _netConnection.ClientId ?? "nil");
                //Service stuff
                remotingMessage.source    = source;
                remotingMessage.operation = operation;
                remotingMessage.body      = arguments;

                FlexInvoke       invoke      = new FlexInvoke();
                PendingCall      pendingCall = new PendingCall(null, new object[] { remotingMessage });
                ResponderHandler handler     = new ResponderHandler(responder);
                pendingCall.RegisterCallback(handler);
                invoke.ServiceCall = pendingCall;
                invoke.InvokeId    = _connection.InvokeId;
                _connection.RegisterPendingCall(invoke.InvokeId, pendingCall);
                Write(invoke);
            } catch (Exception ex) {
                _netConnection.RaiseNetStatus(ex);
            }
        }
Beispiel #3
0
 /// <summary>
 /// Gets the destination Id from the specified IMessage instance.
 /// </summary>
 /// <param name="message">The message that should be handled by the destination.</param>
 /// <returns>The Id if the destination is found; otherwise, null.</returns>
 public string GetDestinationId(IMessage message)
 {
     //If destination is specified then return
     if( message.destination != null )
         return message.destination;
     if( message is RemotingMessage )
     {
         //Search for a destination with the same source
         RemotingMessage remotingMessage = message as RemotingMessage;
         string destinationId = GetDestinationBySource(remotingMessage.source);
         if (destinationId != null)
             return destinationId;
         //Search for a RemotingService
         Destination defaultDestination = null;
         foreach (DictionaryEntry entry in _services)
         {
             IService serviceTmp = entry.Value as IService;
             if (serviceTmp.IsSupportedMessage(message))
             {
                 Destination[] destinations = serviceTmp.GetDestinations();
                 foreach (Destination destination in destinations)
                 {
                     if (destination.Source == remotingMessage.source)
                         return destination.Id;
                     if (destination.Source == "*")
                         defaultDestination = destination;
                 }
             }
         }
         if (defaultDestination != null)
             return defaultDestination.Id;
     }
     return null;
 }
Beispiel #4
0
        public async Task <T> InvokeAsync <T>(string endpoint, string destination, string method, object[] arguments)
        {
            if (objectEncoding != ObjectEncoding.Amf3)
            {
                throw new NotSupportedException("Flex RPC requires AMF3 encoding.");
            }
            var remotingMessage = new RemotingMessage
            {
                ClientId    = ClientId, //Guid.NewGuid().ToString("D"),
                Destination = destination,
                Operation   = method,
                Body        = arguments,
                Headers     = new AsObject
                {
                    { FlexMessageHeaders.Endpoint, endpoint },
                    { FlexMessageHeaders.FlexClientId, ClientId ?? "nil" },
                    { FlexMessageHeaders.RequestTimeout, 60 }
                }
            };

            var invoke = new InvokeAmf3
            {
                InvokeId   = GetNextInvokeId() + int.MaxValue / 4,
                MethodCall = new Method(null, new object[] { remotingMessage })
            };
            var result = await QueueCommandAsTask(invoke, 3, 0);

            return((T)MiniTypeConverter.ConvertTo(result.Body, typeof(T)));
        }
        public async Task <T> InvokeAsync <T>(string endpoint, string destination, string method, object[] arguments)
        {
            if (objectEncoding != ObjectEncoding.Amf3)
            {
                throw new NotSupportedException("Flex RPC requires AMF3 encoding.");
            }
            var client_id       = Guid.NewGuid().ToString("D");
            var remotingMessage = new RemotingMessage
            {
                ClientId    = client_id,
                Destination = destination,
                Operation   = method,
                Body        = arguments,
                Headers     = new Dictionary <string, object>()
                {
                    { FlexMessageHeaders.Endpoint, endpoint },
                    { FlexMessageHeaders.FlexClientId, client_id ?? "nil" }
                }
            };

            var result = await QueueCommandAsTask(new InvokeAmf3()
            {
                InvokeId   = GetNextInvokeId(),
                MethodCall = new Method(null, new object[] { remotingMessage })
            }, 3, 0);

            return((T)MiniTypeConverter.ConvertTo(result, typeof(T)));
        }
Beispiel #6
0
        public override object ServiceMessage(IMessage message)
        {
            RemotingMessage     remotingMessage = message as RemotingMessage;
            RemotingDestination destination     = GetDestination(message) as RemotingDestination;
            ServiceAdapter      adapter         = destination.ServiceAdapter;
            object result = adapter.Invoke(message);

            return(result);
        }
 internal RemotingMessageReceivedEventArgs(RemotingMessage message, string endpoint, string clientId, int invokeId)
 {
     this.Message     = message;
     this.Operation   = message.Operation;
     this.Destination = message.Destination;
     this.Endpoint    = endpoint;
     this.MessageId   = clientId;
     this.InvokeId    = invokeId;
 }
        public override async Task <object> ServiceMessage(IMessage message)
        {
            RemotingMessage     remotingMessage = message as RemotingMessage;
            RemotingDestination destination     = GetDestination(message) as RemotingDestination;
            ServiceAdapter      adapter         = destination.ServiceAdapter;
            Task <object>       result          = adapter.Invoke(message);
            await result;

            return(result.Result);
        }
 internal RemotingMessageReceivedEventArgs(RemotingMessage message, string endpoint, string clientId,
                                           int invokeId)
 {
     Message     = message;
     Operation   = message.Operation;
     Destination = message.Destination;
     Endpoint    = endpoint;
     MessageId   = clientId;
     InvokeId    = invokeId;
 }
Beispiel #10
0
        internal async Task <T> InvokeAsync <T>(RemotingMessage message)
        {
            InvokeAmf3 invokeAmf3 = new InvokeAmf3();

            invokeAmf3.InvokeId   = this.GetNextInvokeId();
            invokeAmf3.MethodCall = new Method((string)null, new object[1]
            {
                (object)message
            }, 1 != 0, CallStatus.Request);
            return((T)MiniTypeConverter.ConvertTo((await this.QueueCommandAsTask((Command)invokeAmf3, 3, 0, true)).Body, typeof(T)));
        }
Beispiel #11
0
 public RemotingMessageReceivedEventArgs(RemotingMessage originalMessage, string operation, string endpoint, string destination, string messageId, object body, int invokeId)
 {
     OriginalMessage = originalMessage;
     Operation       = operation;
     Destination     = destination;
     Endpoint        = endpoint;
     MessageId       = messageId;
     Body            = body;
     ReturnRequired  = false;
     InvokeId        = invokeId;
 }
Beispiel #12
0
        internal async Task <AcknowledgeMessageExt> InvokeAckAsync(int invokeId, RemotingMessage message)
        {
            InvokeAmf3 invokeAmf3 = new InvokeAmf3();

            invokeAmf3.InvokeId   = invokeId;
            invokeAmf3.MethodCall = new Method((string)null, new object[1]
            {
                (object)message
            }, 1 != 0, CallStatus.Request);
            return(await this.QueueCommandAsTask((Command)invokeAmf3, 3, 0, true));
        }
Beispiel #13
0
        internal async Task <T> InvokeAsync <T>(RemotingMessage message)
        {
            var invoke = new InvokeAmf3()
            {
                InvokeId   = GetNextInvokeId(),
                MethodCall = new Method(null, new object[] { message })
            };
            var result = await QueueCommandAsTask(invoke, 3, 0);

            return((T)MiniTypeConverter.ConvertTo(result, typeof(T)));
        }
Beispiel #14
0
        internal async Task <AcknowledgeMessageExt> InvokeAckAsync(int invokeId, RemotingMessage message)
        {
            //TODO: this is very bad
            //this.invokeId = invokeId;

            var invoke = new InvokeAmf3
            {
                InvokeId   = invokeId,
                MethodCall = new Method(null, new object[] { message })
            };

            return(await QueueCommandAsTask(invoke, 3, 0));
        }
Beispiel #15
0
        public Notify InvokeRemotingMessage(string service, string operation, params object[] args)
        {
            var msg = new RemotingMessage();

            msg.operation   = operation;
            msg.destination = service;
            msg.headers["DSRequestTimeout"] = 60;
            msg.headers["DSId"]             = RtmpUtil.RandomUidString();
            msg.headers["DSEndpoint"]       = "my-rtmps";
            msg.body      = args;
            msg.messageId = RtmpUtil.RandomUidString();

            return(Invoke(msg));
        }
Beispiel #16
0
 public void Call(string endpoint, string destination, string source, string operation, IPendingServiceCallback callback, params object[] arguments)
 {
     if (this._netConnection.ObjectEncoding == ObjectEncoding.AMF0)
     {
         throw new NotSupportedException("AMF0 not supported for Flex RPC");
     }
     try
     {
         TypeHelper._Init();
         Uri            requestUri = new Uri(this._gatewayUrl);
         HttpWebRequest request    = (HttpWebRequest)WebRequest.Create(requestUri);
         request.ContentType     = "application/x-amf";
         request.Method          = "POST";
         request.CookieContainer = this._netConnection.CookieContainer;
         AMFMessage      amfMessage = new AMFMessage((ushort)this._netConnection.ObjectEncoding);
         RemotingMessage message2   = new RemotingMessage {
             clientId    = Guid.NewGuid().ToString("D"),
             destination = destination,
             messageId   = Guid.NewGuid().ToString("D"),
             timestamp   = 0L,
             timeToLive  = 0L
         };
         message2.SetHeader("DSEndpoint", endpoint);
         if (this._netConnection.ClientId == null)
         {
             message2.SetHeader("DSId", "nil");
         }
         else
         {
             message2.SetHeader("DSId", this._netConnection.ClientId);
         }
         message2.source    = source;
         message2.operation = operation;
         message2.body      = arguments;
         foreach (KeyValuePair <string, AMFHeader> pair in this._netConnection.Headers)
         {
             amfMessage.AddHeader(pair.Value);
         }
         AMFBody body = new AMFBody(null, null, new object[] { message2 });
         amfMessage.AddBody(body);
         PendingCall call  = new PendingCall(source, operation, arguments);
         RequestData state = new RequestData(request, amfMessage, call, callback);
         request.BeginGetRequestStream(new AsyncCallback(this.BeginRequestFlexCall), state);
     }
     catch (Exception exception)
     {
         this._netConnection.RaiseNetStatus(exception);
     }
 }
        private RemotingMessage GetLoginMessage()
        {
            var msg = new RemotingMessage();

            msg.operation   = "login";
            msg.source      = null;
            msg.timestamp   = 0;
            msg.destination = "sessionLocalService";
            msg.messageId   = Guid.NewGuid().ToString();
            msg.clientId    = null;
            msg.body        = new[] { "admin", "dors1000", "MAIN" };
            msg.timeToLive  = 0;
            msg.headers     = null;
            return(msg);
        }
        private RemotingMessage GetIsActiveMessage()
        {
            var msg = new RemotingMessage();

            msg.operation   = "isSessionActive";
            msg.source      = null;
            msg.timestamp   = 0;
            msg.destination = "sessionLocalService";
            msg.messageId   = Guid.NewGuid().ToString();
            msg.clientId    = null;
            msg.body        = new object[0];
            msg.timeToLive  = 0;
            msg.headers     = GetHeaderDictionary();
            return(msg);
        }
Beispiel #19
0
        /// <summary>
        /// Used to invoke a service which you don't know what it returns.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="operation"></param>
        /// <param name="args"></param>
        /// <returns>ASObject body</returns>
        public object InvokeServiceUnknown(string service, string operation, params object[] args)
        {
            var msg = new RemotingMessage();

            msg.operation   = operation;
            msg.destination = service;
            msg.headers["DSRequestTimeout"] = 60;
            msg.headers["DSId"]             = RtmpUtil.RandomUidString();
            msg.headers["DSEndpoint"]       = "my-rtmps";
            msg.body      = args;
            msg.messageId = RtmpUtil.RandomUidString();

            string endpoint = service + "." + operation;

            var result = Host.Call(msg);

            if (result == null)
            {
                StaticLogger.Warning(string.Format("Invoking {0} returned null", endpoint));
                return(null);
            }

            if (RtmpUtil.IsError(result))
            {
                var error       = RtmpUtil.GetError(result);
                var errordetail = error != null && error.faultDetail != null?string.Format(" [{0}]", error.faultDetail) : "";

                var errorstr = error != null && error.faultString != null?string.Format(", {0}", error.faultString) : "";

                StaticLogger.Warning(string.Format(
                                         "{0} returned an error{1}{2}",
                                         endpoint,
                                         errorstr,
                                         errordetail
                                         ));
                return(null);
            }

            var body = RtmpUtil.GetBodies(result).FirstOrDefault();

            if (body == null)
            {
                StaticLogger.Debug(endpoint + " RtmpUtil.GetBodies returned null");
                return(null);
            }

            return(body.Item1);
        }
Beispiel #20
0
        public void Call(string endpoint, string destination, string source, string operation, IPendingServiceCallback callback, params object[] arguments)
        {
            if (_netConnection.ObjectEncoding == ObjectEncoding.AMF0)
            {
                throw new NotSupportedException("AMF0 not supported for Flex RPC");
            }
            try
            {
                TypeHelper._Init();

                Uri            uri     = new Uri(_gatewayUrl);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.ContentType = ContentType.AMF;
                request.Method      = "POST";
#if !(SILVERLIGHT)
                request.CookieContainer = _netConnection.CookieContainer;
#endif
                AMFMessage amfMessage = new AMFMessage((ushort)_netConnection.ObjectEncoding);

                RemotingMessage remotingMessage = new RemotingMessage();
                remotingMessage.clientId    = Guid.NewGuid().ToString("D");
                remotingMessage.destination = destination;
                remotingMessage.messageId   = Guid.NewGuid().ToString("D");
                remotingMessage.timestamp   = 0;
                remotingMessage.timeToLive  = 0;
                remotingMessage.SetHeader(MessageBase.EndpointHeader, endpoint);
                remotingMessage.SetHeader(MessageBase.FlexClientIdHeader, _netConnection.ClientId ?? "nil");
                //Service stuff
                remotingMessage.source    = source;
                remotingMessage.operation = operation;
                remotingMessage.body      = arguments;

                foreach (KeyValuePair <string, AMFHeader> entry in _netConnection.Headers)
                {
                    amfMessage.AddHeader(entry.Value);
                }
                AMFBody amfBody = new AMFBody(null, null, new object[] { remotingMessage });
                amfMessage.AddBody(amfBody);

                PendingCall    call           = new PendingCall(source, operation, arguments);
                AmfRequestData amfRequestData = new AmfRequestData(request, amfMessage, call, callback, null);
                request.BeginGetRequestStream(BeginRequestFlexCall, amfRequestData);
            }
            catch (Exception ex)
            {
                _netConnection.RaiseNetStatus(ex);
            }
        }
Beispiel #21
0
        private void parse(string amf, string name)
        {
            byte[] bbb = StrToToHexByte(amf);

            AMFDeserializer ad      = new AMFDeserializer(new MemoryStream(bbb));
            AMFMessage      message = ad.ReadAMFMessage();

            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(message);

            //Write that JSON to txt file
            File.WriteAllText(@"z:\temp\hotel\" + name + @".json", json);

            foreach (var body in message.Bodies)
            {
                object[]        content = body.Content as object[];
                RemotingMessage rm      = content[0] as RemotingMessage;

                rm.messageId = Guid.NewGuid().ToString("D");

                object[] bodys = rm.body as object[];
                ASObject ab    = bodys[2] as ASObject;

                ASObject masterBase = ab["masterBase"] as ASObject;
                masterBase["dep"]        = DateTime.Now;
                masterBase["arr"]        = DateTime.Now;
                masterBase["rsvMan"]     = "马一一";
                masterBase["cutoffDate"] = DateTime.Now;

                ASObject masterGuest = ab["masterGuest"] as ASObject;
                masterGuest["name"]  = "马一一";
                masterGuest["name2"] = "Ma Yi Yi";
                masterGuest["sex"]   = "1";

                ArrayCollection rsvSrcList = ab["rsvSrcList"] as ArrayCollection;
                ASObject        rsvObject  = rsvSrcList[0] as ASObject;
                rsvObject["arrDate"]    = DateTime.Now;
                rsvObject["depDate"]    = DateTime.Now;
                rsvObject["rsvArrDate"] = DateTime.Now;
                rsvObject["rsvDepDate"] = DateTime.Now;
                rsvObject["negoRate"]   = 268;
                rsvObject["oldRate"]    = 268;
                rsvObject["realRate"]   = 268;
                rsvObject["rackRate"]   = 268;
            }
        }
Beispiel #22
0
            public void BeginTask()
            {
                CommandMessage commandMessage = requestMessage as CommandMessage;

                if (commandMessage != null)
                {
                    responseMessage = ErrorMessage.CreateErrorResponse(requestMessage,
                                                                       "Remoting service does not handle command messages currently.",
                                                                       "Gateway.RemotingService.UnsupportedCommandMessage", null);
                    SignalCompletion(true);
                    return;
                }

                RemotingMessage remotingMessage = (RemotingMessage)requestMessage;

                responseMessage = AcknowledgeMessage.CreateAcknowledgeResponse(remotingMessage, new object[] { "Response!" });
                SignalCompletion(true);
            }
Beispiel #23
0
        public async Task <T> InvokeAsync <T>(string endpoint, string destination, string method, object[] arguments)
        {
            if (this._objectEncoding != ObjectEncoding.Amf3)
            {
                throw new NotSupportedException("Flex RPC requires AMF3 encoding.");
            }
            RemotingMessage remotingMessage1 = new RemotingMessage();
            string          clientId         = this.ClientId;

            remotingMessage1.ClientId = clientId;
            string str1 = destination;

            remotingMessage1.Destination = str1;
            string str2 = method;

            remotingMessage1.Operation = str2;
            object[] objArray = arguments;
            remotingMessage1.Body    = (object)objArray;
            remotingMessage1.Headers = new AsObject()
            {
                {
                    "DSEndpoint",
                    (object)endpoint
                },
                {
                    "DSId",
                    (object)(this.ClientId ?? "nil")
                },
                {
                    "DSRequestTimeout",
                    (object)60
                }
            };
            RemotingMessage remotingMessage2 = remotingMessage1;
            InvokeAmf3      invokeAmf3       = new InvokeAmf3();

            invokeAmf3.InvokeId   = this.GetNextInvokeId();
            invokeAmf3.MethodCall = new Method((string)null, new object[1]
            {
                remotingMessage2
            }, 1 != 0, CallStatus.Request);
            return((T)MiniTypeConverter.ConvertTo((await this.QueueCommandAsTask(invokeAmf3, 3, 0, true)).Body, typeof(T)));
        }
Beispiel #24
0
 public async Task <T> InvokeAsync <T>(string endpoint, string destination, string method, object[] arguments)
 {
     try
     {
         if (_objectEncoding != ObjectEncoding.Amf3)
         {
             throw new NotSupportedException("Flex RPC requires AMF3 encoding.");
         }
         RemotingMessage remotingMessage = new RemotingMessage()
         {
             ClientId    = ClientId,
             Destination = destination,
             Operation   = method,
             Body        = arguments,
             Headers     = new AsObject()
             {
                 {
                     "DSEndpoint", endpoint
                 },
                 {
                     "DSId", ClientId ?? "nil"
                 },
                 {
                     "DSRequestTimeout", 60
                 }
             }
         };
         InvokeAmf3 invokeAmf3 = new InvokeAmf3()
         {
             InvokeId   = GetNextInvokeId(),
             MethodCall = new Method(null, new object[1] {
                 remotingMessage
             }, 1 != 0, CallStatus.Request)
         };
         return((T)MiniTypeConverter.ConvertTo((await QueueCommandAsTask(invokeAmf3, 3, 0, true)).Body, typeof(T)));
     }
     catch (Exception ex)
     {
         Tools.Log(ex.StackTrace);
         return(default(T));
     }
 }
Beispiel #25
0
 public string GetDestinationId(IMessage message)
 {
     if (message.destination != null)
     {
         return(message.destination);
     }
     if (message is RemotingMessage)
     {
         RemotingMessage message2            = message as RemotingMessage;
         string          destinationBySource = this.GetDestinationBySource(message2.source);
         if (destinationBySource != null)
         {
             return(destinationBySource);
         }
         Destination destination = null;
         foreach (DictionaryEntry entry in this._services)
         {
             IService service = entry.Value as IService;
             if (service.IsSupportedMessage(message))
             {
                 Destination[] destinations = service.GetDestinations();
                 foreach (Destination destination2 in destinations)
                 {
                     if (destination2.Source == message2.source)
                     {
                         return(destination2.Id);
                     }
                     if (destination2.Source == "*")
                     {
                         destination = destination2;
                     }
                 }
             }
         }
         if (destination != null)
         {
             return(destination.Id);
         }
     }
     return(null);
 }
Beispiel #26
0
        public async Task <T> InvokeAsync <T>(string endpoint, string destination, string method, object[] arguments)
        {
            if (this._objectEncoding != ObjectEncoding.Amf3)
            {
                throw new NotSupportedException("Flex RPC requires AMF3 encoding.");
            }
            RemotingMessage remotingMessage = new RemotingMessage()
            {
                ClientId    = ClientId,
                Destination = destination,
                Operation   = method,
                Body        = arguments,
                Headers     = new AsObject()
                {
                    {
                        "DSEndpoint",
                        (object)endpoint
                    },
                    {
                        "DSId",
                        (object)(this.ClientId ?? "nil")
                    },
                    {
                        "DSRequestTimeout",
                        (object)60
                    }
                }
            };

            InvokeAmf3 invokeAmf = new InvokeAmf3()
            {
                InvokeId   = this.GetNextInvokeId() + 536870911,
                MethodCall = new Method(null, new object[1]
                {
                    remotingMessage
                }, 1 != 0, CallStatus.Request)
            };

            return((T)MiniTypeConverter.ConvertTo((await this.QueueCommandAsTask(invokeAmf, 3, 0, true)).Body, typeof(T)));
        }
Beispiel #27
0
        public object invokeService(string service, string operation, object[] args)
        {
            MessageBroker messageBroker = MessageBroker.GetMessageBroker(null);

            RemotingMessage remotingMessage = new RemotingMessage();

            remotingMessage.source    = service;
            remotingMessage.operation = operation;
            string destinationId = messageBroker.GetDestinationId(remotingMessage);

            remotingMessage.destination = destinationId;
            if (args != null)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    object obj = args[i];
                    if (obj is ASObject)
                    {
                        ASObject aso  = obj as ASObject;
                        Type     type = null;
                        //if (aso.ContainsKey("TypeName"))
                        //    type = TypeHelper.Locate(aso["TypeName"] as string);
                        if (aso.ContainsKey("__type"))
                        {
                            type = TypeHelper.Locate(aso["__type"] as string);
                        }
                        if (type != null)
                        {
                            string tmp = JavaScriptConvert.SerializeObject(obj);
                            args[i] = JavaScriptConvert.DeserializeObject(tmp, type);
                        }
                    }
                }
            }
            remotingMessage.body      = args;
            remotingMessage.timestamp = Environment.TickCount;
            IMessage response = messageBroker.RouteMessage(remotingMessage);

            return(response);
        }
        /// <summary>
        /// 用户认证
        /// </summary>
        /// <returns></returns>
        private byte[] AuthenticateUser(string userID, string psd, string responseNo)
        {
            RemotingMessage rtMsg = new RemotingMessage();

            rtMsg.source      = null;
            rtMsg.operation   = "authenticateUser";
            rtMsg.clientId    = Guid.NewGuid().ToString().ToUpper();
            rtMsg.messageId   = Guid.NewGuid().ToString().ToUpper();
            rtMsg.destination = "userRO";
            rtMsg.timestamp   = 0;
            rtMsg.timeToLive  = 0;
            rtMsg.headers.Add(RemotingMessage.FlexClientIdHeader, Guid.NewGuid().ToString().ToUpper());
            rtMsg.headers.Add(RemotingMessage.EndpointHeader, "my-amf");

            List <object> bodys = new List <object>();

            bodys.Add(userID);
            bodys.Add(psd);

            rtMsg.body = bodys.ToArray();

            AMFMessage _amf3 = new AMFMessage(3);// 创建 AMF

            List <RemotingMessage> lstR = new List <RemotingMessage>();

            lstR.Add(rtMsg);

            AMFBody _amfbody = new AMFBody("null", "/" + responseNo, lstR.ToArray());

            _amf3.AddBody(_amfbody);

            MemoryStream  _Memory     = new MemoryStream();         //内存流
            AMFSerializer _Serializer = new AMFSerializer(_Memory); //序列化

            _Serializer.WriteMessage(_amf3);                        //将消息写入

            return(_Memory.ToArray());
        }
Beispiel #29
0
		private IDictionary Invoke(IDictionary request) {
			ValidationUtils.ArgumentNotNull(request, "request");
			object error = null;
			object result = null;

			ISession session = this.MessageBroker.SessionManager.GetHttpSession(HttpContext.Current);
			FluorineContext.Current.SetSession(session);
			//Context initialized, notify listeners.
			if (session != null && session.IsNew)
				session.NotifyCreated();

			// Get the ID of the request.
			object id = request["id"];
			string credentials = request["credentials"] as string;
			if (!StringUtils.IsNullOrEmpty(credentials)) {
				try {
					CommandMessage commandMessage = new CommandMessage(CommandMessage.LoginOperation);
					commandMessage.body = credentials;
					IMessage message = this.MessageBroker.RouteMessage(commandMessage);
					if (message is ErrorMessage) {
						error = FromException(message as ErrorMessage);
						return CreateResponse(id, result, error);
					}
				} catch (Exception ex) {
					error = FromException(ex);
					return CreateResponse(id, result, error);
				}
			}

			// If the ID is not there or was not set then this is a notification
			// request from the client that does not expect any response. Right
			// now, we don't support this.
			bool isNotification = JavaScriptConvert.IsNull(id);

			if (isNotification)
				throw new NotSupportedException("Notification are not yet supported.");

			log.Debug(string.Format("Received request with the ID {0}.", id.ToString()));

			// Get the method name and arguments.
			string methodName = StringUtils.MaskNullString((string)request["method"]);

			if (methodName.Length == 0)
				throw new JsonRpcException("No method name supplied for this request.");

			if (methodName == "clearCredentials") {
				try {
					CommandMessage commandMessage = new CommandMessage(CommandMessage.LogoutOperation);
					IMessage message = this.MessageBroker.RouteMessage(commandMessage);
					if (message is ErrorMessage) {
						error = FromException(message as ErrorMessage);
						return CreateResponse(id, result, error);
					} else
						return CreateResponse(id, message.body, null);
				} catch (Exception ex) {
					error = FromException(ex);
					return CreateResponse(id, result, error);
				}
			}

			//Info("Invoking method {1} on service {0}.", ServiceName, methodName);

			// Invoke the method on the service and handle errors.
			try {
				RemotingMessage message = new RemotingMessage();
				message.destination = this.Request.QueryString["destination"] as string;
				message.source = this.Request.QueryString["source"] as string;
				message.operation = methodName;
				object argsObject = request["params"];
				object[] args = (argsObject as JavaScriptArray).ToArray();
				message.body = args;
				IMessage response = this.MessageBroker.RouteMessage(message);
				if (response is ErrorMessage)
					error = FromException(response as ErrorMessage);
				else
					result = response.body;

				/*
				Method method = serviceClass.GetMethodByName(methodName);

				object[] args;
				string[] names = null;

				object argsObject = request["params"];
				IDictionary argByName = argsObject as IDictionary;

				if (argByName != null)
				{
					names = new string[argByName.Count];
					argByName.Keys.CopyTo(names, 0);
					args = new object[argByName.Count];
					argByName.Values.CopyTo(args, 0);
				}
				else
				{
					args = (argsObject as JavaScriptArray).ToArray();
				}

				result = method.Invoke(instance, names, args);
				 */
			} catch (Exception ex) {
				log.Error(ex.Message, ex);
				throw;
			}

			// Setup and return the response object.
			return CreateResponse(id, result, error);
		}
Beispiel #30
0
        public T InvokeService <T>(string service, string operation, params object[] args) where T : class
        {
            var msg = new RemotingMessage();

            msg.operation   = operation;
            msg.destination = service;
            msg.headers["DSRequestTimeout"] = 60;
            msg.headers["DSId"]             = RtmpUtil.RandomUidString();
            msg.headers["DSEndpoint"]       = "my-rtmps";
            msg.body      = args;
            msg.messageId = RtmpUtil.RandomUidString();

            string endpoint = service + "." + operation;

            var result = Host.Call(msg);

            if (result == null)
            {
                StaticLogger.Warning(string.Format("Invoking {0} returned null", endpoint));
                return(null);
            }

            if (RtmpUtil.IsError(result))
            {
                var error       = RtmpUtil.GetError(result);
                var errordetail = error != null && error.faultDetail != null?string.Format(" [{0}]", error.faultDetail) : "";

                var errorstr = error != null && error.faultString != null?string.Format(", {0}", error.faultString) : "";

                StaticLogger.Warning(string.Format(
                                         "{0} returned an error{1}{2}",
                                         endpoint,
                                         errorstr,
                                         errordetail
                                         ));
                return(null);
            }

            var body = RtmpUtil.GetBodies(result).FirstOrDefault();

            if (body == null)
            {
                StaticLogger.Debug(endpoint + " RtmpUtil.GetBodies returned null");
                return(null);
            }

            if (body.Item1 == null)
            {
                StaticLogger.Debug(endpoint + " Body.Item1 returned null");
                return(null);
            }

            object obj = null;

            if (body.Item1 is ASObject)
            {
                var ao = (ASObject)body.Item1;
                obj = MessageTranslator.Instance.GetObject <T>(ao);
                if (obj == null)
                {
                    StaticLogger.Debug(endpoint + " expected " + typeof(T) + ", got " + ao.TypeName);
                    return(null);
                }
            }
            else if (body.Item1 is ArrayCollection)
            {
                try
                {
                    obj = Activator.CreateInstance(typeof(T), (ArrayCollection)body.Item1);
                }
                catch (Exception ex)
                {
                    StaticLogger.Warning(endpoint + " failed to construct " + typeof(T));
                    StaticLogger.Debug(ex);
                    return(null);
                }
            }
            else
            {
                StaticLogger.Debug(endpoint + " unknown object " + body.Item1.GetType());
                return(null);
            }

            if (obj is MessageObject)
            {
                ((MessageObject)obj).TimeStamp = body.Item2;
            }

            return((T)obj);
        }
Beispiel #31
0
 public override void Invoke(AMFContext context)
 {
     for (int i = 0; i < context.AMFMessage.BodyCount; i++)
     {
         Type              typeForWebService;
         Exception         exception;
         ErrorResponseBody body2;
         AMFBody           bodyAt = context.AMFMessage.GetBodyAt(i);
         if (!bodyAt.IsEmptyTarget)
         {
             if (bodyAt.IsWebService)
             {
                 try
                 {
                     typeForWebService = this.GetTypeForWebService(bodyAt.TypeName);
                     if (typeForWebService != null)
                     {
                         bodyAt.Target = typeForWebService.FullName + "." + bodyAt.Method;
                     }
                     else
                     {
                         exception = new TypeInitializationException(bodyAt.TypeName, null);
                         if ((log != null) && log.get_IsErrorEnabled())
                         {
                             log.Error(__Res.GetString("Type_InitError", new object[] { bodyAt.Target }), exception);
                         }
                         body2 = new ErrorResponseBody(bodyAt, exception);
                         context.MessageOutput.AddBody(body2);
                     }
                 }
                 catch (Exception exception1)
                 {
                     exception = exception1;
                     if ((log != null) && log.get_IsErrorEnabled())
                     {
                         log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { bodyAt.Target }), exception);
                     }
                     body2 = new ErrorResponseBody(bodyAt, exception);
                     context.MessageOutput.AddBody(body2);
                 }
             }
         }
         else
         {
             object content = bodyAt.Content;
             if (content is IList)
             {
                 content = (content as IList)[0];
             }
             IMessage message = content as IMessage;
             if ((message != null) && (message is RemotingMessage))
             {
                 RemotingMessage message2 = message as RemotingMessage;
                 string          source   = message2.source;
                 if ((source != null) && source.ToLower().EndsWith(".asmx"))
                 {
                     try
                     {
                         typeForWebService = this.GetTypeForWebService(source);
                         if (typeForWebService != null)
                         {
                             message2.source = typeForWebService.FullName;
                         }
                         else
                         {
                             exception = new TypeInitializationException(source, null);
                             if ((log != null) && log.get_IsErrorEnabled())
                             {
                                 log.Error(__Res.GetString("Type_InitError", new object[] { source }), exception);
                             }
                             body2 = new ErrorResponseBody(bodyAt, message, exception);
                             context.MessageOutput.AddBody(body2);
                         }
                     }
                     catch (Exception exception2)
                     {
                         exception = exception2;
                         if ((log != null) && log.get_IsErrorEnabled())
                         {
                             log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { source }), exception);
                         }
                         body2 = new ErrorResponseBody(bodyAt, message, exception);
                         context.MessageOutput.AddBody(body2);
                     }
                 }
             }
         }
     }
 }