コード例 #1
0
        public void ReturnTupleTest()
        {
            var callsCount        = 0;
            var serviceInstance   = new TestService(() => callsCount++);
            var serializerFactory = new MessagePackSerializerFactory();
            var serviceDispatcher = new ServiceDispatcher <ITestService>(serializerFactory, new LoggerStub());

            var argumentsData = new byte[2][];

            argumentsData[0] = serializerFactory.CreateSerializer <int>().Serialize(0);
            argumentsData[1] = serializerFactory.CreateSerializer <int>().Serialize(2);

            var result = serviceDispatcher.Dispatch(serviceInstance, new RpcMessage()
            {
                ServiceCode   = typeof(ITestService).FullName.GetHashCode(),
                OperationCode = 3,
                ArgumentsData = argumentsData
            });

            Assert.NotNull(result);
            Assert.True(result.HasReturnValue);
            var resultTuple = serializerFactory.CreateSerializer <(int count, SerializableObject[] objects)>()
                              .Deserialize(result.ReturnValue);

            Assert.Equal(2, resultTuple.count);
            Assert.Equal(SerializableObject.TestInt, resultTuple.objects[0].IntProperty);
            Assert.Equal(SerializableObject.TestString, resultTuple.objects[0].StringProperty);
            Assert.Equal(
                SerializableObject.TestDouble,
                resultTuple.objects[0].NestedObject.DoubleProperty);
        }
コード例 #2
0
 /// <summary>
 /// Apply the service behavior
 /// </summary>
 public void ApplyServiceBehavior(RestService service, ServiceDispatcher dispatcher)
 {
     foreach (var ep in dispatcher.Service.Endpoints)
     {
         ep.Dispatcher.MessageInspectors.Add(this);
     }
 }
コード例 #3
0
        void GetLists()
        {
            List <TwitterResource> userLists;

            lock (listCacheSync)
                userLists = listsCache.Where(x => x.User == user).ToList();

            if (userLists.Count > 0)
            {
                lock (resourcesSync)
                    foreach (var item in userLists.Except(Resources))
                    {
                        Resources.Add(item);
                    }
            }
            else
            {
                var service = ServiceDispatcher.GetService(user);

                loading += 2;
                service.ListListsFor(new ListListsForOptions {
                    ScreenName = user.ScreenName
                }, ReceiveLists);
                service.ListSubscriptions(new ListSubscriptionsOptions {
                    ScreenName = user.ScreenName
                }, ReceiveLists);
            }
        }
コード例 #4
0
ファイル: LoadedApk.cs プロジェクト: zhouweiaccp/XobotOS
 internal DeathMonitor(ServiceDispatcher _enclosing, android.content.ComponentName
                       name, android.os.IBinder service)
 {
     this._enclosing = _enclosing;
     this.mName      = name;
     this.mService   = service;
 }
コード例 #5
0
ファイル: NotificationsModel.cs プロジェクト: swinghu/Ocell
        public void OnLoad()
        {
            lastCheckTime = DateSync.GetLastCheckDate();

            var mentionOptions = new ListTweetsMentioningMeOptions
            {
                Count = 20,
            };

            var dmOption = new ListDirectMessagesReceivedOptions
            {
                Count = 20,
            };

            foreach (var account in Config.Accounts)
            {
                if (account.Preferences.MentionsPreferences != Library.Notifications.NotificationType.None)
                {
                    IsLoading = true;
                    Interlocked.Increment(ref requestsPending);
                    ServiceDispatcher.GetService(account).ListTweetsMentioningMe(mentionOptions, (t, r) => FilterAndAddStatuses(t.Cast <ITweetable>(), r)); // Ugh.
                }
                if (account.Preferences.MessagesPreferences != Library.Notifications.NotificationType.None)
                {
                    IsLoading = true;
                    Interlocked.Increment(ref requestsPending);
                    ServiceDispatcher.GetService(account).ListDirectMessagesReceived(dmOption, (t, r) => FilterAndAddStatuses(t.Cast <ITweetable>(), r));
                }
            }
#if WP8
            this.LoadFinished += (s, e) => SpeakNotifications();
#endif
        }
コード例 #6
0
 private void GetTopics()
 {
     IsLoading = true;
     ServiceDispatcher.GetCurrentService().ListLocalTrendsFor(new ListLocalTrendsForOptions {
         Id = (int)currentLocation
     }, ReceiveTrends);
 }
コード例 #7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Service Dispatcher");
            var dispatcher = new ServiceDispatcher();

            dispatcher.Run();
        }
コード例 #8
0
        void ChooserCompleted(object sender, PhotoResult e)
        {
            if (e.TaskResult != TaskResult.OK)
            {
                return;
            }

            IsLoading = true;
            BarText   = Resources.UploadingPicture;

            TwitterService srv = ServiceDispatcher.GetService(DataTransfer.CurrentAccount) as TwitterService;

            if (srv == null)
            {
                return; // Dirty trick: it will never be null if we're not testing.
            }
            RestRequest req    = srv.PrepareEchoRequest();
            RestClient  client = new RestClient {
                Authority = "http://api.twitpic.com/", VersionPath = "1"
            };

            req.AddFile("media", e.OriginalFileName, e.ChosenPhoto);
            req.AddField("key", "1abb1622666934158f4c2047f0822d0a");
            req.AddField("message", TweetText);
            req.AddField("consumer_token", Ocell.Library.SensitiveData.ConsumerToken);
            req.AddField("consumer_secret", SensitiveData.ConsumerSecret);
            req.AddField("oauth_token", DataTransfer.CurrentAccount.Key);
            req.AddField("oauth_secret", DataTransfer.CurrentAccount.Secret);
            req.Path = "upload.xml";
            //req.Method = Hammock.Web.WebMethod.Post;

            client.BeginRequest(req, (RestCallback)uploadCompleted);
        }
コード例 #9
0
        public void Loaded(string resource, string userName)
        {
            whatUserList = resource;
            user         = userName;

            if (whatUserList == "followers")
            {
                ServiceDispatcher.GetCurrentService().ListFollowers(new ListFollowersOptions {
                    ScreenName = user, IncludeUserEntities = true
                }, ReceiveUsers);
                BarText   = Resources.DownloadingFollowers;
                PageTitle = Resources.Followers;
            }
            else if (whatUserList == "following")
            {
                ServiceDispatcher.GetCurrentService().ListFriends(new ListFriendsOptions {
                    ScreenName = user, IncludeUserEntities = true
                }, ReceiveUsers);
                BarText   = Resources.DownloadingFollowing;
                PageTitle = Resources.Following;
            }
            else
            {
                MessageService.ShowError(Resources.NotValidResource);
                GoBack();
                return;
            }

            IsLoading = true;
        }
コード例 #10
0
ファイル: CreateList.xaml.cs プロジェクト: swinghu/Ocell
        private void CreateButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ITwitterService srv = ServiceDispatcher.GetService(DataTransfer.CurrentAccount);
            TwitterListMode mode;

            if (PublicBtn.IsChecked == true)
            {
                mode = TwitterListMode.Public;
            }
            else
            {
                mode = TwitterListMode.Private;
            }
            Dispatcher.BeginInvoke(() => pBar.IsVisible = true);
            srv.CreateList(new CreateListOptions {
                ListOwner = DataTransfer.CurrentAccount.ScreenName, Name = ListName.Text, Description = ListDescp.Text, Mode = mode
            }, (list, response) =>
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(Localization.Resources.ListCreated);
                        NavigationService.GoBack();
                    });
                }
                else
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show(Localization.Resources.ErrorCreatingList));
                }

                Dispatcher.BeginInvoke(() => pBar.IsVisible = false);
            });
        }
コード例 #11
0
        void SendBufferUpdate(object param)
        {
            if (!TrialInformation.IsFullFeatured)
            {
                TrialInformation.ShowBuyDialog();
                return;
            }

            if (Config.BufferProfiles.Count == 0)
            {
                AskBufferLogin();
                return;
            }

            List <string> profiles = new List <string>();

            foreach (var account in SelectedAccounts.Cast <UserToken>())
            {
                var profile = Config.BufferProfiles.Where(x => x.ServiceUsername == account.ScreenName).FirstOrDefault();

                if (profile != null)
                {
                    profiles.Add(profile.Id);
                }
            }

            var service = ServiceDispatcher.GetBufferService();

            if (service != null)
            {
                IsLoading = true;
                service.PostUpdate(TweetText, profiles, ReceiveBufferResponse);
            }
        }
コード例 #12
0
 /// <summary>
 /// Apply the service behavior
 /// </summary>
 public void ApplyServiceBehavior(RestService service, ServiceDispatcher dispatcher)
 {
     foreach (var itm in service.Endpoints)
     {
         itm.AddEndpointBehavior(this);
     }
 }
コード例 #13
0
        public void ProcessRequest(HttpContext context)
        {
            var serializer    = new JavaScriptSerializer();
            var serviceName   = context.Request["serviceName"];
            var operationName = context.Request["operationName"];

            try
            {
                var ops        = ServiceDispatcher.GetOperation(serviceName, operationName);
                var parameters = new List <object>();
                int num        = 0;
                foreach (var parameterInfo in ops.MethodInfo.GetParameters())
                {
                    ++num;
                    var input = context.Request["parameter" + num];
                    parameters.Add(serializer.Deserialize(input, parameterInfo.ParameterType));
                }
                var result = ops.MethodInfo.Invoke(ops.ServiceDescriptor.TargetInstance, parameters.ToArray());
                context.Response.ContentType = "text/json";
                context.Response.Write(new JavaScriptSerializer().Serialize(result));
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error executing {0}.{1}", serviceName, operationName), ex);
            }
        }
コード例 #14
0
ファイル: LoadedApk.cs プロジェクト: zhouweiaccp/XobotOS
 internal RunConnection(ServiceDispatcher _enclosing, android.content.ComponentName
                        name, android.os.IBinder service, int command)
 {
     this._enclosing = _enclosing;
     this.mName      = name;
     this.mService   = service;
     this.mCommand   = command;
 }
コード例 #15
0
        public void Test()
        {
            ServiceRegistry.Register <DemoService>();

            string expected = "hello abc";
            string actual   = ServiceDispatcher.Dispatch <string>("Demo", "hello", new { name = expected });

            Assert.AreEqual(expected, actual);
        }
コード例 #16
0
        public void Test()
        {
            ServiceRegistry.Register <CalculteService>();

            int expected = 5;
            int actual   = ServiceDispatcher.Dispatch <int>("Calculte", "Add", new { a = 2, b = 3 });

            Assert.AreEqual(expected, actual);
        }
コード例 #17
0
 public void Execute(object parameter)
 {
     Dependency.Resolve <IMessageService>().SetLoadingBar(true);
     ServiceDispatcher.GetService(DataTransfer.CurrentAccount).Retweet(new RetweetOptions {
         Id = ((ITweetable)parameter).Id
     }, (sts, resp) =>
     {
         Dependency.Resolve <IMessageService>().ShowLightNotification(Resources.Retweeted);
     });
 }
コード例 #18
0
        public void DispatchReflection_ServiceShouldReturnValue()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 service1 = new Service1();

            serviceDispatcher.Subscribe <IService1>(service1);
            Assert.Equal(3, serviceDispatcher.Dispatch("service1", "serviceMethod3", new object[] { 1, 2 }).Cast <int>().Single());
        }
コード例 #19
0
        public void Dispatch_ServiceShouldReturnValue()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 service1 = new Service1();

            serviceDispatcher.Subscribe <IService1>(service1);
            Assert.Equal(3, serviceDispatcher.Dispatch <IService1, int>(s => s.ServiceMethod3(1, 2)).Single());
        }
コード例 #20
0
        public XmlElement Process(ServiceDispatcher header, XmlElement request)
        {
            var inValue = new ProcessRequest
            {
                Header  = header,
                Request = request
            };
            var retVal = ((IDispatcherV2SignedService)(this)).Process(inValue);

            return(retVal.Response);
        }
コード例 #21
0
        public void Dispatch_ServiceShouldHaveBeenCalledWithParameter()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 service1 = new Service1();

            serviceDispatcher.Subscribe <IService1>(service1);
            serviceDispatcher.Dispatch <IService1>(s => s.ServiceMethod2(42));

            Assert.Equal(42, service1.ServiceMethod2Result);
        }
コード例 #22
0
        public void DispatchReflection_ServiceShouldHaveBeenCalled()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 service1 = new Service1();

            serviceDispatcher.Subscribe <IService1>(service1);
            serviceDispatcher.Dispatch("service1", "serviceMethod1", null);

            Assert.True(service1.ServiceMethod1Called);
        }
コード例 #23
0
        void ListManager_Loaded(object sender, RoutedEventArgs e)
        {
            if (!NavigationContext.QueryString.TryGetValue("user", out _userName))
            {
                NavigationService.GoBack();
                return;
            }

            _srv = ServiceDispatcher.GetService(DataTransfer.CurrentAccount);

            LoadListsIn();
            LoadUserLists();
        }
コード例 #24
0
        public void DispatchReflection_NamedService_ServiceShouldReturnValue()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 instance1 = new Service1("Instance1");
            Service1 instance2 = new Service1("Instance2");

            serviceDispatcher.Subscribe <IService1>(instance1);
            serviceDispatcher.Subscribe <IService1>(instance2);
            Assert.Equal(3, Convert.ToInt32(serviceDispatcher.Dispatch("service1", "Instance1", "serviceMethod3", new object[] { 1, 2 })));
        }
コード例 #25
0
        public void Dispatch_NamedService_ServiceShouldReturnValue()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 instance1 = new Service1("Instance1");
            Service1 instance2 = new Service1("Instance2");

            serviceDispatcher.Subscribe <IService1>(instance1);
            serviceDispatcher.Subscribe <IService1>(instance2);
            Assert.Equal(3, serviceDispatcher.Dispatch <IService1, int>("Instance1", s => s.ServiceMethod3(1, 2)));
        }
コード例 #26
0
        public void DispatchReflection_ServiceShouldHaveBeenCalledWithDifferentParameterType()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 service1 = new Service1();

            serviceDispatcher.Subscribe <IService1>(service1);
            serviceDispatcher.Dispatch("service1", "serviceMethod2", new object[] { 42L });

            Assert.Equal(42, service1.ServiceMethod2Result);
        }
コード例 #27
0
        public void Dispatch_NoSubscribedService_ServiceShouldNotHaveBeenCalled()
        {
            ServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 service1 = new Service1();

            serviceDispatcher.Subscribe <IService1>(service1);
            serviceDispatcher.Unsubscribe <IService1>(service1);
            serviceDispatcher.Dispatch <IService1>(s => s.ServiceMethod1());

            Assert.False(service1.ServiceMethod1Called);
        }
コード例 #28
0
        void ReceiveTLResponse(TwitlongerPost post, TwitlongerResponse response)
        {
            if (response.StatusCode != HttpStatusCode.OK || post == null || post.Post == null || string.IsNullOrEmpty(post.Post.Content) || response.Sender == null)
            {
                IsLoading = false;
                MessageService.ShowError(Resources.ErrorCreatingTwitlonger);
                return;
            }

            BarText = Resources.SendingTweet;

            string name = response.Sender.Username;

            var account = Config.Accounts.FirstOrDefault(x => x.ScreenName == name);

            if (account == null)
            {
                IsLoading = false;
                MessageService.ShowError(Resources.ErrorCreatingTwitlonger);
                return;
            }

            try
            {
                lock (dicLock)
                    TwitlongerIds.Add(name, post.Post.Id);
            }
            catch
            {
                // TODO: Sometimes, this gives a weird OutOfRange exception. Don't know why, investigate it.
            }

            if (IsGeotagged)
            {
                var location = geoWatcher.Position.Location;
                ServiceDispatcher.GetService(account).SendTweet(new SendTweetOptions
                {
                    Status            = post.Post.Content,
                    InReplyToStatusId = DataTransfer.ReplyId,
                    Lat  = location.Latitude,
                    Long = location.Longitude
                }, ReceiveResponse);
            }
            else
            {
                ServiceDispatcher.GetService(account).SendTweet(new SendTweetOptions {
                    Status = post.Post.Content, InReplyToStatusId = DataTransfer.ReplyId
                }, ReceiveResponse);
            }
        }
コード例 #29
0
ファイル: TweetModel.cs プロジェクト: swinghu/Ocell
 void FillUser()
 {
     ServiceDispatcher.GetDefaultService().GetUserProfileFor(new GetUserProfileForOptions {
         ScreenName = Tweet.Author.ScreenName
     }, (user, response) =>
     {
         if (response.StatusCode != HttpStatusCode.OK)
         {
             MessageService.ShowError(Localization.Resources.ErrorGettingProfile);
         }
         Tweet.User = user;
         SetAvatar();
     });
 }
コード例 #30
0
        public void ShouldSuccessfullySubscribeWithMultipleSubscribedServices()
        {
            EventHandler event1Handler = (o, e) => { };

            IServiceDispatcher serviceDispatcher = new ServiceDispatcher(new TestPlatformProvider());

            serviceDispatcher.Initialize();

            Service1 service1 = new Service1();
            Service2 service2 = new Service2();

            serviceDispatcher.Subscribe <IService1>(service1);
            serviceDispatcher.SubscribeEvent <IService1>(s => s.Event1 += event1Handler, s => s.Event1 -= event1Handler);
            serviceDispatcher.Subscribe <IService2>(service2);
        }
コード例 #31
0
        /// <summary>
        /// Loads location specific settings for each module via a service request.
        /// </summary>
        /// <param name="requestPath"></param>
        internal void LoadLocationContextSettings(string requestPath)
        {
            // Get settings from a service
            var dispatcher = new ServiceDispatcher();
            var settings = dispatcher.GetLocationContextSettings();

            if (settings != null)
            {
                _id = settings.Single(s => s.Key.ToString() == "LocationContextId").Value;

                AddModuleUrlInfoToCollection("Provider", settings);
                AddModuleUrlInfoToCollection("Event", settings);
                AddModuleUrlInfoToCollection("Location", settings);
                AddModuleUrlInfoToCollection("Service", settings);
            }
        }
コード例 #32
0
ファイル: LoadedApk.cs プロジェクト: hakeemsm/XobotOS
				internal DeathMonitor(ServiceDispatcher _enclosing, android.content.ComponentName
					 name, android.os.IBinder service)
				{
					this._enclosing = _enclosing;
					this.mName = name;
					this.mService = service;
				}
コード例 #33
0
ファイル: LoadedApk.cs プロジェクト: hakeemsm/XobotOS
				internal RunConnection(ServiceDispatcher _enclosing, android.content.ComponentName
					 name, android.os.IBinder service, int command)
				{
					this._enclosing = _enclosing;
					this.mName = name;
					this.mService = service;
					this.mCommand = command;
				}
コード例 #34
0
        /// <summary>
        /// Determines the ID of an entity based on its direct URL.
        /// </summary>
        /// <param name="requestPath">The direct URL.</param>
        /// <param name="moduleName">Name of the module to which the entity belongs.</param>
        /// <returns></returns>
        private string ResolveEntityId(string requestPath, string moduleName)
        {
            var entityId = "0";

            // Extract Direct URL identifier from request URL
            var directUrl = requestPath
                .Substring(requestPath.LastIndexOf("/") + 1)
                .Replace(".aspx", string.Empty);

            // First attempt to find entity ID in cache
            var cacheKey = "DirectUrlEntityId_" + moduleName + "_" + directUrl;

            if (_cache.Contains(cacheKey))
            {
                entityId = (string)_cache.Get(cacheKey);
            }
            else
            {
                // Get entity ID from service
                var dispatcher = new ServiceDispatcher();
                entityId = dispatcher.GetModuleEntityIdFromDirectUrl(moduleName, directUrl);

                _cache.Put(cacheKey, entityId);
            }

            return entityId;
        }