Example #1
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            //AndroidPclExportClient.Configure();

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var btnSync = FindViewById<Button>(Resource.Id.btnSync);
            var btnAsync = FindViewById<Button>(Resource.Id.btnAsync);
            var btnAwait = FindViewById<Button>(Resource.Id.btnAwait);
            var txtName = FindViewById<EditText>(Resource.Id.txtName);
            var lblResults = FindViewById<TextView>(Resource.Id.lblResults);

            //10.0.2.2 = loopback
            //http://developer.android.com/tools/devices/emulator.html
            var client = new JsonServiceClient("http://10.0.2.2:81/");

            btnSync.Click += delegate
            {
                try
                {
                    var response = client.Get(new Hello { Name = txtName.Text });
                    lblResults.Text = response.Result;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };

            btnAsync.Click += delegate
            {
                client.GetAsync(new Hello { Name = txtName.Text })
                    .Success(response => lblResults.Text = response.Result)
                    .Error(ex => lblResults.Text = ex.ToString());
            };

            btnAwait.Click += async delegate
            {
                try
                {
                    var response = await client.GetAsync(new Hello { Name = txtName.Text });
                    lblResults.Text = response.Result;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };
        }
Example #2
0
 public async Task IsAlive()
 {
     var client = new JsonServiceClient(AcDomain.NodeHost.Nodes.ThisNode.Node.AnycmdApiAddress);
     var isAlive = new IsAlive
     {
         Version = "v1"
     };
     var response = await client.GetAsync(isAlive);
     Assert.IsTrue(response.IsAlive);
     isAlive.Version = "version2";
     response = await client.GetAsync(isAlive);
     Assert.IsFalse(response.IsAlive);
     Assert.IsTrue(Status.InvalidApiVersion.ToName() == response.ReasonPhrase, response.Description);
 }
        public async Task Can_report_progress_when_downloading_async()
        {
            var hold = AsyncServiceClient.BufferSize;
            AsyncServiceClient.BufferSize = 100;

            try
            {
                var asyncClient = new JsonServiceClient(ListeningOn);

                var progress = new List<string>();

                //Note: total = -1 when 'Transfer-Encoding: chunked'
                //Available in ASP.NET or in HttpListener when downloading responses with known lengths: 
                //E.g: Strings, Files, etc.
                asyncClient.OnDownloadProgress = (done, total) =>
                    progress.Add("{0}/{1} bytes downloaded".Fmt(done, total));

                var response = await asyncClient.GetAsync(new TestProgress());

                progress.Each(x => x.Print());

                Assert.That(response.Length, Is.GreaterThan(0));
                Assert.That(progress.Count, Is.GreaterThan(0));
                Assert.That(progress.First(), Is.EqualTo("100/1160 bytes downloaded"));
                Assert.That(progress.Last(), Is.EqualTo("1160/1160 bytes downloaded"));
            }
            finally
            {
                AsyncServiceClient.BufferSize = hold;
            }
        }         
Example #4
0
        public async Task <IList <System.IdentityModel.Tokens.SecurityToken> > GetAsync()
#endif
        {
            var httpClient = new JsonServiceClient();

            string document;

            try
            {
                document = await httpClient.GetAsync <string>(appSettings.JwksUrl)
                           .ConfigureAwait(false);
            }
            catch (AggregateException exception)
            {
                foreach (var ex in exception.InnerExceptions)
                {
                    Log.Error($"Error occurred requesting json web key set from {appSettings.JwksUrl}", ex);
                }
                return(null);
            }

#if NETSTANDARD1_6
            var webKeySet = new Microsoft.IdentityModel.Tokens.JsonWebKeySet(document);
            return(webKeySet.GetSigningKeys());
#elif NET45
            var webKeySet = new Microsoft.IdentityModel.Protocols.JsonWebKeySet(document);
            return(webKeySet.GetSigningTokens());
#endif
        }
Example #5
0
 partial void getFilesAtPathAsync(MonoTouch.UIKit.UIButton sender)
 {
     //calling async web service
     gateway.GetAsync <FilesResponse>(txtPath.Text,
                                      r => InvokeOnMainThread(() => txtResults.Text = r.Dump()),
                                      null);
 }
Example #6
0
        public async Task Can_report_progress_when_downloading_GET_async()
        {
            var hold = AsyncServiceClient.BufferSize;

            AsyncServiceClient.BufferSize = 100;

            try
            {
                var asyncClient = new JsonServiceClient(ListeningOn);

                var progress = new List <string>();

                //Note: total = -1 when 'Transfer-Encoding: chunked'
                //Available in ASP.NET or in HttpListener when downloading responses with known lengths:
                //E.g: Strings, Files, etc.
                asyncClient.OnDownloadProgress = (done, total) =>
                                                 progress.Add("{0}/{1} bytes downloaded".Fmt(done, total));

                var response = await asyncClient.GetAsync(new TestProgressString());

                progress.Each(x => x.Print());

                Assert.That(response.Length, Is.GreaterThan(0));
                Assert.That(progress.Count, Is.GreaterThan(0));
                Assert.That(progress.First(), Is.EqualTo("100/1160 bytes downloaded"));
                Assert.That(progress.Last(), Is.EqualTo("1160/1160 bytes downloaded"));
            }
            finally
            {
                AsyncServiceClient.BufferSize = hold;
            }
        }
Example #7
0
        public Task <RegisterUserResponse> RegisterUserAsync(RegisterUserRequest request)
        {
            var client = new JsonServiceClient(Config.http);
            var task   = client.GetAsync(request);

            return(task);
        }
Example #8
0
        async partial void btnJwt_Click(NSObject sender)
        {
            try
            {
                var authClient   = CreateClient();
                var authResponse = await authClient.PostAsync(new Authenticate
                {
                    provider = "credentials",
                    UserName = "******",
                    Password = "******",
                });

                var client = new JsonServiceClient(BaseUrl)
                {
                    BearerToken = authResponse.BearerToken //JWT
                };

                var response = await client.GetAsync(new HelloAuth { Name = "JWT Auth" });

                lblResults.StringValue = response.Result;
            }
            catch (Exception ex)
            {
                lblResults.StringValue = ex.ToString();
            }
        }
        public async Task <DocumentDiscoveryResult> GetAsync(string endpoint)
        {
            IJsonServiceClient client = new JsonServiceClient(appSettings.AuthRealm);

            string document;

            try
            {
                document = await client.GetAsync <string>(endpoint)
                           .ConfigureAwait(false);
            }
            catch (AggregateException exception)
            {
                foreach (var ex in exception.InnerExceptions)
                {
                    Log.Error($"Error occurred requesting document data from {endpoint}", ex);
                }
                return(null);
            }

            var configuration = new Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration(document);

            return(new DocumentDiscoveryResult
            {
                AuthorizeUrl = configuration.AuthorizationEndpoint,
                IntrospectUrl = GetStringValue(document, "introspection_endpoint"),
                UserInfoUrl = configuration.UserInfoEndpoint,
                TokenUrl = configuration.TokenEndpoint,
                JwksUrl = configuration.JwksUri
            });
        }
Example #10
0
        public async Task IsAlive()
        {
            var client  = new JsonServiceClient(AcDomain.NodeHost.Nodes.ThisNode.Node.AnycmdApiAddress);
            var isAlive = new IsAlive
            {
                Version = "v1"
            };
            var response = await client.GetAsync(isAlive);

            Assert.IsTrue(response.IsAlive);
            isAlive.Version = "version2";
            response        = await client.GetAsync(isAlive);

            Assert.IsFalse(response.IsAlive);
            Assert.IsTrue(Status.InvalidApiVersion.ToName() == response.ReasonPhrase, response.Description);
        }
Example #11
0
 public Task <List <CoinDTO> > GetAllCurrenciesByDefaultFiatCurrencyAsync()
 {
     using (var client = new JsonServiceClient(SERVICE_URL))
     {
         String path = PreferenceManager.DefaultCurrencyId == "USD" ? "/" : "/?convert=" + DependencyService.Get <IVM>().GetFiatCurrencyManager().GetFiatCurrencyById(PreferenceManager.DefaultCurrencyId).ApiConvertAppendix;
         return(client.GetAsync <List <CoinDTO> >(path));
     }
 }
Example #12
0
        public async Task Simulate_broken_Network()
        {
            var client = new JsonServiceClient("http://test.servicestack.net");

            var response = await client.GetAsync(new Wait { ForMs = 50000 });

            response.PrintDump();
        }
Example #13
0
 private void btnGoAsync_Click(object sender, RoutedEventArgs e)
 {
     client.GetAsync(new Hello {
         Name = txtName.Text
     })
     .Success(r => lblResults.Text = r.Result)
     .Error(ex => lblResults.Text  = ex.ToString());
 }
Example #14
0
        public async Task Does_fire_all_filters_async()
        {
            var client = new JsonServiceClient(Config.ServiceStackBaseUri);

            var response = await client.GetAsync(new TestFiltersAsync());

            Assert.That(AllFieldsTrue(response));
        }
 partial void btnGoAsync_Click(NSObject sender)
 {
     client.GetAsync(new Hello {
         Name = txtName.Text
     })
     .Success(response => lblResults.Text = response.Result)
     .Error(ex => lblResults.Text         = ex.ToString());
 }
Example #16
0
        public Task <CheckUserResponse> CheckUserAsync(CheckUserRequest request)
        {
            //
            var client = new JsonServiceClient(Config.http);
            var task   = client.GetAsync(request);

            return(task);
            //
        }
Example #17
0
        public override Task <T> CookieAuthGET <T>(D8Cookie cookie, string resourceUrl, CancellationToken cancelTkn)
        {
            var client = new JsonServiceClient(Creds.BaseURL);

            client.SetCookie(cookie.Name, cookie.Id);

            return(Retry.Forever <T>(resourceUrl, (x, ct)
                                     => client.GetAsync <string>(resourceUrl), cancelTkn));
        }
 partial void btnGoAsync_TouchUpInside(UIButton sender)
 {
     Console.WriteLine("btnGoAsync_TouchUpInside");
     client.GetAsync(new Hello {
         Name = txtName.Text
     })
     .Success(response => lblResults.Text = response.Result)
     .Error(ex => lblResults.Text         = ex.ToString());
 }
        //

        //
        public Task <GetSchoolResponse> GetSchoolAsync(GetSchoolRequest request)
        {
            //
            var client = new JsonServiceClient(Config.http);
            var task   = client.GetAsync(request);

            return(task);
            //
        }
        public async Task ShouldRetrieveCreatedSchedule()
        {
            var scheduleWebApiClient = new JsonServiceClient(ScheduleWebApiBaseUrl);

            var maintenanceWindowServiceLocation = new ServiceLocation
            {
                Location = new Uri("http://localhost:5678")
            };

            _mockServer.Given(
                Request.Create().UsingGet().WithPath("/MaintenanceWindowService"))
            .RespondWith(
                Response.Create().WithSuccess().WithBodyAsJson(maintenanceWindowServiceLocation));

            var maintenanceWindows = new MaintenanceWindow
            {
                LengthInHours = 5
            };

            _mockServer.Given(
                Request.Create().UsingGet().WithPath("/Planned"))
            .RespondWith(
                Response.Create().WithSuccess().WithBodyAsJson(maintenanceWindows));

            var workloadItems = new List <WorkloadItem>
            {
                new WorkloadItem
                {
                    Identifier      = Guid.NewGuid(),
                    DurationInHours = 7
                },
                new WorkloadItem
                {
                    Identifier      = Guid.NewGuid(),
                    DurationInHours = 3
                }
            };
            var createScheduleRequest = new CreateScheduleRequest
            {
                WorkloadItems = workloadItems
            };

            var createScheduleResponse = await scheduleWebApiClient.PostAsync(createScheduleRequest).ConfigureAwait(false);

            var getScheduleByIdRequest = new GetScheduleByIdRequest
            {
                ScheduleId = createScheduleResponse.Id
            };
            var getScheduleByIdResponse = await scheduleWebApiClient.GetAsync(getScheduleByIdRequest).ConfigureAwait(false);

            getScheduleByIdResponse.Schedule.Count.Should().Be(2);
            getScheduleByIdResponse.Schedule.Should().Contain(x => x.Identifier == workloadItems[0].Identifier &&
                                                              x.Order == 2);
            getScheduleByIdResponse.Schedule.Should().Contain(x => x.Identifier == workloadItems[1].Identifier &&
                                                              x.Order == 1);
        }
Example #21
0
        public Task <List <SubscriptionDTO> > GetUserSubscription(int userId)
        {
            var client = new JsonServiceClient(BaseUrl);

            client.AddHeader("Authorization", "Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ=");

            var result = client.GetAsync <List <SubscriptionDTO> >($"/api/subscription/UserSubscriptions/{userId}");

            return(result);
        }
Example #22
0
        public Task <List <RouteDTO> > GetAllRoutes()
        {
            var client = new JsonServiceClient(BaseUrl);

            client.AddHeader("Authorization", "Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ=");

            var result = client.GetAsync <List <RouteDTO> >("/api/Route/GetAll");

            return(result);
        }
Example #23
0
        public async Task <T> GetAsync <T>(IReturn <T> request)
        {
            var taskCompletionSource = new TaskCompletionSource <T>();

            await AuthorizeAsync(_userSettingsService.GetSettings());

            _jsonServiceClient.GetAsync(request,
                                        taskCompletionSource.SetResult,
                                        (obj, error) => taskCompletionSource.SetException(error));
            return(await taskCompletionSource.Task);
        }
Example #24
0
        public void WhenIRequestDataByIdThruGetAsyncAction(int id)
        {
            var request = new GetOrderById
            {
                Id = id
            };
            JsonServiceClient client   = GetClient();
            List <Order>      response = client.GetAsync <List <Order> >(request).Result;

            ScenarioContext.Current[ResopnseKey] = response;
        }
Example #25
0
        public static async Task <T> GetAsync <T>(string query)
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            var service = new JsonServiceClient();
            var r       = await service.GetAsync <T>(query);

            service.Dispose();
            //sw.Stop();
            //Trace.WriteLine($"query={query}, datetime={DateTime.Now}, sw={sw.ElapsedMilliseconds}");
            return(r);
        }
Example #26
0
        public async Task Can_proxy_to_techstacks_Async()
        {
            var client = new JsonServiceClient(ListeningOn.CombineWith("techstacks"));

            var request = new GetTechnology
            {
                Slug = "ServiceStack"
            };
            var response = await client.GetAsync(request);

            Assert.That(response.Technology.VendorUrl, Is.EqualTo("https://servicestack.net"));
        }
Example #27
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            //AndroidPclExportClient.Configure();

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var btnGoSync  = FindViewById <Button>(Resource.Id.btnGoSync);
            var btnGoAsync = FindViewById <Button>(Resource.Id.btnGoAsync);
            var btnTest    = FindViewById <Button>(Resource.Id.btnTest);
            var txtName    = FindViewById <EditText>(Resource.Id.txtName);
            var lblResults = FindViewById <TextView>(Resource.Id.lblResults);

            //10.0.2.2 = loopback
            //http://developer.android.com/tools/devices/emulator.html
            var client = new JsonServiceClient("http://10.0.2.2:81/");

            btnGoSync.Click += delegate
            {
                try
                {
                    var response = client.Get(new Hello {
                        Name = txtName.Text
                    });
                    lblResults.Text = response.Result;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };

            btnGoAsync.Click += delegate
            {
                client.GetAsync(new Hello {
                    Name = txtName.Text
                })
                .Success(response => lblResults.Text = response.Result)
                .Error(ex => lblResults.Text         = ex.ToString());
            };

            btnTest.Click += delegate
            {
                try
                {
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };
        }
Example #28
0
        private async Task FabOnClick(object sender, EventArgs eventArgs)
        {
            var client   = new JsonServiceClient("https://todoworld.servicestack.net");
            var response = await client.GetAsync(new Hello
            {
                Name = "Xamarin.Android async"
            });

            View view = (View)sender;

            Snackbar.Make(view, response.Result, Snackbar.LengthLong)
            .SetAction("Action", (Android.Views.View.IOnClickListener)null).Show();
        }
 protected async override Task <IMessageDto> TransmitCoreAsync(DistributeContext context)
 {
     try
     {
         var client = new JsonServiceClient(context.Responder.AnycmdApiAddress);
         return(await client.GetAsync(GetRequest(context)));
     }
     catch (Exception ex)
     {
         context.Exception = ex;
         return(null);
     }
 }
 protected async override Task<IBeatResponse> IsAliveCoreAsync(BeatContext context)
 {
     try
     {
         var client = new JsonServiceClient(context.Node.Node.AnycmdApiAddress);
         return await client.GetAsync(GetRequest(context));
     }
     catch (Exception ex)
     {
         context.Exception = ex;
         return null;
     }
 }
 protected async override Task<IMessageDto> TransmitCoreAsync(DistributeContext context)
 {
     try
     {
         var client = new JsonServiceClient(context.Responder.AnycmdApiAddress);
         return await client.GetAsync(GetRequest(context));
     }
     catch (Exception ex)
     {
         context.Exception = ex;
         return null;
     }
 }
        public async Task <IActionResult> CallServiceClient()
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var client = new JsonServiceClient("https://localhost:5001/")
            {
                BearerToken = accessToken
            };
            var response = await client.GetAsync(new GetIdentity());

            ViewBag.Json = response.ToJson().IndentJson();
            return(View("json"));
        }
 protected async override Task <IBeatResponse> IsAliveCoreAsync(BeatContext context)
 {
     try
     {
         var client = new JsonServiceClient(context.Node.Node.AnycmdApiAddress);
         return(await client.GetAsync(GetRequest(context)));
     }
     catch (Exception ex)
     {
         context.Exception = ex;
         return(null);
     }
 }
Example #34
0
        private async void TemplateForm_Load(object sender, EventArgs e)
        {
            if (ontologies == null)
            {
                try
                {
                    ShowProgressBar();
                    lblCaption.Text = "努力加载中……";
                    var getAllOntology = new GetAllOntologies();
                    var client         = new JsonServiceClient(serviceBaseUrl);
                    var response       = await client.GetAsync(getAllOntology);

                    ontologies = response.Ontologies;
                    foreach (var ontology in ontologies)
                    {
                        if (!ontology.IsSystem)
                        {
                            var pnl = new FlowLayoutPanel()
                            {
                                Tag        = ontology,
                                AutoScroll = true
                            };
                            var tabPage = new TabPage()
                            {
                                Text = ontology.Name, Tag = pnl
                            };
                            tabPage.Controls.Add(pnl);
                            pnl.Dock = DockStyle.Fill;
                            tabControl.TabPages.Add(tabPage);
                            foreach (var element in ontology.Elements)
                            {
                                var chkb = new CheckBox()
                                {
                                    Text  = element.Name + "(" + element.Key + ")",
                                    Tag   = element,
                                    Width = 150
                                };
                                chkb.CheckedChanged += chkb_CheckedChanged;
                                pnl.Controls.Add(chkb);
                            }
                        }
                    }
                    HideProgressBar();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        public async Task <List <ChannelInfo> > GetChannelsAsync()
        {
            List <ChannelInfo> channels = new List <ChannelInfo>();

            GetChannelsResponse response = await client.GetAsync(new GetChannelsRequest());

            if (response.Channels != null)
            {
                foreach (VdrChannel channel in response.Channels)
                {
                    channels.Add(new ChannelInfo()
                    {
                        Id          = channel.channel_id,
                        ChannelType = channel.is_radio ? ChannelType.Radio : ChannelType.TV,
                        Name        = channel.name,
                        Number      = channel.number.ToString(),
                        HasImage    = channel.image,
                        ImageUrl    = string.Format("{0}/channels/image/{1}", baseUrl, channel.channel_id)
                    });
                }
            }

            return(channels);
        }
Example #36
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            AndroidPclExportClient.Configure();

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            var button = FindViewById<Button>(Resource.Id.MyButton);
            button.Click += delegate { button.Text = string.Format("{0} clicks!!", count++); };

            var btnGoSync = FindViewById<Button>(Resource.Id.btnGoSync);
            var btnGoAsync = FindViewById<Button>(Resource.Id.btnGoAsync);
            var txtName = FindViewById<EditText>(Resource.Id.txtName);
            var txvResults = FindViewById<TextView>(Resource.Id.txvResults);

            //10.0.2.2 = loopback
            //http://developer.android.com/tools/devices/emulator.html
            var client = new JsonServiceClient("http://10.0.2.2:81/");

            btnGoSync.Click += delegate
            {
                try
                {
                    var response = client.Get(new Hello { Name = txtName.Text });
                    txvResults.Text = response.Result;
                }
                catch (Exception ex)
                {
                    txvResults.Text = ex.ToString();
                }
            };

            btnGoAsync.Click += delegate
            {
                client.GetAsync(new Hello { Name = txtName.Text })
                    .Success(response => {
                        txvResults.Text = response.Result;
                    })
                    .Error(ex => {
                        txvResults.Text = ex.ToString();    
                    });
            };
        }
Example #37
0
 private async void TemplateForm_Load(object sender, EventArgs e)
 {
     if (ontologies == null)
     {
         try
         {
             ShowProgressBar();
             lblCaption.Text = "努力加载中……";
             var getAllOntology = new GetAllOntologies();
             var client = new JsonServiceClient(serviceBaseUrl);
             var response = await client.GetAsync(getAllOntology);
             ontologies = response.Ontologies;
             foreach (var ontology in ontologies)
             {
                 if (!ontology.IsSystem)
                 {
                     var pnl = new FlowLayoutPanel()
                     {
                         Tag = ontology,
                         AutoScroll = true
                     };
                     var tabPage = new TabPage() { Text = ontology.Name, Tag = pnl };
                     tabPage.Controls.Add(pnl);
                     pnl.Dock = DockStyle.Fill;
                     tabControl.TabPages.Add(tabPage);
                     foreach (var element in ontology.Elements)
                     {
                         var chkb = new CheckBox()
                         {
                             Text = element.Name + "(" + element.Key + ")",
                             Tag = element,
                             Width = 150
                         };
                         chkb.CheckedChanged += chkb_CheckedChanged;
                         pnl.Controls.Add(chkb);
                     }
                 }
             }
             HideProgressBar();
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
Example #38
0
        private async void btnAuth_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var client = new JsonServiceClient("http://localhost:81/");

                await client.PostAsync(new Authenticate
                {
                    provider = "credentials",
                    UserName = "******",
                    Password = "******",
                });

                var response = await client.GetAsync(new HelloAuth { Name = "secure" });

                lblResults.Content = response.Result;
            }
            catch (Exception ex)
            {
                lblResults.Content = ex.ToString();
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.login);

            SupportToolbar mToolbar = FindViewById<SupportToolbar>(Resource.Id.loginToolbar);
            SetSupportActionBar(mToolbar);
            SupportActionBar.SetHomeButtonEnabled(true);
            SupportActionBar.SetDisplayShowTitleEnabled(true);

            progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);

            animation = ObjectAnimator.OfInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animale towards that value
            animation.RepeatMode = ValueAnimatorRepeatMode.Reverse;
            animation.RepeatCount = 100;
            animation.SetDuration(1500);
            animation.SetInterpolator(new FastOutLinearInInterpolator());

            var btnTwitter = FindViewById<ImageButton>(Resource.Id.btnTwitter);
            var btnAnon = FindViewById<ImageButton>(Resource.Id.btnAnon);
            var client = new JsonServiceClient(MainActivity.BaseUrl);
            
            btnTwitter.Click += (sender, args) =>
            {
                StartProgressBar();
                Account existingAccount;
                // If cookies saved from twitter login, automatically continue to chat activity.
                if (TryResolveAccount(out existingAccount))
                {
                    try
                    {
                        client.CookieContainer = existingAccount.Cookies;
                        var task = client.GetAsync(new GetUserDetails());
                        task.ConfigureAwait(false);
                        task.ContinueWith(res =>
                        {
                            if (res.Exception != null)
                            {
                                // Failed with current cookie 
                                client.ClearCookies();
                                PerformServiceStackAuth(client);
                                StopProgressBar();
                            }
                            else
                            {
                                StartAuthChatActivity(client, existingAccount);
                                StopProgressBar();
                            }
                            
                        });
                    }
                    catch (Exception)
                    {
                        // Failed with current cookie 
                        client.ClearCookies();
                        StopProgressBar();
                        PerformServiceStackAuth(client);
                    }
                }
                else
                {
                    StopProgressBar();
                    PerformServiceStackAuth(client);
                }
                    
            };

            btnAnon.Click += (sender, args) =>
            {
                StartProgressBar();
                StartGuestChatActivity(client);
                StopProgressBar();
            };
        }
 private static Task<WeatherResponse> GetResponse(string m_uri)
 {
     JsonServiceClient client = new JsonServiceClient("http://api.wunderground.com/api");
     return client.GetAsync<WeatherResponse>(m_uri);
 }
Example #41
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            //AndroidPclExportClient.Configure();

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var btnGoSync = FindViewById<Button>(Resource.Id.btnGoSync);
            var btnGoAsync = FindViewById<Button>(Resource.Id.btnGoAsync);
            var btnGoShared = FindViewById<Button>(Resource.Id.btnGoShared);
            var btnTest = FindViewById<Button>(Resource.Id.btnTest);
            var txtName = FindViewById<EditText>(Resource.Id.txtName);
            var lblResults = FindViewById<TextView>(Resource.Id.lblResults);

            //10.0.2.2 = loopback
            //http://developer.android.com/tools/devices/emulator.html
            var client = new JsonServiceClient("http://10.0.2.2:81/");
            var gateway = new SharedGateway("http://10.0.2.2:81/");

            btnGoSync.Click += delegate
            {
                try
                {
                    var response = client.Get(new Hello { Name = txtName.Text });
                    lblResults.Text = response.Result;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };

            btnGoAsync.Click += delegate
            {
                client.GetAsync(new Hello { Name = txtName.Text })
                    .Success(response => lblResults.Text = response.Result)
                    .Error(ex => lblResults.Text = ex.ToString());
            };

            btnTest.Click += delegate
            {
                try
                {
                    var dto = new Question
                    {
                        Id = Guid.NewGuid(),
                        Title = "Title",
                    };

                    var json = dto.ToJson();
                    var q = json.FromJson<Question>();
                    lblResults.Text = "{0}:{1}".Fmt(q.Id, q.Title);
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };

            btnGoShared.Click += async delegate
            {
                try
                {
                    var greeting = await gateway.SayHello(txtName.Text);
                    lblResults.Text = greeting;
                }
                catch (Exception ex)
                {
                    var lbl = ex.ToString();
                    lbl.Print();

                    lblResults.Text = ex.ToString();
                }
            };
        }
Example #42
0
        public async Task Load_test_GetFactorialGenericAsync_async()
        {
            var client = new JsonServiceClient(Config.ServiceStackBaseUri);

            int i = 0;

            var fetchTasks = NoOfTimes.Times(() =>
                client.GetAsync(new GetFactorialGenericAsync { ForNumber = 3 })
                .ContinueWith(t =>
                {
                    if (++i % 100 == 0)
                    {
                        "{0}: {1}".Print(i, t.Result.Result);
                    }
                }));

            await Task.WhenAll(fetchTasks);
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            client = new JsonServiceClient ("http://10.1.1.109/api");

            PopulateSelectUsers ();

            Spinner usersSpinner = FindViewById<Spinner> (Resource.Id.usersSpinner);
            usersSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
            {
                var selectedUser = users[usersSpinner.SelectedItemPosition];
                TextView goalTextView = FindViewById<TextView> (Resource.Id.GoalTotal);
                TextView totalTextView = FindViewById<TextView> (Resource.Id.Total);

                goalTextView.Text = selectedUser.Goal.ToString();
                totalTextView.Text = selectedUser.Total.ToString();

            };

            // event for add user
            var addUserButton = FindViewById<Button> (Resource.Id.AddUser);
            addUserButton.Click += (object sender, EventArgs e) => {
                TextView goalTextView = FindViewById<TextView> (Resource.Id.Goal);
                TextView nameTextView = FindViewById<TextView> (Resource.Id.Name);
                var goal = int.Parse (goalTextView.Text);
                var response = client.Send (new AddUser { Goal = goal, Name = nameTextView.Text });

                PopulateSelectUsers ();
                goalTextView.Text = string.Empty;
                nameTextView.Text = string.Empty;

                Toast.MakeText (this, "Added new user", ToastLength.Short).Show();

            };

            // event for add Protein
            var addProteinButton = FindViewById<Button> (Resource.Id.AddProtein);
            addProteinButton.Click += (object sender, EventArgs e) => {
                TextView amountTextView = FindViewById<TextView> (Resource.Id.Amount);
                var amount = int.Parse(amountTextView.Text);
                var selectedUser = users[usersSpinner.SelectedItemPosition];

                var response = client.Send (new AddProtein { Amount = amount, UserID = selectedUser.Id });
                selectedUser.Total = response.NewTotal;
                TextView totalTextView = FindViewById<TextView> (Resource.Id.Total);
                totalTextView.Text = selectedUser.Total.ToString();
                amountTextView.Text = string.Empty;

                //string usermessage =  "Added Protein to :" & selectedUser.Name;

                Toast.MakeText (this, "Added Protein to :" + selectedUser.Name, ToastLength.Short).Show();

            };

            client.GetAsync<UserResponse>("users",(w2) => {
                Console.WriteLine(w2);
                foreach(var c in w2.Users) {
                    Console.WriteLine(c);
                    Console.WriteLine(c.Name);

                }
            },
            (w2, ex) => {
                Console.WriteLine(ex.Message);
            });
        }
Example #44
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            //AndroidPclExportClient.Configure();

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var btnSync = FindViewById<Button>(Resource.Id.btnSync);
            var btnAsync = FindViewById<Button>(Resource.Id.btnAsync);
            var btnAwait = FindViewById<Button>(Resource.Id.btnAwait);
            var btnAuth = FindViewById<Button>(Resource.Id.btnAuth);
            var btnShared = FindViewById<Button>(Resource.Id.btnShared);
            var txtName = FindViewById<EditText>(Resource.Id.txtName);
            var lblResults = FindViewById<TextView>(Resource.Id.lblResults);

            //10.0.2.2 = loopback
            //http://developer.android.com/tools/devices/emulator.html
            var client = new JsonServiceClient("http://10.0.2.2:2000/");
            var gateway = new SharedGateway("http://10.0.2.2:2000/");

            btnSync.Click += delegate
            {
                try
                {
                    var response = client.Get(new Hello { Name = txtName.Text });
                    lblResults.Text = response.Result;

                    using (var ms = new MemoryStream("Contents".ToUtf8Bytes()))
                    {
                        ms.Position = 0;
                        var fileResponse = client.PostFileWithRequest<HelloResponse>(
                            "/hello", ms, "filename.txt", new Hello { Name = txtName.Text });

                        lblResults.Text = fileResponse.Result;
                    }
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };

            btnAsync.Click += delegate
            {
                client.GetAsync(new Hello { Name = txtName.Text })
                    .Success(response => lblResults.Text = response.Result)
                    .Error(ex => lblResults.Text = ex.ToString());
            };

            btnAwait.Click += async delegate
            {
                try
                {
                    var response = await client.GetAsync(new Hello { Name = txtName.Text });
                    lblResults.Text = response.Result;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };

            btnAuth.Click += async delegate
            {
                try
                {
                    await client.PostAsync(new Authenticate
                    {
                        provider = "credentials",
                        UserName = "******",
                        Password = "******",
                    });

                    var response = await client.GetAsync(new HelloAuth { Name = "Secure " + txtName.Text });

                    lblResults.Text = response.Result;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };

            btnShared.Click += async delegate
            {
                try
                {
                    var greeting = await gateway.SayHello(txtName.Text);
                    lblResults.Text = greeting;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.ToString();
                }
            };
        }
Example #45
0
 public async Task Action_Get_PerformanceAsync()
 {
     var client = new JsonServiceClient(AcDomain.NodeHost.Nodes.ThisNode.Node.AnycmdApiAddress);
     for (int i = 0; i < 1000; i++)
     {
         var request = new Message
         {
             MessageId = System.Guid.NewGuid().ToString(),
             Version = "v1",
             Verb = "Get",
             MessageType = "action",
             IsDumb = false,
             Ontology = "JS",
             Body = new BodyData(new KeyValueBuilder().Append("Id", Guid.NewGuid().ToString()).ToArray(), null),
             TimeStamp = DateTime.UtcNow.Ticks
         }.JspxToken();
         var response = await client.GetAsync(request);
     }
 }