Example #1
0
        public HttpStatusCode QueryTables(string tableName, ContType pContentType = ContType.applicationIatomIxml, AcceptType pAcceptType = AcceptType.applicationIjson, bool useSharedKeyLite = false)
        {
            OperationResultsClear();;
            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);
            if (tableName != string.Empty)
            {
                queryString = StringUtilities.Format("Tables('{0}')", tableName);
            }
            string authorizationHeader = CreateTableAuthorizationHeader(payload, StringUtilities.Format("/{0}/{1}", _account.AccountName, queryString), timestamp, HttpVerb, pContentType, out ContentMD5, useSharedKeyLite);

            string TableEndPoint    = _account.UriEndpoints["Table"].ToString();
            Uri    uri              = new Uri(TableEndPoint + "/" + queryString);
            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("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 string getContentTypeString(ContType pContentType)
 {
     if (pContentType == ContType.applicationIatomIxml)
     {
         return("application/atom+xml");
     }
     else
     {
         return("application/json");
     }
 }
 public string this[string columnName]
 {
     get
     {
         string result = null;
         if (columnName == "LocType")
         {
             if (LocType != null && LocType.ToString().Length > 3)
             {
                 result = "LocType exceeds maximum length (3).";
                 //LocType = (int?)int.Parse(LocType.ToString().Substring(0, 3));
             }
         }
         if (columnName == "ContType")
         {
             if (ContType != null && ContType.ToString().Length > 2)
             {
                 result = "ContType exceeds maximum length (2).";
                 //ContType = (int?)int.Parse(ContType.ToString().Substring(0, 2));
             }
         }
         return(result);
     }
 }
 public ElementContainer(ContType contType = ContType.Element)
 {
     Amount   = 1;
     LineType = contType;
 }
        /*
         * private string MD5ComputeHash(byte[] data)
         * {
         *
         *  if (data.Length != 0)
         *  {
         *      wifi.CreateRamFile("fileToHash", data);
         *      return Encoding.UTF8.GetString(wifi.ComputeHash("3", "fileToHash")).Substring(4);
         *  }
         *  else
         *  {
         *      return "D41D8CD98F00B204E9800998ECF8427E";
         *  }
         *
         *
         *  //byte[] hash= xBrainLab.Security.Cryptography.MD5.GetHash(StringData);
         *  //string hashString = xBrainLab.Security.Cryptography.MD5.GetHashString(StringData);
         *
         *
         *  //using (HashAlgorithm csp = new HashAlgorithm(PervasiveDigital.Security.ManagedProviders.HashAlgorithmType.MD5))
         *  //using (HashAlgorithm csp = new HashAlgorithm(xBrainLab.Security.Cryptography.MD5)
         *
         *  //using (HashAlgorithm csp = HashAlgorithm.Create("Md5"))
         *
         *  //using (HashAlgorithm csp = HashAlgorithm.Create("MD5"))
         *  //{
         *
         *     // hash = csp.ComputeHash(data);
         *  //}
         *
         *  //string hashString = ByteExtensions.ToHexString(hash, "");
         *
         *  //return hashString;
         * }
         */
        #endregion

        #region CreateTableAuthorizationHeader
        protected string CreateTableAuthorizationHeader(byte[] content, string canonicalResource, string ptimeStamp, string pHttpVerb, ContType pContentType, out string pMD5Hash, out byte[] pHash, bool useSharedKeyLite = false)
        {
            string contentType = getContentTypeString(pContentType);

            pMD5Hash = string.Empty;
            pHash    = null;

            if (!useSharedKeyLite)
            {
                // long startTime = DateTime.Now.Ticks;

                pHash    = xBrainLab.Security.Cryptography.MD5.GetHash(content);
                pMD5Hash = BitConverter.ToString(pHash);
                pMD5Hash = pMD5Hash.Replace("-", string.Empty);

                // long endTime = DateTime.Now.Ticks;
                // Debug.WriteLine("Needed for MD5-hash (1): " + ((endTime - startTime) / TimeSpan.TicksPerMillisecond).ToString());  // about 80 ms
            }

            string toSign = string.Empty;

            if (useSharedKeyLite)
            {
                toSign = String.Format("{0}\n{1}", ptimeStamp, canonicalResource);
            }
            else
            {
                toSign = String.Format("{0}\n{4}\n{1}\n{2}\n{3}", pHttpVerb, contentType, ptimeStamp, canonicalResource, pMD5Hash);
            }

            string signature;

            #region Region: Tests to use SPWF04SA for SHA256 encoding (not used)
            //toSign = @"POST\n56487EFE04B9981AB97DE7D20353F298\napplication/atom+xml\nTue, 29 Jan 2019 22:38:48 GMT\n/roschmi01/Tables()";

            /*
             * wifi.CreateRamFile("fileSHA256", Convert.FromBase64String(_account.AccountKey));
             * string strSHA256Hash = Encoding.UTF8.GetString(Program.wifi.ComputeHash("2", "fileSHA256")).Substring(7);
             * byte[] theHmac = Convert.FromBase64String(strSHA256Hash);
             */
            //var theHmac = wifi.ComputeHash("2", "fileSHA256");
            #endregion

            //long startTime = DateTime.Now.Ticks;

            //RoSchmi debugging
            //byte[] decodedKey = Convert.FromBase64String(_account.AccountKey);

            var hmac      = new PervasiveDigital.Security.ManagedProviders.HMACSHA256(Convert.FromBase64String(_account.AccountKey));
            var hmacBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(toSign));
            signature = Convert.ToBase64String(hmacBytes).Replace("!", "+").Replace("*", "/");

            /*
             * var hmac = new PervasiveDigital.Security.ManagedProviders.HMACSHA256(Convert.FromBase64String(_account.AccountKey));
             * var hmacBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes("Roland"));
             * signature = Convert.ToBase64String(hmacBytes).Replace("!", "+").Replace("*", "/");
             */


            // long endTime = DateTime.Now.Ticks;
            // Debug.WriteLine("Needed for MD5SHA256-hash: " + ((endTime - startTime) / TimeSpan.TicksPerMillisecond).ToString());  // about 160 ms



            if (useSharedKeyLite)
            {
                return("SharedKeyLite " + _account.AccountName + ":" + signature);
            }
            else
            {
                return("SharedKey " + _account.AccountName + ":" + signature);
            }
        }
        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);
            }
        }
 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));
 }
        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);
            }
        }
        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);
            }
        }
Example #10
0
        protected string CreateTableAuthorizationHeader(byte[] content, string canonicalResource, string ptimeStamp, string pHttpVerb, ContType pContentType, out string pMD5Hash, bool useSharedKeyLite = false)
        {
            string contentType = getContentTypeString(pContentType);

            pMD5Hash = string.Empty;
            if (!useSharedKeyLite)
            {
                pMD5Hash = MD5ComputeHash(content);
            }

            string toSign = string.Empty;

            if (useSharedKeyLite)
            {
                toSign = StringUtilities.Format("{0}\n{1}", ptimeStamp, canonicalResource);
            }
            else
            {
                toSign = StringUtilities.Format("{0}\n{4}\n{1}\n{2}\n{3}", pHttpVerb, contentType, ptimeStamp, canonicalResource, pMD5Hash);
            }

            string signature;
            var    hmac      = new HMACSHA256(Convert.FromBase64String(_account.AccountKey));
            var    hmacBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(toSign));

            signature = Convert.ToBase64String(hmacBytes).Replace("!", "+").Replace("*", "/");;
            if (useSharedKeyLite)
            {
                return("SharedKeyLite " + _account.AccountName + ":" + signature);
            }
            else
            {
                return("SharedKey " + _account.AccountName + ":" + signature);
            }
        }
Example #11
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);
            }
        }
Example #12
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);
            }
        }