Example #1
0
        private async void btnTest_Click(object sender, RoutedEventArgs e)
        {
            //Make all access to UI components in UI Thread, i.e. before entering bg thread.
            var name = txtName.Text;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    var client = new JsonServiceClient("http://localhost:2000/")
                    {
                        //this tries to access UI component which is invalid in bg thread
                        ShareCookiesWithBrowser = false
                    };
                    var fileStream = new MemoryStream("content body".ToUtf8Bytes());
                    var response = client.PostFileWithRequest<UploadFileResponse>(
                        fileStream, "file.txt", new UploadFile { Name = name });

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = "File Size: {0} bytes".Fmt(response.FileSize);
                    });
                }
                catch (Exception ex)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = ex.ToString();
                    });
                }
            });
        }
Example #2
0
        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            var name = txtName.Text;

            ThreadPool.QueueUserWorkItem(_ => {
                try
                {
                    client.ShareCookiesWithBrowser = false;
                    var fileStream = new MemoryStream("content body".ToUtf8Bytes());
                    var response   = client.PostFileWithRequest <UploadFileResponse>(
                        fileStream, "file.txt", new UploadFile {
                        Name = name
                    });

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = "File Size: {0} bytes".Fmt(response.FileSize);
                    });
                }
                catch (Exception ex)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = ex.ToString();
                    });
                }
            });
        }
Example #3
0
        private async void btnTest_Click(object sender, RoutedEventArgs e)
        {
            //Make all access to UI components in UI Thread, i.e. before entering bg thread.
            var name = txtName.Text;

            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    var client = new JsonServiceClient("http://localhost:2000/")
                    {
                        //this tries to access UI component which is invalid in bg thread
                        ShareCookiesWithBrowser = false
                    };
                    var fileStream = new MemoryStream("content body".ToUtf8Bytes());
                    var response   = client.PostFileWithRequest <SendFileResponse>(
                        fileStream, "file.txt", new SendFile {
                        Name = name
                    });

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = "File Size: {0} bytes".Fmt(response.FileSize);
                    });
                }
                catch (Exception ex)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        lblResults.Content = ex.ToString();
                    });
                }
            });
        }
Example #4
0
        internal static TResult Execute <TResult>(JsonServiceClient client, RestRequest request, ILog log)
            where TResult : class
        {
            client.BaseUri = request.Options.BaseUrl.TrimEnd('/') + "/";  //make sure we only have a single slash on end always


            var fileRestRequest = request as FileRestRequest;

            if (fileRestRequest != null)
            {
                Func <TResult> funcFile = () => client.PostFileWithRequest <TResult>(fileRestRequest.RelativeOrAbsoluteUrl,
                                                                                     fileRestRequest.FileInfo,
                                                                                     fileRestRequest.Request);

                return(WrapResult(funcFile, log, fileRestRequest.Options.RetryAttempts, fileRestRequest.Name));
            }
            var restRequest = request as StreamingRestRequest;

            if (restRequest != null)
            {
                var sr = restRequest;

                Func <TResult> funcStream =
                    () => client.PostFileWithRequest <TResult>(restRequest.RelativeOrAbsoluteUrl, sr.Stream,
                                                               sr.FileName,
                                                               restRequest.Request);

                return(WrapResult(funcStream, log, restRequest.Options.RetryAttempts, restRequest.Name));
            }

            Func <TResult> func =
                () =>
            {
                currentRequestOptions = request.Options;          //we need to set the default options here
                return(client.Send <TResult>(request.Method.ToString(), request.RelativeOrAbsoluteUrl, request.Request));
            };

            return(WrapResult(func, log, request.Options.RetryAttempts, request.Name));
        }
        public void Can_POST_upload_file_using_ServiceClient_with_request_containing_utf8_chars()
        {
            var client = new JsonServiceClient(ListeningOn);
            var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath());

            var request = new FileUpload { CustomerId = 123, CustomerName = "Föяšč" };
            var response = client.PostFileWithRequest<FileUploadResponse>(ListeningOn + "/fileuploads", uploadFile, request);

            var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd();
            Assert.That(response.FileName, Is.EqualTo(uploadFile.Name));
            Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length));
            Assert.That(response.Contents, Is.EqualTo(expectedContents));
            Assert.That(response.CustomerName, Is.EqualTo("Föяšč"));
            Assert.That(response.CustomerId, Is.EqualTo(123));
        }
Example #6
0
        public void Can_POST_upload_file_using_ServiceClient_with_request_and_QueryString()
        {
            IServiceClient client = new JsonServiceClient(Config.ServiceStackBaseUri);

            var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapHostAbsolutePath());

            var request  = new FileUpload();
            var response = client.PostFileWithRequest <FileUploadResponse>(
                Config.ServiceStackBaseUri + "/fileuploads?CustomerId=123&CustomerName=Foo,Bar",
                uploadFile, request);

            var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd();

            Assert.That(response.FileName, Is.EqualTo(uploadFile.Name));
            Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length));
            Assert.That(response.Contents, Is.EqualTo(expectedContents));
            Assert.That(response.CustomerName, Is.EqualTo("Foo,Bar"));
            Assert.That(response.CustomerId, Is.EqualTo(123));
        }
        public void Can_POST_upload_file_using_ServiceClient_with_request_and_QueryString()
        {
            IServiceClient client = new JsonServiceClient(ListeningOn);

            var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPlatformPath());

            var request  = new FileUpload();
            var response = client.PostFileWithRequest <FileUploadResponse>(
                ListeningOn + "/fileuploads?CustomerId=123&CustomerName=Foo,Bar",
                uploadFile, request);

            var expectedContents = uploadFile.OpenRead().ReadToEnd();

            Assert.That(response.Name, Is.EqualTo("upload"));
            Assert.That(response.FileName, Is.EqualTo(uploadFile.Name));
            Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length));
            Assert.That(response.Contents, Is.EqualTo(expectedContents));
            Assert.That(response.CustomerName, Is.EqualTo("Foo,Bar"));
            Assert.That(response.CustomerId, Is.EqualTo(123));
        }
Example #8
0
        public void Can_upload_file_with_Request()
        {
            var client = new JsonServiceClient(BaseUrl);

            var fileInfo = new FileInfo("~/App_Data/file.json".MapProjectPath());

            var response = client.PostFileWithRequest <UploadFileResponse>(
                "/UploadFile",
                fileToUpload: fileInfo,
                request: new UploadFile {
                File = "Request DTO Property"
            },
                fieldName: "file");

            Assert.That(response.Name, Is.EqualTo("file"));
            Assert.That(response.FileName, Is.EqualTo("file.json"));
            Assert.That(response.ContentLength, Is.EqualTo(fileInfo.Length));
            Assert.That(response.Contents, Is.EqualTo(fileInfo.ReadAllText()));
            Assert.That(response.File, Is.EqualTo("Request DTO Property"));
        }
Example #9
0
        public void PostFileWithRequest_returns_the_same_date_as_normal_Put_with_ServiceClient()
        {
            var client = new JsonServiceClient(ListeningOn);

            using (var fileStream = new FileInfo("~/TestExistingDir/upload.html".MapProjectPlatformPath()).OpenRead())
            {
                var request = new FileUpload {
                    CreatedDate = new DateTime(2014, 1, 1, 1, 0, 0)
                };

                var response = client.PostFileWithRequest <FileUploadResponse>(
                    "/fileuploads",
                    fileStream,
                    "upload.html",
                    request);

                Assert.That(response.CreatedDate, Is.EqualTo(request.CreatedDate).Within(TimeSpan.FromHours(1)));

                response = client.Put(request);

                Assert.That(response.CreatedDate, Is.EqualTo(request.CreatedDate).Within(TimeSpan.FromHours(1)));
            }
        }
            public bool Deploy(ZipPackage package, ILog logger)
            {
                var options = package.GetPackageOptions<WebOptions>();

                logger.Info("Deploying iis package to {0}:{1} using {2}".Fmt(options.WebsiteName, options.WebsitePort, options.DeployService));

                var client = new JsonServiceClient(options.DeployService); // todo
                var request = new TriggerDeployment()
                {
                    AppPoolName = "ZZZ_Integration_PoolName",
                    AppPoolUser = "******",
                    AppPoolPassword = "******",
                    WebsiteName = "ZZZ_Integration_Website_Simple",
                    AppRoot = "/",
                    PackageId = "IntegrationTest",
                    PackageVersion = "1.3.3.7",
                    WebsitePhysicalPath = @"C:\temp\integrationtests",
                    RuntimeVersion = RuntimeVersion.Version40,
                };

                var response = client.PostFileWithRequest<TriggerDeploymentResponse>("/deployments", new FileInfo("package.zip"), request);

                return true;
            }
Example #11
0
            public bool Deploy(ZipPackage package, ILog logger)
            {
                var options = package.GetPackageOptions <WebOptions>();

                logger.Info("Deploying iis package to {0}:{1} using {2}".Fmt(options.WebsiteName, options.WebsitePort, options.DeployService));

                var client  = new JsonServiceClient(options.DeployService); // todo
                var request = new TriggerDeployment()
                {
                    AppPoolName         = "ZZZ_Integration_PoolName",
                    AppPoolUser         = "******",
                    AppPoolPassword     = "******",
                    WebsiteName         = "ZZZ_Integration_Website_Simple",
                    AppRoot             = "/",
                    PackageId           = "IntegrationTest",
                    PackageVersion      = "1.3.3.7",
                    WebsitePhysicalPath = @"C:\temp\integrationtests",
                    RuntimeVersion      = RuntimeVersion.Version40,
                };

                var response = client.PostFileWithRequest <TriggerDeploymentResponse>("/deployments", new FileInfo("package.zip"), request);

                return(true);
            }
        public void Can_POST_upload_file_using_ServiceClient_with_request_and_QueryString()
        {
            IServiceClient client = new JsonServiceClient(Config.ServiceStackBaseUri);

            var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapHostAbsolutePath());

            var request = new FileUpload();
            var response = client.PostFileWithRequest<FileUploadResponse>(
                Config.ServiceStackBaseUri + "/fileuploads?CustomerId=123&CustomerName=Foo,Bar", 
                uploadFile, request);

            var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd();
            Assert.That(response.Name, Is.EqualTo("upload"));
            Assert.That(response.FileName, Is.EqualTo(uploadFile.Name));
            Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length));
            Assert.That(response.Contents, Is.EqualTo(expectedContents));
            Assert.That(response.CustomerName, Is.EqualTo("Foo,Bar"));
            Assert.That(response.CustomerId, Is.EqualTo(123));
        }
 public TResponse PostFileWithRequest <TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request)
 {
     return(client.PostFileWithRequest <TResponse>(relativeOrAbsoluteUrl, fileToUpload, request));
 }
Example #14
0
        public static void Main(List <NZEDBRelease> releases, IDbConnection db)
        {
            var client = new JsonServiceClient(appSettings.GetString("BaseUrl"));
            var folder = appSettings.GetString("FSPath");
            var apiKey = appSettings.GetString("ApiKey");

            foreach (var release in releases)
            {
                if (release.guid == null || release.guid.Length < 5)
                {
                    Console.WriteLine("Invalid Guid");
                    continue;
                }

                var filename = String.Format("/{5}/{0}/{1}/{2}/{3}/{4}.nzb.gz",
                                             release.guid[0],
                                             release.guid[1],
                                             release.guid[2],
                                             release.guid[3],
                                             release.guid, folder);

                var success    = false;
                var nzb        = new ImportNZB();
                var fileExists = true;

                if (File.Exists((filename)))
                {
                    NZEDBTVEpisode episode = null;

                    if (release.tv_episodes_id != 0)
                    {
                        episode = db.SingleById <NZEDBTVEpisode>(release.tv_episodes_id);
                        if (episode != null)
                        {
                            episode.Summary = String.Empty;                 // System.Net.WebUtility.UrlEncode(episode.Summary);
                        }
                    }

                    NZEDBVideo video = null;

                    if (release.videos_id != 0)
                    {
                        video = db.SingleById <NZEDBVideo>(release.videos_id);
                    }

                    nzb = new ImportNZB()
                    {
                        Key         = apiKey,
                        Name        = release.searchname,
                        Name1       = String.IsNullOrEmpty(release.movie_title) ? release.tv_title : release.movie_title,
                        Name2       = String.IsNullOrEmpty(release.se_complete) ? String.Empty : release.se_complete,
                        Parts       = release.totalpart,
                        GroupId     = release.groups_id,
                        Size        = release.size,
                        Guid        = release.guid,
                        ImdbId      = release.imdbid,
                        VideoId     = release.videos_id,
                        ReleaseId   = release.id,
                        TVEpisodeId = release.tv_episodes_id,
                        PostDate    = release.postdate,
                        TVEpisode   = new TVEpisode().PopulateWith(episode),
                        Video       = new Video().PopulateWith(video),
                        CategoryId  = release.categories_id,
                        AddDate     = release.adddate
                    };

                    try
                    {
                        client.PostFileWithRequest <bool>(File.OpenRead(filename), String.Format("{0}.nzb.gz", release.guid), nzb);

                        success = true;
                    }
                    catch (WebServiceException e)
                    {
                        Console.WriteLine("Web Exception: {0}", e.Message);

                        if (e.Message == "NZB already imported")
                        {
                            success = true;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                else
                {
                    Console.WriteLine("File does not exists");
                    fileExists = false;
                    success    = false;
                }

                // try one more time with base64
                if (success == false && fileExists)
                {
                    try
                    {
                        Console.WriteLine("\tRetrying...");

                        nzb.Data = File.Exists(filename) ? Convert.ToBase64String(File.ReadAllBytes(filename)) : String.Empty;
                        client.Post(nzb);
                        success = true;
                    }
                    catch (WebServiceException e)
                    {
                        Console.WriteLine("\tWeb Exception: {0}", e.Message);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("\t{0}", e.Message);
                    }
                }

                if (success)
                {
                    db.Update <NZEDBRelease>(new { exported = true }, q => q.id == release.id);
                }
                else
                {
                    db.Update <NZEDBRelease>(new { failedexport = (release.failedexport + 1) }, q => q.id == release.id);
                }
            }
        }
Example #15
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 #16
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();
                }
            };
        }