Beispiel #1
0
        /// <summary>
        /// <para>
        /// Get a set of temporary security credentials representing your account.
        /// </para>
        /// <para>
        /// An extra ACL string can be set in the request, which specify permissions for the returning credentials.
        /// </para>
        /// </summary>
        /// <param name="request"> The GetSessionTokenRequest object that specifies all the parameters of this
        ///     operation. </param>
        public GetSessionTokenResponse GetSessionToken(GetSessionTokenRequest request)
        {
            CheckNotNull(request, "request should not be null.");

            InternalRequest internalRequest = this.CreateInternalRequest(
                request, BceConstants.HttpMethod.Post, new string[] { UrlPrefix, "sessionToken" });

            if (request.DurationSeconds.HasValue)
            {
                internalRequest.Parameters["durationSeconds"] = request.DurationSeconds.ToString();
            }
            if (request.AccessControlList != null)
            {
                FillRequestBodyForJson(internalRequest, request.AccessControlList);
            }

            return(internalRequest.Config.RetryPolicy.Execute(attempt =>
            {
                var httpWebResponse = this.httpClient.Execute(internalRequest);
                using (httpWebResponse)
                {
                    return ToObject <GetSessionTokenResponse>(httpWebResponse);
                }
            }));
        }
Beispiel #2
0
 /// <summary>
 /// Converts the json string into UTF-8 string and set it as the content of internalRequest, which will be
 /// used as the http request body. Content-Length and Content-Type ard set accordingly.
 /// </summary>
 /// <param name="internalRequest">The request used to build the http request</param>
 /// <param name="json">The json string to be set as content</param>
 protected void FillRequestBodyForJson(InternalRequest internalRequest, string json)
 {
     byte[] jsonUTF8 = Encoding.UTF8.GetBytes(json);
     internalRequest.Headers[BceConstants.HttpHeaders.ContentLength] = jsonUTF8.Length.ToString();
     internalRequest.Headers[BceConstants.HttpHeaders.ContentType]   = "application/json; charset=utf-8";
     internalRequest.Content = new MemoryStream(jsonUTF8);
 }
 public override Task <InternalReply> SayHello(InternalRequest request, ServerCallContext context)
 {
     _logger.LogInformation($"Sending hello to {request.Name}");
     return(Task.FromResult(new InternalReply {
         Message = "Hello " + request.Name
     }));
 }
Beispiel #4
0
    //运行内部控制命令
    private void RunInternal(HttpTask task)
    {
        InternalRequest request = task.request as InternalRequest;

        switch (request.CommondType)
        {
        case InternalRequestType.RESET:
            ResetRequet();
            break;

        case InternalRequestType.SHUT_DOWN:
            Loop = false;
            break;

        case InternalRequestType.RESUME:
            break;

        case InternalRequestType.HOLDING_ON:
            break;

        default:
            //Do nothing...
            break;
        }
    }
        public override void StartOpen()
        {
            if (requestSent)
            {
                throw new InvalidOperationException("Open already called! You can't reuse this WebSocket instance!");
            }

            if (this.Parent.Extensions != null)
            {
                try
                {
                    for (int i = 0; i < this.Parent.Extensions.Length; ++i)
                    {
                        var ext = this.Parent.Extensions[i];
                        if (ext != null)
                        {
                            ext.AddNegotiation(InternalRequest);
                        }
                    }
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("OverHTTP1", "Open", ex, this.Parent.Context);
                }
            }

            InternalRequest.Send();
            requestSent = true;
            this.State  = WebSocketStates.Connecting;
        }
        public async Task <Http.IHttpResponse> GetResponseAsync()
        {
            CreateRequest();
            var response = await InternalRequest.GetResponseAsync();

            return(new WrappedHttpWebResponse((HttpWebResponse)response));
        }
Beispiel #7
0
 public void Open()
 {
     if (!requestSent && InternalRequest != null)
     {
         InternalRequest.Send();
         requestSent = true;
     }
 }
Beispiel #8
0
        /// <summary>
        /// Start the opening process.
        /// </summary>
        public void Open()
        {
            if (requestSent || InternalRequest == null)
                return;

            InternalRequest.Send();
            requestSent = true;
        }
Beispiel #9
0
        private InternalAnswer ProcessOrderRequest(InternalRequest request)
        {
            var service   = IoC.Resolve <IRentalService>();
            var equipment = JsonConvert.DeserializeObject <List <EquipmentRental> >(request.Payload.ToString());
            var result    = service.RentEquipment(request.UserId, equipment);

            return(new InternalAnswer()
            {
                RequestType = request.Type,
                Payload = result
            });
        }
Beispiel #10
0
        private InternalAnswer ProcessRequest(InternalRequest request)
        {
            switch (request.Type)
            {
            case InternalRequestType.GetEquipmentList:
                return(ProcessEquipmentListRequest());

            case InternalRequestType.OrderRequest:
                return(ProcessOrderRequest(request));

            default:
                throw new Exception("Unknown request");
            }
        }
Beispiel #11
0
        private static long GetContentLengthFromInternalRequest(InternalRequest request)
        {
            string contentLengthString;

            if (request.Headers.TryGetValue(BceConstants.HttpHeaders.ContentLength, out contentLengthString))
            {
                long contentLength;
                if (long.TryParse(contentLengthString, out contentLength))
                {
                    return(contentLength);
                }
            }
            return(-1);
        }
        /// <summary>
        /// 开始打开web过程。
        /// </summary>
        public void Open()
        {
#if (!UNITY_WEBGL || UNITY_EDITOR)
            if (requestSent)
            {
                //     GameStart.OpenCommonConfirm("请求失败", "打开已调用!不能重用此WebSocket实例", null, null);
                throw new InvalidOperationException("打开已调用!不能重用此WebSocket实例!");
            }

            if (this.Extensions != null)
            {
                try
                {
                    for (int i = 0; i < this.Extensions.Length; ++i)
                    {
                        var ext = this.Extensions[i];
                        if (ext != null)
                        {
                            ext.AddNegotiation(InternalRequest);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //GameStart.OpenCommonConfirm("连接到web服务器捕获异常", ex.Message, () => { });
                    HTTPManager.Logger.Exception("WebSocket", "Open", ex);
                }
            }

            InternalRequest.Send();
            requestSent = true;
            this.State  = WebSocketStates.Connecting;
#else
            try
            {
                ImplementationId = WS_Create(this.Uri.OriginalString, this.Protocol, OnOpenCallback, OnTextCallback, OnBinaryCallback, OnErrorCallback, OnCloseCallback);
                WebSockets.Add(ImplementationId, this);
            }
            catch (Exception ex)
            {
                Facade.Instance.SendNotification(ProConst.Msg_ShowHintInfo, new MsgModel("连接到web服务器捕获异常:" + ex, Color.red));
                HTTPManager.Logger.Exception("WebSocket", "Open", ex);
            }
#endif
        }
Beispiel #13
0
        protected InternalRequest CreateInternalRequest(
            BceClientConfiguration config, string httpMethod, string[] pathComponents)
        {
            var internalRequest = new InternalRequest();

            internalRequest.Config = this.config.Merge(config);
            internalRequest.Uri    = new Uri(
                HttpUtils.AppendUri(this.ComputeEndpoint(internalRequest.Config), pathComponents));
            internalRequest.HttpMethod = httpMethod;
            var timestamp = internalRequest.Config.SignOptions.Timestamp;

            if (timestamp == DateTime.MinValue)
            {
                timestamp = DateTime.Now;
            }
            internalRequest.Headers[BceConstants.HttpHeaders.BceDate] = DateUtils.FormatAlternateIso8601Date(timestamp);
            internalRequest.Headers[BceConstants.HttpHeaders.Host]    = HttpUtils.GenerateHostHeader(internalRequest.Uri);
            return(internalRequest);
        }
        /// <summary>
        /// Start the opening process.
        /// </summary>
        public void Open()
        {
#if !UNITY_WEBGL || UNITY_EDITOR
            if (requestSent)
            {
                throw new InvalidOperationException("Open already called! You can't reuse this WebSocket instance!");
            }

            if (this.Extensions != null)
            {
                try
                {
                    for (int i = 0; i < this.Extensions.Length; ++i)
                    {
                        var ext = this.Extensions[i];
                        if (ext != null)
                        {
                            ext.AddNegotiation(InternalRequest);
                        }
                    }
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "Open", ex, this.Context);
                }
            }

            InternalRequest.Send();
            requestSent = true;
            this.State  = WebSocketStates.Connecting;
#else
            try
            {
                ImplementationId = WS_Create(this.Uri.OriginalString, this.Protocol, OnOpenCallback, OnTextCallback, OnBinaryCallback, OnErrorCallback, OnCloseCallback);
                WebSockets.Add(ImplementationId, this);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("WebSocket", "Open", ex, this.Context);
            }
#endif
        }
Beispiel #15
0
        /// <summary>
        /// Creates HttpClient method object based on the specified request and
        /// populates any parameters, headers, etc. from the internal request.
        /// </summary>
        /// <param name="request"> The request to convert to an HttpClient method object. </param>
        /// <returns> The converted HttpClient method object with any parameters, headers, etc. from the original request set. </returns>
        private static HttpWebRequest CreateHttpWebRequest(InternalRequest request)
        {
            BceClientConfiguration config      = request.Config;
            IBceCredentials        credentials = config.Credentials;
            string uri           = request.Uri.AbsoluteUri;
            string encodedParams = HttpUtils.GetCanonicalQueryString(request.Parameters, false);

            if (encodedParams.Length > 0)
            {
                uri += "?" + encodedParams;
            }
            var httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;

            httpWebRequest.Timeout          = config.TimeoutInMillis ?? BceClientConfiguration.DefaultTimeoutInMillis;
            httpWebRequest.ReadWriteTimeout =
                config.ReadWriteTimeoutInMillis ?? BceClientConfiguration.DefaultReadWriteTimeoutInMillis;
            if (request.Range != null && request.Range.Length == 2)
            {
                AddRange(httpWebRequest, request.Range);
            }
            if (!string.IsNullOrEmpty(config.ProxyHost) && config.ProxyPort.GetValueOrDefault() > 0)
            {
                WebProxy proxy = new WebProxy(config.ProxyHost, config.ProxyPort.GetValueOrDefault());
                if (config.ProxyCredentials != null)
                {
                    proxy.Credentials = config.ProxyCredentials;
                }
                httpWebRequest.Proxy = proxy;
            }
            if (config.UseNagleAlgorithm != null)
            {
                httpWebRequest.ServicePoint.UseNagleAlgorithm = (bool)config.UseNagleAlgorithm;
            }
            httpWebRequest.ServicePoint.MaxIdleTime =
                config.MaxIdleTimeInMillis ?? BceClientConfiguration.DefaultMaxIdleTimeInMillis;
            httpWebRequest.ServicePoint.ConnectionLimit =
                config.ConnectionLimit ?? BceClientConfiguration.DefaultConnectionLimit;
            httpWebRequest.ServicePoint.Expect100Continue = request.Expect100Continue;
            httpWebRequest.Method = request.HttpMethod;
            return(httpWebRequest);
        }
Beispiel #16
0
        /// <summary>
        /// Start the opening process.
        /// </summary>
        public void Open()
        {
#if (!UNITY_WEBGL || UNITY_EDITOR)
            if (requestSent || InternalRequest == null)
            {
                return;
            }

            if (this.Extensions != null)
            {
                try
                {
                    for (int i = 0; i < this.Extensions.Length; ++i)
                    {
                        var ext = this.Extensions[i];
                        if (ext != null)
                        {
                            ext.AddNegotiation(InternalRequest);
                        }
                    }
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "Open", ex);
                }
            }

            InternalRequest.Send();
            requestSent = true;
#else
            try
            {
                ImplementationId = WS_Create(this.Uri.ToString(), this.Protocol, OnOpenCallback, OnTextCallback, OnBinaryCallback, OnErrorCallback, OnCloseCallback);
                WebSockets.Add(ImplementationId, this);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("WebSocket", "Open", ex);
            }
#endif
        }
Beispiel #17
0
 private static void PopulateRequestHeaders(InternalRequest request, HttpWebRequest httpWebRequest)
 {
     httpWebRequest.UserAgent = request.Config.UserAgent;
     foreach (KeyValuePair <string, string> entry in request.Headers)
     {
         string key = entry.Key;
         if (key.Equals(BceConstants.HttpHeaders.ContentLength, StringComparison.CurrentCultureIgnoreCase))
         {
             httpWebRequest.ContentLength = Convert.ToInt64(entry.Value);
         }
         else if (key.Equals(BceConstants.HttpHeaders.ContentType, StringComparison.CurrentCultureIgnoreCase))
         {
             httpWebRequest.ContentType = entry.Value;
         }
         // can't direct set Host in httpwebrequest
         else if (!key.Equals(BceConstants.HttpHeaders.Host, StringComparison.CurrentCultureIgnoreCase))
         {
             httpWebRequest.Headers[key] = entry.Value;
         }
     }
 }
        private InternalAnswer SendRequest(InternalRequest request)
        {
            if (!PipesHelper.DoesNamedPipeExist(Config.CommunicationServiceName))
            {
                throw new Exception("Unable to connect to the internal logic server");
            }

            using (var client = new NamedPipeClientStream(Config.CommunicationServiceName))
            {
                client.Connect(5000);
                if (client.IsConnected)
                {
                    client.ReadMode = PipeTransmissionMode.Message;

                    string message = JsonConvert.SerializeObject(request);
                    byte[] msgBuff = Encoding.ASCII.GetBytes(message);

                    client.Write(msgBuff, 0, msgBuff.Length);
                    if (request.HasAnswer)
                    {
                        int           count = 0;
                        byte[]        buff  = new byte[Config.CommunicatorBufferSize];
                        StringBuilder mb    = new StringBuilder();

                        do
                        {
                            count = client.Read(buff, 0, Config.CommunicatorBufferSize);
                            mb.Append(Encoding.ASCII.GetString(buff, 0, count));
                        } while (!client.IsMessageComplete);

                        return(JsonConvert.DeserializeObject <InternalAnswer>(mb.ToString()));
                    }
                }

                return(null);
            }
        }
        public async Task <TResponse> GetAsync <TResponse>(string key,
                                                           Func <CancellationToken, Task <TResponse> > getMethod,
                                                           CancellationToken cancellationToken,
                                                           Func <TResponse, TimeSpan?> cacheTTL = null)
            where TResponse : class
        {
            var itr = new InternalRequest {
                Token = cancellationToken
            };

            List <InternalRequest> request = null;

            lock (requests)
            {
                if (!requests.TryGetValue(key, out request))
                {
                    request = new List <InternalRequest>();
                    requests.Add(key, request);
                }
                lock (request)
                {
                    if (request.Count != 0)
                    {
                        var ts = new TaskCompletionSource <TResponse>();

                        itr.TaskSource = ts;
                    }
                    request.Add(itr);
                }
            }

            TResponse r = null;

            if (itr.TaskSource == null)
            {
                r = await getMethod(cancellationToken);

                lock (requests)
                {
                    lock (request)
                    {
                        foreach (var rq in request)
                        {
                            if (rq.TaskSource == null)
                            {
                                continue;
                            }
                            if (rq.Token.IsCancellationRequested)
                            {
                                rq.AsTaskSource <TResponse>().TrySetCanceled();
                            }
                            else
                            {
                                rq.AsTaskSource <TResponse>().TrySetResult(r);
                            }
                        }
                        request.Clear();
                    }

                    requests.Remove(key);
                }
            }
            else
            {
                r = await itr.AsTaskSource <TResponse>().Task;
            }

            return(r);
        }
Beispiel #20
0
        /// <summary>
        /// Sign the given request. Modifies the passed-in request to apply the signature.
        /// </summary>
        /// <param name="request">     the request to sign. </param>
        public string Sign(InternalRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request should NOT be null.");
            }

            var config = request.Config;

            if (config == null)
            {
                throw new ArgumentNullException("request.Config should NOT be null.");
            }

            var credentials = config.Credentials;

            if (credentials == null)
            {
                throw new ArgumentNullException("request.Config.Credentials should NOT be null.");
            }

            var options = request.Config.SignOptions;

            if (options == null)
            {
                options = new SignOptions();
            }

            string accessKeyId     = credentials.AccessKeyId;
            string secretAccessKey = credentials.SecretKey;

            var timestamp = options.Timestamp;

            if (timestamp == DateTime.MinValue)
            {
                timestamp = DateTime.Now;
            }

            string authString =
                BceAuthVersion + "/" + accessKeyId + "/"
                + DateUtils.FormatAlternateIso8601Date(timestamp) + "/" + options.ExpirationInSeconds;

            string signingKey = BceV1Signer.Sha256Hex(secretAccessKey, authString);
            // Formatting the URL with signing protocol.
            string canonicalURI = BceV1Signer.GetCanonicalURIPath(HttpUtility.UrlDecode(request.Uri.AbsolutePath));
            // Formatting the query string with signing protocol.
            string canonicalQueryString = HttpUtils.GetCanonicalQueryString(request.Parameters, true);
            // Sorted the headers should be signed from the request.
            SortedDictionary <string, string> headersToSign =
                BceV1Signer.GetHeadersToSign(request.Headers, options.HeadersToSign);
            // Formatting the headers from the request based on signing protocol.
            string canonicalHeader = BceV1Signer.GetCanonicalHeaders(headersToSign);
            string signedHeaders   = "";

            if (options.HeadersToSign != null)
            {
                signedHeaders = string.Join(";", headersToSign.Keys.ToArray()).Trim().ToLower();
            }

            string canonicalRequest =
                request.HttpMethod + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalHeader;

            // Signing the canonical request using key with sha-256 algorithm.
            string signature = BceV1Signer.Sha256Hex(signingKey, canonicalRequest);

            string authorizationHeader = authString + "/" + signedHeaders + "/" + signature;

            log.Debug(string.Format(
                          "CanonicalRequest:{0}\tAuthorization:{1}",
                          canonicalRequest.Replace("\n", "[\\n]"),
                          authorizationHeader));

            return(authorizationHeader);
        }
Beispiel #21
0
        /// <summary>
        /// Executes the request and returns the result.
        /// </summary>
        /// <param name="request">          The BCE request to send to the remote server </param>
        /// <exception cref="BaiduBce.BceClientException">  If any errors are encountered on the client while making the
        ///             request or handling the response. </exception>
        /// <exception cref="BaiduBce.BceServiceException"> If any errors occurred in BCE while processing the request. </exception>
        public HttpWebResponse Execute(InternalRequest request)
        {
            BceClientConfiguration config = request.Config;

            if (config.Credentials != null)
            {
                if (config.Credentials is IBceSessionCredentials)
                {
                    request.Headers[BceConstants.HttpHeaders.BceSecurityToken] =
                        (config.Credentials as IBceSessionCredentials).SessionToken;
                }
                request.Headers[BceConstants.HttpHeaders.Authorization] = config.Signer.Sign(request);
            }
            HttpWebRequest httpWebRequest = CreateHttpWebRequest(request);

            PopulateRequestHeaders(request, httpWebRequest);
            if (request.Content != null)
            {
                if (request.Content.CanSeek)
                {
                    request.Content.Position = request.StartPosition;
                }
                httpWebRequest.AllowWriteStreamBuffering = false;
                using (Stream requestStream = WebRequestExtension.GetRequestStreamWithTimeout(httpWebRequest))
                {
                    var  buffer         = new byte[(int)config.SocketBufferSizeInBytes];
                    int  bytesRead      = 0;
                    int  totalBytesRead = 0;
                    long contentLength  = GetContentLengthFromInternalRequest(request);
                    try
                    {
                        while ((bytesRead = request.Content.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            if (contentLength > 0 && (bytesRead + totalBytesRead) >= contentLength)
                            {
                                requestStream.Write(buffer, 0, (int)(contentLength - totalBytesRead));
                                break;
                            }
                            else
                            {
                                requestStream.Write(buffer, 0, bytesRead);
                                totalBytesRead += bytesRead;
                            }
                        }
                    }
                    catch (NotSupportedException e)
                    {
                        //a very strange phenomenon:
                        //if bos server is down, we will receive a NotSupportedException when execute requestStream.Write(...)
                        if (log.IsDebugEnabled)
                        {
                            log.Debug("error when put data.", e);
                        }
                    }
                }
            }
            try
            {
                return(WebRequestExtension.GetResponseWithTimeout(httpWebRequest) as HttpWebResponse);
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.ProtocolError)
                {
                    throw e;
                }
                using (var response = e.Response as HttpWebResponse)
                {
                    throw BceServiceException.CreateFromHttpWebResponse(response);
                }
            }
        }
Beispiel #22
0
        public virtual IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings)
        {
            if (query == null)
            {
                throw Error.ArgumentNull("query");
            }

            if (querySettings == null)
            {
                throw Error.ArgumentNull("querySettings");
            }

            IQueryable result = query;

            // First apply $apply
            // Section 3.15 of the spec http://docs.oasis-open.org/odata/odata-data-aggregation-ext/v4.0/cs01/odata-data-aggregation-ext-v4.0-cs01.html#_Toc378326311
            ApplyClause apply = null;

            if (IsAvailableODataQueryOption(Apply, AllowedQueryOptions.Apply))
            {
                result = Apply.ApplyTo(result, querySettings);
                InternalRequest.Context.ApplyClause = Apply.ApplyClause;
                this.Context.ElementClrType         = Apply.ResultClrType;
                apply = Apply.ApplyClause;
            }

            // Construct the actual query and apply them in the following order: filter, orderby, skip, top
            if (IsAvailableODataQueryOption(Filter, AllowedQueryOptions.Filter))
            {
                result = Filter.ApplyTo(result, querySettings);
            }

            if (IsAvailableODataQueryOption(Count, AllowedQueryOptions.Count))
            {
                if (InternalRequest.Context.TotalCountFunc == null)
                {
                    Func <long> countFunc = Count.GetEntityCountFunc(result);
                    if (countFunc != null)
                    {
                        InternalRequest.Context.TotalCountFunc = countFunc;
                    }
                }

                if (InternalRequest.IsCountRequest())
                {
                    return(result);
                }
            }

            OrderByQueryOption orderBy = OrderBy;

            // $skip or $top require a stable sort for predictable results.
            // Result limits require a stable sort to be able to generate a next page link.
            // If either is present in the query and we have permission,
            // generate an $orderby that will produce a stable sort.
            if (querySettings.EnsureStableOrdering &&
                (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip) ||
                 IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top) ||
                 querySettings.PageSize.HasValue))
            {
                // If there is no OrderBy present, we manufacture a default.
                // If an OrderBy is already present, we add any missing
                // properties necessary to make a stable sort.
                // Instead of failing early here if we cannot generate the OrderBy,
                // let the IQueryable backend fail (if it has to).
                List <string> applySortOptions = GetApplySortOptions(apply);

                orderBy = orderBy == null
                            ? GenerateDefaultOrderBy(Context, applySortOptions)
                            : EnsureStableSortOrderBy(orderBy, Context, applySortOptions);
            }

            if (IsAvailableODataQueryOption(orderBy, AllowedQueryOptions.OrderBy))
            {
                result = orderBy.ApplyTo(result, querySettings);
            }

            if (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip))
            {
                result = Skip.ApplyTo(result, querySettings);
            }

            if (IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top))
            {
                result = Top.ApplyTo(result, querySettings);
            }

            AddAutoSelectExpandProperties();

            if (SelectExpand != null)
            {
                var tempResult = ApplySelectExpand(result, querySettings);
                if (tempResult != default(IQueryable))
                {
                    result = tempResult;
                }
            }

            int pageSize = -1;

            if (querySettings.PageSize.HasValue)
            {
                pageSize = querySettings.PageSize.Value;
            }
            else if (querySettings.ModelBoundPageSize.HasValue)
            {
                pageSize = querySettings.ModelBoundPageSize.Value;
            }

            if (pageSize > 0)
            {
                bool resultsLimited;
                result = LimitResults(result, pageSize, out resultsLimited);
                if (resultsLimited && InternalRequest.RequestUri != null && InternalRequest.RequestUri.IsAbsoluteUri &&
                    InternalRequest.Context.NextLink == null)
                {
                    Uri nextPageLink = InternalRequest.GetNextPageLink(pageSize);
                    InternalRequest.Context.NextLink = nextPageLink;
                }
            }

            return(result);
        }
Beispiel #23
0
        public string Index(string httpMethod, string path, string queries, string headers, string policy, string sts, string callback)
        {
            string ak = "<your ak>";
            string sk = "<your sk>";
            BceClientConfiguration config = new BceClientConfiguration()
            {
                Credentials = new DefaultBceCredentials(ak, sk)
            };

            string result = null;

            if (sts != null)
            {
                StsClient client               = new StsClient(config);
                string    accessControlList    = sts;
                GetSessionTokenRequest request = new GetSessionTokenRequest()
                {
                    DurationSeconds   = 60 * 60 * 24,
                    AccessControlList = accessControlList
                };
                GetSessionTokenResponse response = client.GetSessionToken(request);
                result = JsonConvert.SerializeObject(response);
            }
            else if (policy != null)
            {
                string base64    = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy));
                var    hash      = new HMACSHA256(Encoding.UTF8.GetBytes(sk));
                string signature = EncodeHex(hash.ComputeHash(Encoding.UTF8.GetBytes(base64)));
                result = JsonConvert.SerializeObject(new PolicySignatureResult()
                {
                    policy    = base64,
                    signature = signature,
                    accessKey = ak,
                });
            }
            else
            {
                InternalRequest internalRequest = new InternalRequest();
                internalRequest.Config     = config;
                internalRequest.Uri        = new Uri("http://www.baidu.com" + path);
                internalRequest.HttpMethod = httpMethod;
                if (headers != null)
                {
                    internalRequest.Headers = JsonConvert.DeserializeObject <Dictionary <string, string> > (headers);
                }
                if (queries != null)
                {
                    internalRequest.Parameters = JsonConvert.DeserializeObject <Dictionary <string, string> > (queries);
                }

                BceV1Signer bceV1Signer = new BceV1Signer();
                string      sign        = bceV1Signer.Sign(internalRequest);

                string xbceDate = DateUtils.FormatAlternateIso8601Date(DateTime.Now);
                result = JsonConvert.SerializeObject(new SignatureResult()
                {
                    statusCode = 200,
                    signature  = sign,
                    xbceDate   = xbceDate,
                });
            }

            if (callback != null)
            {
                result = callback + "(" + result + ")";
            }

            return(result);
        }
 public async Task <Stream> GetRequestStreamAsync()
 {
     CreateRequest();
     return(await InternalRequest.GetRequestStreamAsync());
 }
Beispiel #25
0
        private void BuildQueryOptions(IDictionary <string, string> queryParameters)
        {
            foreach (KeyValuePair <string, string> kvp in queryParameters)
            {
                switch (kvp.Key.ToLowerInvariant())
                {
                case "$filter":
                    ThrowIfEmpty(kvp.Value, "$filter");
                    RawValues.Filter = kvp.Value;
                    Filter           = new FilterQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                case "$orderby":
                    ThrowIfEmpty(kvp.Value, "$orderby");
                    RawValues.OrderBy = kvp.Value;
                    OrderBy           = new OrderByQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                case "$top":
                    ThrowIfEmpty(kvp.Value, "$top");
                    RawValues.Top = kvp.Value;
                    Top           = new TopQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                case "$skip":
                    ThrowIfEmpty(kvp.Value, "$skip");
                    RawValues.Skip = kvp.Value;
                    Skip           = new SkipQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                case "$select":
                    RawValues.Select = kvp.Value;
                    break;

                case "$count":
                    ThrowIfEmpty(kvp.Value, "$count");
                    RawValues.Count = kvp.Value;
                    Count           = new CountQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                case "$expand":
                    RawValues.Expand = kvp.Value;
                    break;

                case "$format":
                    RawValues.Format = kvp.Value;
                    break;

                case "$skiptoken":
                    RawValues.SkipToken = kvp.Value;
                    SkipToken           = new SkipTokenQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                case "$deltatoken":
                    RawValues.DeltaToken = kvp.Value;
                    break;

                case "$apply":
                    ThrowIfEmpty(kvp.Value, "$apply");
                    RawValues.Apply = kvp.Value;
                    Apply           = new ApplyQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                case "$compute":
                    ThrowIfEmpty(kvp.Value, "$compute");
                    RawValues.Compute = kvp.Value;
                    Compute           = new ComputeQueryOption(kvp.Value, Context, _queryOptionParser);
                    break;

                default:
                    // we don't throw if we can't recognize the query
                    break;
                }
            }

            if (RawValues.Select != null || RawValues.Expand != null)
            {
                SelectExpand = new SelectExpandQueryOption(RawValues.Select, RawValues.Expand,
                                                           Context, _queryOptionParser);
            }

            if (InternalRequest.IsCountRequest())
            {
                Count = new CountQueryOption(
                    "true",
                    Context,
                    new ODataQueryOptionParser(
                        Context.Model,
                        Context.ElementType,
                        Context.NavigationSource,
                        new Dictionary <string, string> {
                    { "$count", "true" }
                },
                        Context.RequestContainer));
            }
        }
Beispiel #26
0
 /// <summary>
 /// Gets the EntityTagHeaderValue ETag>.
 /// </summary>
 /// <remarks>This signature uses types that are AspNetCore-specific.</remarks>
 internal override ETag GetETag(EntityTagHeaderValue etagHeaderValue)
 {
     return(InternalRequest.GetETag <TEntity>(etagHeaderValue));
 }
Beispiel #27
0
        public virtual IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings)
        {
            if (query == null)
            {
                throw Error.ArgumentNull("query");
            }

            if (querySettings == null)
            {
                throw Error.ArgumentNull("querySettings");
            }

            IQueryable result = query;

            // First apply $apply
            // Section 3.15 of the spec http://docs.oasis-open.org/odata/odata-data-aggregation-ext/v4.0/cs01/odata-data-aggregation-ext-v4.0-cs01.html#_Toc378326311
            if (IsAvailableODataQueryOption(Apply, AllowedQueryOptions.Apply))
            {
                result = Apply.ApplyTo(result, querySettings);
                InternalRequest.Context.ApplyClause = Apply.ApplyClause;
                if (Apply.SelectExpandClause != null)
                {
                    // In case of just expand in $apply falling back to $expand serialization
                    InternalRequest.Context.ProcessedSelectExpandClause = Apply.SelectExpandClause;
                }
                this.Context.ElementClrType = Apply.ResultClrType;
            }

            // Apply compute
            // It should be executed before $filter, because it defines computed properties that can be used in a $select or within a $filter or $orderby expression.
            if (IsAvailableODataQueryOption(Compute, AllowedQueryOptions.Compute))
            {
                result = Compute.ApplyTo(result, querySettings);
            }

            // Construct the actual query and apply them in the following order: filter, orderby, skip, top
            if (IsAvailableODataQueryOption(Filter, AllowedQueryOptions.Filter))
            {
                result = Filter.ApplyTo(result, querySettings);
            }

            if (IsAvailableODataQueryOption(Count, AllowedQueryOptions.Count))
            {
                if (InternalRequest.Context.TotalCountFunc == null)
                {
                    Func <long> countFunc = Count.GetEntityCountFunc(result);
                    if (countFunc != null)
                    {
                        InternalRequest.Context.TotalCountFunc = countFunc;
                    }
                }

                if (InternalRequest.IsCountRequest())
                {
                    return(result);
                }
            }

            OrderByQueryOption orderBy = OrderBy;

            // $skip or $top require a stable sort for predictable results.
            // Result limits require a stable sort to be able to generate a next page link.
            // If either is present in the query and we have permission,
            // generate an $orderby that will produce a stable sort.
            if (querySettings.EnsureStableOrdering &&
                (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip) ||
                 IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top) ||
                 querySettings.PageSize.HasValue))
            {
                // If there is no OrderBy present, we manufacture a default.
                // If an OrderBy is already present, we add any missing
                // properties necessary to make a stable sort.
                // Instead of failing early here if we cannot generate the OrderBy,
                // let the IQueryable backend fail (if it has to).

                orderBy = GenerateStableOrder();
            }

            if (IsAvailableODataQueryOption(orderBy, AllowedQueryOptions.OrderBy))
            {
                result = orderBy.ApplyTo(result, querySettings);
            }

            if (IsAvailableODataQueryOption(SkipToken, AllowedQueryOptions.SkipToken))
            {
                result = SkipToken.ApplyTo(result, querySettings, this);
            }


            if (!IsAggregated(Apply?.ApplyClause))
            {
                AddAutoSelectExpandProperties();
            }

            if (SelectExpand != null)
            {
                var tempResult = ApplySelectExpand(result, querySettings);
                if (tempResult != default(IQueryable))
                {
                    result = tempResult;
                }
            }

            if (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip))
            {
                result = Skip.ApplyTo(result, querySettings);
            }

            if (IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top))
            {
                result = Top.ApplyTo(result, querySettings);
            }

            result = ApplyPaging(result, querySettings);

            return(result);
        }
Beispiel #28
0
 /// <summary>
 /// Gets the EntityTagHeaderValue ETag.
 /// </summary>
 internal virtual ETag GetETag(EntityTagHeaderValue etagHeaderValue)
 {
     return(InternalRequest.GetETag(etagHeaderValue));
 }