Ejemplo n.º 1
0
        protected void RespondTo(Action <ResponseFormat> collectFormats)
        {
            MimeTypes registeredMimes = new MimeTypes();

            registeredMimes.RegisterBuiltinTypes();

            ResponseHandler handler = new ResponseHandler()
            {
                ControllerBridge = new ControllerBridge(this, _controllerAction),
                AcceptedMimes    = AcceptType.Parse(Request.Headers["Accept"], registeredMimes),
                Format           = new ResponseFormat()
            };

            collectFormats(handler.Format);
            handler.Respond();
        }
Ejemplo n.º 2
0
        protected static async Task <BackendResponse> GetFromBackendWithBadRequestAsync(
            IRestClient restClient,
            Func <IRestRequest> createBackendRequestFunc,
            AcceptType acceptType,
            Action <HttpStatusCode> handleNotOkResponseAction,
            ProblemDetailsHelper problemDetailsHelper,
            CancellationToken cancellationToken)
        {
            var contentType = acceptType.ToMimeTypeString();

            var backendRequest = createBackendRequestFunc();

            backendRequest.AddHeader(HeaderNames.Accept, contentType);

            var response = await ExecuteRequestAsync(restClient, backendRequest, cancellationToken);

            var downstreamVersion = response
                                    .Headers
                                    .FirstOrDefault(x => x.Name.Equals(AddVersionHeaderMiddleware.HeaderName, StringComparison.InvariantCultureIgnoreCase));

            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                return(new BackendResponse(
                           GetPublicContentValue(response, problemDetailsHelper),
                           downstreamVersion?.Value.ToString(),
                           DateTimeOffset.UtcNow,
                           response.ContentType,
                           false,
                           response.HeadersToKeyValuePairs(),
                           response.StatusCode));
            }
            if (response.StatusCode is HttpStatusCode.OK or HttpStatusCode.Created or HttpStatusCode.Accepted)
            {
                return(new BackendResponse(
                           response.Content,
                           downstreamVersion?.Value.ToString(),
                           DateTimeOffset.UtcNow,
                           contentType,
                           false,
                           response.HeadersToKeyValuePairs(),
                           response.StatusCode));
            }

            handleNotOkResponseAction(response.StatusCode);

            throw new ApiException("Fout bij de bron.", (int)response.StatusCode, response.ErrorException);
        }
Ejemplo n.º 3
0
        private MimeType[] GetAcceptedTypes(MimeTypes registeredMimes)
        {
            var mimeTypes   = new List <MimeType>();
            var originalUrl = Request.Uri.GetLeftPart(UriPartial.Authority) + Request.Url;
            var lastSegment = new Uri(originalUrl).Segments.Last();

            if (lastSegment.Contains(".") && (lastSegment.LastIndexOf(".") < lastSegment.Length - 1))
            {
                var extension = lastSegment.Substring(lastSegment.LastIndexOf(".") + 1);
                var mimeType  = registeredMimes.GetMimeTypeForExtension(extension);

                if (mimeType != null)
                {
                    mimeTypes.Add(mimeType);
                }
            }

            mimeTypes.AddRange(AcceptType.Parse(AcceptHeader, registeredMimes));

            return(mimeTypes.Distinct().ToArray());
        }
Ejemplo n.º 4
0
        protected static async Task <BackendResponse> GetFromBackendWithBadRequestAsync(
            IRestClient restClient,
            Func <IRestRequest> createBackendRequestFunc,
            AcceptType acceptType,
            Action <HttpStatusCode> handleNotOkResponseAction,
            CancellationToken cancellationToken)
        {
            var contentType = acceptType.ToMimeTypeString();

            var backendRequest = createBackendRequestFunc();

            backendRequest.AddHeader(HeaderNames.Accept, contentType);

            var response = await restClient.ExecuteTaskAsync(backendRequest, cancellationToken);

            if ((response.IsSuccessful && response.StatusCode == HttpStatusCode.OK) || response.StatusCode == HttpStatusCode.BadRequest)
            {
                var downstreamVersion = response
                                        .Headers
                                        .FirstOrDefault(x => x.Name.Equals(AddVersionHeaderMiddleware.HeaderName, StringComparison.InvariantCultureIgnoreCase));

                var responseContentType = response.StatusCode == HttpStatusCode.OK
                    ? contentType
                    : response.ContentType;

                return(new BackendResponse(
                           response.Content,
                           downstreamVersion?.Value.ToString(),
                           DateTimeOffset.UtcNow,
                           responseContentType,
                           false,
                           response.StatusCode));
            }

            handleNotOkResponseAction(response.StatusCode);

            throw new ApiException("Fout bij de bron.", (int)response.StatusCode, response.ErrorException);
        }
 /// <summary>
 /// 发送post请求
 /// </summary>
 /// <param name="url">地址</param>
 /// <param name="paras">参数</param>
 /// <param name="headers">请求包头</param>
 /// <param name="contentType">请求内容格式</param>
 /// <param name="accept">接收内容格式</param>
 /// <returns></returns>
 public static string Post(string url, string paras, Dictionary<string, string> headers, RequestContentType? contentType, AcceptType? accept)
 {
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
     request.Method = HttpMethodType.Post.GetDescription();
     request.ContentType = RequestContentType.UrlEncoded.GetDescription();
     request.Accept = AcceptType.json.GetDescription();
     if (headers != null)
     {
         foreach (KeyValuePair<string, string> kv in headers)
         {
             request.Headers.Add(kv.Key, kv.Value);
         }
     }
     if (contentType != null) request.ContentType = contentType.GetDescription();
     if (accept != null) request.Accept = accept.GetDescription();
     byte[] bs = Encoding.UTF8.GetBytes(paras);
     using (Stream requestStream = request.GetRequestStream())
     {
         requestStream.Write(bs, 0, bs.Length);
     }
     try
     {
         using (WebResponse response = request.GetResponse())
         {
             using (StreamReader reader = new StreamReader(response.GetResponseStream()))
             {
                 return reader.ReadToEnd();
             }
         }
     }
     catch (WebException ex)
     {
         LogHelper.ErrorLog(ex);
         return null;
     }
 }
        public HttpStatusCode CreateTable(string tableName, ContType pContentType = ContType.applicationIatomIxml, AcceptType pAcceptType = AcceptType.applicationIjson, ResponseType pResponseType = ResponseType.returnContent, bool useSharedKeyLite = false)
        {
            OperationResultsClear();
            string timestamp = GetDateHeader();

            // RoSchmi, for Debugging
            //timestamp = "2020-09-30T23:31:04";
            String timestampUTC = timestamp + ".0000000Z";

            string content = string.Empty;

            string contentType = getContentTypeString(pContentType);
            string acceptType  = getAcceptTypeString(pAcceptType);

            //long totalMemory = GC.GetTotalMemory(true);

            content = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" +
                      "<entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\"  " +
                      "xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" " +
                      "xmlns=\"http://www.w3.org/2005/Atom\"> " +
                      "<id>http://" + _account.AccountName + ".table.core.windows.net/Tables('"
                      + tableName +
                      "')</id>" +
                      "<title />" +
                      "<updated>" + timestampUTC + "</updated>" +
                      "<author><name/></author> " +
                      "<content type=\"application/xml\"><m:properties><d:TableName>" + tableName + "</d:TableName></m:properties></content></entry>";

            // "<updated>" + timestampUTC + "</updated>" +
            //"<updated>" + DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.0000000Z") + "</updated>" +
            string HttpVerb   = "POST";
            string ContentMD5 = string.Empty;

            byte[] hashContentMD5 = null;
            int    contentLength  = 0;

            // RoSchmi for debugging
            // Debug.WriteLine(content);

            byte[] payload = GetBodyBytesAndLength(content, out contentLength);

            content = null; // free memory

            string authorizationHeader = CreateTableAuthorizationHeader(payload, String.Format("/{0}/{1}", _account.AccountName, "Tables()"), timestamp, HttpVerb, pContentType, out ContentMD5, out hashContentMD5, useSharedKeyLite = false);

            string urlPath = String.Format("{0}", tableName);

            string canonicalizedResource = String.Format("/{0}/{1}", _account.AccountName, urlPath);

            string canonicalizedHeaders = String.Format("Date:{0}\nx-ms-date:{1}\nx-ms-version:{2}", timestamp, timestamp, VersionHeader);

            string TableEndPoint = _account.UriEndpoints["Table"].ToString();

            Uri uri = new Uri(TableEndPoint + "/Tables()");

            var tableTypeHeaders = new Hashtable();

            tableTypeHeaders.Add("Accept-Charset", "UTF-8");
            tableTypeHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
            tableTypeHeaders.Add("Content-Type", contentType);
            tableTypeHeaders.Add("DataServiceVersion", "3.0");
            tableTypeHeaders.Add("Prefer", getResponseTypeString(pResponseType));
            tableTypeHeaders.Add("Content-MD5", ContentMD5);

            if (_fiddlerIsAttached)
            {
                AzureStorageHelper.AttachFiddler(_fiddlerIsAttached, _fiddlerIP, _fiddlerPort);
            }

            BasicHttpResponse response = new BasicHttpResponse();

            try
            {
                AzureStorageHelper.SetDebugMode(_debug);
                AzureStorageHelper.SetDebugLevel(_debug_level);

                response = AzureStorageHelper.SendWebRequest(caCerts, uri, authorizationHeader, timestamp, VersionHeader, payload, contentLength, HttpVerb, false, acceptType, tableTypeHeaders);

                return(response.StatusCode);
            }
            catch (Exception ex)
            {
                _Print_Debug("Exception was cought: " + ex.Message);
                //Debug.WriteLine("Exception was cought: " + ex.Message);
                response.StatusCode = HttpStatusCode.Forbidden;
                return(response.StatusCode);
            }
        }
Ejemplo n.º 7
0
 public PendingAllianceMember(DateTime date, Alliance alliance, Airline airline, AcceptType type)
 {
     Alliance = alliance;
     Airline = airline;
     Date = date;
     Type = type;
 }
 private ContentFormat(AcceptType contentType)
 {
     ContentType = contentType;
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Will return the best matching content type OR the first given!
        /// </summary>
        /// <param name="myContentTypes"></param>
        /// <returns></returns>
        public ContentType GetBestMatchingAcceptHeader(params ContentType[] myContentTypes)
        {
            var _ListOfFoundAcceptHeaders = new List<AcceptType>();
            UInt32 pos = 0;

            foreach (var _ContentType in myContentTypes)
            {

                var _AcceptType = new AcceptType(_ContentType.ToString(), pos++);

                var _Match = AcceptTypes.Find(_AType => _AType.Equals(_AcceptType));

                if (_Match != null)
                {

                    if (_Match.ContentType.GetMediaSubType() == "*") // this was a * and we will set the quality to lowest
                        _AcceptType.Quality = 0;

                    _ListOfFoundAcceptHeaders.Add(_AcceptType);

                }

            }

            _ListOfFoundAcceptHeaders.Sort();

            if (!_ListOfFoundAcceptHeaders.IsNullOrEmpty())
                return _ListOfFoundAcceptHeaders.First().ContentType;
            else if (!myContentTypes.IsNullOrEmpty())
                return myContentTypes.First();
            else
                return null;
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Add an AcceptType to the Accept header field.
 /// </summary>
 /// <param name="AcceptType">An AcceptType.</param>
 public HTTPRequestBuilder AddAccept(AcceptType AcceptType)
 {
     this.Accept.Add(AcceptType);
     return this;
 }
Ejemplo n.º 11
0
        public HttpStatusCode DeleteTableEntity(string tableName, string partitionKey, string rowKey, ContType pContentType = ContType.applicationIatomIxml, AcceptType pAcceptType = AcceptType.applicationIjson, string ETag = "", bool useSharedKeyLite = false)
        {
            string timestamp   = GetDateHeader();
            string content     = string.Empty;
            string contentType = getContentTypeString(pContentType);
            string acceptType  = getAcceptTypeString(pAcceptType);

            if (pAcceptType == AcceptType.applicationIjson)
            {
                acceptType = "application/json;odata=minimalmetadata";
            }

            string HttpVerb      = "DELETE";
            int    contentLength = 0;

            byte[] payload     = GetBodyBytesAndLength(content, out contentLength);
            string ContentMD5  = string.Empty;
            string matchString = StringUtilities.Format("{1}(PartitionKey='{2}',RowKey='{3}')", _account.AccountName, tableName, partitionKey, rowKey);

            var authorizationHeader = CreateTableAuthorizationHeader(payload, StringUtilities.Format("/{0}/{1}", _account.AccountName, matchString), timestamp, HttpVerb, ContType.applicationIatomIxml, out ContentMD5, useSharedKeyLite);

            string TableEndPoint = _account.UriEndpoints["Table"].ToString();

            Uri uri = new Uri(TableEndPoint + "/" + matchString);

            var tableTypeHeaders = new Hashtable();



            if (ETag == "")
            {
                tableTypeHeaders.Add("If-Match", "*");
            }
            else
            {
                tableTypeHeaders.Add("If-Match", ETag);
            }

            tableTypeHeaders.Add("Accept-Charset", "UTF-8");
            tableTypeHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
            tableTypeHeaders.Add("Content-Type", contentType);
            tableTypeHeaders.Add("DataServiceVersion", "3.0");
            tableTypeHeaders.Add("Content-MD5", ContentMD5);

            if (_fiddlerIsAttached)
            {
                AzureStorageHelper.AttachFiddler(_fiddlerIsAttached, _fiddlerIP, _fiddlerPort);
            }

            BasicHttpResponse response = new BasicHttpResponse();

            try
            {
                AzureStorageHelper.SetDebugMode(_debug);
                AzureStorageHelper.SetDebugLevel(_debug_level);
                response = AzureStorageHelper.SendWebRequest(uri, authorizationHeader, timestamp, VersionHeader, payload, contentLength, HttpVerb, false, acceptType, tableTypeHeaders);

                return(response.StatusCode);
            }
            catch (Exception ex)
            {
                _Print_Debug("Exception was cought: " + ex.Message);
                response.StatusCode = HttpStatusCode.Forbidden;
                return(response.StatusCode);
            }
        }
        private HttpStatusCode QueryTableEntities(string tableName, ContType pContentType = ContType.applicationIatomIxml, AcceptType pAcceptType = AcceptType.applicationIjson, bool useSharedKeyLite = false)
        {
            OperationResultsClear();
            string pQuery       = _Query;
            string partitionKey = _PartitionKey;
            string rowKey       = _RowKey;

            string timestamp = GetDateHeader();
            string content   = string.Empty;
            //string queryString = "Tables";

            string contentType = getContentTypeString(pContentType);

            string acceptType = getAcceptTypeString(pAcceptType);
            //if (pAcceptType == AcceptType.applicationIjson)
            //{ acceptType = "application/json;odata=minimalmetadata"; }
            // { acceptType = "application/json;odata=nometadata"; }
            //{ acceptType = "application/json;odata=fullmetadata"; }


            string HttpVerb   = "GET";
            string ContentMD5 = string.Empty;

            byte[] hashContentMD5 = null;

            int contentLength = 0;

            byte[] payload = GetBodyBytesAndLength(content, out contentLength);
            content = null;    // clear memory

            string resourceString = string.Empty;
            string queryString    = string.Empty;

            if (!String.IsNullOrEmpty(pQuery))
            {
                queryString = "?" + pQuery;
            }

            if ((!String.IsNullOrEmpty(partitionKey) && (!String.IsNullOrEmpty(rowKey))))
            {
                resourceString = String.Format("{1}(PartitionKey='{2}',RowKey='{3}')", _account.AccountName, tableName, partitionKey, rowKey);
            }
            if ((String.IsNullOrEmpty(partitionKey) && (String.IsNullOrEmpty(rowKey))))
            {
                resourceString = String.Format("{1}()", _account.AccountName, tableName, partitionKey, rowKey);
            }

            var authorizationHeader = CreateTableAuthorizationHeader(payload, String.Format("/{0}/{1}", _account.AccountName, resourceString), timestamp, HttpVerb, ContType.applicationIatomIxml, out ContentMD5, out hashContentMD5, useSharedKeyLite);

            string TableEndPoint = _account.UriEndpoints["Table"].ToString();

            Uri uri = new Uri(TableEndPoint + "/" + resourceString + queryString);

            var tableTypeHeaders = new Hashtable
            {
                { "MaxDataServiceVersion", "3.0;NetFx" },
                { "Content-Type", contentType },
                { "DataServiceVersion", "3.0;NetFx" },
                { "Content-MD5", ContentMD5 }
            };

            if (_fiddlerIsAttached)
            {
                AzureStorageHelper.AttachFiddler(_fiddlerIsAttached, _fiddlerIP, _fiddlerPort);
            }

            BasicHttpResponse response = new BasicHttpResponse();

            try
            {
                AzureStorageHelper.SetDebugMode(_debug);
                AzureStorageHelper.SetDebugLevel(_debug_level);
                response = AzureStorageHelper.SendWebRequest(caCerts, uri, authorizationHeader, timestamp, VersionHeader, payload, contentLength, HttpVerb, false, acceptType, tableTypeHeaders);

                /*
                 * long freeMemory = GHIElectronics.TinyCLR.Native.Memory.ManagedMemory.FreeBytes;
                 * long totalMemory = GC.GetTotalMemory(true);
                 * Debug.WriteLine("TableClient: QueryTableEntities. Total Memory: " + totalMemory.ToString("N0") + " Free Bytes: " + freeMemory.ToString("N0"));
                 */

                ArrayList entities = null;
                if ((response.Body != null) && (response.Body.StartsWith("<?xml")))
                {
                    entities = ParseResponse(response.Body);
                    _OperationResponseQueryList = entities;
                }
                else if ((response.Body != null) && (response.Body.StartsWith("{\"odata.metadata\":")))
                {
                    throw new NotSupportedException("Json serialization is actually not supported");
                    //response.Body = response.Body.Substring(0, response.Body.Length - 7);
                    //var newInstance = (QueryEntity)JsonConverter.DeserializeObject(response.Body, typeof(QueryEntity), CreateInstance);
                }

                _OperationResponseBody = response.Body.Substring(0, Math.Min(response.Body.Length, 300));   // not more than 300 char

                if (entities.Count == 1)
                {
                    _OperationResponseETag        = response.ETag;
                    _OperationResponseSingleQuery = entities[0] as Hashtable;
                }


                return(response.StatusCode);
            }
            catch (OutOfMemoryException e)
            {
                throw new OutOfMemoryException(e.Message);
            }
            catch (Exception ex)
            {
                //_Print_Debug("Exception was cought: " + ex.Message);
                Debug.WriteLine("Exception was cought: " + ex.Message);
                response.StatusCode = HttpStatusCode.NotFound;

                return(response.StatusCode);
            }
        }
Ejemplo n.º 13
0
 private MimeType[] ParseHeader(string header)
 {
     return(AcceptType.Parse(header, TestMimes));
 }
Ejemplo n.º 14
0
        protected async Task <BackendResponse> GetFromCacheThenFromBackendAsync(
            AcceptType acceptType,
            IRestClient restClient,
            Func <IRestRequest> createBackendRequestFunc,
            string cacheKey,
            Action <HttpStatusCode> handleNotOkResponseAction,
            CancellationToken cancellationToken)
        {
            if (_redis != null)
            {
                var key = $"{cacheKey}.{acceptType}".ToLowerInvariant();

                try
                {
                    var db = _redis.GetDatabase();

                    var cachedValues =
                        await db.HashGetAllAsync(
                            key,
                            CommandFlags.PreferReplica);

                    if (cachedValues.Length > 0)
                    {
                        var cachedSetByRegistry = cachedValues.First(x => x.Name.Equals(SetByRegistryKey));

                        if (cachedSetByRegistry.Value == true.ToString(CultureInfo.InvariantCulture))
                        {
                            var cachedValue        = cachedValues.FirstOrDefault(x => x.Name.Equals(ValueKey));
                            var cachedHeaders      = cachedValues.FirstOrDefault(x => x.Name.Equals(HeadersKey));
                            var cachedLastModified = cachedValues.FirstOrDefault(x => x.Name.Equals(LastModifiedKey));

                            var headers = JsonConvert.DeserializeObject <Dictionary <string, string[]> >(cachedHeaders.Value);
                            headers.TryGetValue(AddVersionHeaderMiddleware.HeaderName, out var downstreamVersion);

                            return(new BackendResponse(
                                       cachedValue.Value,
                                       downstreamVersion?.First(),
                                       DateTimeOffset.ParseExact(
                                           cachedLastModified.Value,
                                           "O",
                                           CultureInfo.InvariantCulture),
                                       acceptType.ToMimeTypeString(),
                                       true,
                                       Enumerable.Empty <KeyValuePair <string, StringValues> >()));
                        }

                        _logger.LogError("Failed to retrieve record {Record} from Redis, cached values not set by registry.", key);
                    }
                    else
                    {
                        _logger.LogError("Failed to retrieve record {Record} from Redis, no cached values.", key);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Failed to retrieve record {Record} from Redis.", key);
                }
            }

            return(await GetFromBackendAsync(
                       restClient,
                       createBackendRequestFunc,
                       acceptType,
                       handleNotOkResponseAction,
                       cancellationToken));
        }
Ejemplo n.º 15
0
 public PendingAllianceMember(DateTime date, Alliance alliance, Airline airline, AcceptType type)
 {
     this.Alliance = alliance;
     this.Airline  = airline;
     this.Date     = date;
     this.Type     = type;
 }
Ejemplo n.º 16
0
        public HttpStatusCode UpdateTableEntity(string tableName, string partitionKey, string rowKey, TableEntity pEntity, ContType pContentType = ContType.applicationIatomIxml, AcceptType pAcceptType = AcceptType.applicationIjson, ResponseType pResponseType = ResponseType.returnContent, string ETag = "", bool useSharedKeyLite = false)
        {
            OperationResultsClear();;
            string timestamp = GetDateHeader();
            string content   = string.Empty;

            string contentType = getContentTypeString(pContentType);
            string acceptType  = getAcceptTypeString(pAcceptType);

            switch (contentType)
            {
            case "application/json":
            {
                content = pEntity.ReadJson();
            }
            break;

            case "application/atom+xml":
            {
                content = StringUtilities.Format("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" xmlns=\"http://www.w3.org/2005/Atom\">" +
                                                 "<id>http://{0}.table.core.windows.net/{5}(PartitionKey='{2}',RowKey='{3}')</id>" +
                                                 "<title/><updated>{1}</updated>" +
                                                 "<author><name /></author>" +
                                                 "<content type=\"application/atom+xml\"><m:properties><d:PartitionKey>{2}</d:PartitionKey><d:RowKey>{3}</d:RowKey>" +
                                                 "{4}" +
                                                 "</m:properties>" +
                                                 "</content>" +
                                                 "</entry>", _account.AccountName, timestamp, pEntity.PartitionKey, pEntity.RowKey, GetTableXml(pEntity.Properties), tableName);
            }
            break;

            default:
            {
                throw new NotSupportedException("ContentType must be 'application/json' or 'application/atom+xml'");
            }
            }


            string HttpVerb      = "PUT";
            var    contentLength = 0;
            var    payload       = GetBodyBytesAndLength(content, out contentLength);
            string ContentMD5    = string.Empty;

            string matchString = StringUtilities.Format("{1}(PartitionKey='{2}',RowKey='{3}')", _account.AccountName, tableName, partitionKey, rowKey);

            var authorizationHeader = CreateTableAuthorizationHeader(payload, StringUtilities.Format("/{0}/{1}", _account.AccountName, matchString), timestamp, HttpVerb, ContType.applicationIatomIxml, out ContentMD5, useSharedKeyLite);

            string TableEndPoint = _account.UriEndpoints["Table"].ToString();

            Uri uri = new Uri(TableEndPoint + "/" + matchString);

            var tableTypeHeaders = new Hashtable();

            if (ETag == "")
            {
                tableTypeHeaders.Add("If-Match", "*");
            }
            else
            {
                tableTypeHeaders.Add("If-Match", ETag);
            }

            tableTypeHeaders.Add("Accept-Charset", "UTF-8");
            tableTypeHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
            tableTypeHeaders.Add("Content-Type", contentType);
            tableTypeHeaders.Add("DataServiceVersion", "3.0");
            tableTypeHeaders.Add("Prefer", getResponseTypeString(pResponseType));
            tableTypeHeaders.Add("Content-MD5", ContentMD5);

            if (_fiddlerIsAttached)
            {
                AzureStorageHelper.AttachFiddler(_fiddlerIsAttached, _fiddlerIP, _fiddlerPort);
            }

            BasicHttpResponse response = new BasicHttpResponse();

            try
            {
                AzureStorageHelper.SetDebugMode(_debug);
                AzureStorageHelper.SetDebugLevel(_debug_level);
                response = AzureStorageHelper.SendWebRequest(uri, authorizationHeader, timestamp, VersionHeader, payload, contentLength, HttpVerb, false, acceptType, tableTypeHeaders);
                _OperationResponseETag = response.ETag;
                _OperationResponseMD5  = response.Content_MD5;
                return(response.StatusCode);
            }
            catch (Exception ex)
            {
                _Print_Debug("Exception was cought: " + ex.Message);
                response.StatusCode = HttpStatusCode.Forbidden;
                return(response.StatusCode);
            }
        }
        public HttpStatusCode InsertTableEntity(string tableName, TableEntity pEntity, ContType pContentType = ContType.applicationIatomIxml, AcceptType pAcceptType = AcceptType.applicationIjson, ResponseType pResponseType = ResponseType.returnContent, bool useSharedKeyLite = false)
        {
            OperationResultsClear();;
            string timestamp = GetDateHeader();

            //RoSchmi: for tests
            //timestamp = "Wed, 21 Oct 2020 08:53:19 GMT";



            string content = string.Empty;

            string contentType = getContentTypeString(pContentType);
            string acceptType  = getAcceptTypeString(pAcceptType);

            //long totalMemory = GC.GetTotalMemory(true);

            switch (contentType)
            {
            case "application/json":
            {
                content = pEntity.ReadJson();
            }
            break;

            case "application/atom+xml":
            {
                content =
                    String.Format("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" xmlns=\"http://www.w3.org/2005/Atom\">" +
                                  "<id>http://{0}.table.core.windows.net/{5}(PartitionKey='{2}',RowKey='{3}')</id>" +
                                  "<title/><updated>{1}</updated>" +
                                  "<author><name /></author>" +
                                  "<content type=\"application/atom+xml\"><m:properties><d:PartitionKey>{2}</d:PartitionKey><d:RowKey>{3}</d:RowKey>" +
                                  "{4}" +
                                  "</m:properties>" +
                                  "</content>" +
                                  "</entry>", _account.AccountName, timestamp, pEntity.PartitionKey, pEntity.RowKey, GetTableXml(pEntity.Properties), tableName);
            }
            break;

            default:
            {
                throw new NotSupportedException("ContentType must be 'application/json' or 'application/atom+xml'");
            }
            }
            string HttpVerb      = "POST";
            int    contentLength = 0;

            byte[] payload = GetBodyBytesAndLength(content, out contentLength);
            content = null;     // free memory
            string ContentMD5 = string.Empty;

            byte[] hashContentMD5 = null;

            var authorizationHeader = CreateTableAuthorizationHeader(payload, String.Format("/{0}/{1}", _account.AccountName, tableName + "()"), timestamp, HttpVerb, pContentType, out ContentMD5, out hashContentMD5, useSharedKeyLite);

            string urlPath = String.Format("{0}", tableName);

            string canonicalizedResource = String.Format("/{0}/{1}", _account.AccountName, urlPath);

            string canonicalizedHeaders = String.Format("Date:{0}\nx-ms-date:{1}\nx-ms-version:{2}", timestamp, timestamp, VersionHeader);

            string TableEndPoint = _account.UriEndpoints["Table"].ToString();

            Uri uri = new Uri(TableEndPoint + "/" + tableName + "()");

            var tableTypeHeaders = new Hashtable
            {
                { "Accept-Charset", "UTF-8" },
                { "MaxDataServiceVersion", "3.0;NetFx" },
                { "Content-Type", contentType },
                { "DataServiceVersion", "3.0" },
                { "Prefer", getResponseTypeString(pResponseType) },
                { "Content-MD5", ContentMD5 }
            };


            if (_fiddlerIsAttached)
            {
                AzureStorageHelper.AttachFiddler(_fiddlerIsAttached, _fiddlerIP, _fiddlerPort);
            }

            BasicHttpResponse response = new BasicHttpResponse();

            try
            {
                AzureStorageHelper.SetDebugMode(_debug);
                AzureStorageHelper.SetDebugLevel(_debug_level);

                response = AzureStorageHelper.SendWebRequest(caCerts, uri, authorizationHeader, timestamp, VersionHeader, payload, contentLength, HttpVerb, false, acceptType, tableTypeHeaders);
                _OperationResponseETag = response.ETag;
                _OperationResponseMD5  = response.Content_MD5;
                return(response.StatusCode);
            }
            catch (OutOfMemoryException ex1)
            {
                throw new OutOfMemoryException("Exc at 01: " + ex1.Message);
            }
            catch (Exception ex)
            {
                _Print_Debug("Exception was cought: " + ex.Message);
                //Debug.WriteLine("Exception was cought: " + ex.Message);
                response.StatusCode = HttpStatusCode.Forbidden;
                return(response.StatusCode);
            }
        }
Ejemplo n.º 18
0
 public Accept SetType(AcceptType type)
 {
     this.type = type;
     return this;
 }
 public HttpStatusCode QueryTableEntities(string tableName, string query = "", ContType contentType = ContType.applicationIatomIxml, AcceptType acceptType = AcceptType.applicationIjson, bool useSharedKeyLite = false)
 {
     _Query        = query;
     _PartitionKey = "";
     _RowKey       = "";
     return(QueryTableEntities(tableName, contentType, acceptType, useSharedKeyLite));
 }
Ejemplo n.º 20
0
 public PendingAllianceMember(DateTime date,Alliance alliance, Airline airline, AcceptType type)
 {
     this.Alliance = alliance;
     this.Airline = airline;
     this.Date = date;
     this.Type = type;
 }
Ejemplo n.º 21
0
 public static void SetAcceptType(this HttpRequest request, AcceptType acceptType)
 => request.Headers[HeaderNames.Accept] = acceptType.ToMimeTypeString();
Ejemplo n.º 22
0
        private HttpStatusCode QueryTableEntities(string tableName, ContType pContentType = ContType.applicationIatomIxml, AcceptType pAcceptType = AcceptType.applicationIjson, bool useSharedKeyLite = false)
        {
            OperationResultsClear();
            string pQuery       = _Query;
            string partitionKey = _PartitionKey;
            string rowKey       = _RowKey;

            string timestamp = GetDateHeader();
            string content   = string.Empty;
            //string queryString = "Tables";

            string contentType = getContentTypeString(pContentType);

            string acceptType = getAcceptTypeString(pAcceptType);

            if (pAcceptType == AcceptType.applicationIjson)
            {
                acceptType = "application/json;odata=minimalmetadata";
            }

            string HttpVerb      = "GET";
            string ContentMD5    = string.Empty;
            int    contentLength = 0;

            byte[] payload = GetBodyBytesAndLength(content, out contentLength);

            string resourceString = string.Empty;
            string queryString    = string.Empty;

            if (!StringUtilities.IsNullOrEmpty(pQuery))
            {
                queryString = "?" + pQuery;
            }

            if ((!StringUtilities.IsNullOrEmpty(partitionKey) && (!StringUtilities.IsNullOrEmpty(rowKey))))
            {
                resourceString = StringUtilities.Format("{1}(PartitionKey='{2}',RowKey='{3}')", _account.AccountName, tableName, partitionKey, rowKey);
            }
            if ((StringUtilities.IsNullOrEmpty(partitionKey) && (StringUtilities.IsNullOrEmpty(rowKey))))
            {
                resourceString = StringUtilities.Format("{1}()", _account.AccountName, tableName, partitionKey, rowKey);
            }

            var authorizationHeader = CreateTableAuthorizationHeader(payload, StringUtilities.Format("/{0}/{1}", _account.AccountName, resourceString), timestamp, HttpVerb, ContType.applicationIatomIxml, out ContentMD5, useSharedKeyLite);

            // only for tests to provoke an authentication error
            // var authorizationHeader = CreateTableAuthorizationHeader(payload, StringUtilities.Format("/{0}/{1}", "Hallo", resourceString), timestamp, HttpVerb, ContType.applicationIatomIxml, out ContentMD5, useSharedKeyLite);

            string TableEndPoint = _account.UriEndpoints["Table"].ToString();

            // Changed by RoSchmi (Tests)
            //IPAddress[] AzureIPs = ALL3075V3_433_Azure.myDNS.ResolveHostname("roschmi01.table.core.windows.net");
            //IPAddress[] AzureIPs = ALL3075V3_433_Azure.myDNS.ResolveHostname("www.google.de");


            Uri uri = new Uri(TableEndPoint + "/" + resourceString + queryString);

            var tableTypeHeaders = new Hashtable();

            tableTypeHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
            tableTypeHeaders.Add("Content-Type", contentType);
            tableTypeHeaders.Add("DataServiceVersion", "3.0;NetFx");
            tableTypeHeaders.Add("Content-MD5", ContentMD5);

            if (_fiddlerIsAttached)
            {
                AzureStorageHelper.AttachFiddler(_fiddlerIsAttached, _fiddlerIP, _fiddlerPort);
            }

            BasicHttpResponse response = new BasicHttpResponse();

            try
            {
                AzureStorageHelper.SetDebugMode(_debug);
                AzureStorageHelper.SetDebugLevel(_debug_level);
                response = AzureStorageHelper.SendWebRequest(uri, authorizationHeader, timestamp, VersionHeader, payload, contentLength, HttpVerb, false, acceptType, tableTypeHeaders);
                var entities = ParseResponse(response.Body);
                _OperationResponseBody      = response.Body;
                _OperationResponseQueryList = entities;
                //if (entities.Count != 0)
                //{
                if (entities.Count == 1)
                {
                    _OperationResponseETag        = response.ETag;
                    _OperationResponseSingleQuery = entities[0] as Hashtable;
                }
                // }

                return(response.StatusCode);
            }
            catch (Exception ex)
            {
                _Print_Debug("Exception was cought: " + ex.Message);
                response.StatusCode = HttpStatusCode.Forbidden;
                //return null;
                return(response.StatusCode);
            }
        }