public RemoteMultipartRequest(ScheduledExecutorService workExecutor, HttpClientFactory
			 clientFactory, string method, Uri url, MultipartEntity multiPart, IDictionary<string
			, object> requestHeaders, RemoteRequestCompletionBlock onCompletion) : base(workExecutor
			, clientFactory, method, url, null, requestHeaders, onCompletion)
		{
			this.multiPart = multiPart;
		}
    public static async Task<HttpClient> CreateHttpClient (string user, string userAgentHeader)
    {
      var userCredential = await LoginToGoogle (user);

      var client = new HttpClientFactory().CreateHttpClient (new CreateHttpClientArgs() { ApplicationName = userAgentHeader });
      userCredential.Initialize (client);

      return client;
    }
 public IEnumerable<GlimpseContributor> Get(string top = "")
 {
     string teamMemberJsonFile = HostingEnvironment.MapPath("~/Content/glimpseTeam.json");
     string githubKey = ConfigurationManager.AppSettings.Get("GithubKey");
     string githubSecret = ConfigurationManager.AppSettings.Get("GithubSecret");
     var httpClient = new HttpClientFactory().CreateHttpClient(githubKey, githubSecret);
     var contributorService = new ContributorService(new GlimpseTeamMemberRepository(teamMemberJsonFile),new GithubContributorService(httpClient));
     return contributorService.GetContributors().Take(string.IsNullOrEmpty(top) ? 11 : int.Parse(top));
 }
Example #4
0
        public void return_a_correct_response_for_a_default_get_request()
        {

            using (var httpClient = new HttpClientFactory().Create())
            {
                var response = httpClient.GetAsync("").Result;

                Assert.True(response.IsSuccessStatusCode, "Status code: " + response.StatusCode);
            }
        }
        public CompaniesHouseClient(ICompaniesHouseSettings settings)
        {
            var httpClientFactory = new HttpClientFactory(settings);
            _httpClient = httpClientFactory.CreateHttpClient();

            _companiesHouseSearchClient = new CompaniesHouseSearchClient(_httpClient, new SearchUriBuilderFactory());
            _companiesHouseCompanyProfileClient = new CompaniesHouseCompanyProfileClient(_httpClient, new CompanyProfileUriBuilder());
            _companiesHouseCompanyFilingHistoryClient = new CompaniesHouseCompanyFilingHistoryClient(_httpClient, new CompanyFilingHistoryUriBuilder());
            _companiesHouseOfficersClient = new CompaniesHouseOfficersClient(_httpClient, new OfficersUriBuilder());
            _companiesHouseCompanyInsolvencyInformationClient = new CompaniesHouseCompanyInsolvencyInformationClient(_httpClient);
        }
		public RemoteRequest(ScheduledExecutorService workExecutor, HttpClientFactory clientFactory
			, string method, Uri url, object body, IDictionary<string, object> requestHeaders
			, RemoteRequestCompletionBlock onCompletion)
		{
			this.clientFactory = clientFactory;
			this.method = method;
			this.url = url;
			this.body = body;
			this.onCompletion = onCompletion;
			this.workExecutor = workExecutor;
			this.requestHeaders = requestHeaders;
		}
		private async Task<User> Login()
		{
			HttpClientFactory factory = new HttpClientFactory();
			UserRepository repository = new UserRepository(factory);

			LoginViewModel loginModel = new LoginViewModel();
			loginModel.Email = txtEmail.Text;
			loginModel.Password = txtPassword.Text;


			return await repository.LoginAsync(loginModel);
			//string token = response.Result;
		}
Example #8
0
        public void return_a_correct_response_for_a_post_request()
        {
            using (var httpClient = new HttpClientFactory().Create())
            {
                var entry =
                    new
                    {
                        id = new Guid().ToString(),
                        name = "John Smith",
                        email = "*****@*****.**",
                        active = true,
                        creationTime = new DateTime(2016, 1, 1)
                    };
                var response = httpClient.PostAsJsonAsync("", entry).Result;

                Assert.True(response.IsSuccessStatusCode, "Status code: " + response.StatusCode);
            }
        }
Example #9
0
        public void return_a_posted_entry_after_a_post_request()
        {
            using (var httpClient = new HttpClientFactory().Create())
            {
                var json =
                    new 
                    {
                        id = new Guid(),
                        name = "John Smith",
                        email = "*****@*****.**",
                        active = true,
                        creationTime = new DateTime(2016, 1, 1)
                    };
                var expected = json.ToJObject();
                httpClient.PostAsJsonAsync("", json).Wait();

                var response = httpClient.GetAsync("").Result;

                var actual = response.Content.ReadAsJsonAsync().Result;
                Assert.Contains(expected, actual.appUsers);
            }
        }
Example #10
0
        private void UploadFiles(string[] files)
        {
            ProgressMessageHandler progress = new ProgressMessageHandler();

            progress.HttpSendProgress += new EventHandler <HttpProgressEventArgs>(HttpSendProgress);

            HttpRequestMessage       message = new HttpRequestMessage();
            MultipartFormDataContent content = new MultipartFormDataContent();

            try
            {
                foreach (var file in files)
                {
                    FileStream filestream = new FileStream(file, FileMode.Open);
                    string     fileName   = System.IO.Path.GetFileName(file);
                    content.Add(new StreamContent(filestream), "file", fileName);
                }

                message.Method     = HttpMethod.Post;
                message.Content    = content;
                message.RequestUri = new Uri("http://localhost:51884/api/uploading/");

                ThreadSafeUpdateStatus(String.Format("Uploading {0} files", files.Count()));

                var client = HttpClientFactory.Create(progress);
                client.SendAsync(message).ContinueWith(task =>
                {
                    if (task.Result.IsSuccessStatusCode)
                    {
                        ThreadSafeUpdateStatus(String.Format("Uploaded {0} files", files.Count()));
                        var response = task.Result.Content.ReadAsStringAsync();
                        dynamic json = JsonConvert.DeserializeObject <List <FileDesc> >(response.Result);

                        foreach (var item in json)
                        {
                            var listitem = _files.FirstOrDefault(i => i.Contains(item.name));

                            Application.Current.Dispatcher.Invoke(
                                DispatcherPriority.Normal, (Action) delegate()
                            {
                                _files.Remove(listitem);
                            });

                            listitem += String.Format(" - successfully uploaded. Size: {0}", item.size);

                            Application.Current.Dispatcher.Invoke(
                                DispatcherPriority.Normal, (Action) delegate()
                            {
                                _files.Add(listitem);
                            });
                        }
                    }
                    else
                    {
                        ThreadSafeUpdateStatus("Sorry there has been an error");
                    }
                });
            }
            catch (Exception e)
            {
                //Handle exceptions - file not found, access denied, no internet connection, threading issues etc etc
            }
        }
Example #11
0
        public async override Task <(ISource source, string failReason)> FindHandlerAsync(DiscordMessage message, ICollection <IArchiveHandler> handlers)
        {
            if (string.IsNullOrEmpty(message.Content))
            {
                return(null, null);
            }

            var matches = ExternalLink.Matches(message.Content);

            if (matches.Count == 0)
            {
                return(null, null);
            }

            using var httpClient = HttpClientFactory.Create();
            foreach (Match m in matches)
            {
                try
                {
                    if (m.Groups["onedrive_link"].Value is string lnk &&
                        !string.IsNullOrEmpty(lnk) &&
                        Uri.TryCreate(lnk, UriKind.Absolute, out var uri) &&
                        await client.ResolveContentLinkAsync(uri, Config.Cts.Token).ConfigureAwait(false) is DriveItemMeta itemMeta)
                    {
                        try
                        {
                            var filename = itemMeta.Name;
                            var filesize = itemMeta.Size;
                            uri = new Uri(itemMeta.ContentDownloadUrl);

                            using var stream = await httpClient.GetStreamAsync(uri).ConfigureAwait(false);

                            var buf = bufferPool.Rent(1024);
                            try
                            {
                                var read = await stream.ReadBytesAsync(buf).ConfigureAwait(false);

                                foreach (var handler in handlers)
                                {
                                    var(canHandle, reason) = handler.CanHandle(filename, filesize, buf.AsSpan(0, read));
                                    if (canHandle)
                                    {
                                        return(new OneDriveSource(uri, handler, filename, filesize), null);
                                    }
                                    else if (!string.IsNullOrEmpty(reason))
                                    {
                                        return(null, reason);
                                    }
                                }
                            }
                            finally
                            {
                                bufferPool.Return(buf);
                            }
                        }
                        catch (Exception e)
                        {
                            Config.Log.Warn(e, $"Error sniffing {m.Groups["link"].Value}");
                        }
                    }
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e, $"Error sniffing {m.Groups["mega_link"].Value}");
                }
            }
            return(null, null);
        }
Example #12
0
        static void Main(string[] args)
        {
            var jsonFormatter = new JsonMediaTypeFormatter();

            // For fiddler change the base address to http://localhost.fiddler:9001

            var baseAddress = new Uri("http://localhost.fiddler:9001");

            var authenticatingClient = HttpClientFactory.Create(new SharedKeySigningHandler(Properties.Settings.Default.AccountName, Properties.Settings.Default.SharedSecret));

            authenticatingClient.BaseAddress = baseAddress;
            authenticatingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var nonAuthenticatingClient = HttpClientFactory.Create();

            nonAuthenticatingClient.BaseAddress = baseAddress;
            nonAuthenticatingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            Console.WriteLine("Press return when the receiving web app has started and you've started fiddler (if appropriate).");
            Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("GET api/Subscribers");
            var getResponse = nonAuthenticatingClient.GetStringAsync("api/Subscribers").Result;

            Console.WriteLine(getResponse);

            Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
            Console.ReadLine();
            Console.WriteLine();


            Console.WriteLine("POST api/Subscribers with SharedSigningKeyHandler");
            var newSubscriber = new Subscriber {
                Email = "*****@*****.**", Name = "Barry Dorrans"
            };
            var requestContent = new ObjectContent <Subscriber>(newSubscriber, jsonFormatter);
            var postResponse   = authenticatingClient.PostAsync("api/subscribers", requestContent).Result;
            var location       = postResponse.Headers.Location;

            Console.WriteLine(postResponse);

            Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
            Console.ReadLine();
            Console.WriteLine();

            Console.WriteLine("POST api/Subscribers without SharedSigningKeyHandler");
            try
            {
                newSubscriber = new Subscriber {
                    Email = "*****@*****.**", Name = "Steve Ballmer"
                };
                postResponse = nonAuthenticatingClient.PostAsJsonAsync("api/Subscribers", newSubscriber).Result;
                Console.WriteLine(postResponse);
            }
            catch (Exception e)
            {
                Console.WriteLine("Ooops");
                Console.WriteLine(e);
            }

            Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
            Console.ReadLine();
            Console.WriteLine();

            Console.WriteLine("DELETE " + location.PathAndQuery);
            var deleteResponse = authenticatingClient.DeleteAsync(location.PathAndQuery).Result;

            Console.WriteLine(deleteResponse);

            Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
            Console.ReadLine();
            Console.WriteLine();


            Console.WriteLine("GET api/Subscribers");
            getResponse = nonAuthenticatingClient.GetStringAsync("api/Subscribers").Result;
            Console.WriteLine(getResponse);

            Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
            Console.ReadLine();
        }
Example #13
0
 public LargeFiles(B2Options options)
 {
     _options = options;
     _client  = HttpClientFactory.CreateHttpClient(options.RequestTimeout);
 }
Example #14
0
 public SmsWindow()
 {
     InitializeComponent();
     _smsApi = RestService.For <ISmsApi>(HttpClientFactory.Create(AppEnvironment.ApiBaseUrl));
 }
Example #15
0
 public void SetUp()
 {
     _client = HttpClientFactory.Create();
 }
 public BraviService(string baseUrl, HttpClientFactory clientFactory, X509Certificate2 certificate, string version)
     : base(baseUrl, clientFactory, certificate, version)
 {
 }
Example #17
0
        internal async Task <WorkItemBatchPostResponse> InvokeAsync(BatchRequest[] batchRequests, CancellationToken cancellationToken)
        {
            string baseUriString = _context.Client.BaseAddress.AbsoluteUri;
            string credentials   = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{_context.PersonalAccessToken}"));
            var    converters    = new JsonConverter[] { new JsonPatchOperationConverter() };

            string requestBody = JsonConvert.SerializeObject(batchRequests, Formatting.Indented, converters);

            _context.Logger.WriteVerbose($"Workitem(s) batch request:");
            _context.Logger.WriteVerbose(requestBody);

            if (_commit)
            {
                using (var client = HttpClientFactory.Create())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                    var batchRequest = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    var method       = new HttpMethod("POST");

                    // send the request
                    var request = new HttpRequestMessage(method, $"{baseUriString}/_apis/wit/$batch?{ApiVersion}")
                    {
                        Content = batchRequest
                    };
                    var response = await client.SendAsync(request, cancellationToken);

                    if (response.IsSuccessStatusCode)
                    {
                        WorkItemBatchPostResponse batchResponse = await response.Content.ReadAsAsync <WorkItemBatchPostResponse>(cancellationToken);

                        string stringResponse = JsonConvert.SerializeObject(batchResponse, Formatting.Indented);
                        _context.Logger.WriteVerbose($"Workitem(s) batch response:");
                        _context.Logger.WriteVerbose(stringResponse);

                        bool succeeded = true;
                        foreach (var batchElement in batchResponse.values)
                        {
                            if (batchElement.code != 200)
                            {
                                _context.Logger.WriteError($"Save failed: {batchElement.body}");
                                succeeded = false;
                            }
                        }

                        if (!succeeded)
                        {
                            throw new InvalidOperationException($"Save failed.");
                        }

                        return(batchResponse);
                    }
                    else
                    {
                        string stringResponse = await response.Content.ReadAsStringAsync();

                        _context.Logger.WriteError($"Save failed: {stringResponse}");
                        throw new InvalidOperationException($"Save failed: {response.ReasonPhrase}.");
                    }
                }//using
            }

            _context.Logger.WriteWarning($"Dry-run mode: no updates sent to Azure DevOps.");
            return(null);
        }
Example #18
0
 public Files(B2Options options)
 {
     _options = options;
     _client  = HttpClientFactory.CreateHttpClient();
 }
Example #19
0
        static async Task RunAsync()
        {
            Console.WriteLine("Calling the back-end API");

            HMACDelegatingHandler customDelegatingHandler = new HMACDelegatingHandler(false);

            HttpClient client = HttpClientFactory.Create(customDelegatingHandler);

            ConsoleKey          key      = ConsoleKey.S;
            HttpResponseMessage response = null;

            HMACResponseAuthentication hmacResponseAuthenticator = new HMACResponseAuthentication(true, false);


            while (true)
            {
                // azioni developer usano un'api key developer
                if (key == ConsoleKey.S || key == ConsoleKey.P || key == ConsoleKey.O || key == ConsoleKey.I)
                {
                    HMACDelegatingHandler.ClientId  = "378ce77c-5b45-4126-9dfa-0371daa51563";
                    HMACDelegatingHandler.ClientKey = "anI4ICTj9bs+gNQRa3aBbbQmsYCGvNIKB1qTkWZoj/k=";
                }

                if (key == ConsoleKey.Q || key == ConsoleKey.W || key == ConsoleKey.E)
                {
                    // azioni del device usano un'api key device
                    HMACDelegatingHandler.ClientId  = "50148590-1b48-4cf5-a76d-8a7f9474a3de";
                    HMACDelegatingHandler.ClientKey = "U8a2xaaYz2sNhEGDO9T4Ms9Wf4AWMQv+gDpmYJx+YmI=";
                }


                if (key == ConsoleKey.S)
                {
                    response = await TestProtocol(client);
                }

                else if (key == ConsoleKey.P)
                {
                    response = await DeveloperConnectionRequest_FAIL(client);
                }

                else if (key == ConsoleKey.O)
                {
                    response = await DeveloperConnectionRequest_DONE(client);
                }

                else if (key == ConsoleKey.I)
                {
                    response = await DeveloperCheckDeviceConnectionState(client);
                }

                else if (key == ConsoleKey.Q)
                {
                    response = await DeviceCheckConnectionRequest(client);
                }

                else if (key == ConsoleKey.W)
                {
                    response = await DeviceSetActiveConnectionStatus(client);
                }

                if (response.IsSuccessStatusCode)
                {
                    bool authenticated = hmacResponseAuthenticator.IsResponseAuthenticated(response);
                    if (authenticated)
                    {
                        string responseString = await response.Content.ReadAsStringAsync();

                        Console.WriteLine(responseString);
                    }
                }
                else
                {
                    Console.WriteLine("Failed to call the API. HTTP Status: {0}, Reason {1}", response.StatusCode, response.ReasonPhrase);
                    string responseString = await response.Content.ReadAsStringAsync();

                    Console.WriteLine(responseString);
                }

                key = Console.ReadKey(true).Key;
                Console.WriteLine("-----------------------------------------------------------");
            }
        }
Example #20
0
        private async Task <(int created, int updated)> SaveChanges_Batch(bool commit, CancellationToken cancellationToken)
        {
            // see https://github.com/redarrowlabs/vsts-restapi-samplecode/blob/master/VSTSRestApiSamples/WorkItemTracking/Batch.cs
            // and https://docs.microsoft.com/en-us/rest/api/vsts/wit/workitembatchupdate?view=vsts-rest-4.1
            // BUG this code won't work if there is a relation between a new (id<0) work item and an existing one (id>0): it is an API limit

            const string ApiVersion = "api-version=4.1";

            int created = _context.Tracker.NewWorkItems.Count();
            int updated = _context.Tracker.ChangedWorkItems.Count();

            string baseUriString = _context.Client.BaseAddress.AbsoluteUri;

            BatchRequest[] batchRequests        = new BatchRequest[created + updated];
            Dictionary <string, string> headers = new Dictionary <string, string>
            {
                { "Content-Type", "application/json-patch+json" }
            };
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{_context.PersonalAccessToken}"));

            int index = 0;

            foreach (var item in _context.Tracker.NewWorkItems)
            {
                _context.Logger.WriteInfo($"Found a request for a new {item.WorkItemType} workitem in {item.TeamProject}");

                batchRequests[index++] = new BatchRequest
                {
                    method  = "PATCH",
                    uri     = $"/{item.TeamProject}/_apis/wit/workitems/${item.WorkItemType}?{ApiVersion}",
                    headers = headers,
                    body    = item.Changes
                              .Where(c => c.Operation != Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Test)
                              .ToArray()
                };
            }

            foreach (var item in _context.Tracker.ChangedWorkItems)
            {
                _context.Logger.WriteInfo($"Found a request to update workitem {item.Id.Value} in {item.TeamProject}");

                batchRequests[index++] = new BatchRequest
                {
                    method  = "PATCH",
                    uri     = FormattableString.Invariant($"/_apis/wit/workitems/{item.Id.Value}?{ApiVersion}"),
                    headers = headers,
                    body    = item.Changes
                              .Where(c => c.Operation != Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Test)
                              .ToArray()
                };
            }

            var    converters  = new JsonConverter[] { new JsonPatchOperationConverter() };
            string requestBody = JsonConvert.SerializeObject(batchRequests, Formatting.Indented, converters);

            _context.Logger.WriteVerbose(requestBody);

            if (commit)
            {
                using (var client = HttpClientFactory.Create())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                    var batchRequest = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    var method       = new HttpMethod("POST");

                    // send the request
                    var request = new HttpRequestMessage(method, $"{baseUriString}/_apis/wit/$batch?{ApiVersion}")
                    {
                        Content = batchRequest
                    };
                    var response = await client.SendAsync(request, cancellationToken);

                    if (response.IsSuccessStatusCode)
                    {
                        WorkItemBatchPostResponse batchResponse = await response.Content.ReadAsAsync <WorkItemBatchPostResponse>(cancellationToken);

                        string stringResponse = JsonConvert.SerializeObject(batchResponse, Formatting.Indented);
                        _context.Logger.WriteVerbose(stringResponse);
                        bool succeeded = true;
                        foreach (var batchElement in batchResponse.values)
                        {
                            if (batchElement.code != 200)
                            {
                                _context.Logger.WriteError($"Save failed: {batchElement.body}");
                                succeeded = false;
                            }
                        }

                        if (!succeeded)
                        {
                            throw new InvalidOperationException("Save failed.");
                        }
                    }
                    else
                    {
                        string stringResponse = await response.Content.ReadAsStringAsync();

                        _context.Logger.WriteError($"Save failed: {stringResponse}");
                        throw new InvalidOperationException($"Save failed: {response.ReasonPhrase}.");
                    }
                }//using
            }
            else
            {
                _context.Logger.WriteWarning($"Dry-run mode: no updates sent to Azure DevOps.");
            }//if

            return(created, updated);
        }
Example #21
0
 public WalletManagerViewModel(WalletManager walletManager, UiConfig uiConfig, Config config, BitcoinStore bitcoinStore,
                               LegalChecker legalChecker, TransactionBroadcaster broadcaster, HttpClientFactory httpClientFactory)
 {
     WalletManager            = walletManager;
     BitcoinStore             = bitcoinStore;
     LegalChecker             = legalChecker;
     _walletDictionary        = new Dictionary <Wallet, WalletViewModelBase>();
     _walletActionsDictionary = new Dictionary <WalletViewModelBase, List <NavBarItemViewModel> >();
     _actions         = new ObservableCollection <NavBarItemViewModel>();
     _selectedWallets = new ObservableCollection <NavBarItemViewModel>();
     _wallets         = new ObservableCollection <WalletViewModelBase>();
     _loggedInAndSelectedAlwaysFirst = true;
     _config   = config;
     _uiConfig = uiConfig;
     _transactionBroadcaster = broadcaster;
     _httpClientFactory      = httpClientFactory;
Example #22
0
 public LocationApi(HttpClientFactory factory)
 {
     this.factory = factory;
 }
Example #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViaCepClient"/> class.
 /// </summary>
 public ViaCepClient()
 {
     _httpClient             = HttpClientFactory.Create();
     _httpClient.BaseAddress = new Uri(BaseUrl);
 }
Example #24
0
 public RoleService()
 {
     _roleApi = RestService.For <IRoleApi>(HttpClientFactory.Create(AppEnvironment.ApiBaseUrl));
 }
Example #25
0
 /// <summary>
 /// Creates the HTTP client.
 /// </summary>
 /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
 /// <returns>HttpClient.</returns>
 protected override HttpClient CreateHttpClient(bool enableHttpCompression)
 {
     return(HttpClientFactory.GetHttpClient(enableHttpCompression));
 }
Example #26
0
 public ReminderStorageWebApiClient(string baseWebApiUrl)
 {
     _baseWebApiUrl = baseWebApiUrl;
     _httpClient    = HttpClientFactory.Create();
 }
        private void DownloadNewZPResume()
        {
            const string cookie = "dywez=95841923.1511179053.1.1.dywecsr=(direct)|dyweccn=(direct)|dywecmd=(none)|dywectr=undefined; UM_distinctid=15fd950d4002e-078f03d618be3a-7b113d-1fa400-15fd950d401b16; companyCuurrentCity=765; __zpWAM=1511179690788.221570.1511179691.1511179691.1; __zpWAMs2=1; LastCity=%e6%b7%b1%e5%9c%b3; LastCity%5Fid=765; _jzqckmp=1; monitorlogin=Y; firstchannelurl=https%3A//passport.zhaopin.com/%3Fy7bRbP%3DdrD8ktbNjFbNjFbNAGbM.F5i4vPMMvKO_E1CyE_.RF9; JSweixinNum=3; usermob=46654A2C4576447646764065442C44764176417643655; userphoto=; userwork=11; bindmob=1; rinfo=JL050895042R90500000000_1; dywem=95841923.y; _jzqx=1.1511246953.1511246953.1.jzqsr=passport%2Ezhaopin%2Ecom|jzqct=/account/logout.-; urlfrom=121126445; urlfrom2=121126445; adfcid=none; adfcid2=none; adfbid=0; adfbid2=0; Hm_lvt_38ba284938d5eddca645bb5e02a02006=1511179417; Hm_lpvt_38ba284938d5eddca645bb5e02a02006=1511246974; _jzqa=1.3386187871408075000.1511226539.1511226539.1511246953.2; _jzqc=1; _jzqb=1.2.10.1511246953.1; JsOrglogin=2049139034; at=fc522dbb32ce478eb97b33e0042dff42; Token=fc522dbb32ce478eb97b33e0042dff42; rt=608743d8649f44468d71c79c80ba3d93; uiioit=2264202C55795C6900374679586B4364522C5B795E690C374E792A6B3364592C5D795A69003743795A6B4764552C5A7951695; lastchannelurl=https%3A//passport.zhaopin.com/org/login; __utma=269921210.1889805250.1511179053.1511226539.1511246953.3; __utmb=269921210.10.9.1511246998154; __utmc=269921210; __utmz=269921210.1511179053.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmv=269921210.|2=Member=204885552=1; JsNewlogin=683046344; NewPinLoginInfo=; cgmark=2; NewPinUserInfo=; isNewUser=1; RDpUserInfo=; ihrtkn=; utype=2; nTalk_CACHE_DATA={uid:kf_9051_ISME9754_guest713A8EDA-E83E-25,tid:1511247000031838}; NTKF_T2D_CLIENTID=guest713A8EDA-E83E-256A-17CC-D94EA8BBD23C; RDsUserInfo=236A2D6B566A5C6450695A7555725173477659695F6B5E6A5F6825693B654F651B710E6A5B6B466A58645F69527530722B734C76EBE13B304B0A5F6827693B654F654871346A2D6B566A5F64586951755372577341765B69596B516A2668276948655F2B1CFE8B3C2CFDBA13EA06650EC8276C1535E51D27923A9A06593D623A05388D36496527713B6A546B5A6A2C6453692C752872587308761F690A6B046A1E6800690C651B653371156A016B026A046409691A750A72037305760369056B096A4A680A691A651F654871256A3D6B566A5864536928753172587340765B69466B586A55684969446546654971436A5B6B506A2E642C69547554725473437653695D6B596A53685A69406549653771386A546B5302A93B5A6981E55E7229733C7657695B6B5A6A546858694565426542714F6A526B286A2E6455695E75537256734A762B69276B576A54685269206533654E714D6A2A6B2A6A57642B692A755072557349765C69596B5A6A55685B69436549653771376A546B286A29645D6959755D72537343765A695A6B586A52682D694C6542654171436A596B5B6A5B6451695975557255734A762E69286B576A5468526926653B654E71456A526B226A3A6455695B75517257735F765B69586B536A5F683C6921654F654271466A5B6B506A2; rd_applyorderBy=CreateTime; rd_apply_lastsearchcondition=11%3B12%3B13%3B14%3B15%3B16; dywea=95841923.4452105838603920000.1511179053.1511226539.1511246953.3; dywec=95841923; dyweb=95841923.63.9.1511248182640";

            var cookieContainer = cookie.Serialize(".zhaopin.com");

            var queue = new ConcurrentQueue <string>();

            var tasks = new List <Task>();

            Task.Run(() =>
            {
                var pageIndex = 1;

                var typeIndex = 1;

                while (true)
                {
                    #region 参数

                    var paramDic = new Dictionary <string, string>
                    {
                        { "PageList2", "" },
                        { "DColumn_hidden", "" },
                        { "searchKeyword", "" },
                        { "curSubmitRecord", "4461" },
                        { "curMaxPageNum", "224" },
                        { "buttonAsse", "导入测评系统" },
                        { "buttonInfo", "发通知信" },
                        { "SF_1_1_50", $"{typeIndex}" },
                        { "SF_1_1_51", "-1" },
                        { "SF_1_1_45", "" },
                        { "SF_1_1_44", "" },
                        { "SF_1_1_52", "0" },
                        { "SF_1_1_49", "0" },
                        { "IsInvited", "0" },
                        { "position_city", "[%%POSITION_CITY%%]" },
                        { "deptName", "" },
                        { "select_unique_id", "" },
                        { "selectedResumeList", "" },
                        { "PageNo", "" },
                        { "PosState", "" },
                        { "MinRowID", "" },
                        { "MaxRowID", "2722819791" },
                        { "RowsCount", "123" },
                        { "PagesCount", "5" },
                        { "PageType", "0" },
                        { "CurrentPageNum", $"{pageIndex}" },
                        { "Position_IDs", "[%%POSITION_IDS%%]" },
                        { "Position_ID", "[%%POSITION_ID%%]" },
                        { "SortType", "0" },
                        { "isCmpSum", "0" },
                        { "SelectIndex_Opt", "0" },
                        { "Resume_count", "0" },
                        { "CID", "112963735" },
                        { "forwardingEmailList", "" },
                        { "click_search_op_type", "-1" },
                        { "X-Requested-With", "XMLHttpRequest" }
                    };

                    #endregion

                    var requestResult = HttpClientFactory.RequestForString("https://rd2.zhaopin.com/rdapply/resumes/apply/search?SF_1_1_38=6%2C9&orderBy=CreateTime", HttpMethod.Post, paramDic, cookieContainer, isRandomIP: true);

                    if (!requestResult.IsSuccess)
                    {
                        this.AsyncSetLog(this.tbx_Log, requestResult.ErrorMsg);

                        continue;
                    }

                    if (requestResult.Data.Contains("当前状态下暂无简历,您可以点击其他状态查看简历"))
                    {
                        this.AsyncSetLog(this.tbx_Log, $"第 {typeIndex} 类 已扫描完成!");

                        if (typeIndex >= 4)
                        {
                            break;
                        }

                        typeIndex++;

                        pageIndex = 1;

                        continue;
                    }

                    foreach (Match match in Regex.Matches(requestResult.Data, "href=\"(//rd\\.zhaopin\\.com/resumepreview.+?)\""))
                    {
                        queue.Enqueue("https:" + match.Result("$1"));
                    }

                    this.AsyncSetLog(this.tbx_Log, $"已扫描 {pageIndex} 页");

                    SpinWait.SpinUntil(() => !queue.Any());

                    pageIndex++;
                }
            });

            var dictionary = new ConcurrentDictionary <string, string>();

            for (var i = 0; i < 1; i++)
            {
                tasks.Add(Task.Run(() =>
                {
                    while (true)
                    {
                        string url;

                        if (!queue.TryDequeue(out url))
                        {
                            continue;
                        }

                        Thread.Sleep(TimeSpan.FromSeconds(20));

                        var requestResult = HttpClientFactory.RequestForString(url, HttpMethod.Get, null, cookieContainer, isRandomIP: true);

                        if (!requestResult.IsSuccess)
                        {
                            this.AsyncSetLog(this.tbx_Log, requestResult.ErrorMsg);

                            LogFactory.Warn(requestResult.ErrorMsg);

                            continue;
                        }

                        var matchResult = Regex.Match(requestResult.Data, "left-tips-id\">ID:&nbsp;(.+?)</");

                        if (!matchResult.Success)
                        {
                            this.AsyncSetLog(this.tbx_Log, $"匹配 ResumeNumber 失败! url=>{url}");

                            LogFactory.Warn($"匹配 ResumeNumber 失败! url=>{url}");

                            continue;
                        }

                        var resumeNumber = matchResult.Result("$1");

                        if (!dictionary.TryAdd(resumeNumber, resumeNumber))
                        {
                            this.AsyncSetLog(this.tbx_Log, $"去重! ResumeNumber=>{resumeNumber}");

                            continue;
                        }

                        File.WriteAllText($@"D:\Badoucai\OldZhaopinResume\50862012\{resumeNumber}.txt", requestResult.Data);

                        this.AsyncSetLog(this.tbx_Log, $"下载成功! ResumeNumber=>{resumeNumber}");
                    }
                }));
            }

            Task.WaitAll(tasks.ToArray());
        }
        public static async Task <(bool hasInvalidInvite, bool attemptToWorkaround, List <DiscordInvite> invites)> GetInvitesAsync(this DiscordClient client, string message, DiscordUser author = null, bool tryMessageAsACode = false)
        {
            if (string.IsNullOrEmpty(message))
            {
                return(false, false, new List <DiscordInvite>(0));
            }

            var inviteCodes         = new HashSet <string>(InviteLink.Matches(message).Select(m => m.Groups["invite_id"]?.Value).Where(s => !string.IsNullOrEmpty(s)));
            var discordMeLinks      = InviteLink.Matches(message).Select(m => m.Groups["me_id"]?.Value).Distinct().Where(s => !string.IsNullOrEmpty(s)).ToList();
            var attemptedWorkaround = false;

            if (author != null && InviteCodeCache.TryGetValue(author.Id, out HashSet <string> recentInvites))
            {
                foreach (var c in recentInvites)
                {
                    if (message.Contains(c))
                    {
                        attemptedWorkaround |= inviteCodes.Add(c);
                        InviteCodeCache.Set(author.Id, recentInvites, CacheDuration);
                    }
                }
            }
            if (inviteCodes.Count == 0 && discordMeLinks.Count == 0 && !tryMessageAsACode)
            {
                return(false, attemptedWorkaround, new List <DiscordInvite>(0));
            }

            var hasInvalidInvites = false;

            foreach (var meLink in discordMeLinks)
            {
                /*
                 * discord.me is a f*****g joke and so far they were unwilling to provide any kind of sane api
                 * here's their current flow:
                 * 1. get vanity page (e.g. https://discord.me/rpcs3)
                 * 2. POST web form with csrf token and server EID to https://discord.me/server/join
                 * 3. this will return a 302 redirect (Location header value) to https://discord.me/server/join/protected/_some_id_
                 * 4. this page will have a "refresh" meta tag in its body to ttps://discord.me/server/join/redirect/_same_id_
                 * 5. this one will return a 302 redirect to an actual https://discord.gg/_invite_id_
                 */
                try
                {
                    using var handler    = new HttpClientHandler { AllowAutoRedirect = false }; // needed to store cloudflare session cookies
                    using var httpClient = HttpClientFactory.Create(handler, new CompressionMessageHandler());
                    using var request    = new HttpRequestMessage(HttpMethod.Get, "https://discord.me/" + meLink);
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
                    request.Headers.CacheControl = CacheControlHeaderValue.Parse("no-cache");
                    request.Headers.UserAgent.Add(new ProductInfoHeaderValue("RPCS3CompatibilityBot", "2.0"));
                    using var response = await httpClient.SendAsync(request).ConfigureAwait(false);

                    var html = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    if (response.IsSuccessStatusCode)
                    {
                        if (string.IsNullOrEmpty(html))
                        {
                            continue;
                        }

                        hasInvalidInvites = true;
                        var csrfTokenMatch = Regex.Match(html, @"name=""csrf-token"" content=""(?<csrf_token>\w+)""");
                        var serverEidMatch = Regex.Match(html, @"name=""serverEid"" value=""(?<server_eid>\w+)""");
                        if (csrfTokenMatch.Success && serverEidMatch.Success)
                        {
                            using var postRequest = new HttpRequestMessage(HttpMethod.Post, "https://discord.me/server/join")
                                  {
                                      Content = new FormUrlEncodedContent(new Dictionary <string, string>
                                {
                                    ["_token"]    = csrfTokenMatch.Groups["csrf_token"].Value,
                                    ["serverEid"] = serverEidMatch.Groups["server_eid"].Value,
                                }),
                                  };
                            postRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
                            postRequest.Headers.UserAgent.Add(new ProductInfoHeaderValue("RPCS3CompatibilityBot", "2.0"));
                            using var postResponse = await httpClient.SendAsync(postRequest).ConfigureAwait(false);

                            if (postResponse.StatusCode == HttpStatusCode.Redirect)
                            {
                                var redirectId = postResponse.Headers.Location.Segments.Last();
                                using var getDiscordRequest            = new HttpRequestMessage(HttpMethod.Get, "https://discord.me/server/join/redirect/" + redirectId);
                                getDiscordRequest.Headers.CacheControl = CacheControlHeaderValue.Parse("no-cache");
                                getDiscordRequest.Headers.UserAgent.Add(new ProductInfoHeaderValue("RPCS3CompatibilityBot", "2.0"));
                                using var discordRedirect = await httpClient.SendAsync(getDiscordRequest).ConfigureAwait(false);

                                if (discordRedirect.StatusCode == HttpStatusCode.Redirect)
                                {
                                    inviteCodes.Add(discordRedirect.Headers.Location.Segments.Last());
                                    hasInvalidInvites = false;
                                }
                                else
                                {
                                    Config.Log.Warn($"Unexpected response code from GET discord redirect: {discordRedirect.StatusCode}");
                                }
                            }
                            else
                            {
                                Config.Log.Warn($"Unexpected response code from POST: {postResponse.StatusCode}");
                            }
                        }
                        else
                        {
                            Config.Log.Warn($"Failed to get POST arguments from discord.me: {html}");
                        }
                    }
                    else
                    {
                        Config.Log.Warn($"Got {response.StatusCode} from discord.me: {html}");
                    }
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e);
                }
            }

            if (tryMessageAsACode)
            {
                inviteCodes.Add(message);
            }

            var result = new List <DiscordInvite>(inviteCodes.Count);

            foreach (var inviteCode in inviteCodes)
            {
                try
                {
                    if (await client.GetInviteByCodeAsync(inviteCode).ConfigureAwait(false) is DiscordInvite invite)
                    {
                        result.Add(invite);
                    }
                }
                catch (Exception e)
                {
                    hasInvalidInvites = true;
                    Config.Log.Warn(e, $"Failed to get invite for code {inviteCode}");
                }
            }
            return(hasInvalidInvites, attemptedWorkaround, result);
        }
Example #29
0
        public void RefreshServerList()
        {
            // Query in progress
            if (activeQuery)
            {
                return;
            }

            searchStatus = SearchStatus.Fetching;

            var queryURL = new HttpQueryBuilder(services.ServerList)
            {
                { "protocol", GameServer.ProtocolVersion },
                { "engine", Game.EngineVersion },
                { "mod", Game.ModData.Manifest.Id },
                { "version", Game.ModData.Manifest.Metadata.Version }
            }.ToString();

            Task.Run(async() =>
            {
                var games  = new List <GameServer>();
                var client = HttpClientFactory.Create();
                var httpResponseMessage = await client.GetAsync(queryURL);
                var result = await httpResponseMessage.Content.ReadAsStringAsync();

                activeQuery = true;

                try
                {
                    var yaml = MiniYaml.FromString(result);
                    foreach (var node in yaml)
                    {
                        try
                        {
                            var gs = new GameServer(node.Value);
                            if (gs.Address != null)
                            {
                                games.Add(gs);
                            }
                        }
                        catch
                        {
                            // Ignore any invalid games advertised.
                        }
                    }
                }
                catch
                {
                    searchStatus = SearchStatus.Failed;
                }

                var lanGames = new List <GameServer>();
                foreach (var bl in lanGameLocations)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(bl.Data))
                        {
                            continue;
                        }

                        var game   = MiniYaml.FromString(bl.Data)[0].Value;
                        var idNode = game.Nodes.FirstOrDefault(n => n.Key == "Id");

                        // Skip beacons created by this instance and replace Id by expected int value
                        if (idNode != null && idNode.Value.Value != Platform.SessionGUID.ToString())
                        {
                            idNode.Value.Value = "-1";

                            // Rewrite the server address with the correct IP
                            var addressNode = game.Nodes.FirstOrDefault(n => n.Key == "Address");
                            if (addressNode != null)
                            {
                                addressNode.Value.Value = bl.Address.ToString().Split(':')[0] + ":" + addressNode.Value.Value.Split(':')[1];
                            }

                            game.Nodes.Add(new MiniYamlNode("Location", "Local Network"));

                            lanGames.Add(new GameServer(game));
                        }
                    }
                    catch
                    {
                        // Ignore any invalid LAN games advertised.
                    }
                }

                var groupedLanGames = lanGames.GroupBy(gs => gs.Address).Select(g => g.Last());
                if (games != null)
                {
                    games.AddRange(groupedLanGames);
                }
                else if (groupedLanGames.Any())
                {
                    games = groupedLanGames.ToList();
                }

                Game.RunAfterTick(() => RefreshServerListInner(games));

                activeQuery = false;
            });
        }
 public StrainApi(HttpClientFactory factory)
 {
     this.factory = factory;
 }
Example #31
0
 public CookieContainer GetCookieContainer()
 {
     return(HttpClientFactory.GetCookieContainer());
 }
Example #32
0
 public void DeleteCookie(Uri domain, string name)
 {
     HttpClientFactory.DeleteCookie(domain, name);
 }
Example #33
0
		public async Task<User> UpdateAsync (User user)
		{
			//Does not work. There is a security stamp field in the database that gets out of sync when using the UsersRepository to make these updates. Look at UserManager instead
			HttpClientFactory factory = new HttpClientFactory(user.UserAccessToken);
			client = factory.CreateHttpClient ();

			string userJson = JsonConvert.SerializeObject (user);
			HttpContent content = new StringContent (userJson, Encoding.UTF8, "application/json");
			HttpResponseMessage response = await client.PutAsync ("api/account/update/", content);

			if (response.IsSuccessStatusCode) {
				string jsonMessage;
				using (Stream responseStream = await response.Content.ReadAsStreamAsync ()) {
					jsonMessage = new StreamReader (responseStream).ReadToEnd ();
				}

				user = (User)JsonConvert.DeserializeObject (jsonMessage, typeof(User));
				return user;
			} else {
				return null;
			}

		}
Example #34
0
 public void AddCookies(CookieCollection cookies)
 {
     HttpClientFactory.AddCookies(cookies);
 }
Example #35
0
 public Api(string appKey, string appId)
 {
     var f = new HttpClientFactory(appKey, appId);
     this.Strains = new StrainApi(f);
     this.Locations = new LocationApi(f);
 }
Example #36
0
        private static void Main(string[] args)
        {
            // ==== Create the client ====
            var tenant    = ConfigurationManager.AppSettings["Tenant"];
            var address   = ConfigurationManager.AppSettings["Address"];
            var aadFormat = ConfigurationManager.AppSettings["AADInstanceFormat"];
            var resource  = ConfigurationManager.AppSettings["Resource"];
            var appId     = ConfigurationManager.AppSettings["AppId"];
            var appKey    = ConfigurationManager.AppSettings["AppKey"];

            // A formal client should be wrapped in a retry handler.
            HttpClient client = HttpClientFactory.Create(new WebRequestHandler(),
                                                         new AuthenticationHandler(resource, tenant, aadFormat, appId, appKey));

            client.BaseAddress = new Uri(address);

            // ==== Get or create the namespace, type and stream(s) ====
            var space = new QiNamespace()
            {
                Id = ConfigurationManager.AppSettings["Namespace"]
            };
            HttpResponseMessage response = client.GetAsync($"Qi/{tenant}/Namespaces/{space.Id}").GetAwaiter().GetResult();

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                response = client.PostAsJsonAsync($"Qi/{tenant}/Namespaces", space).GetAwaiter().GetResult();
            }
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            var type = QiTypeBuilder.CreateQiType <WaveData>();

            response = client.GetAsync($"Qi/{tenant}/{space.Id}/Types/{type.Id}").GetAwaiter().GetResult();
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                response = client.PostAsJsonAsync($"Qi/{tenant}/{space.Id}/Types", type).GetAwaiter().GetResult();
            }
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            var stream = new QiStream()
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = typeof(WaveData).Name,
                Description = "Sample",
                TypeId      = type.Id
            };

            response = client.GetAsync($"Qi/{tenant}/{space.Id}/Streams/{stream.Id}").GetAwaiter().GetResult();
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                response = client.PostAsJsonAsync($"Qi/{tenant}/{space.Id}/Streams", stream).GetAwaiter().GetResult();
            }
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            // ==== Perform basic CRUD optations ====

            // insert a single event
            var wave = GetWave(0, 200, 2);

            response =
                client.PutAsJsonAsync($"Qi/{tenant}/{space.Id}/Streams/{stream.Id}/Data/UpdateValue", wave)
                .GetAwaiter()
                .GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            // Insert another single event using a Post instead of a Put
            wave.Order += 1;
            response    =
                client.PostAsJsonAsync($"Qi/{tenant}/{space.Id}/Streams/{stream.Id}/Data/InsertValue", wave)
                .GetAwaiter()
                .GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            // Insert a collection of events
            var events = new List <WaveData>();

            for (var i = 2; i <= 200; i += 2)
            {
                events.Add(GetWave(i, 200, 2));
            }

            response =
                client.PostAsJsonAsync($"Qi/{tenant}/{space.Id}/Streams/{stream.Id}/Data/InsertValues", events)
                .GetAwaiter()
                .GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            // retrieve the newly inserted events
            response =
                client.GetAsync(
                    $"Qi/{tenant}/{space.Id}/Streams/{stream.Id}/Data/GetValues?startIndex={0}&endIndex={200}&count={100}")
                .GetAwaiter()
                .GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }
            var retrievedEvents = response.Content.ReadAsAsync <WaveData[]>().GetAwaiter().GetResult();

            // Update the events
            Array.ForEach(retrievedEvents, w => GetWave(w.Order, 200, 3));
            response =
                client.PutAsJsonAsync($"Qi/{tenant}/{space.Id}/Streams/{stream.Id}/Data/UpdateValues", events)
                .GetAwaiter()
                .GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            // ==== Clean up ====

            // It's not necessary to delete the values if you're deleting the stream
            response =
                client.DeleteAsync(
                    $"Qi/{tenant}/{space.Id}/Streams/{stream.Id}/Data/RemoveWindowValues?startIndex={0}&endIndex={200}")
                .GetAwaiter()
                .GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }

            response = client.DeleteAsync($"Qi/{tenant}/{space.Id}/Streams/{stream.Id}").GetAwaiter().GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }
            response = client.DeleteAsync($"Qi/{tenant}/{space.Id}/Types/{type.Id}").GetAwaiter().GetResult();
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }
        }
Example #37
0
 public HttpClient GetHttpClient()
 {
     return(HttpClientFactory.GetHttpClient());
 }
Example #38
0
 public ApiClient()
 {
     this.Client = HttpClientFactory.Create();
 }
        // Your application's entry point. Here you can initialize your MVVM framework, DI
        // container, etc.
        private static void AppMain(Avalonia.Application app, string[] args)
        {
            var cla = new CommandLineApplication();

            cla.HelpOption();
            var optionPromptType = cla.Option("-p|--prompt <USERPASS,AUTHCODE>", "The prompt type",
                                              CommandOptionType.SingleValue);
            var optionHostUrl = cla.Option("-h|--host <HOST_URL>", "The URL of the target host, displayed to the user and used to determine host type",
                                           CommandOptionType.SingleValue);
            var optionProxyUrl = cla.Option("--proxy <PROXY_URL>", "The URL of the proxy",
                                            CommandOptionType.SingleValue);
            var optionVerifySsl = cla.Option("--verifyssl <TRUE_FALSE>", "Whether SSL shoudl be verified or not",
                                             CommandOptionType.SingleValue);
            var optionOAuthConsumerKey = cla.Option("--oauthkey <KEY>", "The OAuth Consumer Key to use during OAuth flows",
                                                    CommandOptionType.SingleValue);
            var optionOAuthConsumerSecret = cla.Option("--oauthsecret <SECRET>", "The OAuth Consumer Secret to use during OAuth flows",
                                                       CommandOptionType.SingleValue);
            var optionTrace = cla.Option("--trace <TRUE_FALSE_FILEPATH>", "False for no logging, True to log to console, Filepath to log to file",
                                         CommandOptionType.SingleValue);

            cla.OnExecute(() =>
            {
                var prompt = optionPromptType.HasValue()
                            ? optionPromptType.Value()
                            : "userpass";

                var hostUrl = optionHostUrl.HasValue()
                            ? optionHostUrl.Value()
                            : BitbucketConstants.BitbucketBaseUrl; // default to https://bitbucket.org
                var proxyUrl = optionProxyUrl.HasValue()
                            ? optionProxyUrl.Value()
                            : null; // default to no proxy
                var verifySsl = optionVerifySsl.HasValue()
                            ? optionVerifySsl.Value()
                            : "true"; // default to true
                var oAuthConsumerKey = optionOAuthConsumerKey.HasValue()
                            ? optionOAuthConsumerKey.Value()
                            : null; // default to no key
                var oAuthConsumerSecret = optionOAuthConsumerSecret.HasValue()
                            ? optionOAuthConsumerSecret.Value()
                            : null; // default to no secret
                var traceConfig = optionTrace.HasValue()
                            ? optionTrace.Value()
                            : null; // default to no logging

                var streams = new StandardStreams();

                using (var trace = new Itofinity.Bitbucket.Authentication.Helpers.Microsoft.Git.CredentialManager.Trace())
                    using (var settings = new Settings(hostUrl, proxyUrl, verifySsl, oAuthConsumerKey, oAuthConsumerSecret, traceConfig))
                    {
                        var httpClientFactory = new HttpClientFactory(trace, settings, streams);

                        // Enable tracing
                        ConfigureTrace(trace, settings, streams);

                        var viewModel = GetViewModel(prompt, hostUrl, trace, httpClientFactory, settings);
                        var window    = GetWindow(viewModel);
                        app.Run(window);

                        if (viewModel.Output != null &&
                            viewModel.Output.Any())
                        {
                            streams.Out.WriteDictionary(viewModel.Output);
                        }
                    }

                return(0);
            });

            var result = cla.Execute(args);
        }
Example #40
0
		public UserRepository (HttpClientFactory httpClientFactory)
		{
			clientFactory = httpClientFactory;
		}
Example #41
0
 public async Task FillPipeAsync(PipeWriter writer, CancellationToken cancellationToken)
 {
     using (var client = HttpClientFactory.Create())
         using (var stream = await client.GetStreamAsync(uri).ConfigureAwait(false))
             await handler.FillPipeAsync(stream, writer, cancellationToken).ConfigureAwait(false);
 }
 public RemoteRequest(ScheduledExecutorService workExecutor, HttpClientFactory clientFactory
     , string method, Uri url, object body, Database db, IDictionary<string, object> 
     requestHeaders, RemoteRequestCompletionBlock onCompletion)
 {
     this.clientFactory = clientFactory;
     this.method = method;
     this.url = url;
     this.body = body;
     this.onCompletion = onCompletion;
     this.workExecutor = workExecutor;
     this.requestHeaders = requestHeaders;
     this.db = db;
     this.request = CreateConcreteRequest();
     Log.V(Log.TagSync, "%s: RemoteRequest created, url: %s", this, url);
 }
Example #43
0
        public override async Task <(ISource source, string failReason)> FindHandlerAsync(DiscordMessage message, ICollection <IArchiveHandler> handlers)
        {
            if (string.IsNullOrEmpty(message.Content))
            {
                return(null, null);
            }

            var matches = ExternalLink.Matches(message.Content);

            if (matches.Count == 0)
            {
                return(null, null);
            }

            using (var client = HttpClientFactory.Create())
                foreach (Match m in matches)
                {
                    if (m.Groups["dropbox_link"].Value is string lnk &&
                        !string.IsNullOrEmpty(lnk) &&
                        Uri.TryCreate(lnk, UriKind.Absolute, out var uri))
                    {
                        try
                        {
                            uri = uri.SetQueryParameter("dl", "1");
                            var filename = Path.GetFileName(lnk);
                            var filesize = -1;

                            using (var request = new HttpRequestMessage(HttpMethod.Head, uri))
                                using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Config.Cts.Token))
                                {
                                    if (response?.Content?.Headers?.ContentLength > 0)
                                    {
                                        filesize = (int)response.Content.Headers.ContentLength.Value;
                                    }
                                    if (response?.Content?.Headers?.ContentDisposition?.FileNameStar is string fname && !string.IsNullOrEmpty(fname))
                                    {
                                        filename = fname;
                                    }
                                    uri = response.RequestMessage.RequestUri;
                                }

                            using (var stream = await client.GetStreamAsync(uri).ConfigureAwait(false))
                            {
                                var buf = bufferPool.Rent(1024);
                                try
                                {
                                    var read = await stream.ReadBytesAsync(buf).ConfigureAwait(false);

                                    foreach (var handler in handlers)
                                    {
                                        var(canHandle, reason) = handler.CanHandle(filename, filesize, buf.AsSpan(0, read));
                                        if (canHandle)
                                        {
                                            return(new DropboxSource(uri, handler, filename, filesize), null);
                                        }
                                        else if (!string.IsNullOrEmpty(reason))
                                        {
                                            return(null, reason);
                                        }
                                    }
                                }
                                finally
                                {
                                    bufferPool.Return(buf);
                                }
                            }
                        }

                        catch (Exception e)
                        {
                            Config.Log.Warn(e, $"Error sniffing {m.Groups["dropbox_link"].Value}");
                        }
                    }
                }
            return(null, null);
        }
Example #44
0
		public Replication GetReplicator(Uri remote, HttpClientFactory httpClientFactory, 
			bool push, bool continuous, ScheduledExecutorService workExecutor)
		{
			Replication result = GetActiveReplicator(remote, push);
			if (result != null)
			{
				return result;
			}
			result = push ? new Pusher(this, remote, continuous, httpClientFactory, workExecutor
				) : new Puller(this, remote, continuous, httpClientFactory, workExecutor);
			return result;
		}
Example #45
0
 public Puller(Database db, Uri remote, bool continuous, HttpClientFactory clientFactory
               , ScheduledExecutorService workExecutor) : base(db, remote, continuous, clientFactory
                                                               , workExecutor)
 {
 }
Example #46
0
 public void SetDefaultHttpClientFactory(HttpClientFactory defaultHttpClientFactory
     )
 {
     this.defaultHttpClientFactory = defaultHttpClientFactory;
 }
Example #47
0
 private void OnSettings(bool open, Toggl.TogglSettingsView settings)
 {
     _httpClientFactory = HttpClientFactoryFromProxySettings(settings);
 }
Example #48
0
        public void return_a_correct_data_from_database_for_a_default_get_request()
        {
            var aGuid = Guid.NewGuid();
            dynamic entry = new ExpandoObject();
            entry.id = aGuid;
            entry.name = "John Smith";
            entry.email = "*****@*****.**";
            entry.active = true;
            entry.creationTime = new DateTime(2016, 1, 1);

            var expected = ((object) entry).ToJObject();

            var appUser = new AppUser
            {
                Id = aGuid,
                Name = "John Smith",
                Email = "*****@*****.**",
                Active = true,
                CreationTime = new DateTime(2016, 1, 1)
            };
            var connectionString = ConfigurationManager.ConnectionStrings["CraftingTable"].ConnectionString;

            using (IDbConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Execute(
                    @"insert AppUsers(Id, Name, Email, Active, CreationTime)
                      values (@Id, @Name, @Email, @Active, @CreationTime)",
                    appUser);
                sqlConnection.Close();
            }

            using (var httpClient = new HttpClientFactory().Create())
            {
                var response = httpClient.GetAsync("").Result;

                var actual = response.Content.ReadAsJsonAsync().Result;
                foreach (var user in actual.appUsers)
                {
                    Console.WriteLine(user.ToString());
                }
                Assert.Contains(expected, actual.appUsers);
            }
        }
Example #49
-1
		public Pusher(Database db, Uri remote, bool continuous, HttpClientFactory clientFactory
			, ScheduledExecutorService workExecutor) : base(db, remote, continuous, clientFactory
			, workExecutor)
		{
			createTarget = false;
			observing = false;
		}
 public RemoteMultipartDownloaderRequest(ScheduledExecutorService workExecutor, HttpClientFactory
      clientFactory, string method, Uri url, object body, Database db, IDictionary<string
     , object> requestHeaders, RemoteRequestCompletionBlock onCompletion) : base(workExecutor
     , clientFactory, method, url, body, db, requestHeaders, onCompletion)
 {
     this.db = db;
 }
 private PackageIssueProvider CreatePackageIssueProvider(string packagesFile)
 {
     string githubKey = ConfigurationManager.AppSettings.Get("GithubKey");
     string githubSecret = ConfigurationManager.AppSettings.Get("GithubSecret");
     var httpClient = new HttpClientFactory().CreateHttpClient(githubKey, githubSecret);
     _githubMilestoneService = new GithubMilestoneService(httpClient);
     return new PackageIssueProvider(new PackageRepository(packagesFile), new IssueRepository(new GithubIssueService(httpClient), _githubMilestoneService), _githubMilestoneService);
 }