Exemple #1
0
 private static void Main(string[] args)
 {
     var http = new HttpClient();
     http.Request.Accept = HttpContentTypes.ApplicationJson;
     http.Request.ParametersAsSegments = true;
     var trees = http.Get("http://localhost:65367/trees");
     Console.WriteLine(trees.StaticBody<Object>().SerializeToString());
     var result = http.Get("http://localhost:65367/trees/1");
     Console.WriteLine(result.StaticBody<Object>().SerializeToString());
     result = http.Get("http://localhost:65367/trees", new { Id = 2 });
     var tree2 = result.DynamicBody;
     Console.WriteLine(tree2.Id);
     Console.WriteLine(tree2.Genus);
     http.Request.Accept = "application/pdf";
     http.Request.ParametersAsSegments = true;
     const string filename = "e:\\temp\\Test.pdf";
     const string filename2 = "e:\\temp\\Test2.pdf";
     if (File.Exists(filename)) File.Delete(filename);
     if (File.Exists(filename2)) File.Delete(filename2);
     Console.WriteLine("Get pdf of 1 tree");
     http.GetAsFile("http://localhost:65367/trees/1", filename);
     Console.WriteLine("Pdf created");
     Console.WriteLine("Get pdf of all trees");
     http.GetAsFile("http://localhost:65367/trees", filename2);
     Console.WriteLine("Pdf created");
     Console.ReadLine();
 }
 public void easyhttp()
 {
     var httpClient = new HttpClient();
     var response = httpClient.Get("http://www.amazon.co.uk/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=Testing+ASP.net&x=0&y=0");
     var dom = CsQuery.CQ.Create(response.RawText);
     StringAssert.Contains("Ben Hall", dom.Find(".ptBrand").Text());
 }
        private void Check(object sender, ElapsedEventArgs e)
        {
            var http = new HttpClient();
            var result = false;
            string message = "";

            try
            {
                var response = http.Get(_url);
                result =  response.RawText.Contains(_textToMatch);
                message += result ?  string.Format(@"Message:  ""{0}"" found in page", _textToMatch) : string.Format(@"Message:  ""{0}"" not found in page", _textToMatch);

            }
            catch (Exception exception)
            {
                message += exception.Message;
            }

            _threadDispatcher.Invoke(DispatcherPriority.Input, new Action(() =>
            {
                _statusIndicator.Fill = result
                    ? new SolidColorBrush(Colors.Chartreuse)
                    : new SolidColorBrush(Colors.Red);
                _lastUpdatedTextBlock.Text = string.Format("Last tested at {0}", DateTime.Now);
                _messageTextBox.Text = message;

            }));
        }
Exemple #4
0
        public static HttpResponse Get(string url)
        {
            var httpClient = new EasyHttp.Http.HttpClient();

            httpClient.Request.Accept = HttpContentTypes.ApplicationJson;

            return(httpClient.Get(url));
        }
        public dynamic Get(string apiName)
        {
            var url = string.Format("https://slack.com/api/{0}?token={1}", apiName, SlackWindowsTray.Default.SlackToken);

            var http = new HttpClient();
            var response = http.Get(url);
            return JsonConvert.DeserializeObject(response.RawText);
        }
Exemple #6
0
        public static HttpResponse Get(string uri)
        {
            var httpClient = new EasyHttp.Http.HttpClient();

            httpClient.Request.Accept  = HttpContentTypes.ApplicationJson;
            httpClient.Request.Timeout = Convert.ToInt32(TimeSpan.FromSeconds(10).TotalMilliseconds);

            return(httpClient.Get(uri));
        }
Exemple #7
0
        static void Main(string[] args)
        {
            var client = new HttpClient();
            var response = client.Get("http://localhost:5656");

            Console.WriteLine();
            Console.WriteLine(response.RawText);
            Console.WriteLine();
        }
		public void GET_DidNotExist_NotFound()
		{
			var repository = Substitute.For<ITranslationRepository>();
			Replacing(repository);
			repository.Get(Arg.Any<string>(), Arg.Any<CultureInfo>()).Returns(default(TranslationMdl));

			var client = new HttpClient();
			HttpResponse response = client.Get(UrlFor("/translation/DK/es"));

			Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
		}
		public void Countries_Empty_NotFound()
		{
			var repository = Substitute.For<ICountryRepository>();
			Replacing(repository);
			repository.FindCurrent(Arg.Any<CultureInfo>()).Returns(new Country[] { });

			var client = new HttpClient();
			client.Request.AcceptLanguage = "en";
			HttpResponse response = client.Get(UrlFor("/countries"));

			Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
		}
        public GeolocalizationResult PerformGeolocalization(GeolocalizationCommand command)
        {
            var http = new HttpClient
            {
                Request = { Accept = HttpContentTypes.ApplicationJson }
            };

            var builtUrl = string.Format(ServiceUrl, command);
            var response = http.Get(builtUrl);
            var parser = new GoogleMapsGeolocalizationServiceParser();
            return parser.ParseJsonText(response.RawText);
        }
		public void GET_NotAvailableLanguage_NotFound()
		{
			var repository = Substitute.For<ITranslationRepository>();
			Replacing(repository);

			var client = new HttpClient();
			HttpResponse response = client.Get(UrlFor("/translation/DK/es-ES"));

			Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));

			repository.DidNotReceive().Get(Arg.Any<string>(), Arg.Any<CultureInfo>());
		}
        public void Send(TextMessage message)
        {
            if (!message.IsValid())
                throw new ArgumentException("Invalid Message");

            var http = new HttpClient { Request = { Accept = HttpContentTypes.ApplicationJson } };
            var url = string.Format("http://api.clickatell.com/http/sendmsg?user={0}&password={1}&api_id={2}&{3}&to={4}&text={5}",
                                    _user,
                                    _password,
                                    _apiId,
                                    string.IsNullOrWhiteSpace(_sender) ? null : string.Format("&from={0}", _sender),
                                    HttpUtility.UrlEncode(message.Number),
                                    HttpUtility.UrlEncode(message.Message));
            http.Get(url);
        }
		public void Country_Get_NotEmptyBody()
		{
			var repository = Substitute.For<ICountryRepository>();
			Replacing(repository);
			string translation = "España";
			repository.Get("ES", Arg.Any<CultureInfo>()).Returns(
				new Country { Translation = new Translation { Name = translation}});

			var client = new HttpClient();
			client.Request.Accept = HttpContentTypes.ApplicationJson;
			HttpResponse response = client.Get(UrlFor("/country/ES/en"));

			Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
			Assert.That(response.ContentType, Is.EqualTo(HttpContentTypes.ApplicationJson));
			Assert.That(response.DynamicBody.country.name, Is.EqualTo(translation));
		}
		public void FormatNotSupported_HtmlReturned()
		{
			var repository = Substitute.For<ILanguageRepository>();
			Replacing(repository);
			repository.FindAll().Returns(new[] { "es" });

			var client = new HttpClient
			{
				Request = { Accept = HttpContentTypes.ApplicationOctetStream }
			};

			HttpResponse response = client.Get(UrlFor("/languages"));

			Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
			Assert.That(response.RawHeaders[HttpResponseHeader.ContentType], Is.EqualTo(HttpContentTypes.TextHtml));
		}
        public Version GetVersion()
        {
            var client = new HttpClient(m_BaseUri)
                         {
                             Request = { Accept = HttpContentTypes.ApplicationJson }
                         };

            var response = client.Get("/about/version",
                                      new
                                      {
                                          // TODO: should be in settings right!?
                                          apiKey="pass@word1"
                                      });
            var version = JsonConvert.DeserializeObject<Version>(response.RawText);

            return version;
        }
		public void GET_Existing_OK()
		{
			string code = "DK", language = "es", translation = "Dinamarca";
			var repository = Substitute.For<ITranslationRepository>();
			Replacing(repository);
			repository.Get(code, Arg.Is(CultureInfo.GetCultureInfo(language))).Returns(
				new TranslationMdl{Alpha2 = code, Language = language, Name = translation});

			var client = new HttpClient();
			client.Request.Accept = HttpContentTypes.ApplicationJson;
			HttpResponse response = client.Get(UrlFor("/translation/DK/es"));

			Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
			Assert.That(response.DynamicBody.success, Is.True);
			Assert.That(response.DynamicBody.translation.data, Is.EqualTo(translation));

		}
        public void Validate()
        {
            if (string.IsNullOrWhiteSpace(Url))
                throw new ArgumentNullException("Url", "Url to validate must be specified");

            string urlToValidate = BuildUrl(ValidatorType);
            var http = new HttpClient
            {
                Request = { Accept = HttpContentTypes.TextHtml }
            };

            var response = http.Get(urlToValidate);
            var validationSummary = response.RawText;

            var reportName = string.Format("{0}Report.html", ValidatorType);
            FileSave.SaveTheResponse(validationSummary, reportName);
        }
        public static string Authorize(string baseUrl, string accountId, string apiKey)
        {
            var http = new HttpClient();
            var uri = new UriBuilder(baseUrl);
            uri.Path = "authenticate";

            var result = http.Get(uri.ToString(), new { accountid = accountId, key = apiKey });
            var json = JObject.Parse(result.RawText);
            if (((string)json["status"]).ToLower() == "error")
            {
                Logger.WriteError((string)json["msg"]);
                throw new ApplicationException((string)json["msg"]);
            }
            if (!String.IsNullOrEmpty((string)json["accesstoken"]))
                return json["accesstoken"].ToString();
            throw new ApplicationException(result.RawText);
        }
        public Tuple <bool, PriceInfo, string> GetPrice(string userToken)
        {
            var priceUrl = $"{LoginUrl}&method=price.price.get&access_token={userToken}";

            try
            {
                var response = _easyHttpClient.Get(priceUrl);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var responseInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseInfo>(response.RawText);
                    if (responseInfo.code == 20000)
                    {
                        var priceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <PriceInfo>(responseInfo.result);
                        return(Tuple.Create <bool, PriceInfo, string>(true, priceInfo, string.Empty));
                    }
                    else
                    {
                        var message = responseInfo.msg;
                        List <MessageInfo> messageInfo;
                        try
                        {
                            messageInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <List <MessageInfo> >(message);
                            StringBuilder stringBuilder = new StringBuilder();
                            messageInfo?.ForEach(mi => {
                                stringBuilder.AppendLine($"({mi.ErrorCode}){mi.Description}");
                            });
                            return(Tuple.Create <bool, PriceInfo, string>(false, null, stringBuilder.ToString()));
                        }
                        catch
                        {
                            return(Tuple.Create <bool, PriceInfo, string>(false, null, $"{responseInfo.msg}"));
                        }
                    }
                }
                else
                {
                    return(Tuple.Create <bool, PriceInfo, string>(false, null, $"{response.StatusCode}-{response.StatusDescription}"));
                }
            }
            catch (Exception ex)
            {
                return(Tuple.Create <bool, PriceInfo, string>(false, null, ex.Message));
            }
        }
Exemple #20
0
        public SurfModule()
        {
            Get["/"] = _ => Response.AsRedirect("/nexus4", Nancy.Responses.RedirectResponse.RedirectType.SeeOther);

            Get["/nexus4"] = _ =>
                Response.AsText(
                    String.Format(
                        new HttpClient()
                            .Get("http://play.google.com/store/devices/details?id=nexus_4_16gb&feature=microsite&hl=en")
                            .RawText
                            .Contains("We are out of inventory. Please check back soon.") ? "Fortfarande s**t {0}" : "Nu finns telefonen inne {0}!",
                        DateTime.Now.ToString("G")
                    )
                );

            Get["/surf"] = _ =>
                {
                    Uri path;

                    if (Uri.TryCreate(Request.Query.url, UriKind.Absolute, out path))
                    {
                        var client = new HttpClient();
                        client.StreamResponse = true;
                        client.Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11";

                        client.Get(path.ToString());

                        using (var responseStream = client.Response.ResponseStream)
                        {
                            var memoryStream = new MemoryStream();
                            responseStream.CopyTo(memoryStream);
                            memoryStream.Position = 0;

                            return Response.FromStream(memoryStream, "text/html");
                        }
                    }
                    else
                    {
                        return Response.AsText("ogiltig url");
                    }
                };
        }
        public HttpResponseMessage List()
        {
            string hostAddress = string.Empty;

            //string hostAddress = "http://13.93.209.195:4243/";

            if (Request.Headers.Contains(hostaddress))
            {
                hostAddress = Request.Headers.GetValues(hostaddress).First();
            }

            var url  = string.Join("/", hostAddress, "images/json");
            var http = new HttpClient();

            http.Request.Accept = HttpContentTypes.ApplicationJson;
            HttpResponse        response            = http.Get(url);
            var                 deserializeObject   = JsonConvert.DeserializeObject(response.RawText);
            HttpResponseMessage httpResponseMessage = Request.CreateResponse(response.StatusCode, deserializeObject, new HttpConfiguration().Formatters.JsonFormatter);

            return(httpResponseMessage);
        }
        public LoadBalancerStateDTO GetCurrentState()
        {
            try
            {
                var http = new HttpClient();
                var uri = new Uri(_agentUri, "server-status");

                var result = http.Get(string.Format("{0}?name={1}&{2}", uri, _config.LoadBalancerServerId, _config.GetLoadBalancerParametersAsQueryString()));
                dynamic obj = result.DynamicBody;

                return new LoadBalancerStateDTO()
                {
                    serverId = _config.LoadBalancerServerId,
                    connectionCount = (int)obj.connections,
                    enabled = obj.status == "enabled"
                };
            }
            catch (Exception ex)
            {
                _log.Error("Failed to get slb state", ex);
                return null;
            }
        }
		public void Get_ApplicationFormatOverride_YamlResponse()
		{
			var repository = Substitute.For<ILanguageRepository>();
			Replacing(repository);
			repository.FindAll().Returns(new[] { "es", "da" });

			var client = new HttpClient();

			var response = client.Get(UrlFor("/languages?format=prs-iso3166-1-yaml"));

			Assert.That(response.RawText, Is.EqualTo(
@"Languages:
- Code: es
- Code: da
"));

		}
Exemple #24
0
        /// <summary>
        ///     Updates the stored spartan tokens used for authenticating with 343's backend api systems.
        /// </summary>
        /// <returns>A boolean saying if everything was</returns>
        public static bool UpdateAuthentication(AzureStorage storage)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var everythingWentGucci = false;
                var strResponse = "";
                var httpClient = new HttpClient();

                // Try up to 10 times
                for (var i = 0; i < 10; i++)
                {
                    var response = httpClient.Get(CloudConfigurationManager.GetSetting("SpartanTokenApi"));

                    if (response.StatusCode == HttpStatusCode.OK && !String.IsNullOrEmpty(response.RawText.Trim()))
                    {
                        try
                        {
                            strResponse = response.RawText;

                            var waypointToken = JsonConvert.DeserializeObject<Halo4Waypoint>(response.RawText);
                            if (waypointToken != null && !String.IsNullOrWhiteSpace(waypointToken.SpartanToken))
                            {
                                var authentication = new Models.Sql.Authentication
                                {
                                    Type = AuthenticationType.Halo4,
                                    IsValid = true,
                                    Key = waypointToken.SpartanToken
                                };
                                sqlStorage.Authentications.AddOrUpdate(a => a.Type, authentication);
                                sqlStorage.SaveChanges();

                                everythingWentGucci = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.ToString());
                            everythingWentGucci = false;
                        }
                    }

                    if (everythingWentGucci)
                        break;
                }

                if (everythingWentGucci)
                    return true;

                // make sure halo 4 auth row has been deleted
                var invalidAuthentication = sqlStorage.Authentications.FirstOrDefault(a => a.Type == AuthenticationType.Halo4);
                if (invalidAuthentication != null)
                {
                    invalidAuthentication.Key = null;
                    invalidAuthentication.IsValid = false;
                }

                // send glorious email!
                var text =
                    String.Format(
                        "Sup guys, {0}Halo 4's authenication failed to update. Might want to look into it. Below is the response the server recieved from the auth service: {0}{0}{1}{0}{0}Best Regards,{0}Branch",
                        Environment.NewLine, strResponse);

                new Web(new NetworkCredential(CloudConfigurationManager.GetSetting("SendGridUser"),
                    CloudConfigurationManager.GetSetting("SendGridPass"))).Deliver(
                        new SendGridMessage(new MailAddress("*****@*****.**"),
                            new[]
                            {
                                new MailAddress(CloudConfigurationManager.GetSetting("SendGridTo")),
                                new MailAddress("*****@*****.**"),
                            },
                            "[Halo 4] Authentication Failed", null, text));

                sqlStorage.SaveChanges();

                return false;
            }
        }
 private void sendLog(string action, string extraParam = "")
 {
     try
     {
         var http = new HttpClient();
         http.Request.Accept = HttpContentTypes.ApplicationJson;
         var response = http.Get(FServer.URL + "/report/log/?broker=fxpro&account=" + FServer.ACCOUNT_NO + "&ticket=" + pos.Id + "&action=" + action + "&price=" + price + "&spread=" + spread + "&" + extraParam);
     } catch (WebException e)
     {
         return;
     }
 }
 public void easyhttp_json()
 {
     var httpClient = new HttpClient();
     var response = httpClient.Get("http://search.twitter.com/search.json?q=prognet&&rpp=5&include_entities=true&result_type=mixed");
     Assert.That(response.DynamicBody.results.Length > 0);
 }
 public ServerTradeUpdate(Position pos)
 {
     try
     {
         var http = new HttpClient();
         http.Request.Accept = HttpContentTypes.ApplicationJson;
         var response = http.Get(FServer.URL + "/report/trade/?broker=fxpro&account=" + FServer.ACCOUNT_NO + "&ticket=" + pos.Id + "&commision=" + pos.Commissions + "&swap=" + pos.Swap + "&net_profit=" + pos.NetProfit + "&gross_profit=" + pos.GrossProfit);
     } catch (WebException e)
     {
         return;
     }
 }
 private void fetchSignals()
 {
     try
     {
         var http = new HttpClient();
         http.Request.Accept = HttpContentTypes.ApplicationJson;
         var response = http.Get(FServer.URL + "/signal/reader/?broker=fxpro&account=" + FServer.ACCOUNT_NO + "&type=json&pair=" + Symbol.Code);
         signal = response.StaticBody<ServerSignal>();
     } catch (WebException e)
     {
         return;
     }
 }
 private void sendLog(string action, Position position)
 {
     try
     {
         var http = new HttpClient();
         http.Request.Accept = HttpContentTypes.ApplicationJson;
         var response = http.Get(FServer.URL + "/report/log/?broker=fxpro&account=" + FServer.ACCOUNT_NO + "&action=" + action + "&ticket_id=" + position.Id + "&profit=" + position.NetProfit);
     } catch (WebException e)
     {
         Print("Cannot connect to the server (sendLog)");
         return;
     }
 }
Exemple #30
0
        public async Task UpdateLocalFiles(CategoryTextImage Category)
        {
            await Task.Run(async() =>
            {
                UpdateRecord uDao          = new UpdateRecord();
                Category.ProgressBarIsShow = true;
                Category.ProgressBarVal    = 0;
                //1.GET /products?categoryId=00UGEYYE86PP30V&pageSize=33&page=1&search= HTTP/1.1   根据分页加载所有产品
                var RequestResult   = http.Get(url + string.Format(APIConst.GetProductByCategoryID, Category.CategoryID)).DynamicBody;
                int MaxCount        = RequestResult.total;
                var RequestResult_2 = http.Get(url + string.Format(APIConst.GetProductByCategoryID_2, Category.CategoryID, MaxCount)).DynamicBody;

                //1.2 收集产品ID
                List <string> productIdS = new List <string>();
                foreach (var item in RequestResult_2.data)
                {
                    productIdS.Add(item.id);
                }
                Category.ProgressBarVal = 5;
                //2.GET /products/Y6UN35PAVZMYPP6 HTTP/1.1
                foreach (var item in productIdS)
                {
                    List <fileItemObj> fileDics = new List <fileItemObj>();
                    var v1              = http.Get(url + string.Format(APIConst.GetProductObj, item)).DynamicBody;
                    string url_         = v1.specifications[0].staticMeshes[0].url + "," + v1.specifications[0].staticMeshes[0].packageName;
                    string dependencies = v1.specifications[0].staticMeshes[0].dependencies;
                    List <string> arr   = dependencies.Split(';').ToList();
                    arr.Add(url_);
                    foreach (string item_2 in arr)
                    {
                        fileItemObj f = new fileItemObj();
                        if (string.IsNullOrEmpty(item_2))
                        {
                            continue;
                        }
                        List <string> a = item_2.Split(',').ToList();
                        f.localUrl      = a[1];
                        f.serverUrl     = a[0];
                        f.houzui        = "." + a[0].Split('.')[1];
                        f.name          = v1.specifications[0].staticMeshes[0].packageName;

                        fileDics.Add(f);
                    }

                    double i       = 100 / productIdS.Count;
                    string baseUrl = Environment.CurrentDirectory;
                    //比较是否需要下载(更新)
                    foreach (fileItemObj obj in fileDics)
                    {
                        string serverUrl, localUrl;
                        string newLocal     = obj.localUrl.Replace("Game", "Content");
                        string filePath     = (baseUrl + "/AZMJ" + newLocal).Replace("/", "\\");
                        double oneI         = i / fileDics.Count;
                        serverUrl           = url + obj.serverUrl;
                        localUrl            = filePath;
                        string FileFullName = filePath + obj.houzui;
                        if (File.Exists(FileFullName))
                        {
                            string md5 = MD5.CalcFile(FileFullName);

                            try
                            {
                                var vvv1       = http.Get(url + string.Format(APIConst.GetMd5IsExist, md5)).DynamicBody;
                                string id      = vvv1.id;
                                Category.State = $"下载完成{newLocal}文件";
                                //跳过不需要更新
                                continue;
                            }
                            catch (Exception)
                            {
                                Category.State = $"正在下载{newLocal}文件";
                                //执行下载
                                await downFile(serverUrl, FileFullName);
                                Category.State = $"下载完成{newLocal}文件";
                            }
                        }
                        else
                        {
                            Category.State = $"正在下载{newLocal}文件";

                            await downFile(serverUrl, FileFullName);

                            Category.State = $"下载完成{newLocal}文件";
                        }

                        Category.ProgressBarVal += Convert.ToDouble(decimal.Round(decimal.Parse(oneI.ToString()), 2));
                    }
                }

                Category.State             = "下载完成";
                Category.ProgressBarVal    = 100;
                Category.ShowOpacity       = 1;
                Category.ProgressBarIsShow = false;
                Category.IsCompleteDown    = true;
                uDao.insert(new UpdateRecoreModel()
                {
                    CategoryId = Category.CategoryID, Type = eCategoryType.产品, Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
            });
        }
Exemple #31
0
        /// <summary>
        /// Parse the command line arguments and take appropriate actions. Stolen from Modboy
        /// </summary>
        public static void ParseArguments(string[] args)
        {
            if (!args.AnySafe())
            {
                return;
            }

            bool launchedViaProtocolHandle = args[0].ContainsInvariant(Constants.ProtocolHandle);

            // Launched via protocol handle - parse task
            if (launchedViaProtocolHandle)
            {
                // find example at: https://dev.gamebanana.com/skins/150504?modboy
                // ex: modboy://Skin,150504,363769
                // Extract the input from the arguments
                var regex = new Regex(Constants.ProtocolHandle + "([A-Za-z]+),([0-9]+),([0-9]+)",
                                      RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
                if (!regex.IsMatch(args[0]))
                {
                    MessageBox.Show("QLMM failed to process the URL. Sorry!");
                    return;
                }
                var match = regex.Match(args[0]);

                // Get the valuable data
                var subType = match.Groups[1].Value;
                var subId   = match.Groups[2].Value;
                var fileId  = match.Groups[3].Value;

                string httptarget = "https://gamebanana.com/apiv3/" + subType + "/" + subId;
                Uri    uritarget  = new Uri(httptarget);
                EasyHttp.Http.HttpClient client = new EasyHttp.Http.HttpClient();
                httpresponse = client.Get(httptarget).RawText;

                JObject apiJSON = JObject.Parse(httpresponse);

                try
                {
                    string modName = (string)apiJSON[""]["_sName"]; // Causes NullReferenceException, please fix.
                    string modUrl  = "https://gamebanana.com/dl/" + fileId;
                    //string modfileName = (string)apiJSON["_aFiles"]["_sFile"];

                    // Create directory if necessary
                    if (!Directory.Exists(FileSystem.TempStorageDirectory))
                    {
                        Directory.CreateDirectory(FileSystem.TempStorageDirectory);
                    }

                    WebClient fileClient = new WebClient();
                    fileClient.DownloadFileCompleted   += new AsyncCompletedEventHandler(Completed);
                    fileClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
                    fileClient.DownloadFileAsync(new Uri(modUrl), Path.Combine(FileSystem.TempStorageDirectory, fileId));

                    outerFilePath  = Path.Combine(FileSystem.TempStorageDirectory, fileId);
                    outerFileName  = fileId;
                    modDisplayName = modName;

                    main.label1.Text = "Downloading " + modName + "...";
                }
                catch (Exception e) {
                    MessageBox.Show("An error has occurred!\n\n" + e.Message + "\n\n" + e.StackTrace);
                    Process.GetCurrentProcess().Kill();
                }
            }
        }
        private void TestButton_Click(object sender, RoutedEventArgs e)
        {
            var address = SiteTextBox.Text;
            var textToMatch = TextToMatchTextBox.Text;
            MessageTextBox.Text = "Message: ";

            var http = new HttpClient();
            bool result = false;
            try
            {
                var response = http.Get(address);
                result = response.RawText.Contains(textToMatch);
                MessageTextBox.Text = result ? string.Format(@"Message:  ""{0}"" found in page", textToMatch) : string.Format(@"Message:  ""{0}"" not found in page", textToMatch);
            }
            catch (Exception ex)
            {
                MessageTextBox.Text = "Message: " + ex.Message;
            }

                StatusIndicator.Fill = result ? new SolidColorBrush(Colors.Chartreuse) : new SolidColorBrush(Colors.Red);
                LastTestAtTextBox.Text = string.Format("Last tested at {0}", DateTime.Now);
        }
		public void Logging_DoublesCanBeUsed_ForInteractionTesting()
		{
			var factory = Substitute.For<ILogFactory>();
			var log = Substitute.For<ILog>();
			factory.GetLogger(Arg.Any<string>()).Returns(log);
			Replacing(factory);
			Replacing(Substitute.For<ILanguageRepository>());

			var client = new HttpClient
			{
				Request = { Accept = HttpContentTypes.ApplicationJson }
			};

			client.Get(UrlFor("/languages"));

			log.Received().Warn(Arg.Any<string>(), Arg.Any<ObjectNotFoundException>());
		}
		public void Get_ApplicationFormat_YamlResponse()
		{
			var repository = Substitute.For<ILanguageRepository>();
			Replacing(repository);
			repository.FindAll().Returns(new[] { "es", "da" });

			var client = new HttpClient
			{
				Request = { Accept = ApplicationFormat.ContentType }
			};

			var response = client.Get(UrlFor("/languages"));

			Assert.That(response.RawText, Is.EqualTo(
@"Languages:
- Code: es
- Code: da
"));
		}
		public void Format_CanBeOverridenWithQueryString()
		{
			var repository = Substitute.For<ILanguageRepository>();
			Replacing(repository);
			repository.FindAll().Returns(new []{"es"});

			var client = new HttpClient
			{
				Request = { Accept = HttpContentTypes.ApplicationJson }
			};

			HttpResponse response = client.Get(UrlFor("/languages?format=xml"));

			Assert.That(response.ContentType, Is.EqualTo(HttpContentTypes.ApplicationXml));
		}
		public void Logging_ATestingLoggerCanBeUsed_ForStateTesting()
		{
			Replacing(Substitute.For<ILanguageRepository>());
			Replacing<ILogFactory>(new TestLogFactory());
			
			var client = new HttpClient
			{
				Request = { Accept = HttpContentTypes.ApplicationJson }
			};

			client.Get(UrlFor("/languages"));

			var logs = TestLogger.GetLogs();
			Assert.That(logs[0].Key, Is.EqualTo(TestLogger.Levels.WARN));
			Assert.That(logs[0].Value, Is.StringContaining("IEnumerable<string>"));
		}