Esempio n. 1
0
        public void Result <TMessage>(IWampFormatter <TMessage> formatter,
                                      ResultDetails details,
                                      TMessage[] arguments,
                                      IDictionary <string, TMessage> argumentsKeywords)
        {
            List <TRetorno> _resultList = new List <TRetorno>();

            int c  = formatter.Deserialize <int>(argumentsKeywords["c"]);
            int ci = formatter.Deserialize <int>(argumentsKeywords["ci"]);

            Console.WriteLine("Got result: " + new { c, ci });

            _resultList.Clear();

            arguments.ToList().ForEach(i =>
            {
                try
                {
                    _resultList.Add(i as TRetorno);
                }
                catch (InvalidCastException)
                {
                    //TODO: Log de Erro!
                }
            });
        }
Esempio n. 2
0
        public IWampClientProxy <TMessage> Create(IMessagePlayer <TMessage> player,
                                                  IMessageRecorder <TMessage> recorder,
                                                  WampMessage <TMessage> welcomeMessage)
        {
            ProxyGenerationOptions options =
                new ProxyGenerationOptions();

            options.Selector = new MockClientInterceptorSelector();

            IWampFormatter <TMessage> formatter = mBinding.Formatter;

            long           sessionId      = formatter.Deserialize <long>(welcomeMessage.Arguments[0]);
            WelcomeDetails welcomeDetails = formatter.Deserialize <WelcomeDetails>(welcomeMessage.Arguments[1]);


            IWampClientProxy <TMessage> result =
                mGenerator.CreateInterfaceProxyWithoutTarget
                    (typeof(IWampClientProxy),
                    new[]
            {
                typeof(IWampClientProxy <TMessage>),
                typeof(IWampConnectionMonitor)
            },
                    options,
                    new RecordAndPlayRawInterceptor <TMessage>(player, recorder, mBinding),
                    new RecordAndPlayInterceptor <TMessage>
                        (mOutgoingSerializer, player, recorder, mBinding),
                    new SessionPropertyInterceptor(sessionId),
                    new WelcomeDetailsInterceptor(welcomeDetails))
                as IWampClientProxy <TMessage>;

            return(result);
        }
Esempio n. 3
0
            public IWampCancellableInvocation Invoke <TMessage>(IWampRawRpcOperationRouterCallback caller, IWampFormatter <TMessage> formatter,
                                                                InvocationDetails details,
                                                                TMessage[] arguments)
            {
                TMessage number = arguments[0];
                int      n      = formatter.Deserialize <int>(number);

                bool endWithError = arguments.Length > 1 && formatter.Deserialize <bool>(arguments[1]);

                for (int i = 0; i < n; i++)
                {
                    caller.Result(WampObjectFormatter.Value,
                                  new YieldOptions {
                        Progress = true
                    },
                                  new object[] { i });
                }

                if (endWithError)
                {
                    caller.Error(WampObjectFormatter.Value,
                                 new Dictionary <string, string>(),
                                 "Something bad happened");
                }
                else
                {
                    caller.Result(WampObjectFormatter.Value,
                                  new YieldOptions(),
                                  new object[] { n });
                }

                return(null);
            }
Esempio n. 4
0
        public void Event <TMessage>(IWampFormatter <TMessage> formatter, long publicationId, EventDetails details, TMessage[] arguments, IDictionary <string, TMessage> argumentsKeywords)
        {
            // TMessage is used to represent a serialized message type
            // We know by contract that the child element is another dictionary
            IDictionary <string, TMessage> childDict = formatter.Deserialize <IDictionary <string, TMessage> >(argumentsKeywords["child"]);
            // Again, we know by contract that a field containing a string is expected for the key "id"
            string id = formatter.Deserialize <string>(childDict["id"]);

            Console.WriteLine("A child was added, ID={0}", id);
            Console.WriteLine("Press any key to continue...");

            // Dispose to unsubscribe
            mContext.unsubscribeDisposable.DisposeAsync().Wait();
        }
Esempio n. 5
0
        public async void Call(IWampClient client, string callId, string procUri, params TMessage[] arguments)
        {
            procUri = ResolveUri(client, procUri);

            IWampRpcMethod method = mRpcMetadataCatalog.ResolveMethodByProcUri(procUri);

            try
            {
                WampRequestContext.Current = new WampRequestContext(client);

                object[] parameters =
                    arguments.Zip(method.Parameters,
                                  (argument, type) =>
                                  mFormatter.Deserialize(type, argument))
                    .ToArray();

                object result = await method.InvokeAsync(client, parameters).ConfigureAwait(false);

                client.CallResult(callId, result);
            }
            catch (Exception ex)
            {
                HandleException(client, callId, ex);
            }
            finally
            {
                WampRequestContext.Current = null;
            }
        }
Esempio n. 6
0
        public void Result <TMessage>(IWampFormatter <TMessage> formatter, ResultDetails details, TMessage[] arguments, IDictionary <string, TMessage> argumentsKeywords)
        {
            string name      = argumentsKeywords["displayName"].ToString();
            string copyright = formatter.Deserialize <JToken>(argumentsKeywords["version"])["displayName"].ToString();

            Console.WriteLine("ak.wwise.core.getInfo: Hello {0} {1}", name, copyright);
        }
Esempio n. 7
0
        private static void InnerInvoke <T>(Func <IRequestContext, IMessage, Task <TResponse> > serviceMethod,
                                            IWampRawRpcOperationRouterCallback caller,
                                            IWampFormatter <T> formatter,
                                            T[] arguments)
        {
            var dummyDetails = new YieldOptions();

            try
            {
                var x = formatter.Deserialize <MessageDto>(arguments[0]);

                var message = new Message
                {
                    ReplyTo = new WampTransientDestination(x.ReplyTo),
                    Payload = Encoding.UTF8.GetBytes(x.Payload.ToString()) // TODO need to stop this from deserializing
                };

                var userSession = new UserSession
                {
                    Username = x.Username
                };

                var userContext = new RequestContext(message, userSession);

                var response = serviceMethod(userContext, message).Result;


                caller.Result(WampObjectFormatter.Value, dummyDetails, new object[] { response });
            }
            catch (Exception e)
            {
                Log.Error(e);
                caller.Error(WampObjectFormatter.Value, dummyDetails, e.Message);
            }
        }
Esempio n. 8
0
        public async void Call(IWampClient client, string callId, string procUri, params TMessage[] arguments)
#endif
        {
            procUri = ResolveUri(client, procUri);

            IWampRpcMethod method = mRpcMetadataCatalog.ResolveMethodByProcUri(procUri);

            try
            {
                WampRequestContext.Current = new WampRequestContext(client);

                object[] parameters =
                    arguments.Zip(method.Parameters,
                                  (argument, type) =>
                                  mFormatter.Deserialize(type, argument))
                    .ToArray();

#if !NET45
                InnerCall(client, callId, method.InvokeAsync(client, parameters));
            }
#else
                object result = await method.InvokeAsync(client, parameters).ConfigureAwait(false);

                client.CallResult(callId, result);
            }
Esempio n. 9
0
        public void PopulateOutOrRefValues <TMessage>(IWampFormatter <TMessage> formatter,
                                                      object[] arguments,
                                                      IDictionary <string, TMessage> outOrRefParameters)
        {
            if (mOutOrRefValues.Length != 0)
            {
                foreach (ParameterInfo parameter in mOutOrRefValues)
                {
                    TMessage currentValue;

                    if (!outOrRefParameters.TryGetValue(parameter.Name, out currentValue))
                    {
                        throw new Exception(string.Format("Argument {0} not found in arguments dictionary",
                                                          parameter.Name));
                    }
                    else
                    {
                        Type parameterType = parameter.ParameterType.StripByRef();

                        object deserializedValue =
                            formatter.Deserialize(parameterType, currentValue);

                        arguments[parameter.Position] = deserializedValue;
                    }
                }
            }
        }
Esempio n. 10
0
 public void Result <TMessage>(IWampFormatter <TMessage> formatter,
                               ResultDetails details,
                               TMessage[] arguments,
                               IDictionary <string, TMessage> argumentsKeywords)
 {
     _log.Info($"Got callback for procedure {_procedureName}");
     OnResult(formatter.Deserialize <T>(arguments[0]));
 }
Esempio n. 11
0
            public override void Result <TMessage>(IWampFormatter <TMessage> formatter, ResultDetails details, TMessage[] arguments, IDictionary <string, TMessage> argumentsKeywords)
            {
                string[] result =
                    arguments.Select(x => formatter.Deserialize <string>(x))
                    .ToArray();

                mTask.SetResult(result);
            }
        private void InnerInvoke <T>(Func <IRequestContext, IMessage, Task> serviceMethod,
                                     IWampRawRpcOperationRouterCallback caller,
                                     IWampFormatter <T> formatter,
                                     T[] arguments)
        {
            var dummyDetails = new YieldOptions();

            try
            {
                Task.Run(async() =>
                {
                    try
                    {
                        var guid = Guid.NewGuid();

                        Log.Debug($"[{guid}] RPC operation inner invoke");

                        var x = formatter.Deserialize <MessageDto>(arguments[0]);

                        var payload = x.Payload.ToString();

                        var message = new Message
                        {
                            ReplyTo = new WampTransientDestination(x.ReplyTo),
                            Payload = Encoding.UTF8.GetBytes(payload)
                        };

                        var userSession = new UserSession
                        {
                            Username = x.Username
                        };

                        var userContext = new RequestContext(message, userSession);

                        Log.Debug(
                            $"[{guid}] Calling service method from Username: {userSession.Username}, ReplyTo: {message.ReplyTo}, Payload: {payload}");

                        await serviceMethod(userContext, message);

                        Log.Debug($"[{guid}] Service method called with no exceptions");
                    }
                    catch (Exception e1)
                    {
                        Log.Error(e1, "Error processing RPC operation");
                    }
                });

                caller.Result(WampObjectFormatter.Value, dummyDetails);
            }
            catch (Exception e2)
            {
                Log.Error(e2, "Error processing RPC operation");
                caller.Error(WampObjectFormatter.Value, dummyDetails, e2.Message);
            }
        }
Esempio n. 13
0
            public void Error <TMessage>(IWampFormatter <TMessage> formatter, TMessage details, string error,
                                         TMessage[] arguments,
                                         TMessage argumentsKeywords)
            {
                IDictionary <string, object> deserializedDetails =
                    formatter.Deserialize <IDictionary <string, object> >(details);

                object[] deserializedArguments = arguments.Cast <object>().ToArray();

                IDictionary <string, object> deserializedArgumentsKeywords =
                    formatter.Deserialize <IDictionary <string, object> >(argumentsKeywords);

                WampException exception = new WampException
                                              (deserializedDetails,
                                              error,
                                              deserializedArguments,
                                              deserializedArgumentsKeywords);

                mTask.SetException(exception);
            }
Esempio n. 14
0
 /// <summary>
 /// Authenticate the WAMP session to server.
 /// </summary>
 /// <param name="proxy">The proxy.</param>
 /// <param name="formatter">The formatter.</param>
 /// <param name="authKey">The key of the authentication credentials, something like a user or
 /// application name.</param>
 /// <param name="authExtra">Any extra authentication information.</param>
 /// <param name="authSecret">The secret of the authentication credentials, something like the user
 /// password or application secret key.</param>
 /// <returns>The WampCraPermissions.</returns>
 static WampCraPermissions Authenticate(IWampCraProcedures proxy, IWampFormatter<JToken> formatter, string authKey, IDictionary<string, string> authExtra, string authSecret)
 {
     string challenge = proxy.AuthReq(authKey, authExtra);
     if (string.IsNullOrEmpty(authKey))
     {
         return proxy.Auth(null);
     }
     WampCraChallenge info = formatter.Deserialize<WampCraChallenge>(JObject.Parse(challenge));
     string sig = WampCraHelpers.AuthSignature(challenge, authSecret, info.authextra);
     return proxy.Auth(sig);
 }
Esempio n. 15
0
            public void Error <TMessage>(IWampFormatter <TMessage> formatter, TMessage details, string error)
            {
                IDictionary <string, object> deserializedDetails =
                    formatter.Deserialize <IDictionary <string, object> >(details);

                WampException exception = new WampException
                                              (deserializedDetails,
                                              error);

                mTask.SetException(exception);
            }
Esempio n. 16
0
        /// <summary>
        /// The results returned from Wwise.
        /// </summary>
        /// <typeparam name="TMessage">The type of the message.</typeparam>
        /// <param name="formatter">The formatter.</param>
        /// <param name="details">The details.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="argumentsKeywords">The arguments keywords.</param>
        public virtual void Result <TMessage>(IWampFormatter <TMessage> formatter, ResultDetails details, TMessage[] arguments, IDictionary <string, TMessage> argumentsKeywords)
        {
            Console.WriteLine("Procedure " + _packet.procedure + " executed.");

            if (argumentsKeywords.Count == 1)
            {
                _packet.results = new List <Dictionary <string, object> >();
                foreach (var value in argumentsKeywords.Values)
                {
                    foreach (JObject jsonObject in formatter.Deserialize <JToken>(value))
                    {
                        Dictionary <string, object> results = new Dictionary <string, object>();
                        foreach (KeyValuePair <string, JToken> pair in jsonObject)
                        {
                            results[pair.Key] = pair.Value;
                        }
                        _packet.results.Add(results);
                    }
                }
            }
            else
            {
                _packet.results = new Dictionary <string, object>();
                foreach (string key in argumentsKeywords.Keys)
                {
                    dynamic value = argumentsKeywords[key];
                    if (value.Type == JTokenType.Array)
                    {
                        value = formatter.Deserialize <object>(value);
                        _packet.results[key] = value;
                    }
                    else
                    {
                        _packet.results[key] = value.Value;
                    }
                }
            }

            // Allow the application to continue
            SetResetEventQueue();
        }
Esempio n. 17
0
 private object DeserializeArgument(ParameterInfo parameter, TMessage argument)
 {
     try
     {
         return(mFormatter.Deserialize(parameter.ParameterType, argument));
     }
     catch (Exception ex)
     {
         mLogger.ErrorFormat(ex, "Failed deserializing {ParameterName}", parameter.Name);
         throw;
     }
 }
 public TResult GetResult <TMessage>(IWampFormatter <TMessage> formatter, TMessage[] arguments)
 {
     if (!mHasReturnValue || !arguments.Any())
     {
         // TODO: throw exception if not nullable.
         return(default(TResult));
     }
     else
     {
         TResult result = formatter.Deserialize <TResult>(arguments[0]);
         return(result);
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Authenticate the WAMP session to server.
        /// </summary>
        /// <param name="proxy">The proxy.</param>
        /// <param name="formatter">The formatter.</param>
        /// <param name="authKey">The key of the authentication credentials, something like a user or
        /// application name.</param>
        /// <param name="authExtra">Any extra authentication information.</param>
        /// <param name="authSecret">The secret of the authentication credentials, something like the user
        /// password or application secret key.</param>
        /// <returns>The WampCraPermissions.</returns>
        static WampCraPermissions Authenticate(IWampCraProcedures proxy, IWampFormatter <JToken> formatter, string authKey, IDictionary <string, string> authExtra, string authSecret)
        {
            string challenge = proxy.AuthReq(authKey, authExtra);

            if (string.IsNullOrEmpty(authKey))
            {
                return(proxy.Auth(null));
            }
            WampCraChallenge info = formatter.Deserialize <WampCraChallenge>(JObject.Parse(challenge));
            string           sig  = WampCraHelpers.AuthSignature(challenge, authSecret, info.authextra);

            return(proxy.Auth(sig));
        }
Esempio n. 20
0
            public void Result <TMessage>(IWampFormatter <TMessage> formatter, ResultDetails details, TMessage[] arguments)
            {
                int current = formatter.Deserialize <int>(arguments[0]);

                if (details.Progress == true)
                {
                    ProgressiveResults.Add(current);
                }
                else
                {
                    mTask.SetResult(current);
                }
            }
        public TResult[] GetResult <TMessage>(IWampFormatter <TMessage> formatter, TMessage[] arguments)
        {
            if (!arguments.Any())
            {
                return(null);
            }
            else
            {
                TResult[] deserialized =
                    arguments.Select(x => formatter.Deserialize <TResult>(x))
                    .ToArray();

                return(deserialized);
            }
        }
Esempio n. 22
0
            public void Invoke <TMessage>(IWampRawRpcOperationRouterCallback caller, IWampFormatter <TMessage> formatter,
                                          InvocationDetails details,
                                          TMessage[] arguments)
            {
                TMessage number = arguments[0];
                int      n      = formatter.Deserialize <int>(number);

                for (int i = 0; i < n; i++)
                {
                    caller.Result(WampObjectFormatter.Value,
                                  new YieldOptions {
                        Progress = true
                    },
                                  new object[] { i });
                }

                caller.Result(WampObjectFormatter.Value,
                              new YieldOptions(),
                              new object[] { n });
            }
Esempio n. 23
0
        public void Result <TMessage>(IWampFormatter <TMessage> formatter, ResultDetails details, TMessage[] arguments, IDictionary <string, TMessage> argumentsKeywords)
        {
            string prefix = "ak.wwise.ui.getSelectedObjects: ";

            Console.WriteLine(prefix + "Got selected object data!");

            IEnumerable <JToken> objects = formatter.Deserialize <IEnumerable <JToken> >(argumentsKeywords["objects"]);
            int selectedObjectsNum       = objects.Count <JToken>();

            Console.WriteLine(prefix + "Got {0} object(s)!", selectedObjectsNum);

            if (selectedObjectsNum >= 1)
            {
                JToken firstObject = objects.First <JToken>();

                Console.WriteLine(prefix + "The first selected object is '{0}' ({1})",
                                  firstObject["name"].ToString(),
                                  firstObject["id"].ToString());

                JToken parent = firstObject["parent"];
                if (parent == null)
                {
                    Console.WriteLine(prefix + "It has no parent.");
                }
                else
                {
                    Console.WriteLine(prefix + "Its parent is '{0}' ({1})",
                                      parent["name"].ToString(),
                                      parent["id"].ToString());
                }
            }
            else
            {
                Console.WriteLine(prefix + "Select something and try again!");
            }
        }
Esempio n. 24
0
 public T Deserialize <T>()
 {
     return(mFormatter.Deserialize <T>(mValue));
 }
Esempio n. 25
0
 private object ConvertParameter <TMessage>(IWampFormatter <TMessage> formatter, LocalParameter parameter, TMessage value)
 {
     return(formatter.Deserialize(parameter.Type, value));
 }
Esempio n. 26
0
            public override void Result <TMessage>(IWampFormatter <TMessage> formatter, ResultDetails details, TMessage[] arguments, IDictionary <string, TMessage> argumentsKeywords)
            {
                string result = formatter.Deserialize <string>(arguments[0]);

                mTask.SetResult(result);
            }
Esempio n. 27
0
            public override void Result <TMessage>(IWampFormatter <TMessage> formatter, ResultDetails details, TMessage[] arguments)
            {
                int result = formatter.Deserialize <int>(arguments[0]);

                mTask.SetResult(result);
            }
Esempio n. 28
0
 private static IDictionary <string, object> DeserializeDictionary <TMessage>(TMessage details, IWampFormatter <TMessage> formatter)
 {
     return(formatter.Deserialize <IDictionary <string, object> >(details));
 }