예제 #1
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="route"></param>
 /// <param name="method"></param>
 /// <param name="isSecure"></param>
 /// <param name="roleLevel"></param>
 public ApiAttribute(string route, ApiMethod method, bool isSecure, AccessLevel roleLevel)
 {
     this._route = route;
     this._method = method;
     this._isSecure = isSecure;
     this._roleLevel = (int)roleLevel;
 }
예제 #2
0
파일: Method.cs 프로젝트: 392HEMI/Api
 public Method(DbEntity entity, ApiMethod method, bool isVisible, bool forAutorized)
 {
     this.entity = entity;
     this.method = method;
     this.isVisible = isVisible;
     this.forAutorized = forAutorized;
 }
        public StreamCopyOperation(
            LiveConnectClient client, 
            ApiMethod method, 
            Stream inputStream, 
            Stream outputStream, 
            long contentLength, 
            object progress,
            SynchronizationContextWrapper syncContext, 
            Action<bool, Exception> onCopyCompleted)
            : base(syncContext)
        {
            Debug.Assert(client != null, "client must not be null.");
            Debug.Assert(
                method == ApiMethod.Download || method == ApiMethod.Upload,
                "Only Download and Upload methods are allowed.");
            Debug.Assert(inputStream.CanRead, "Input stream is not readable.");
            Debug.Assert(outputStream.CanWrite, "Output stream is not writable.");

            this.LiveClient = client;
            this.Method = method;
            this.InputStream = inputStream;
            this.OutputStream = outputStream;
            this.ContentLength = contentLength;
            this.buffer = new byte[StreamCopyOperation.BufferSize];
            this.copyCompletedCallback = onCopyCompleted;
            this.progress = progress;
        }
        public MusixmatchApiResponse SendRequestLegacy(ApiMethod method, Dictionary <string, string> additionalArguments = null, string data = null)
        {
            CustomRequestParameters requestParameters;

            if (CustomRequestParameters.ContainsKey(method))
            {
                requestParameters = CustomRequestParameters[method];
            }
            else
            {
                requestParameters = new CustomRequestParameters();
            }

            string endpoint = requestParameters.EndpointResource;

            if (additionalArguments == null)
            {
                additionalArguments = new Dictionary <string, string>();
            }

            additionalArguments.Add("format", "json");
            additionalArguments.Add("app_id", Context.AppId);
            additionalArguments.Add("usertoken", UserToken);

            additionalArguments.Add("guid", UserGuid.ToString());

            string arguments = GetArgumentString(additionalArguments);

            string requestUrl = SignRequestUrl($"{Context.ApiUrl}{endpoint}{arguments}");

            string response = string.Empty;

            switch (requestParameters.RequestMethod)
            {
            case RequestMethod.GET:
                response = RequestProcessor.Get(requestUrl);
                break;

            case RequestMethod.POST:
                response = RequestProcessor.Post(requestUrl, data);
                break;
            }

            var responseParsed = JObject.Parse(response);
            var statusCode     = responseParsed.SelectToken("$..status_code", false).Value <int>(); // I guess, that value always exists

            if (statusCode != 200 && AssertOnError)
            {
                throw new MusixmatchRequestException((Model.Types.StatusCode)statusCode);
            }

            return(new MusixmatchApiResponse
            {
                StatusCode = statusCode,
                TimeElapsed = responseParsed.SelectToken("$..execute_time", false).Value <double>(),
                Body = responseParsed.SelectToken("$..body").ToString(),
                Header = responseParsed.SelectToken("$..header").ToString()
            });
        }
        private ApiOperation GetApiOperation(string path, ApiMethod method, string body)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("path");
            }

            if (IsAbsolutePath(path))
            {
                throw new ArgumentException(
                          String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("RelativeUrlRequired"), "path"),
                          "path");
            }

            Uri apiUri = this.GetResourceUri(path, method);

            if (this.Session == null)
            {
                throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn"));
            }

            ApiOperation operation = null;

            switch (method)
            {
            case ApiMethod.Get:
            case ApiMethod.Delete:
                operation = new ApiOperation(this, apiUri, method, null, null);
                break;

            case ApiMethod.Post:
            case ApiMethod.Put:
            case ApiMethod.Copy:
            case ApiMethod.Move:
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }

                if (string.IsNullOrWhiteSpace(body))
                {
                    throw new ArgumentException("body");
                }

                operation = new ApiWriteOperation(this, apiUri, method, body, null);
                break;

            default:
                Debug.Assert(false, "method not suppported.");
                break;
            }

            return(operation);
        }
 public ApiWriteOperation(
     LiveConnectClient client, 
     Uri url, 
     ApiMethod method, 
     string body, 
     SynchronizationContextWrapper syncContext)
     : base(client, url, method, body, syncContext)
 {
 }
        /// <summary>
        /// Calls API Methods.
        /// </summary>
        /// <typeparam name="T">Type to which the response content will be converted.</typeparam>
        /// <param name="method">HTTPMethod (POST-GET-PUT-DELETE)</param>
        /// <param name="endpoint">Url endpoing.</param>
        /// <param name="isSigned">Specifies if the request needs a signature.</param>
        /// <param name="parameters">Request parameters.</param>
        /// <returns></returns>
        public async Task <T> CallAsync <T>(ApiMethod method, string endpoint, bool isSigned = false, string parameters = null)
        {
            var finalEndpoint = endpoint + (string.IsNullOrWhiteSpace(parameters) ? "" : $"?{parameters}");

            if (isSigned)
            {
                // Joining provided parameters
                parameters += (!string.IsNullOrWhiteSpace(parameters) ? "&timestamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now.ToUniversalTime());

                // Creating request signature
                var signature = Utilities.GenerateSignature(_apiSecret, parameters);
                finalEndpoint = $"{endpoint}?{parameters}&signature={signature}";
            }

            finalEndpoint = "https://api.binance.com" + finalEndpoint;
            var request  = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint);
            var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                // Api return is OK
                response.EnsureSuccessStatusCode();

                // Get the result
                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // Serialize and return result
                return(JsonConvert.DeserializeObject <T>(result));
            }

            // We received an error
            if (response.StatusCode == HttpStatusCode.GatewayTimeout)
            {
                throw new Exception("Api Request Timeout.");
            }

            // Get te error code and message
            var e = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            // Error Values
            var    eCode = 0;
            string eMsg  = "";

            if (e.IsValidJson())
            {
                try
                {
                    var i = JObject.Parse(e);

                    eCode = i["code"]?.Value <int>() ?? 0;
                    eMsg  = i["msg"]?.Value <string>();
                }
                catch { }
            }

            throw new Exception(string.Format("Api Error Code: {0} Message: {1}", eCode, eMsg));
        }
예제 #8
0
 public ApiWriteOperation(
     LiveConnectClient client,
     Uri url,
     ApiMethod method,
     string body,
     SynchronizationContextWrapper syncContext)
     : base(client, url, method, body, syncContext)
 {
 }
예제 #9
0
        public void SingleMetricIsGenerated_WhenOneMethodIsRecorded(ApiMethod apiMethod)
        {
            _apiSupportabilityMetricCounters.Record(apiMethod);
            _apiSupportabilityMetricCounters.CollectMetrics();
            var metric = _publishedMetrics.Single();

            Assert.AreEqual(SupportabilityPrefix + apiMethod, metric.MetricName.Name);
            Assert.AreEqual(1, metric.Data.Value0);
        }
예제 #10
0
        protected virtual void Process(HierarchyObject parent, ApiMethod method)
        {
            var hierarchyMethod = CreateHierarchyElementInternal <HierarchyMethod> (parent);

            hierarchyMethod.Init(method);
            AddLocationComment(method, hierarchyMethod);
            AddMethodMembers(hierarchyMethod, method);
            parent.AddMember(hierarchyMethod);
        }
예제 #11
0
        private T PostRequest <T>(ApiMethod method, string jsonData) where T : class
        {
            var methodName = char.ToLowerInvariant(method.ToString()[0]) + method.ToString().Substring(1);

            var response = HttpHelper.Post <T>(
                new Uri(AnticaptchaInfoBase.Scheme + "://" + AnticaptchaInfoBase.Host + "/" + methodName),
                jsonData);

            return(response);
        }
예제 #12
0
        public static string ApiGetUrl(ApiMethod method, string clientId = "")
        {
            string url = Host + GetRelationUrlByType(method);

            if (!string.IsNullOrWhiteSpace(clientId))
            {
                url += $@"/{clientId}";
            }
            return(url);
        }
예제 #13
0
        private void MakeSmaregiEndpoints()
        {
            _smaregiApiMethod = new ApiMethod(ApiAccount.Url, ApiAccount.ContractId, ApiAccount.AccessToken);

            SmaregiEndpoints       = SmaregiEndpoints ?? new ReactiveProperty <List <ISmaregiEndpoint> >();
            SmaregiEndpoints.Value = new List <ISmaregiEndpoint>()
            {
                new TransactionHead(_smaregiApiMethod)
            };
        }
        private Result <T> Request <T>(
            ApiMethod method,
            string uri,
            ApiQueryField[] apiQueryFields,
            JToken jsonRequest,
            HttpStatusCode expectedStatusCode,
            bool readJsonResponse,
            Func <string, T> parseResponse)
        {
            Result <T> result;

            string xrfKey = GenerateXrfKey();

            var apiQueryFieldList = new List <ApiQueryField> {
                new ApiQueryField("Xrfkey", xrfKey)
            };

            if (apiQueryFields != null)
            {
                apiQueryFieldList.AddRange(apiQueryFields);
            }

            string fullUri = ComposeUri(uri, apiQueryFieldList);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri);

            request.Method = method.ToString().ToUpperInvariant();
            request.Headers.Add("X-Qlik-Xrfkey", xrfKey);
            request.Headers.Add("X-Qlik-User", $"UserDirectory={_user.UserDirectory}; UserId={_user.UserId}");
            request.Accept      = "application/json";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout     = (int)TimeSpan.FromSeconds(ApiTimeoutSeconds).TotalMilliseconds;
            if (_clientCertificate != null)
            {
                request.ClientCertificates.Add(_clientCertificate);
            }

            WriteJsonRequest(jsonRequest, request);

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == expectedStatusCode)
                {
                    string jsonResponse = ReadJsonResponse(readJsonResponse, response);

                    result = new Result <T>(true, parseResponse(jsonResponse));
                }
                else
                {
                    result = new Result <T>(false, default(T));
                }
            }

            return(result);
        }
예제 #15
0
 /// <summary>
 /// Constructs a new ApiOperation object.
 /// </summary>
 public ApiOperation(
     LiveConnectClient client,
     Uri url,
     ApiMethod method,
     string body,
     SynchronizationContextWrapper syncContext)
     : base(url, body, syncContext)
 {
     this.Method     = method;
     this.LiveClient = client;
 }
예제 #16
0
        public void CorrectMetricCounts_WhenMethodIsRecordedMultipleTimes(ApiMethod apiMethod, int recordCount)
        {
            for (var x = 0; x < recordCount; x++)
            {
                _apiSupportabilityMetricCounters.Record(apiMethod);
            }
            _apiSupportabilityMetricCounters.CollectMetrics();
            var metric = _publishedMetrics.Single();

            Assert.AreEqual(recordCount, metric.Data.Value0);
        }
예제 #17
0
        public bool TryGetXml(INN inn, ApiMethod method, out XmlDocument document)
        {
            if (!cleared && Inn == inn && method == this.method)
            {
                document = this.document;
                return(true);
            }

            document = new XmlDocument();
            return(false);
        }
예제 #18
0
        public static bool IsBodyAllowed(this ApiMethod method)
        {
            switch (method)
            {
            case ApiMethod.Get:
                return(false);

            default:
                return(true);
            }
        }
예제 #19
0
 /// <summary>
 /// Constructs a new ApiOperation object.
 /// </summary>
 public ApiOperation(
     LiveConnectClient client, 
     Uri url, 
     ApiMethod method, 
     string body, 
     SynchronizationContextWrapper syncContext)
     : base(url, body, syncContext)
 {
     this.Method = method;
     this.LiveClient = client;
 }
예제 #20
0
        public static void RecordCustomEvent(string eventType, IEnumerable <KeyValuePair <string, object> > attributes)
        {
            const ApiMethod apiMetric = ApiMethod.RecordCustomEvent;
            const string    apiName   = nameof(RecordCustomEvent);

            void work()
            {
                InternalApi.RecordCustomEvent(eventType, attributes);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #21
0
        public static void RecordMetric(string name, float value)
        {
            const ApiMethod apiMetric = ApiMethod.RecordMetric;
            const string    apiName   = nameof(RecordMetric);

            void work()
            {
                InternalApi.RecordMetric(name, value);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #22
0
        public static void DisableBrowserMonitoring(bool overrideManual = false)
        {
            const ApiMethod apiMetric = ApiMethod.DisableBrowserMonitoring;
            const string    apiName   = nameof(DisableBrowserMonitoring);

            void work()
            {
                InternalApi.DisableBrowserMonitoring(overrideManual);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #23
0
        public static void SetUserParameters(string?userName, string?accountName, string?productName)
        {
            const ApiMethod apiMetric = ApiMethod.SetUserParameters;
            const string    apiName   = nameof(SetUserParameters);

            void work()
            {
                InternalApi.SetUserParameters(userName, accountName, productName);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #24
0
        public static void SetTransactionUri(Uri uri)
        {
            const ApiMethod apiMetric = ApiMethod.SetTransactionUri;
            const string    apiName   = nameof(SetTransactionUri);

            void work()
            {
                InternalApi.SetTransactionUri(uri);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #25
0
        public static void SetTransactionName(string?category, string name)
        {
            const ApiMethod apiMetric = ApiMethod.SetTransactionName;
            const string    apiName   = nameof(SetTransactionName);

            void work()
            {
                InternalApi.SetTransactionName(category, name);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #26
0
        public static void NoticeError(string message, IDictionary <string, object>?customAttributes, bool isExpected)
        {
            const ApiMethod apiMetric = ApiMethod.NoticeError;
            const string    apiName   = nameof(NoticeError);

            void work()
            {
                InternalApi.NoticeError(message, customAttributes, isExpected);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #27
0
        public static void NoticeError(Exception exception)
        {
            const ApiMethod apiMetric = ApiMethod.NoticeError;
            const string    apiName   = nameof(NoticeError);

            void work()
            {
                InternalApi.NoticeError(exception);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #28
0
        public static void NoticeError(Exception exception, IDictionary <string, object>?customAttributes)
        {
            const ApiMethod apiMetric = ApiMethod.NoticeError;
            const string    apiName   = nameof(NoticeError);

            void work()
            {
                InternalApi.NoticeError(exception, customAttributes);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #29
0
        public static void IncrementCounter(string name)
        {
            const ApiMethod apiMetric = ApiMethod.IncrementCounter;
            const string    apiName   = nameof(IncrementCounter);

            void work()
            {
                InternalApi.IncrementCounter(name);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #30
0
        public static void RecordResponseTimeMetric(string name, long millis)
        {
            const ApiMethod apiMetric = ApiMethod.RecordResponseTimeMetric;
            const string    apiName   = nameof(RecordResponseTimeMetric);

            void work()
            {
                InternalApi.RecordResponseTimeMetric(name, millis);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #31
0
        public static void AddCustomParameter(string key, string value)
        {
            const ApiMethod apiMetric = ApiMethod.AddCustomParameter;
            const string    apiName   = nameof(AddCustomParameter);

            void work()
            {
                InternalApi.AddCustomParameter(key, value);
            }

            TryInvoke(work, apiName, apiMetric);
        }
예제 #32
0
        public void Http_method_is_respected(string httpMethod)
        {
            var method = new ApiMethod(
                "func", "/func", new HttpMethod(httpMethod), new ApiMethodParam[0],
                typeof(void), false, false);
            var sb        = new IndentedStringBuilder();
            var generator = createGenerator(method, sb);

            generator.WriteBody(false, false);

            TextAssert.ContainsLine($"const method = '{httpMethod}';", sb.ToString());
        }
예제 #33
0
        public void TestExecute()
        {
            WebRequestFactory.Current = new TestWebRequestFactory();
            LiveConnectClient connectClient = new LiveConnectClient(new LiveConnectSession());
            Uri       requestUri            = new Uri("http://foo.com");
            ApiMethod apiMethod             = ApiMethod.Copy;
            string    body = string.Empty;
            SynchronizationContextWrapper syncContextWrapper = SynchronizationContextWrapper.Current;

            var apiOperation =
                new ApiOperation(connectClient, requestUri, apiMethod, body, syncContextWrapper);
        }
예제 #34
0
        public bool TryGetXml(INN inn, ApiMethod method, out XmlDocument document)
        {
            document = new XmlDocument();
            var path = $"{cacheFolder}/{inn}.{method}";

            if (!File.Exists(path))
            {
                return(false);
            }
            document.Load(path);
            return(true);
        }  //TODO cache fluency
예제 #35
0
 public async Task <HttpResponse> Request(string uri, ApiMethod method,
                                          IDictionary <string, string> queryParams, string data, bool isFile)
 {
     if (!String.IsNullOrEmpty(data) && isFile)
     {
         using (FileStream fileStream = File.Open(data, FileMode.Open, FileAccess.Read))
         {
             var contentType = "application/" + Path.GetExtension(data).Substring(1);
             return(await Request(uri, method, queryParams, null, fileStream, contentType));
         }
     }
     return(await Request(uri, method, queryParams, data, null, null));
 }
예제 #36
0
        public IEnumerable<IArtist> GetArtists(string user, int? page = null, int? limit = null)
        {
            IApiMethod method = new ApiMethod("library.getArtists");
            method.AddParameter("api_key", this.Session.ApiKey);
            method.AddParameter("user", user);

            if(page.HasValue)
                method.AddParameter("page", page.Value.ToString());

            if(limit.HasValue)
                method.AddParameter("limit", limit.Value.ToString());

            var response = method.Execute();

            var artists = (JArray)response["artists"]["artist"];

            foreach (var artist in artists)
            {
                yield return new Artist { Name = artist.Value<string>("name") };
            }
        }
        internal Uri GetResourceUri(string path, ApiMethod method)
        {
            try
            {
                if ((path.StartsWith("https://", StringComparison.OrdinalIgnoreCase) &&
                   !path.StartsWith(this.ApiEndpoint, StringComparison.OrdinalIgnoreCase)) ||
                    path.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                {
                    return new Uri(path, UriKind.Absolute);
                }

                StringBuilder sb;
                if (path.StartsWith(this.ApiEndpoint, StringComparison.OrdinalIgnoreCase))
                {
                    sb = new StringBuilder(path);
                }
                else
                {
                    sb = new StringBuilder(this.ApiEndpoint);
                    sb = sb.AppendUrlPath(path);
                }

                var resourceUrl = new Uri(sb.ToString(), UriKind.Absolute);
                sb.Append(string.IsNullOrEmpty(resourceUrl.Query) ? "?" : "&");

                if (method != ApiMethod.Download)
                {
                    sb.AppendQueryParam(QueryParameters.SuppressResponseCodes, "true");
                    sb.Append("&").AppendQueryParam(QueryParameters.SuppressRedirects, "true");
                }

                return new Uri(sb.ToString(), UriKind.Absolute);
            }
            catch (FormatException)
            {
                throw new ArgumentException(
                    String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path"),
                    "path");
            }
        }
예제 #38
0
        /// <summary>
        /// Método utilizado para parsear la respuesta JSon de la api a un objeto del dominio del wrapper
        /// </summary>
        /// <param name="result">respuesta en formato JSon de la API</param>
        /// <param name="apiMethod">Enumerado que representa el método en cuestión</param>
        /// <returns></returns>
        private object ConvertResultToObject(string result, ApiMethod apiMethod)
        {
            object objectResult = null;

            switch (apiMethod)
            {
                case ApiMethod.GetAccountBalance:
                    {
                        //{"opstat": "ok","response": {"credits": "1003.60"}}
                        object resultJson = JsonConvert.DeserializeObject(result);
                        JObject responseJson = (JObject)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;
                        string creditsStr = responseJson.Property("credits").Value.ToString();
                        creditsStr = creditsStr.Replace("\"", "");
                        objectResult = Convert.ToSingle(creditsStr);

                        break;
                    }
                case ApiMethod.GetMyJobs:
                    {
                        //{"opstat":"ok","response":[{
                        //                          "job_id": "77777",
                        //                          "slug": "adfadfdsfaf.",
                        //                          "body_src": "Un texto",
                        //                          "lc_src": "en",
                        //                          "lc_tgt": "ja",
                        //                          "unit_count": "2",
                        //                          "tier": "machine",
                        //                          "credits": "0.80",
                        //                          "status": "available",
                        //                          "eta": "",
                        //                          "ctime": 1315423968,
                        //                          "callback_url": "",
                        //                          "auto_approve": "0",
                        //                          "custom_data": ""
                        //                          },{
                        //                              //otro job
                        //                          }]}

                        object resultJson = JsonConvert.DeserializeObject(result);
                        //JObject responseJson = (JObject)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;
                        JArray array = (JArray)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;

                        List<Job> jobsList = new List<Job>();
                        Job jobClient = null;
                        foreach (JObject job in array)
                        {
                            //NO se muestra un job con este estado!!! (17-3-2012). Razón: una vex z que se ordena un trabajo con tier = ultra,
                            //La API devuelve doble dicho trabajo, la copia vuelve con tier = ultra_proofread y no nos interesa motrar esto.
                            string tier = job.Property("tier").Value.ToString().Replace("\"", "");
                            if (tier == Properties.Resources.TIER_ULTRA_PROOFREAD)
                                continue;

                            jobClient = new Job();
                            jobClient.Job_Id = job.Property("job_id").Value.ToString().Replace("\"", "");
                            jobClient.Slug = job.Property("slug").Value.ToString().Replace("\"", "");
                            jobClient.Body_src = job.Property("body_src").Value.ToString().Replace("\"", "");
                            jobClient.Lc_src = job.Property("lc_src").Value.ToString().Replace("\"", "");
                            jobClient.Lc_tgt = job.Property("lc_tgt").Value.ToString().Replace("\"", "");
                            jobClient.Unit_count = Convert.ToInt32(job.Property("unit_count").Value.ToString().Replace("\"", ""));
                            jobClient.Tier = job.Property("tier").Value.ToString().Replace("\"", "");
                            string credits_str = job.Property("credits").Value.ToString().Replace("\"", "");
                            jobClient.Credits = Convert.ToSingle(credits_str);
                            //jobClient.Credits = (float)Convert.ToDouble(credits_str);
                            //jobClient.Credits = float.Parse(credits_str, System.Globalization.NumberStyles.Currency);
                            //jobClient.Credits = float.Parse(credits_str, System.Globalization.NumberStyles.Currency);
                            jobClient.Status = job.Property("status").Value.ToString().Replace("\"", "");
                            jobClient.Eta = job.Property("eta").Value.ToString().Replace("\"", "");

                            //TODO: Buscar mecasimo para convertir a una fecha váldia!!!
                            string ctimeStr = job.Property("ctime").Value.ToString().Replace("\"", "");
                            jobClient.Ctime = Utils.ConvertFromUnixTimeStamp(Convert.ToDouble(ctimeStr));
                            //jobClient.Custom_data = job.Property("custom_data").Value.ToString();

                            if (job.Property("captcha_url") != null && job.Property("captcha_url").Value != null)
                                jobClient.CaptchaURL = job.Property("captcha_url").Value.ToString().Replace("\"", "");

                            jobsList.Add(jobClient);
                        }

                        objectResult = jobsList;
                        break;
                    }
                case ApiMethod.GetLanguages:
                    {
                        //{"opstat":"ok","response":[{
                        //                          "language": "English",
                        //                          "localized_name": "English",
                        //                          "lc": "en",
                        //                          "unit_type": "word"
                        //                          },{
                        //                              //otro language
                        //                          }]}

                        object resultJson = JsonConvert.DeserializeObject(result);
                        //JObject responseJson = (JObject)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;
                        JArray array = (JArray)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;

                        List<Language> languageList = new List<Language>();
                        Language language = null;
                        foreach (JObject job in array)
                        {
                            language = new Language();
                            language.LanguageName = job.Property("language").Value.ToString().Replace("\"", "");
                            language.LocalizedName = job.Property("localized_name").Value.ToString().Replace("\"", "");
                            language.Lc = job.Property("lc").Value.ToString().Replace("\"", "");
                            language.UnitType = job.Property("unit_type").Value.ToString().Replace("\"", "");
                            languageList.Add(language);
                        }

                        languageList.Insert(0, new Language() { LanguageName = Properties.Resources.NotSpecified, Lc = string.Empty });
                        objectResult = languageList;
                        break;
                    }
                case ApiMethod.GetLanguagePairs:
                    {
                        //{"opstat":"ok","response":[{
                        //                          "lc_src": "de",
                        //                          "lc_tgt": "en",
                        //                          "tier": "machine",
                        //                          "unit_price": "0.0000"
                        //                          },{
                        //                              //otro language pair
                        //                          }]}

                        object resultJson = JsonConvert.DeserializeObject(result);
                        //JObject responseJson = (JObject)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;
                        JArray array = (JArray)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;

                        List<LanguagePair> languageList = new List<LanguagePair>();
                        LanguagePair languagePair = null;
                        foreach (JObject job in array)
                        {
                            languagePair = new LanguagePair();
                            languagePair.Lc_src = job.Property("lc_src").Value.ToString().Replace("\"", "");
                            languagePair.Lc_tgt = job.Property("lc_tgt").Value.ToString().Replace("\"", "");
                            languagePair.Tier = job.Property("tier").Value.ToString().Replace("\"", "");
                            string unitPrice = job.Property("unit_price").Value.ToString().Replace("\"", "");
                            languagePair.Unit_price = Convert.ToSingle(unitPrice);
                            languageList.Add(languagePair);
                        }

                        objectResult = languageList;
                        break;
                    }
                case ApiMethod.TranslateJob:
                    {
                        //                        {
                        //  "opstat": "ok",
                        //  "response": {
                        //    "jobs": [
                        //      {
                        //        "job1": {
                        //          "job_id": "15723",
                        //          "slug": "Un texto para traducir",
                        //          "body_src": "Un texto",
                        //          "lc_src": "en",
                        //          "lc_tgt": "es",
                        //          "unit_count": "2",
                        //          "tier": "ultra_pro",
                        //          "credits": "0.40",
                        //          "status": "available",
                        //          "eta": "",
                        //          "ctime": 1297743137,
                        //          "callback_url": "",
                        //          "auto_approve": "0",
                        //          "custom_data": "",
                        //          "body_tgt": "Un Texto",
                        //          "mt": 1
                        //        }
                        //      }
                        //    ]
                        //  }
                        //}

                        object resultJson = JsonConvert.DeserializeObject(result);
                        JObject resposeObject = (JObject)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;
                        JArray arrayJobs = (JArray)resposeObject.Property("jobs").Value;
                        JObject job = (JObject)((JObject)arrayJobs[0]).Property("job1").Value;

                        //JArray array = (JArray)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;

                        Job jobClient = null;

                        jobClient = new Job();
                        jobClient.Job_Id = job.Property("job_id").Value.ToString().Replace("\"", "");
                        jobClient.Slug = job.Property("slug").Value.ToString().Replace("\"", "");
                        jobClient.Body_src = job.Property("body_src").Value.ToString().Replace("\"", "");
                        jobClient.Lc_src = job.Property("lc_src").Value.ToString().Replace("\"", "");
                        jobClient.Lc_tgt = job.Property("lc_tgt").Value.ToString().Replace("\"", "");
                        jobClient.Unit_count = Convert.ToInt32(job.Property("unit_count").Value.ToString().Replace("\"", ""));
                        jobClient.Tier = job.Property("tier").Value.ToString().Replace("\"", "");
                        jobClient.Credits = Convert.ToSingle(job.Property("credits").Value.ToString().Replace("\"", ""));
                        jobClient.Status = job.Property("status").Value.ToString().Replace("\"", "");
                        jobClient.Eta = job.Property("eta").Value.ToString().Replace("\"", "");

                        //TODO: Buscar mecasimo para convertir a una fecha váldia!!!
                        string ctimeStr = job.Property("ctime").Value.ToString().Replace("\"", "");
                        jobClient.Ctime = Utils.ConvertFromUnixTimeStamp(Convert.ToDouble(ctimeStr));
                        //jobClient.Custom_data = job.Property("custom_data").Value.ToString();

                        objectResult = jobClient;
                        break;
                    }
                case ApiMethod.CancelJob:
                    {
                        //{"opstat": "ok","response": {}}
                        object resultJson = JsonConvert.DeserializeObject(result);
                        string responseJson = (string)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("opstat")).Value.ToString();
                        bool canceldOK = responseJson == "ok";
                        objectResult = canceldOK;

                        break;
                    }
                case ApiMethod.ViewJob:
                    {
                        //                        {
                        //  "opstat": "ok",
                        //  "response": {
                        //    "job": {
                        //      "job_id": "16673",
                        //      "slug": "aplicaci\\u00f3n",
                        //      "body_src": "Un cami\\u00f3n. Confronted with this situation, most IT professionals chose a middle ground, which forced information workers to make critical security decisions. If a document contained ActiveX controls or macros from an unknown source, users were asked whether they wanted to enable the ActiveX controls or the macros. Users were not allowed to access the document until they answered the question. Although this was not a perfect solution, it did provide a mechanism for mitigating security threats without intruding too much on productivity. The main problem was that most users, when confronted with a security warning, dismissed the warning so they could access the document and get their work done. This was acceptable for low-risk internal documents that did not likely contain malicious content, but it was not acceptable for high-risk external documents that passed through the Internet and could contain malicious content. Unfortunately, users did not usually distinguish between high-risk and low-risk files and treated both files the same way — that is, they accepted the risk and enabled the ActiveX controls and macros.",
                        //      "lc_src": "en",
                        //      "lc_tgt": "es",
                        //      "unit_count": "8",
                        //      "tier": "pro",
                        //      "credits": "0.80",
                        //      "status": "approved",
                        //      "eta": "",
                        //      "ctime": 1298861619,
                        //      "callback_url": "",
                        //      "auto_approve": "0",
                        //      "custom_data": "",
                        //      "body_tgt": "Una aplicaci\\u00f3n. Confronted with this situation, most IT professionals chose a middle ground, which forced information workers to make critical security decisions. If a document contained ActiveX controls or macros from an unknown source, users were asked whether they wanted to enable the ActiveX controls or the macros. Users were not allowed to access the document until they answered the question. Although this was not a perfect solution, it did provide a mechanism for mitigating security threats without intruding too much on productivity. The main problem was that most users, when confronted with a security warning, dismissed the warning so they could access the document and get their work done. This was acceptable for low-risk internal documents that did not likely contain malicious content, but it was not acceptable for high-risk external documents that passed through the Internet and could contain malicious content. Unfortunately, users did not usually distinguish between high-risk and low-risk files and treated both files the same way — that is, they accepted the risk and enabled the ActiveX controls and macros. Confronted with this situation, most IT professionals chose a middle ground, which forced information workers to make critical security decisions. If a document contained ActiveX controls or macros from an unknown source, users were asked whether they wanted to enable the ActiveX controls or the macros. Users were not allowed to access the document until they answered the question. Although this was not a perfect solution, it did provide a mechanism for mitigating security threats without intruding too much on productivity. The main problem was that most users, when confronted with a security warning, dismissed the warning so they could access the document and get their work done. This was acceptable for low-risk internal documents that did not likely contain malicious content, but it was not acceptable for high-risk external documents that passed through the Internet and could contain malicious content. Unfortunately, users did not usually distinguish between high-risk and low-risk files and treated both files the same way — that is, they accepted the risk and enabled the ActiveX controls and macros."
                        //    }
                        //  }
                        //}

                        object resultJson = JsonConvert.DeserializeObject(result);
                        JObject resposeObject = (JObject)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;
                        JObject job = (JObject)((JObject)resposeObject).Property("job").Value;

                        Job jobClient = null;

                        jobClient = new Job();
                        jobClient.Job_Id = job.Property("job_id").Value.ToString().Replace("\"", "");
                        jobClient.Slug = job.Property("slug").Value.ToString().Replace("\"", "");
                        jobClient.Body_src = job.Property("body_src").Value.ToString().Replace("\"", "");
                        if (job.Property("body_tgt") != null && job.Property("body_tgt").Value != null)
                            jobClient.Body_tgt = job.Property("body_tgt").Value.ToString().Replace("\"", "");
                        jobClient.Lc_src = job.Property("lc_src").Value.ToString().Replace("\"", "");
                        jobClient.Lc_tgt = job.Property("lc_tgt").Value.ToString().Replace("\"", "");
                        jobClient.Unit_count = Convert.ToInt32(job.Property("unit_count").Value.ToString().Replace("\"", ""));
                        jobClient.Tier = job.Property("tier").Value.ToString().Replace("\"", "");
                        jobClient.Credits = Convert.ToSingle(job.Property("credits").Value.ToString().Replace("\"", ""));
                        jobClient.Status = job.Property("status").Value.ToString().Replace("\"", "");
                        jobClient.Eta = job.Property("eta").Value.ToString().Replace("\"", "");
                        if (job.Property("captcha_url") != null && job.Property("captcha_url").Value != null)
                            jobClient.CaptchaURL = job.Property("captcha_url").Value.ToString().Replace("\"", "");

                        //TODO: Buscar mecasimo para convertir a una fecha váldia!!!
                        string ctimeStr = job.Property("ctime").Value.ToString().Replace("\"", "");
                        jobClient.Ctime = Utils.ConvertFromUnixTimeStamp(Convert.ToDouble(ctimeStr));
                        //jobClient.Custom_data = job.Property("custom_data").Value.ToString();

                        objectResult = jobClient;
                        break;
                    }
                case ApiMethod.ReviewJob:
                    {
                        // {
                        //  "opstat": "ok",
                        //  "response": {
                        //    "job_id": "16613",
                        //    "body_src": " aplicaci\\u00f3n. Developing mobile applications used to be an arcane activity pursued by highly specialized developers, but no more. The surge in popularity of Android devices, BlackBerries, and iPhones has application development professionals gearing up to incorporate mobile development into mainstream development processes. The first step in taking mobile development mainstream is defining your strategy. Learn from your peers in consumer product strategy by applying Forrester's POST method to your mobile development efforts. Begin by understanding what types of mobile users you need to support. Next, determine your objectives, and then build a strategy based on your desired offering and level of corporate commitment to mobile. Once you have completed these three steps, then — and only then — should you choose from among the six mobile development styles at your disposal and the vendors that offer mobile platforms and tools that can aid your efforts.",
                        //    "imagePreview": "~/_wpresources/MiguelRa.spGengo/spGengo/asp_mock/preview/jobPreview16613.jpg"
                        //  }
                        //}

                        object resultJson = JsonConvert.DeserializeObject(result);
                        JObject resposeObject = (JObject)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("response")).Value;
                        //JObject job = (JObject)((JObject)resposeObject).Property("job").Value;

                        Job jobClient = null;

                        jobClient = new Job();
                        jobClient.Job_Id = resposeObject.Property("job_id").Value.ToString().Replace("\"", "");

                        jobClient.Body_src = resposeObject.Property("body_src").Value.ToString().Replace("\"", "");
                        jobClient.PreviewImage = resposeObject.Property("imagePreview").Value.ToString().Replace("\"", "");

                        if (resposeObject.Property("captcha_url") != null && resposeObject.Property("captcha_url").Value != null)
                            jobClient.CaptchaURL = resposeObject.Property("captcha_url").Value.ToString().Replace("\"", "");

                        objectResult = jobClient;

                        break;
                    }
                case ApiMethod.ApproveJob:
                    {
                        //{"opstat": "ok","response": {}}
                        object resultJson = JsonConvert.DeserializeObject(result);
                        string responseJson = (string)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("opstat")).Value.ToString();
                        bool canceldOK = responseJson == "ok";
                        objectResult = canceldOK;

                        break;
                    }
                case ApiMethod.CorrectJob:
                    {
                        //{"opstat": "ok","response": {}}
                        object resultJson = JsonConvert.DeserializeObject(result);
                        string responseJson = (string)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("opstat")).Value.ToString();
                        bool canceldOK = responseJson == "ok";
                        objectResult = canceldOK;

                        break;
                    }
                case ApiMethod.RejectJob:
                    {
                        //{"opstat": "ok","response": {}}
                        object resultJson = JsonConvert.DeserializeObject(result);
                        string responseJson = (string)(((Newtonsoft.Json.Linq.JObject)resultJson).Property("opstat")).Value.ToString();
                        bool canceldOK = responseJson == "ok";
                        objectResult = canceldOK;

                        break;
                    }
                default:
                    break;
            }

            return objectResult;
        }
예제 #39
0
파일: VkApi.cs 프로젝트: ichi404gh/yavaw
 public async Task<JToken> CallApiMethod(ApiMethod method, IEnumerable<KeyValuePair<string, string>> parameters)
 {
     return await CallApiMethod(method.ToString().Replace('_', '.'), parameters);
 }
예제 #40
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="route"></param>
 /// <param name="method"></param>
 public ApiAttribute(string route, ApiMethod method)
 {
     this._route = route;
     this._method = method;
 }
 private Task<LiveOperationResult> Api(string path, ApiMethod method, string body, CancellationToken ct)
 {
     ApiOperation op = this.GetApiOperation(path, method, body);
     return this.ExecuteApiOperation(op, ct);
 }
        private Task<LiveOperationResult> MoveOrCopy(string path, string destination, ApiMethod method, CancellationToken ct)
        {
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }

            if (string.IsNullOrWhiteSpace(destination))
            {
                throw new ArgumentException("destination");
            }

            string body = string.Format(CultureInfo.InvariantCulture, ApiOperation.MoveRequestBodyTemplate, destination);

            return this.Api(path, method, body, ct);
        }
예제 #43
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="route"></param>
 /// <param name="method"></param>
 /// <param name="isSecure"></param>
 public ApiAttribute(string route, ApiMethod method, bool isSecure)
 {
     this._route = route;
     this._method = method;
     this._isSecure = isSecure;
 }
        private ApiOperation GetApiOperation(string path, ApiMethod method, string body)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("path");
            }

            if (IsAbsolutePath(path))
            {
                throw new ArgumentException(
                    String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("RelativeUrlRequired"), "path"),
                    "path");
            }

            Uri apiUri = this.GetResourceUri(path, method);

            if (this.Session == null)
            {
                throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn"));
            }

            ApiOperation operation = null;

            switch (method)
            {
                case ApiMethod.Get:
                case ApiMethod.Delete:
                    operation = new ApiOperation(this, apiUri, method, null, null);
                    break;

                case ApiMethod.Post:
                case ApiMethod.Put:
                case ApiMethod.Copy:
                case ApiMethod.Move:
                    if (body == null)
                    {
                        throw new ArgumentNullException("body");
                    }

                    if (string.IsNullOrWhiteSpace(body))
                    {
                        throw new ArgumentException("body");
                    }

                    operation = new ApiWriteOperation(this, apiUri, method, body, null);
                    break;

                default:
                    Debug.Assert(false, "method not suppported.");
                    break;
            }

            return operation;
        }
예제 #45
0
        /// <summary>
        /// Parses a string response body and creates a LiveOperationResult object from it.
        /// </summary>
        internal static LiveOperationResult CreateOperationResultFrom(string responseBody, ApiMethod method)
        {
            if (string.IsNullOrEmpty(responseBody))
            {
                if (method != ApiMethod.Delete)
                {
                    var error = new LiveConnectException(
                        ApiClientErrorCode, 
                        ResourceHelper.GetString("NoResponseData"));
                    return new LiveOperationResult(error, false);
                }

                return new LiveOperationResult(null, responseBody);
            }

            return LiveOperationResult.FromResponse(responseBody);
        }