示例#1
0
        protected override void Execute(CodeActivityContext context)
        {
            string        api_url         = ApiUrl.Get(context);
            string        api_token       = ApiToken.Get(context);
            List <string> allowed_classes = AllowedClasses.Get(context);
            string        image           = Image.Get(context);

            var ac = String.Join(",", allowed_classes.ToArray());

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Token " + api_token);
            MultipartFormDataContent form = new MultipartFormDataContent();

            FileStream    fs = File.Open(image, FileMode.Open);
            StreamContent sc = new StreamContent(fs);

            form.Add(sc, "image", Path.GetFileName(image));
            form.Add(new StringContent(ac), "text");

            HttpResponseMessage response = client.PostAsync(api_url, form).Result;

            if (response.IsSuccessStatusCode)
            {
                var json = response.Content.ReadAsStringAsync().Result;
                Documents.Set(context, json);
            }
            else
            {
                Documents.Set(context, "");
            }

            client.Dispose();
        }
示例#2
0
        public string GetData(int count, string countries)
        {
            string result = "";

            using (var req = new WebClient())
            {
                try
                {
                    string url = "";
                    if (countries.Equals("all"))
                    {
                        url = ApiUrl.Replace("{token}", Key).Replace("{page}", count.ToString()).Replace("&geo={geo}", "");
                    }
                    else
                    {
                        url = ApiUrl.Replace("{token}", Key).Replace("{page}", count.ToString()).Replace("{geo}", countries.ToUpper());
                    }
                    Debug.WriteLine("Get: " + url);
                    result = req.DownloadString(url).ToString();
                }
                catch
                {
                    result = "ERROR";
                }
            }
            return(result);
        }
示例#3
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (PropertyName.Length != 0)
            {
                hash ^= PropertyName.GetHashCode();
            }
            if (propertyForeignTenancyId_ != null)
            {
                hash ^= PropertyForeignTenancyId.GetHashCode();
            }
            if (ApiUrl.Length != 0)
            {
                hash ^= ApiUrl.GetHashCode();
            }
            if (entityId_ != null)
            {
                hash ^= EntityId.GetHashCode();
            }
            if (WebsiteUrl.Length != 0)
            {
                hash ^= WebsiteUrl.GetHashCode();
            }
            return(hash);
        }
示例#4
0
        public async Task <List <GsFile> > GetProjectFiles(string projectId)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Get, new Uri(ApiUrl.GetProjectFiles(projectId)));
                    ApiUrl.AddRequestHeaders(httpClient, request);

                    var responseMessage = await httpClient.SendAsync(request);

                    var filesResponse = await responseMessage.Content.ReadAsStringAsync();

                    if (responseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        return(JsonConvert.DeserializeObject <List <GsFile> >(filesResponse));
                    }
                }
            }
            catch (Exception e)
            {
                // here we'll add loging
            }
            return(new List <GsFile>());
        }
示例#5
0
        /// <summary>
        /// 開始執行發票功能, 並取得結果
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string Post <T>(T obj)
            where T : Iinvoice
        {
            //清除掉之前的參數
            _parameters = string.Empty;

            //先作驗證
            string Valid = Validate(obj);

            if (!string.IsNullOrEmpty(Valid))
            {
                return(Valid);
            }

            //組出傳送字串
            ObjectToNameValueCollection(obj);

            //取出API位置
            ApiUrl url = _iapi.GetList().FirstOrDefault(p => p.invM == obj.invM && p.env == _settings.Environment);

            //作壓碼字串
            string checkMacValue = BuildCheckMacValue(_parameters);

            //組出實際傳送的字串
            string urlString = $"{_parameters}&CheckMacValue={checkMacValue}";

            //執行api功能, 並取得回傳結果
            string result = ServerPost(urlString, url?.apiUrl);

            //回傳
            return(validReturnString(result));
        }
示例#6
0
 public TokenManager(AppDbContext appDbContext, IOptions <ApiUrl> apiUrl, IOptions <IdentityConfigOptions> identityConfig, ILogger <TokenManager> logger)
 {
     this.appDbContext   = appDbContext;
     this.logger         = logger;
     this.identityConfig = identityConfig.Value;
     this.apiUrl         = apiUrl.Value;
 }
示例#7
0
        public override async Task <IEnumerable <VulnerabilityInfo> > GetVulnerabilitiesAsync(IVulnerabilitySourceContext context)
        {
            var serializer           = new JsonSerializer();
            var layersApi            = ApiUrl.Trim('/') + "/v1/layers";
            var vulnerabilitesApiUrl = ApiUrl.Trim('/') + "/v1/layers/{0}?features&vulnerabilities";



            var vulnerabilityInfos = new List <VulnerabilityInfo>();

            foreach (var blob in context.Blobs.Where(b => !b.MediaType.EndsWith("json", StringComparison.OrdinalIgnoreCase)))
            {
                var postRequest = this.CreatePostWebRequest(layersApi);
                var response    = await this.PushLayerToClair(serializer, postRequest, blob);

                if (response != null)
                {
                    var vResponse = await this.GetVulnerabilitesFromClair(serializer, vulnerabilitesApiUrl, blob, response);

                    if (vResponse?.Layer?.Features?.Any(f => f?.Vulnerabilities?.Any(v => v != null) ?? false) != null)
                    {
                        var vulnerableFeatures = vResponse.Layer.Features.Where(f => f.Vulnerabilities?.Any() ?? false);
                        foreach (var vulnerableFeature in vulnerableFeatures)
                        {
                            foreach (var vulnerability in vulnerableFeature.Vulnerabilities)
                            {
                                vulnerabilityInfos.Add(new ClairVulnerabilityInfo(this.BuildId(vulnerableFeature), blob.FeedType, blob.Digest, vulnerability.Name, this.BuildDescription(vulnerableFeature, vulnerability)));
                            }
                        }
                    }
                }
            }

            return(vulnerabilityInfos);
        }
示例#8
0
        /// <summary>
        /// Apiへのリクエストを実行する
        /// </summary>
        /// <param name="onSuccess">APIへのリクエストに成功した時のコールバック</param>
        /// <param name="onError">エラー発生時のコールバック</param>
        /// <typeparam name="T">成功した時の戻り値の型</typeparam>
        public void SendRequest(Action <T, ApiLinksFormat> onSuccess, Action <ApiErrorFormat> onError)
        {
            var url           = new ApiUrl(EnvironmentConfig.HttpHostUrl, RequestPath);
            var requestHeader = new ApiHeader(Headers);
            var conn          = ConnectionFactory.CreateHttpConnection(url, Methods, Params, requestHeader);

            if (onSuccess != null)
            {
                conn.OnSuccess = (response) => ResponseConverter.Convert(
                    response,
                    (responseTemplate) => onSuccess(responseTemplate.data, responseTemplate._links),
                    onError
                    );
            }
            if (OnDownloadProgress != null)
            {
                conn.OnDownloadProgress = (value) => OnDownloadProgress.Invoke(value);
            }
            if (OnUploadProgress != null)
            {
                conn.OnUploadProgress = (value) => OnUploadProgress.Invoke(value);
            }
            if (onError != null)
            {
                conn.OnError = (error) => onError(ResponseConverter.ConvertError(error.Response));
            }
            conn.RequestAsync(Timeout);
        }
示例#9
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (StatusCode != 0)
            {
                hash ^= StatusCode.GetHashCode();
            }
            if (RequestId != 0UL)
            {
                hash ^= RequestId.GetHashCode();
            }
            if (ApiUrl.Length != 0)
            {
                hash ^= ApiUrl.GetHashCode();
            }
            hash ^= platformReturns_.GetHashCode();
            if (authTicket_ != null)
            {
                hash ^= AuthTicket.GetHashCode();
            }
            hash ^= returns_.GetHashCode();
            if (Error.Length != 0)
            {
                hash ^= Error.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
示例#10
0
        public async Task <ProjectResponse> GetGsProjects(ProjectFilter projectFilter)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var queryString = ApiUrl.GetQuerryString(projectFilter);
                    var request     = new HttpRequestMessage(HttpMethod.Get, new Uri(queryString));
                    ApiUrl.AddRequestHeaders(httpClient, request);

                    var responseMessage = await httpClient.SendAsync(request);

                    var projectsResponse = await responseMessage.Content.ReadAsStringAsync();

                    if (responseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        return(JsonConvert.DeserializeObject <ProjectResponse>(projectsResponse));
                    }
                }
            }
            catch (Exception e)
            {
                Log.Logger.Error($"GetGsProjects service method: {e.Message}\n {e.StackTrace}");
            }
            return(new ProjectResponse());
        }
示例#11
0
        public async Task <IActionResult> Login(LoginRequestDto requestDto)
        {
            var apiResult =
                await new ApiHelper <ApplicationResponse <LoginResponseDto> >(_httpClient, _securityTokenHandler)
                .Post(ApiUrl.Login(_apiUrl), requestDto, false);

            if (apiResult is { State : ResponseState.Success })
示例#12
0
        public async Task <byte[]> DownloadFileVersion(string projectId, string languageFileId, int version)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Get, new Uri(ApiUrl.DownloadFileVersion(projectId, languageFileId, version)));
                    ApiUrl.AddRequestHeaders(httpClient, request);

                    var responseMessage = await httpClient.SendAsync(request);

                    var fileResponse = await responseMessage.Content.ReadAsByteArrayAsync();

                    if (responseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        return(fileResponse);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Logger.Error($"DownloadFileVersion service method: {e.Message}\n {e.StackTrace}");
            }
            return(new byte[0]);
        }
示例#13
0
        public async Task <bool> Authenticate(int companyId, string username, string password, bool setToClose)
        {
            if (ApiUrl != null && ApiUrl.IsValid() && (Token == null || !Token.IsValid()))
            {
                try
                {
                    Token = await ApiUrl.AppendPathSegment("token")
                            .PostUrlEncodedAsync(
                        new
                    {
                        companyId,
                        username,
                        password,
                        setToClose,
                        grant_type = "password"
                    }
                        )
                            .ReceiveJson <ApiTokenModel>();

                    Token.EmployeeViewInfo = await ApiUrl.AppendPathSegment("ws/me")
                                             .GetJsonAsync <EmployeeViewInfoModel>();

                    CompanyId  = companyId;
                    Username   = username;
                    Password   = password;
                    SetToClose = setToClose;

                    return(true);
                }
                catch (FlurlHttpException) { }
                catch (Exception) { }
            }

            return(false);
        }
        public async override void OnNavigatedNewToAsync(INavigationParameters parameters)
        {
            base.OnNavigatedNewToAsync(parameters);
            if (parameters != null)
            {
                if (parameters.ContainsKey(ParamKey.ContentSearch.ToString()))
                {
                    SearchContent = (string)parameters[ParamKey.ContentSearch.ToString()];
                    if (!string.IsNullOrEmpty(SearchContent))
                    {
                        SearchContent = SearchContent.Replace(" ", "+");
                        var tempItem = await LoadData(ApiUrl.GetSearchItem(SearchContent));

                        if (tempItem != null)
                        {
                            SearchItemList = new ObservableCollection <ItemModel>(tempItem);
                            IsExistedItem  = true;
                        }
                        else
                        {
                            IsExistedItem = false;
                        }
                    }
                }
            }
        }
示例#15
0
        public override int GetHashCode()
        {
            var hash = 1;

            if (Unknown1 != 0)
            {
                hash ^= Unknown1.GetHashCode();
            }
            if (Unknown2 != 0L)
            {
                hash ^= Unknown2.GetHashCode();
            }
            if (ApiUrl.Length != 0)
            {
                hash ^= ApiUrl.GetHashCode();
            }
            if (unknown6_ != null)
            {
                hash ^= Unknown6.GetHashCode();
            }
            if (auth_ != null)
            {
                hash ^= Auth.GetHashCode();
            }
            hash ^= payload_.GetHashCode();
            if (ErrorMessage.Length != 0)
            {
                hash ^= ErrorMessage.GetHashCode();
            }
            return(hash);
        }
示例#16
0
        public async Task <IEnumerable <OrganisationModel> > Get(string authorization)
        {
            var endpoint = $"{ApiUrl.TrimEnd('/')}/api/organisations";

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", authorization);
                var response = await client.GetAsync(endpoint);

                var result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(result.DefaultIfNull(response.ToString()));
                }

                var jsonObj = JsonConvert.DeserializeObject(result) as JObject;

                if (jsonObj == null)
                {
                    throw new Exception("Unknow response type");
                }

                return(jsonObj["items"].ToObject <IEnumerable <OrganisationModel> >());
            }
        }
示例#17
0
        public async Task <List <GsFileVersion> > GetFileVersion(string languageFileId)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Get, new Uri(ApiUrl.GetFileVersions(languageFileId)));
                    ApiUrl.AddRequestHeaders(httpClient, request);

                    var responseMessage = await httpClient.SendAsync(request);

                    var filesResponse = await responseMessage.Content.ReadAsStringAsync();

                    if (responseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        return(JsonConvert.DeserializeObject <List <GsFileVersion> >(filesResponse));
                    }
                }
            }
            catch (Exception e)
            {
                Log.Logger.Error($"GetFileVersion service method: {e.Message}\n {e.StackTrace}");
            }
            return(new List <GsFileVersion>());
        }
示例#18
0
        public async Task <IActionResult> Index(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    return(View());
                }

                var apiResult =
                    await new ApiHelper <ApplicationResponse <ShortUrlResponseDto> >(_httpClient, _securityTokenHandler)
                    .Get(ApiUrl.GetShortly(_apiUrl, id));

                if (apiResult is not null && apiResult.State == ResponseState.Success && apiResult.Data is not null)
                {
                    return(Redirect(apiResult.Data.LongUrl));
                }

                return(View());
            }
            catch (Exception e)
            {
                return(View());
            }
        }
示例#19
0
文件: huobi.cs 项目: yuxi214/ccxt.net
        /// <summary>
        ///
        /// </summary>
        /// <param name="endpoint">api link address of a function</param>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async Task <IRestRequest> CreatePostRequest(string endpoint, Dictionary <string, object> args = null)
        {
            var _request = await base.CreatePostRequest(endpoint, args);

            if (IsAuthentication == true)
            {
                var _params = new Dictionary <string, object>();
                {
                    _params.Add("AccessKeyId", ConnectKey);
                    _params.Add("SignatureMethod", "HmacSHA256");
                    _params.Add("SignatureVersion", 2);
                    _params.Add("Timestamp", CUnixTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss"));
                }

                var _post_data = ToQueryString(_params);
                var _signature = GetSignatureStr(Method.POST, ApiUrl.Replace("https://", ""), endpoint, _post_data);

                _post_data += "&Signature=" + _signature;

                _request.AddHeader("Content-Type", "application/json");
                _request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");
                _request.Resource += $"?{_post_data}";
            }

            return(await Task.FromResult(_request));
        }
        internal void Save()
        {
            if (!string.IsNullOrWhiteSpace(ApiKey))
            {
                NativeMethods.WritePrivateProfileString("settings", "api_key", ApiKey.Trim(), _configFilepath);
            }

            if (ApiUrl == Constants.ApiMyPulsesEndpoint || string.IsNullOrWhiteSpace(ApiUrl))
            {
                NativeMethods.WritePrivateProfileString("settings", "api_url", string.Empty, _configFilepath);
            }
            else if (!string.IsNullOrWhiteSpace(ApiUrl))
            {
                NativeMethods.WritePrivateProfileString("settings", "api_url", ApiUrl.Trim(), _configFilepath);
            }

            NativeMethods.WritePrivateProfileString("settings", "stats", Stats.ToString().ToLower(), _configFilepath);
            NativeMethods.WritePrivateProfileString("settings", "guid", this.Guid, _configFilepath);
            NativeMethods.WritePrivateProfileString("settings", "proxy", Proxy.Trim(), _configFilepath);
            NativeMethods.WritePrivateProfileString("settings", "debug", Debug.ToString().ToLower(), _configFilepath);

            NativeMethods.WritePrivateProfileString("detection_order", "use_extension_mapping", UseExtensionMapping.ToString().ToLower(), _configFilepath);
            NativeMethods.WritePrivateProfileString("detection_order", "use_lexer_language", UseLexerLanguage.ToString().ToLower(), _configFilepath);
            NativeMethods.WritePrivateProfileString("detection_order", "priority", ((int)DetectionPriority).ToString(), _configFilepath);
            NativeMethods.WritePrivateProfileString("detection_order", "use_custom_mapping", UseCustomMapping.ToString().ToLower(), _configFilepath);
        }
示例#21
0
        public async Task <IActionResult> Create(ShortUrlRequestDto requestDto)
        {
            var apiResult = await
                            new ApiHelper <ApplicationResponse <ShortUrlResponseDto> >(_httpClient, _securityTokenHandler)
                            .Post(ApiUrl.AddShortly(_apiUrl), requestDto);

            return(Json(apiResult));
        }
示例#22
0
        public async Task <JsonResult> SaveApiUrl(ApiUrl model)
        {
            using (ApiManaRepository rep = new ApiManaRepository())
            {
                var res = await rep.AddOrUpdateApiUrlAsync(model);

                return(Json(new { isOk = res }));
            }
        }
 /// <inheritdoc />
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = (Instance != null ? Instance.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ApiUrl != null ? ApiUrl.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Token != null ? Token.GetHashCode() : 0);
         return(hashCode);
     }
 }
示例#24
0
        public string UrlAddress()
        {
            if (ApiUrl.Contains('-'))
            {
                var s = ApiUrl.Split('-');
                return(string.Format("{0}.challonge.com/{1}", s[0], s[1]));
            }

            return(string.Format("www.challonge.com/{0}", ApiUrl));
        }
示例#25
0
        public async override void OnAppear()
        {
            base.OnAppear();
            await CheckBusy(async() =>
            {
                await LoadingPopup.Instance.Show(TranslateExtension.Get("Loading3dot"));
                var url = ApiUrl.GetWallet() + UserInfo.WalletAddress;

                var response = await HttpRequest.GetTaskAsync <ModelRestFul>(url);
                await GetWalletCallBack(response);
            });
        }
示例#26
0
        public async Task <string> CheckVersion()
        {
            try
            {
                return(await ApiUrl.AppendPathSegment("ws/check-version")
                       .GetStringAsync());
            }
            catch (FlurlHttpException) { }
            catch (Exception) { }

            return(String.Empty);
        }
示例#27
0
        public async Task <string> GetWebServiceVersion()
        {
            try
            {
                return(await ApiUrl.AppendPathSegment("ws/web-service-version")
                       .GetStringAsync());
            }
            catch (FlurlHttpException) { }
            catch (Exception) { }

            return(String.Empty);
        }
示例#28
0
 /// <inheritdoc />
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = (Instance != null ? Instance.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ApiUrl != null ? ApiUrl.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ PaidTill.GetHashCode();
         hashCode = (hashCode * 397) ^ PaymentsCount.GetHashCode();
         hashCode = (hashCode * 397) ^ IsActive.GetHashCode();
         hashCode = (hashCode * 397) ^ (TypeInstance != null ? TypeInstance.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
         return(hashCode);
     }
 }
示例#29
0
        public async Task FinalizeSession()
        {
            if (Token?.AccessToken != null)
            {
                await ApiUrl.AppendPathSegment("ws/finalize-session")
                .WithOAuthBearerToken(Token.AccessToken)
                .GetAsync();

                Token     = null;
                CompanyId = 0;
                Username  = String.Empty;
                Password  = String.Empty;
            }
        }
        public async Task <HttpResponseMessage> ReleaseWarehousePassword(string password)
        {
            try
            {
                return(await ApiUrl.AppendPathSegment($"{Controller}/release-warehouse-password/{password}")
                       .PostJsonAsync(EmployeeViewInfo));
            }
            catch (FlurlHttpException e)
            {
                return(new HttpResponseMessage(e.Call.HttpStatus ?? HttpStatusCode.BadRequest));
            }
            catch (Exception) { }

            return(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }