public Tracker(string accountName, string keyValue)
        {
            _applicationId = IdUtil.ApplicationId();
            _deviceId = IdUtil.DeviceId();
            _anid = IdUtil.GetAnidFromOs();
            _appTitle = IdUtil.ApplicationName();
            _adsRefreshRate = 3;
            _pubCenterAdsId = new List<string>();
            _adsReady = false;

            // Due to Disallowed key in RowKey, /, \, #, ? needs to be removed
            // And excel cannot allow "=" at the beginning
            foreach (var s in _invalidRowKeyChar) {
                _deviceId = _deviceId.Replace(s, string.Empty);
                if (_deviceId.Substring(0, 1) == "=") {
                    _deviceId = "x" + _deviceId;
                }
            }

            GetAdAssemblyVersion();
            RefreshIpInfo();

            _storageCredentials = new StorageCredentials(accountName, keyValue);
            _storageAccount = new CloudStorageAccount(_storageCredentials, false);
            _tableClient = _storageAccount.CreateCloudTableClient();

            EnsureTablesCreated();
        }
Example #2
0
 public TestCacheStats(TestResultStorage testResultStorage, CloudTableClient tableClient)
 {
     _testResultStorage = testResultStorage;
     _unitTestCounterUtil = new CounterUtil<UnitTestCounterEntity>(tableClient.GetTableReference(AzureConstants.TableNames.CounterUnitTestQuery));
     _testCacheCounterUtil = new CounterUtil<TestCacheCounterEntity>(tableClient.GetTableReference(AzureConstants.TableNames.CounterTestCache));
     _testRunCounterUtil = new CounterUtil<TestRunCounterEntity>(tableClient.GetTableReference(AzureConstants.TableNames.CounterTestRun));
 }
        private static RESTCommand<TableQuerySegment> QueryImpl(TableQuery query, TableContinuationToken token, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            UriQueryBuilder builder = query.GenerateQueryBuilder();

            if (token != null)
            {
                token.ApplyToUriQueryBuilder(builder);
            }

            StorageUri tempUriList = NavigationHelper.AppendPathToUri(client.StorageUri, tableName);
            RESTCommand<TableQuerySegment> queryCmd = new RESTCommand<TableQuerySegment>(client.Credentials, tempUriList);
            requestOptions.ApplyToStorageCommand(queryCmd);

            queryCmd.CommandLocationMode = CommonUtility.GetListingLocationMode(token);
            queryCmd.RetrieveResponseStream = true;
            queryCmd.Handler = client.AuthenticationHandler;
            queryCmd.BuildClient = HttpClientFactory.BuildHttpClient;
            queryCmd.Builder = builder;
            queryCmd.BuildRequest = (cmd, uri, queryBuilder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableQuery(uri, builder, serverTimeout, cnt, ctx);
            queryCmd.PreProcessResponse = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp.StatusCode, null /* retVal */, cmd, ex);
            queryCmd.PostProcessResponse = async (cmd, resp, ctx) =>
            {
                TableQuerySegment resSeg = await TableOperationHttpResponseParsers.TableQueryPostProcess(cmd.ResponseStream, resp, ctx);
                if (resSeg.ContinuationToken != null)
                {
                    resSeg.ContinuationToken.TargetLocation = cmd.CurrentResult.TargetLocation;
                }

                return resSeg;
            };

            return queryCmd;
        }
 private void CleanupTable(string tableName)
 {
     var account = CloudStorageAccount.DevelopmentStorageAccount;
     var cloudTableClient = new CloudTableClient(account.TableEndpoint, account.Credentials);
     var table = cloudTableClient.GetTableReference(tableName);
     table.DeleteIfExists();
 }
Example #5
0
 protected CloudCoreStoredTable(string accountSonnectionString = "")
 {
     SetAccount(accountSonnectionString);
     cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
     cloudTable = cloudTableClient.GetTableReference(GetType().Name.Replace("Entity", "").Replace("Table", "").ToLower());
     cloudTable.CreateIfNotExists();
 }
Example #6
0
        public HomeController()
        {
            storageAccount = CloudStorageAccount.Parse(
            ConfigurationManager.AppSettings["StorageConnectionString"]);

            tableClient = storageAccount.CreateCloudTableClient();

            table = tableClient.GetTableReference("fouramigos");

            table.CreateIfNotExists();

            blobClient = storageAccount.CreateCloudBlobClient();

            container = blobClient.GetContainerReference("fouramigos");

            container.CreateIfNotExists();

            BlobContainerPermissions permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(permissions);


            //lägga till nya
            //var tablemodels = new TableModel("Brutus", "Uggla") { Location = "T4", Description="Uggla i träd", Type="Foto" };
            //var tablemodels1 = new TableModel("brutus", "Örn") { Location = "T4", Description="Örn som flyger", Type = "Foto" };

            //var opreation = TableOperation.Insert(tablemodels);
            //var operation2 = TableOperation.Insert(tablemodels1);

            //table.Execute(opreation);
            //table.Execute(operation2);
        }
        public TProduct(string affiliate, string code, int qty, bool force_lookup = false)
        {
            ProductCode = code;
            Qty = qty;

            cloud = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("AbundaStorage"));

            client = cloud.CreateCloudTableClient();

            products = client.GetTableReference("Products");
            products.CreateIfNotExists();

            using (var context = new DataBaseDataContext())
            {
                var aff = (from ev in context.Affiliates
                           where ev.code == affiliate
                           select ev).FirstOrDefault();

                merchantID = aff.MerchantID;
                marketplaceID = aff.MarketPlaceID;
                secretKey = aff.SecretKey;
                accessKey = aff.AccessKey;
            }

            var amzResults = PerformAmazonLookup();
        }
        public AzureTableStorageStatusTraceListener(String initializeData) : base(initializeData)
        {
            string connectionString = null;
            string tableName = "status";

            if (initializeData != null)
            {
                foreach (String keyValuePair in initializeData.Split(','))
                {
                    String[] parts = keyValuePair.Split('*');
                    if (parts.Length == 2)
                    {
                        if (parts[0].Equals("tablestorage", StringComparison.InvariantCultureIgnoreCase))
                        {
                            connectionString = parts[1].Trim();
                        }
                        else if (parts[0].Equals("table", StringComparison.InvariantCultureIgnoreCase))
                        {
                            tableName = parts[1].Trim();
                        }
                    }
                }
            }

            if (String.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException("tablestorage", "The initializeData string must specify the Azure table storage connection string in the tablestorage field.");
            }

            this._storageAccount = CloudStorageAccount.Parse(connectionString);
            this._tableClient = this._storageAccount.CreateCloudTableClient();
            this._table = this._tableClient.GetTableReference(tableName);
            this._table.CreateIfNotExists();
        }
 static NDIAzureTableController()
 {
     _storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
     _tableClient = _storageAccount.CreateCloudTableClient();
     _table = _tableClient.GetTableReference("ndiparams");
     _retrieveOperation = TableOperation.Retrieve("VidParams", "LastVideo");
 }
 public StorageTableAccessor(CloudStorageAccount storageAccount)
 {
     CloudTableClient tableClient = new CloudTableClient(storageAccount.TableStorageUri, storageAccount.Credentials);
     this.table = tableClient.GetTableReference(messageTableName);
     this.table.CreateIfNotExists();
     ReadFirstEntry();
 }
 public AzureTableStorage(string connectionString, string tableName)
 {
     this._storageAccount = CloudStorageAccount.Parse(connectionString);
     this._tableClient = this._storageAccount.CreateCloudTableClient();
     this._table = this._tableClient.GetTableReference(tableName);
     this._table.CreateIfNotExists();
 }
 public AuditAzureTableProvider()
 {
     try
     {
         _account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageConnectionString"]);
         _client = _account.CreateCloudTableClient();
     }
     catch (Exception exp)
     {
         throw new Exception("Error retreiving reference to Azure Storage Account", exp);
     }
     try
     {
         _client = _account.CreateCloudTableClient();
     }
     catch (Exception exp)
     {
         throw new Exception("Error creating Azure Table Client Object", exp);
     }
     try
     {
         _vmAuditTable = _client.GetTableReference("VMAudits");
     }
     catch (Exception exp)
     {
         throw new Exception("Error retreiving reference to Azure Table Object", exp);
     }
 }
Example #13
0
        private void Init()
        {
            Trace.TraceInformation("Starting initialization.");
            Account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings[Constants.ConfigurationSectionKey]);
            TableClient = Account.CreateCloudTableClient();

            Container = Account.CreateCloudBlobClient().GetContainerReference(Constants.ContainerName);

            BlobContainerPermissions blobPermissions = new BlobContainerPermissions();
            blobPermissions.SharedAccessPolicies.Add(ConfigurationManager.AppSettings["AccountId"], new SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(10),
                Permissions = SharedAccessBlobPermissions.Write |
                   SharedAccessBlobPermissions.Read
            });
            blobPermissions.PublicAccess = BlobContainerPublicAccessType.Off;

            // Set the permission policy on the container.
            Container.SetPermissions(blobPermissions);

            SasToken = Container.GetSharedAccessSignature(new SharedAccessBlobPolicy(), ConfigurationManager.AppSettings["AccountId"]);

            BlobBaseUri = Account.BlobEndpoint;
            Trace.TraceInformation("Initialization finished.");
        }
 public BlobStorageManager(string blobConnectionEndPointString)
 {
     this.blobConnectionEndPointString = blobConnectionEndPointString;
     CloudStorageAccount VP2ClientBlobStorageAccount = CloudStorageAccount.Parse(blobConnectionEndPointString);
     VP2CloudBlobClient = VP2ClientBlobStorageAccount.CreateCloudBlobClient();
     VP2CloudTableClient = VP2ClientBlobStorageAccount.CreateCloudTableClient();
 }
Example #15
0
        public virtual void Initialize()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            tableClient = storageAccount.CreateCloudTableClient();
        }
Example #16
0
 public SensorAccess()
 {
     credentials = new StorageCredentials(_accountName, _key);
     storageAccount = new CloudStorageAccount(credentials, true);
     tableClient = storageAccount.CreateCloudTableClient();
     table = tableClient.GetTableReference("AccelerometerTable");
 }
        static void CreateCustomerMetadata(CloudTableClient tableClient)
        {
            Console.WriteLine("Creating customers metadata...");

            CloudTable customersMetadataTable = tableClient.GetTableReference("customersmetadata");
            customersMetadataTable.CreateIfNotExists();

            var msftAddress1 = new DictionaryTableEntity();
            msftAddress1.PartitionKey = "MSFT";
            msftAddress1.RowKey = "ADDRESS-" + Guid.NewGuid().ToString("N").ToUpper();
            msftAddress1.Add("city", "Seattle");
            msftAddress1.Add("street", "111 South Jackson");

            var msftWebsite1 = new DictionaryTableEntity();
            msftWebsite1.PartitionKey = "MSFT";
            msftWebsite1.RowKey = "WEBSITE-" + Guid.NewGuid().ToString("N").ToUpper();
            msftWebsite1.Add("url", "http://www.microsoft.com");

            var msftWebsite2 = new DictionaryTableEntity();
            msftWebsite2.PartitionKey = "MSFT";
            msftWebsite2.RowKey = "WEBSITE-" + Guid.NewGuid().ToString("N").ToUpper();
            msftWebsite2.Add("url", "http://www.windowsazure.com");

            var batch = new TableBatchOperation();
            batch.Add(TableOperation.Insert(msftAddress1));
            batch.Add(TableOperation.Insert(msftWebsite1));
            batch.Add(TableOperation.Insert(msftWebsite2));
            customersMetadataTable.ExecuteBatch(batch);

            Console.WriteLine("Done. Press ENTER to read the customer metadata.");
            Console.ReadLine();
        }
Example #18
0
 public static CloudTableClient GenerateCloudTableClient()
 {
     Uri baseAddressUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint);
     CloudTableClient client = new CloudTableClient(baseAddressUri, TestBase.StorageCredentials);
     client.AuthenticationScheme = DefaultAuthenticationScheme;
     return client;
 }
        private CloudTableClient GetCloudTableClient(string sasUrl)
        {
            int parseIndex = sasUrl.IndexOf('?');
            if (parseIndex > 0)
            {
                string tableAddress = sasUrl.Substring(0, parseIndex);

                int tableParseIndex = tableAddress.LastIndexOf('/');
                if (tableParseIndex > 0)
                {
                    tableName = tableAddress.Substring(tableParseIndex + 1);

                    string endpointAddress = tableAddress.Substring(0, tableParseIndex);
                    string sasSignature = sasUrl.Substring(parseIndex);

                    var tableClient = new CloudTableClient(new Uri(endpointAddress), new StorageCredentials(sasSignature));

                    // This is a hack for the Azure Storage SDK to make it work with version 2012 SAS urls as long as we support them.
                    // Apply hack only if the SAS url is version 2012.
                    if (sasSignature.IndexOf("sv=2012-02-12", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        tableClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.AtomPub;
                        var type = typeof(TableConstants);
                        var field = type.GetField("ODataProtocolVersion", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                        field.SetValue(null, ODataVersion.V2);
                    }

                    return tableClient;
                }
            }

            return null;
        }
        private TableHelpers()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("forgeanalytics_AzureStorageConnectionString"));

            // Create the table client.
            client = storageAccount.CreateCloudTableClient();
        }
        public Mock<ICloudStorageServices> Build()
        {
            var cloudStorageServices = new Mock<ICloudStorageServices>();
            var cloudTableClient = new CloudTableClient(new Uri("http://www.example.com/"));
            cloudStorageServices.SetupGet(x => x.CloudTableClient).Returns(cloudTableClient);

            return cloudStorageServices;
        }
Example #22
0
        public AzureEventStore(CloudStorageAccount account, string tableName)
        {
            this.account = account;
            this.client = account.CreateCloudTableClient();
            this.tableName = tableName;

            this.created = false;
        }
        internal TableResult Execute(CloudTableClient client, CloudTable table, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            TableRequestOptions modifiedOptions = TableRequestOptions.ApplyDefaults(requestOptions, client);
            operationContext = operationContext ?? new OperationContext();
            CommonUtility.AssertNotNullOrEmpty("tableName", table.Name);

            return Executor.ExecuteSync(this.GenerateCMDForOperation(client, table, modifiedOptions), modifiedOptions.RetryPolicy, operationContext);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudTable"/> class.
 /// </summary>
 /// <param name="tableName">The table name.</param>
 /// <param name="client">The client.</param>
 internal CloudTable(string tableName, CloudTableClient client)
 {
     CommonUtility.AssertNotNull("tableName", tableName);
     CommonUtility.AssertNotNull("client", client);
     this.Name = tableName;
     this.Uri = NavigationHelper.AppendPathToUri(client.BaseUri, tableName);
     this.ServiceClient = client;
 }
 public TableStorageRegistry()
 {
     var storageConnectionString = ConfigurationHelper.GetConfigValue<string>("StorageConnectionString");
     var storageClient = CloudStorageAccount.Parse(storageConnectionString);
     _client = storageClient.CreateCloudTableClient();
     _table = _client.GetTableReference(TableName);
     _table.CreateIfNotExists();
 }
Example #26
0
        public static void Initialize(string storageConnectionString)
        {
            // Get storage account
            _storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            // Create the clients
            _tableClient = _storageAccount.CreateCloudTableClient();
        }
        private async Task StartAsync(CloudStorageAccount cloudStorageAccount, string tableName)
        {
            _cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
            _cloudTable = _cloudTableClient.GetTableReference(tableName);

            // create container if it does not exist on startup
            await _cloudTable.CreateIfNotExistAsync();
        }
        public TableHelper(string storageAccountConnectionString)
            : base(storageAccountConnectionString)
        {

            tableClient = base.StorageAccount.CreateCloudTableClient();
            mailingListTable = tableClient.GetTableReference(ConfigurationManager.AppSettings["TableMailinglist"]);
            mailingListTable.CreateIfNotExists();
        }
 public AzureTableReplyChannel(BufferManager bufferManager, MessageEncoderFactory encoderFactory, EndpointAddress address,
    AzureTableReplyChannelListener parent, CloudTableClient cloudTableClient, string tableName, string partitionKey,
     TimeSpan idleSleep, TimeSpan activeSleep)
     : base(bufferManager, encoderFactory, address, parent, parent.MaxReceivedMessageSize, cloudTableClient, tableName, 
     partitionKey, idleSleep, activeSleep)
 {
     this.localAddress = address;
 }
        public StreamstoneEventStoreInitializator(string storageAccountConnectionString)
        {
            if (string.IsNullOrWhiteSpace(storageAccountConnectionString))
                throw new ArgumentNullException("storageAccountConnectionString");

            var account = CloudStorageAccount.Parse(storageAccountConnectionString);
            tableClient = account.CreateCloudTableClient();
        }
Example #31
0
        public async Task <JsonResult> GetExceptionLogChart(string SDate, string EDate)
        {
            string TotalSolved = String.Empty; string TotalUnSolved = String.Empty; string Dates = String.Empty;
            List <SolutionProvidedReportValues> IsSolvedRecordJson = new List <SolutionProvidedReportValues>();
            List <SolutionResult> ResultRecordJson = new List <SolutionResult>();

            try
            {
                string a = Convert.ToString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                // Create the table client.
                Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                // Retrieve a reference to the table.
                // CloudTable table = tableClient.GetTableReference("SolutionProvidedReport");
                table = tableClient.GetTableReference("ExceptionLog");

                await table.CreateIfNotExistsAsync();

                string   StartdateString = SDate; //"2018-10-25T00:00:00.000Z";
                string   EnddateString   = EDate; // "2018-11-10T00:00:00.000Z";
                DateTime StartDate       = DateTime.Parse(StartdateString, System.Globalization.CultureInfo.InvariantCulture);
                DateTime EndDate         = DateTime.Parse(EnddateString, System.Globalization.CultureInfo.InvariantCulture);

                List <SolutionProvidedReport> SutdentListObj = RetrieveEntity <SolutionProvidedReport>();
                var SutdentListObj1 = SutdentListObj.Where(item => item.Timestamp >= StartDate && item.Timestamp <= EndDate).OrderByDescending(item => item.Timestamp).GroupBy(item => item.Timestamp.Date).ToList();

                foreach (var singleData in SutdentListObj1)
                {
                    SolutionProvidedReportValues DataList = new SolutionProvidedReportValues();
                    SolutionResult resultdata             = new SolutionResult();
                    DataList.Timestamp1   = (singleData.Key).ToString();
                    DataList.ExceptionLog = singleData.Count();

                    // resultdata.TotalNoRating += DataList.FailedTicket; //+ ", ";
                    resultdata.ExceptionLogCount += DataList.ExceptionLog;                                      // + ", ";
                    resultdata.Dates             += Convert.ToDateTime(DataList.Timestamp1).ToString("dd MMM"); // + ", ";

                    ResultRecordJson.Add(resultdata);
                    //IsSolvedRecordJson.Add(DataList);
                }
            }
            catch (Exception ex)
            {
                Utility.Utility.GenrateLog(ex.Message);
            }
            finally
            {
            }
            var output = JsonConvert.SerializeObject(ResultRecordJson);

            // var resultData = new {TotalSolved = TotalSolved, TotalUnSolved = TotalUnSolved, Dates = Dates };

            // return Json(resultData, JsonRequestBehavior.AllowGet);
            //return Json(c, JsonRequestBehavior.AllowGet);
            return(Json(output, JsonRequestBehavior.AllowGet));
        }
        static async Task <Microsoft.WindowsAzure.Storage.Table.CloudTable> GetTable(string tableName)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                Constants.StorageConnection);

            Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            Microsoft.WindowsAzure.Storage.Table.CloudTable       table       = tableClient.GetTableReference(tableName);
            await table.CreateIfNotExistsAsync();

            return(table);
        }
Example #33
0
        public TagIdGroupBolt()
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = GetStorageAccount();

            // Create the table client.
            Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            this.table = tableClient.GetTableReference("tagId");

            this.table.CreateIfNotExists();
        }
        public ReportGroupCompletnessBolt()
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = GetStorageAccount();

            // Create the table client.
            Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            this.table = tableClient.GetTableReference("reportCompletness");

            this.table.CreateIfNotExists();
        }
        public ActionResult userquestion(string SDate, string EDate, string Userid)
        {
            string TotalSolved = String.Empty; string TotalUnSolved = String.Empty; string Dates = String.Empty;
            List <SolutionProvidedReportValues> IsSolvedRecordJson = new List <SolutionProvidedReportValues>();
            List <SolutionResult> ResultRecordJson = new List <SolutionResult>();
            DataTable             dt = new DataTable();

            dt.Clear();
            dt.Columns.Add("Userid");
            dt.Columns.Add("Issue");
            dt.Columns.Add("Dates");
            dt.Columns.Add("Status");
            dt.Columns.Add("TotalRating");

            try
            {
                string a = Convert.ToString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                table = tableClient.GetTableReference("SolutionProvidedReport");
                string   StartdateString = SDate; //"2018-10-25T00:00:00.000Z";
                string   EnddateString   = EDate; //"2018-11-10T00:00:00.000Z";
                DateTime StartDate       = DateTime.Parse(StartdateString, System.Globalization.CultureInfo.InvariantCulture);
                DateTime EndDate         = DateTime.Parse(EnddateString, System.Globalization.CultureInfo.InvariantCulture);

                List <SolutionProvidedReport> SutdentListObj = RetrieveEntity <SolutionProvidedReport>();
                var SutdentListObj1 = SutdentListObj.Where(item => (item.Timestamp >= StartDate && item.Timestamp <= EndDate) && item.UserId == Userid).OrderByDescending(item => item.Timestamp).ToList();

                foreach (var singleData in SutdentListObj1)
                {
                    DataRow _rvi = dt.NewRow();
                    _rvi["Userid"]      = singleData.UserId;
                    _rvi["Issue"]       = singleData.Issue;
                    _rvi["Status"]      = singleData.IsSolved;
                    _rvi["TotalRating"] = singleData.Rating;
                    _rvi["Dates"]       = Convert.ToDateTime(singleData.Timestamp.DateTime).ToString("dd-MMM-yyyy");
                    dt.Rows.Add(_rvi);
                }
            }
            catch (Exception ex)
            {
                Utility.Utility.GenrateLog(ex.Message);
            }
            finally
            {
            }
            if (dt.Rows.Count > 0)
            {
                ExcelExport(dt, SDate, EDate, "userquestion_" + Userid + "_");
            }
            return(Redirect("/top10/top10"));
        }
Example #36
0
        public WordCountBolt()
        {
            name = (new Random(DateTime.Now.Millisecond)).Next();

            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = GetStorageAccount();

            // Create the table client.
            Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            this.table = tableClient.GetTableReference("wordcount");

            this.table.CreateIfNotExists();
        }
Example #37
0
        public async Task SaveBench(WalkToSave entityToSave)
        {
            CloudStorageAccount account     = CloudStorageAccount.Parse(_storageConfig.TableConnectionString);
            CloudTableClient    tableClient = account.CreateCloudTableClient();
            CloudTable          table       = tableClient.GetTableReference(_storageConfig.MetadataTableName);
            await table.CreateIfNotExistsAsync();

            var result = await InsertEntity(table, entityToSave);

            if (result.HttpStatusCode != (int)HttpStatusCode.NoContent)
            {
                throw new ApplicationException("Failed to insert entity in database.");
            }
        }
Example #38
0
        public async Task <JsonResult> GetTop10DetectedIntent(string SDate, string EDate)
        {
            string TotalSolved = String.Empty; string TotalUnSolved = String.Empty; string Dates = String.Empty;
            List <SolutionProvidedReportValues> IsSolvedRecordJson = new List <SolutionProvidedReportValues>();
            List <SolutionResult> ResultRecordJson = new List <SolutionResult>();

            try
            {
                string a = Convert.ToString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                // Create the table client.
                Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                // Retrieve a reference to the table.
                // CloudTable table = tableClient.GetTableReference("SolutionProvidedReport");
                table = tableClient.GetTableReference("SolutionProvidedReport");

                await table.CreateIfNotExistsAsync();

                string   StartdateString = SDate;
                string   EnddateString   = EDate;
                DateTime StartDate       = DateTime.Parse(StartdateString, System.Globalization.CultureInfo.InvariantCulture);
                DateTime EndDate         = DateTime.Parse(EnddateString, System.Globalization.CultureInfo.InvariantCulture);

                List <SolutionProvidedReport> SutdentListObj = RetrieveEntity <SolutionProvidedReport>();
                var SutdentListObj1 = SutdentListObj.Where(item => item.Timestamp >= StartDate && item.Timestamp <= EndDate).OrderByDescending(item => item.Timestamp).GroupBy(item => item.DetectedIntent).Take(10).OrderByDescending(g => g.Count()).ToList();

                foreach (var singleData in SutdentListObj1)
                {
                    SolutionProvidedReportValues DataList = new SolutionProvidedReportValues();
                    SolutionResult resultdata             = new SolutionResult();
                    DataList.DetectedIntent         = (singleData.Key).ToString();
                    DataList.Values                 = singleData.Count();
                    resultdata.DetectedIntent      += DataList.DetectedIntent;
                    resultdata.DetectedIntentCount += DataList.Values;
                    ResultRecordJson.Add(resultdata);
                }
            }
            catch (Exception ex)
            {
                Utility.Utility.GenrateLog(ex.Message);
            }
            finally
            {
            }
            var output = JsonConvert.SerializeObject(ResultRecordJson);

            return(Json(output, JsonRequestBehavior.AllowGet));
        }
        public ActionResult Top10DetectedIntentExport(string SDate, string EDate)
        {
            string TotalSolved = String.Empty; string TotalUnSolved = String.Empty; string Dates = String.Empty;
            List <SolutionProvidedReportValues> IsSolvedRecordJson = new List <SolutionProvidedReportValues>();
            List <SolutionResult> ResultRecordJson = new List <SolutionResult>();
            DataTable             dt = new DataTable();

            dt.Clear();
            dt.Columns.Add("DetectedIntent");
            dt.Columns.Add("DetectedIntentCount");
            try
            {
                string a = Convert.ToString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                table = tableClient.GetTableReference("SolutionProvidedReport");
                string   StartdateString = SDate; //"2018-10-25T00:00:00.000Z";
                string   EnddateString   = EDate; //"2018-11-10T00:00:00.000Z";
                DateTime StartDate       = DateTime.Parse(StartdateString, System.Globalization.CultureInfo.InvariantCulture);
                DateTime EndDate         = DateTime.Parse(EnddateString, System.Globalization.CultureInfo.InvariantCulture);

                List <SolutionProvidedReport> SutdentListObj = RetrieveEntity <SolutionProvidedReport>();
                var SutdentListObj1 = SutdentListObj.Where(item => item.Timestamp >= StartDate && item.Timestamp <= EndDate).OrderByDescending(item => item.Timestamp).GroupBy(item => item.DetectedIntent).Take(10).OrderByDescending(g => g.Count()).ToList();

                foreach (var singleData in SutdentListObj1)
                {
                    SolutionProvidedReportValues DataList = new SolutionProvidedReportValues();
                    DataList.DetectedIntent = (singleData.Key).ToString();
                    DataList.Values         = singleData.Count();
                    DataRow _rvi = dt.NewRow();
                    _rvi["DetectedIntent"]      = DataList.DetectedIntent;
                    _rvi["DetectedIntentCount"] = DataList.Values;
                    dt.Rows.Add(_rvi);
                }
            }
            catch (Exception ex)
            {
                Utility.Utility.GenrateLog(ex.Message);
            }
            finally
            {
            }
            if (dt.Rows.Count > 0)
            {
                ExcelExport(dt, SDate, EDate, "TOP10DetectedIntent");
            }
            return(Redirect("/top10/top10"));
        }
        public Microsoft.WindowsAzure.Storage.Table.CloudTable GetTable(string tableName)
        {
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                StorageConnectionString);

            ServicePoint tableServicePoint = ServicePointManager.FindServicePoint(storageAccount.TableEndpoint);

            tableServicePoint.UseNagleAlgorithm = false;

            Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the table if it doesn't exist.
            CloudTable table = tableClient.GetTableReference(tableName);

            table.CreateIfNotExistsAsync().Wait();

            return(table);
        }
Example #41
0
        public async Task <List <WalkToSave> > GetAllEntities()
        {
            CloudStorageAccount account     = CloudStorageAccount.Parse(_storageConfig.TableConnectionString);
            CloudTableClient    tableClient = account.CreateCloudTableClient();
            CloudTable          table       = tableClient.GetTableReference(_storageConfig.MetadataTableName);
            await table.CreateIfNotExistsAsync();

            var query = new TableQuery <WalkToSave>();

            var entities = new List <WalkToSave>();
            TableContinuationToken         token         = null;
            TableQuerySegment <WalkToSave> resultSegment = null;

            do
            {
                resultSegment = await table.ExecuteQuerySegmentedAsync <WalkToSave>(query, token);

                entities.AddRange(resultSegment.Results.OfType <WalkToSave>());
                token = resultSegment.ContinuationToken;
            }while (token != null);

            return(entities);
        }
Example #42
0
        public Boolean UserAuthentication(string UserId, string Password)
        {
            Boolean _result = false;
            string  TotalSolved = String.Empty; string TotalUnSolved = String.Empty; string Dates = String.Empty;
            List <SolutionProvidedReportValues> IsSolvedRecordJson = new List <SolutionProvidedReportValues>();
            List <SolutionResult> ResultRecordJson = new List <SolutionResult>();

            try
            {
                string a = Convert.ToString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

                Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                table = tableClient.GetTableReference("ReportsUsers");

                // await table.CreateIfNotExistsAsync();

                List <HomeLoginViewModel> SutdentListObj = RetrieveEntity <HomeLoginViewModel>();

                var SutdentListObj1 = SutdentListObj.Where(item => item.Username == UserId && item.Password == Password).ToList();

                if (SutdentListObj1.Count > 0)
                {
                    _result = true;
                }
            }
            catch (Exception ex)
            {
                Utility.Utility.GenrateLog(ex.Message);
            }
            finally
            {
            }

            return(_result);
        }
        private static RESTCommand <TableResult> RetrieveImpl(TableOperation operation, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions)
        {
            requestOptions.AssertPolicyIfRequired();

            RESTCommand <TableResult> retrieveCmd = new RESTCommand <TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, table.Name));

            requestOptions.ApplyToStorageCommand(retrieveCmd);

            TableResult result = new TableResult();

            if (operation.SelectColumns != null && operation.SelectColumns.Count > 0)
            {
                // If encryption policy is set, then add the encryption metadata column to Select columns in order to be able to decrypt properties.
                if (requestOptions.EncryptionPolicy != null)
                {
                    operation.SelectColumns.Add(Constants.EncryptionConstants.TableEncryptionKeyDetails);
                    operation.SelectColumns.Add(Constants.EncryptionConstants.TableEncryptionPropertyDetails);
                }

                retrieveCmd.Builder = operation.GenerateQueryBuilder(requestOptions.ProjectSystemProperties);
            }

            retrieveCmd.CommandLocationMode    = operation.isPrimaryOnlyRetrieve ? CommandLocationMode.PrimaryOnly : CommandLocationMode.PrimaryOrSecondary;
            retrieveCmd.RetrieveResponseStream = true;
            retrieveCmd.SignRequest            = client.AuthenticationHandler.SignRequest;
            retrieveCmd.ParseError             = ODataErrorHelper.ReadFromStreamUsingODataLib;
            retrieveCmd.BuildRequestDelegate   = (uri, builder, timeout, useVersionHeader, ctx) => TableOperationHttpWebRequestFactory.BuildRequestForTableOperation(uri, builder, client.BufferManager, timeout, operation, useVersionHeader, ctx, requestOptions, client.AccountName).Item1;
            retrieveCmd.PreProcessResponse     = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex);
            retrieveCmd.PostProcessResponse    = (cmd, resp, ctx) =>
            {
                if (resp.StatusCode == HttpStatusCode.NotFound)
                {
                    return(result);
                }

                result = TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx, requestOptions, client.AccountName);
                return(result);
            };

            return(retrieveCmd);
        }
        public static async Task MyClassInitialize(TestContext testContext)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();

            currentTable = tableClient.GetTableReference(GenerateRandomTableName());
            await currentTable.CreateIfNotExistsAsync();

            // Bulk Query Entities
            for (int i = 0; i < 15; i++)
            {
                TableBatchOperation batch = new TableBatchOperation();

                for (int j = 0; j < 100; j++)
                {
                    var ent = GenerateRandomEnitity("tables_batch_" + i.ToString());
                    ent.RowKey = string.Format("{0:0000}", j);
                    batch.Insert(ent);
                }

                await currentTable.ExecuteBatchAsync(batch);
            }


            complexEntityTable = tableClient.GetTableReference(GenerateRandomTableName());
            await complexEntityTable.CreateAsync();

            // Setup
            TableBatchOperation complexBatch = new TableBatchOperation();
            string pk = Guid.NewGuid().ToString();

            for (int m = 0; m < 100; m++)
            {
                ComplexEntity complexEntity = new ComplexEntity(pk, string.Format("{0:0000}", m));
                complexEntity.String            = string.Format("{0:0000}", m);
                complexEntity.Binary            = new byte[] { 0x01, 0x02, (byte)m };
                complexEntity.BinaryPrimitive   = new byte[] { 0x01, 0x02, (byte)m };
                complexEntity.Bool              = m % 2 == 0 ? true : false;
                complexEntity.BoolPrimitive     = m % 2 == 0 ? true : false;
                complexEntity.Double            = m + ((double)m / 100);
                complexEntity.DoublePrimitive   = m + ((double)m / 100);
                complexEntity.Int32             = m;
                complexEntity.Int32N            = m;
                complexEntity.IntegerPrimitive  = m;
                complexEntity.IntegerPrimitiveN = m;
                complexEntity.Int64             = (long)int.MaxValue + m;
                complexEntity.LongPrimitive     = (long)int.MaxValue + m;
                complexEntity.LongPrimitiveN    = (long)int.MaxValue + m;
                complexEntity.Guid              = Guid.NewGuid();

                complexBatch.Insert(complexEntity);

                if (m == 50)
                {
                    middleRef = complexEntity;
                }

                // Add delay to make times unique
                Thread.Sleep(100);
            }

            await complexEntityTable.ExecuteBatchAsync(complexBatch);
        }
 internal Task <IList <TableResult> > ExecuteAsync(CloudTableClient client, string tableName, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
        private static RESTCommand <IList <TableResult> > BatchImpl(TableBatchOperation batch, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand <IList <TableResult> > batchCmd = new RESTCommand <IList <TableResult> >(client.Credentials, client.StorageUri);

            requestOptions.ApplyToStorageCommand(batchCmd);

            List <TableResult> results = new List <TableResult>();

            batchCmd.CommandLocationMode    = batch.ContainsWrites ? CommandLocationMode.PrimaryOnly : CommandLocationMode.PrimaryOrSecondary;
            batchCmd.RetrieveResponseStream = true;
            batchCmd.Handler             = client.AuthenticationHandler;
            batchCmd.BuildClient         = HttpClientFactory.BuildHttpClient;
            batchCmd.ParseError          = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            batchCmd.BuildRequest        = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableBatchOperation(cmd, uri, builder, serverTimeout, tableName, batch, client, cnt, ctx, requestOptions.PayloadFormat.Value);
            batchCmd.PreProcessResponse  = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.Accepted, resp.StatusCode, results, cmd, ex);
            batchCmd.PostProcessResponse = (cmd, resp, ctx) => TableOperationHttpResponseParsers.TableBatchOperationPostProcess(results, batch, cmd, resp, ctx, requestOptions, client.AccountName);
            batchCmd.RecoveryAction      = (cmd, ex, ctx) => results.Clear();

            return(batchCmd);
        }
Example #47
0
        public async Task CloudTableTestValidCorsRulesAsync()
        {
            CorsRule ruleMinRequired = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.xyz.com"
                },
                AllowedMethods = CorsHttpMethods.Get
            };

            CorsRule ruleBasic = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.ab.com", "www.bc.com"
                },
                AllowedMethods  = CorsHttpMethods.Get | CorsHttpMethods.Put,
                MaxAgeInSeconds = 500,
                ExposedHeaders  =
                    new List <string>()
                {
                    "x-ms-meta-data*",
                    "x-ms-meta-source*",
                    "x-ms-meta-abc",
                    "x-ms-meta-bcd"
                },
                AllowedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-data*",
                    "x-ms-meta-target*",
                    "x-ms-meta-xyz",
                    "x-ms-meta-foo"
                }
            };

            CorsRule ruleAllMethods = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.xyz.com"
                },
                AllowedMethods =
                    CorsHttpMethods.Put | CorsHttpMethods.Trace
                    | CorsHttpMethods.Connect | CorsHttpMethods.Delete
                    | CorsHttpMethods.Get | CorsHttpMethods.Head
                    | CorsHttpMethods.Options | CorsHttpMethods.Post
                    | CorsHttpMethods.Merge
            };

            CorsRule ruleSingleExposedHeader = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                ExposedHeaders = new List <string>()
                {
                    "x-ms-meta-bcd"
                },
            };

            CorsRule ruleSingleExposedPrefixHeader = new CorsRule()
            {
                AllowedOrigins =
                    new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                ExposedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-data*"
                },
            };

            CorsRule ruleSingleAllowedHeader = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders = new List <string>()
                {
                    "x-ms-meta-xyz",
                },
            };

            CorsRule ruleSingleAllowedPrefixHeader = new CorsRule()
            {
                AllowedOrigins =
                    new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-target*"
                },
            };

            CorsRule ruleAllowAll = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "*"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders = new List <string>()
                {
                    "*"
                },
                ExposedHeaders = new List <string>()
                {
                    "*"
                }
            };

            CloudTableClient client = GenerateCloudTableClient();

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleBasic });

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleMinRequired });

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleAllMethods });

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleSingleExposedHeader });

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleSingleExposedPrefixHeader });

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleSingleAllowedHeader });

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleSingleAllowedPrefixHeader });

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleAllowAll });

            // Empty rule set should delete all rules
            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { });

            // Test duplicate rules
            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleBasic, ruleBasic });

            // Test max number of  rules (five)
            await this.TestCorsRulesAsync(
                client,
                null,
                new List <CorsRule>()
            {
                ruleBasic,
                ruleMinRequired,
                ruleAllMethods,
                ruleSingleExposedHeader,
                ruleSingleExposedPrefixHeader
            });


            // Test max number of rules + 1 (six)
            OperationContext context = new OperationContext();
            await TestHelper.ExpectedExceptionAsync(
                async() => await this.TestCorsRulesAsync(
                    client,
                    context,
                    new List <CorsRule>()
            {
                ruleBasic,
                ruleMinRequired,
                ruleAllMethods,
                ruleSingleExposedHeader,
                ruleSingleExposedPrefixHeader,
                ruleSingleAllowedHeader
            }),
                context,
                "Services are limited to a maximum of five CORS rules.",
                HttpStatusCode.BadRequest,
                "InvalidXmlDocument");
        }
Example #48
0
        public async Task <JsonResult> GetAvgRatingReport(string SDate, string EDate)
        {
            string TotalSolved = String.Empty; string TotalUnSolved = String.Empty; string Dates = String.Empty;
            List <SolutionProvidedReportValues> IsSolvedRecordJson = new List <SolutionProvidedReportValues>();
            List <SolutionResult> ResultRecordJson = new List <SolutionResult>();

            try
            {
                string a = Convert.ToString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                // Create the table client.
                Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

                table = tableClient.GetTableReference("SolutionProvidedReport");

                await table.CreateIfNotExistsAsync();

                string   StartdateString = SDate; //"2018-10-25T00:00:00.000Z";
                string   EnddateString   = EDate; // "2018-11-10T00:00:00.000Z";
                DateTime StartDate       = DateTime.Parse(StartdateString, System.Globalization.CultureInfo.InvariantCulture);
                DateTime EndDate         = DateTime.Parse(EnddateString, System.Globalization.CultureInfo.InvariantCulture);

                List <SolutionProvidedReport> SutdentListObj = RetrieveEntity <SolutionProvidedReport>();
                var SutdentListObj1 = SutdentListObj.Where(item => item.Timestamp >= StartDate && item.Timestamp <= EndDate).OrderByDescending(item => item.Timestamp).GroupBy(item => item.Timestamp.Date).ToList();
                //    .Select(g => new {
                //    Date = g.Key,
                //    Count = g.Count(),
                //    Total = g.Sum(i => i.Rating),
                //    Average = g.Average(i => i.Rating)
                //}).ToList();

                foreach (var singleData in SutdentListObj1)
                {
                    SolutionProvidedReportValues DataList = new SolutionProvidedReportValues();
                    SolutionResult resultdata             = new SolutionResult();
                    DataList.Timestamp1 = (singleData.Key).ToString();
                    foreach (var result in singleData)
                    {
                        if (result.Rating > 0)
                        {
                            DataList.RatingTotal += result.Rating;
                            DataList.RatingCount += 1;
                        }
                        else
                        {
                            DataList.isSolvedFalse += 1;
                        }
                    }
                    if (DataList.RatingTotal > 0 && DataList.RatingCount > 0)
                    {
                        resultdata.AvgRating += (DataList.RatingTotal / DataList.RatingCount);
                    }
                    else
                    {
                        resultdata.AvgRating = 0;
                    }

                    resultdata.Dates += Convert.ToDateTime(DataList.Timestamp1).ToString("dd MMM");// + ", ";
                    ResultRecordJson.Add(resultdata);
                }
            }
            catch (Exception ex)
            {
                Utility.Utility.GenrateLog(ex.Message);
            }
            finally
            {
            }
            var output = JsonConvert.SerializeObject(ResultRecordJson);

            return(Json(output, JsonRequestBehavior.AllowGet));
        }
        private static RESTCommand <IList <TableResult> > BatchImpl(TableBatchOperation batch, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions)
        {
            RESTCommand <IList <TableResult> > batchCmd = new RESTCommand <IList <TableResult> >(client.Credentials, client.StorageUri);

            requestOptions.ApplyToStorageCommand(batchCmd);

            List <TableResult> results = new List <TableResult>();

            batchCmd.CommandLocationMode    = batch.ContainsWrites ? CommandLocationMode.PrimaryOnly : CommandLocationMode.PrimaryOrSecondary;
            batchCmd.RetrieveResponseStream = true;
            batchCmd.SignRequest            = client.AuthenticationHandler.SignRequest;
            batchCmd.ParseError             = ODataErrorHelper.ReadFromStreamUsingODataLib;
            batchCmd.BuildRequestDelegate   = (uri, builder, timeout, useVersionHeader, ctx) =>
            {
                Tuple <HttpWebRequest, Stream> res = TableOperationHttpWebRequestFactory.BuildRequestForTableBatchOperation(uri, builder, client.BufferManager, timeout, table.Name, batch, useVersionHeader, ctx, requestOptions);
                batchCmd.SendStream      = res.Item2;
                batchCmd.StreamToDispose = res.Item2;
                return(res.Item1);
            };

            batchCmd.PreProcessResponse  = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.Accepted, resp != null ? resp.StatusCode : HttpStatusCode.Unused, results, cmd, ex);
            batchCmd.PostProcessResponse = (cmd, resp, ctx) => TableOperationHttpResponseParsers.TableBatchOperationPostProcess(results, batch, cmd, resp, ctx, requestOptions, client.AccountName);
            batchCmd.RecoveryAction      = (cmd, ex, ctx) => results.Clear();

            return(batchCmd);
        }
Example #50
0
 internal Task <TableQuerySegment> ExecuteQuerySegmentedAsync(TableContinuationToken continuationToken, CloudTableClient client, string tableName, TableRequestOptions requestOptions, OperationContext operationContext)
 {
     return(ExecuteQuerySegmentedAsync(continuationToken, client, tableName, requestOptions, operationContext, CancellationToken.None));
 }
Example #51
0
        internal Task <TableQuerySegment> ExecuteQuerySegmentedAsync(TableContinuationToken continuationToken, CloudTableClient client, string tableName, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
        {
            CommonUtility.AssertNotNullOrEmpty("tableName", tableName);
            TableRequestOptions modifiedOptions = TableRequestOptions.ApplyDefaults(requestOptions, client);

            operationContext = operationContext ?? new OperationContext();

            RESTCommand <TableQuerySegment> cmdToExecute = QueryImpl(this, continuationToken, client, tableName, EntityUtilities.ResolveEntityByType <DynamicTableEntity>, modifiedOptions);

            return(Task.Run(async() => await Executor.ExecuteAsync(
                                cmdToExecute,
                                modifiedOptions.RetryPolicy,
                                operationContext,
                                cancellationToken), cancellationToken));
        }
Example #52
0
        private static RESTCommand <TableQuerySegment> QueryImpl(TableQuery query, TableContinuationToken token, CloudTableClient client, string tableName, EntityResolver <DynamicTableEntity> resolver, TableRequestOptions requestOptions)
        {
            UriQueryBuilder builder = query.GenerateQueryBuilder(requestOptions.ProjectSystemProperties);

            if (token != null)
            {
                token.ApplyToUriQueryBuilder(builder);
            }

            StorageUri tempUriList = NavigationHelper.AppendPathToUri(client.StorageUri, tableName);
            RESTCommand <TableQuerySegment> queryCmd = new RESTCommand <TableQuerySegment>(client.Credentials, tempUriList);

            requestOptions.ApplyToStorageCommand(queryCmd);

            queryCmd.CommandLocationMode    = CommonUtility.GetListingLocationMode(token);
            queryCmd.RetrieveResponseStream = true;
            queryCmd.Builder             = builder;
            queryCmd.ParseError          = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            queryCmd.BuildRequest        = (cmd, uri, queryBuilder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableQuery(uri, builder, serverTimeout, cnt, ctx, requestOptions.PayloadFormat.Value, client.GetCanonicalizer(), client.Credentials);
            queryCmd.PreProcessResponse  = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp.StatusCode, null /* retVal */, cmd, ex);
            queryCmd.PostProcessResponse = async(cmd, resp, ctx) =>
            {
                ResultSegment <DynamicTableEntity> resSeg = await TableOperationHttpResponseParsers.TableQueryPostProcessGeneric <DynamicTableEntity>(cmd.ResponseStream, resolver.Invoke, resp, requestOptions, ctx, client.AccountName);

                if (resSeg.ContinuationToken != null)
                {
                    resSeg.ContinuationToken.TargetLocation = cmd.CurrentResult.TargetLocation;
                }

                return(new TableQuerySegment(resSeg));
            };

            return(queryCmd);
        }
        public void ListTablesWithPrefixExtended()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();

            int    NumTables       = 50;
            int    TableNameLength = 8;
            int    NumQueries      = 100;
            string alpha           = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string numerics        = "0123456789";
            string legalChars      = alpha + numerics;

            string            queryString = string.Empty;
            List <CloudTable> tableList   = new List <CloudTable>();
            List <CloudTable> localTestCreatedTableList = new List <CloudTable>();

            Random rand = new Random();

            try
            {
                #region Generate Tables

                // Generate Tables in Storage
                // This will generate all caps Tables, i.e. AAAAAAAA, BBBBBBBB....
                for (int h = 26; h < alpha.Length; h++)
                {
                    string tString = string.Empty;
                    for (int i = 0; i < TableNameLength; i++)
                    {
                        tString += alpha[h];
                    }

                    CloudTable table = tableClient.GetTableReference(tString);

                    if (table.CreateIfNotExists())
                    {
                        tableList.Add(table);
                        localTestCreatedTableList.Add(table);
                    }
                }

                // Generate some random tables of TableNameLength, table must start with a letter
                for (int m = 0; m < NumTables; m++)
                {
                    string tableName = GenerateRandomStringFromCharset(1, alpha, rand).ToLower() +
                                       GenerateRandomStringFromCharset(TableNameLength - 1, legalChars, rand).ToLower();

                    CloudTable table = tableClient.GetTableReference(tableName);

                    if (table.CreateIfNotExists())
                    {
                        tableList.Add(table);
                        localTestCreatedTableList.Add(table);
                    }
                }

                #endregion

                #region Generate Query Strings to cover all boundary conditions
                List <string> queryStrings = new List <string>()
                {
                    String.Empty, "aa", "zz", "az", "Az", "Aa", "zZ", "AA", "ZZ", "AZ", "z9", "a9", "aaa"
                };
                for (int k = 0; k < legalChars.Length; k++)
                {
                    queryStrings.Add(legalChars[k].ToString());
                }

                for (int n = 0; n <= NumQueries; n++)
                {
                    queryStrings.Add(GenerateRandomStringFromCharset((n % TableNameLength) + 1, legalChars, rand));
                }
                #endregion

                #region Merge Created Tables With Pre-existing ones
                int totalTables = 0;
                foreach (CloudTable listedTable in tableClient.ListTables())
                {
                    totalTables++;
                    if (tableList.Where((tbl) => tbl.Uri == listedTable.Uri).FirstOrDefault() != null)
                    {
                        continue;
                    }

                    tableList.Add(listedTable);
                }

                Assert.AreEqual(tableList.Count, totalTables);
                #endregion

                List <CloudTable> serviceResult = null;
                List <CloudTable> LINQResult    = null;

                try
                {
                    foreach (string queryValue in queryStrings)
                    {
                        queryString = queryValue;

                        serviceResult = tableClient.ListTables(queryString).OrderBy((table) => table.Name).ToList();
                        LINQResult    = tableList.Where((table) => table.Name.ToLower().StartsWith(queryString.ToLower())).OrderBy((table) => table.Name).ToList();

                        Assert.AreEqual(serviceResult.Count(), LINQResult.Count());

                        for (int listDex = 0; listDex < serviceResult.Count(); listDex++)
                        {
                            Assert.AreEqual(serviceResult[listDex].Name, LINQResult[listDex].Name);
                        }
                    }
                }
                catch (Exception)
                {
                    // On exception log table names for repro
                    this.testContextInstance.WriteLine("Exception in ListTablesWithPrefix, Dumping Tables for repro. QueryString = {0}\r\n", queryString);

                    foreach (CloudTable table in tableList)
                    {
                        this.testContextInstance.WriteLine(table.Name);
                    }

                    this.testContextInstance.WriteLine("Linq results =======================");

                    foreach (CloudTable table in LINQResult)
                    {
                        this.testContextInstance.WriteLine(table.Name);
                    }

                    this.testContextInstance.WriteLine("Service results =======================");

                    foreach (CloudTable table in serviceResult)
                    {
                        this.testContextInstance.WriteLine(table.Name);
                    }
                    throw;
                }
            }
            finally
            {
                // Cleanup
                foreach (CloudTable table in localTestCreatedTableList)
                {
                    // Dont delete Class level tables
                    if (createdTables.Where((tbl) => tbl.Uri == table.Uri).FirstOrDefault() != null)
                    {
                        continue;
                    }

                    // Delete other tables
                    table.DeleteIfExists();
                }
            }
        }
Example #54
0
        private static RESTCommand <TableQuerySegment <RESULT_TYPE> > QueryImpl <T, RESULT_TYPE>(TableQuery <T> query, TableContinuationToken token, CloudTableClient client, string tableName, EntityResolver <RESULT_TYPE> resolver, TableRequestOptions requestOptions) where T : ITableEntity, new()
        {
            UriQueryBuilder builder = query.GenerateQueryBuilder();

            if (token != null)
            {
                token.ApplyToUriQueryBuilder(builder);
            }

            StorageUri tempUri = NavigationHelper.AppendPathToUri(client.StorageUri, tableName);
            RESTCommand <TableQuerySegment <RESULT_TYPE> > queryCmd = new RESTCommand <TableQuerySegment <RESULT_TYPE> >(client.Credentials, tempUri);

            requestOptions.ApplyToStorageCommand(queryCmd);

            queryCmd.CommandLocationMode    = CommonUtility.GetListingLocationMode(token);
            queryCmd.RetrieveResponseStream = true;
            queryCmd.Handler             = client.AuthenticationHandler;
            queryCmd.BuildClient         = HttpClientFactory.BuildHttpClient;
            queryCmd.Builder             = builder;
            queryCmd.BuildRequest        = (cmd, uri, queryBuilder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableQuery(uri, builder, serverTimeout, cnt, ctx);
            queryCmd.PreProcessResponse  = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp.StatusCode, null /* retVal */, cmd, ex);
            queryCmd.PostProcessResponse = async(cmd, resp, ctx) =>
            {
                ResultSegment <RESULT_TYPE> resSeg = await TableOperationHttpResponseParsers.TableQueryPostProcessGeneric <RESULT_TYPE>(cmd.ResponseStream, resolver.Invoke, resp, ctx);

                if (resSeg.ContinuationToken != null)
                {
                    resSeg.ContinuationToken.TargetLocation = cmd.CurrentResult.TargetLocation;
                }

                return(new TableQuerySegment <RESULT_TYPE>(resSeg));
            };

            return(queryCmd);
        }
        static void Main(string[] args)
        {
            var accountName = args[0];
            var accountKey  = args[1];
            var GifsDir     = args[2];

            storageAccount = CloudStorageAccount.Parse(String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountName, accountKey));

            // Create the blob client.
            CloudBlobClient blobClient = new CloudBlobClient(storageAccount.BlobEndpoint, storageAccount.Credentials);

            // Create blob container if it doesn't exist.
            CloudBlobContainer blobContainer = blobClient.GetContainerReference("memes");

            blobContainer.CreateIfNotExists(BlobContainerPublicAccessType.Container);

            // Create the table client.
            CloudTableClient tableClient = new Microsoft.WindowsAzure.Storage.Table.CloudTableClient(storageAccount.TableEndpoint, storageAccount.Credentials);

            // Create the table if it doesn't exist.
            CloudTable table       = tableClient.GetTableReference("MemeMetadata");
            var        statusTable = table.CreateIfNotExists();

            var list = new List <ClipMemeEntity> {
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200312-horse-cannon.gif", BlobName = "20140401-200312-horse-cannon.gif", Description = "Deploy", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200344-updated-visual-studio-theme.gif", BlobName = "20140401-200344-updated-visual-studio-theme.gif", Description = "News vs Theme", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200447-oops.gif", BlobName = "20140401-200447-oops.gif", Description = "First Iteration", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200534-just-learned-about-git-rebase.gif", BlobName = "20140401-200534-just-learned-about-git-rebase.gif", Description = "Tests Pass on First Try", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200606-when-i-unstash-something.gif", BlobName = "20140401-200606-when-i-unstash-something.gif", Description = "Scale up", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200750-dog-race.gif", BlobName = "20140401-200750-dog-race.gif", Description = "Sprint", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200800-cookies.gif", BlobName = "20140401-200800-cookies.gif", Description = "Scottgu Promoted", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200849-when-i-merge-my-own-pull-requests.gif", BlobName = "20140401-200849-when-i-merge-my-own-pull-requests.gif", Description = "to the cloud", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-200924-disco-girl.gif", BlobName = "20140401-200924-disco-girl.gif", Description = "Hanseldance", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-201030-when-someone-merges-your-pull-request-before-its-ready.gif", BlobName = "20140401-201030-when-someone-merges-your-pull-request-before-its-ready.gif", Description = "accidental git push", Username = "******"
                },
                new ClipMemeEntity {
                    BlobUri = "https://clipmeme2014.blob.core.windows.net/memes/20140401-201102-Fat-Dance-Suit-Men-Rave-On-At-Home.gif", BlobName = "20140401-201102-Fat-Dance-Suit-Men-Rave-On-At-Home.gif", Description = "msft at $40", Username = "******"
                }
            };

            foreach (var item in list)
            {
                // Retrieve reference to a blob
                CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(item.BlobName);

                using (var fileStream = System.IO.File.OpenRead(String.Format("{0}\\{1}", GifsDir, item.BlobName)))
                {
                    blockBlob.UploadFromStream(fileStream);
                }

                var requestOptions = new Microsoft.WindowsAzure.Storage.Table.TableRequestOptions()
                {
                    RetryPolicy = new Microsoft.WindowsAzure.Storage.RetryPolicies.LinearRetry(TimeSpan.FromMilliseconds(500), 5)
                };

                table.Execute(Microsoft.WindowsAzure.Storage.Table.TableOperation.Insert(item), requestOptions);
            }

            return;
        }
Example #56
0
 public static void MyClassInitialize(TestContext testContext)
 {
     client          = GenerateCloudTableClient();
     startProperties = client.GetServicePropertiesAsync().AsTask().Result;
 }
        private static RESTCommand <TableResult> ReplaceImpl(TableOperation operation, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions)
        {
            RESTCommand <TableResult> replaceCmd = new RESTCommand <TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, table.Name));

            requestOptions.ApplyToStorageCommand(replaceCmd);

            TableResult result = new TableResult()
            {
                Result = operation.Entity
            };

            replaceCmd.RetrieveResponseStream = false;
            replaceCmd.SignRequest            = client.AuthenticationHandler.SignRequest;
            replaceCmd.ParseError             = ODataErrorHelper.ReadFromStreamUsingODataLib;
            replaceCmd.BuildRequestDelegate   = (uri, builder, timeout, useVersionHeader, ctx) =>
            {
                Tuple <HttpWebRequest, Stream> res = TableOperationHttpWebRequestFactory.BuildRequestForTableOperation(uri, builder, client.BufferManager, timeout, operation, useVersionHeader, ctx, requestOptions, client.AccountName);
                replaceCmd.SendStream = res.Item2;
                return(res.Item1);
            };

            replaceCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex);

            return(replaceCmd);
        }
Example #58
0
        public async Task CloudTableTestCorsMaxHeadersAsync()
        {
            CorsRule ruleManyHeaders = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.xyz.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-target*",
                    "x-ms-meta-other*"
                },
                ExposedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-data*",
                    "x-ms-meta-source*"
                }
            };

            // Add maximum number of non-prefixed headers
            for (int i = 0; i < 64; i++)
            {
                ruleManyHeaders.ExposedHeaders.Add("x-ms-meta-" + i);
                ruleManyHeaders.AllowedHeaders.Add("x-ms-meta-" + i);
            }

            CloudTableClient client = GenerateCloudTableClient();

            await this.TestCorsRulesAsync(client, null, new List <CorsRule>() { ruleManyHeaders });

            // Test with too many Exposed Headers (65)
            ruleManyHeaders.ExposedHeaders.Add("x-ms-meta-toomany");

            OperationContext context = new OperationContext();
            await TestHelper.ExpectedExceptionAsync(
                async() => await this.TestCorsRulesAsync(client, context, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                context,
                "A maximum of 64 literal exposed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.ExposedHeaders.Remove("x-ms-meta-toomany.");

            // Test with too many Allowed Headers (65)
            ruleManyHeaders.AllowedHeaders.Add("x-ms-meta-toomany");

            await TestHelper.ExpectedExceptionAsync(
                async() => await this.TestCorsRulesAsync(client, context, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                context,
                "A maximum of 64 literal allowed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.AllowedHeaders.Remove("x-ms-meta-toomany");

            // Test with too many Exposed Prefixed Headers (three)
            ruleManyHeaders.ExposedHeaders.Add("x-ms-meta-toomany*");

            await TestHelper.ExpectedExceptionAsync(
                async() => await this.TestCorsRulesAsync(client, context, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                context,
                "A maximum of two prefixed exposed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.ExposedHeaders.Remove("x-ms-meta-toomany*");

            // Test with too many Allowed Prefixed Headers (three)
            ruleManyHeaders.AllowedHeaders.Add("x-ms-meta-toomany*");

            await TestHelper.ExpectedExceptionAsync(
                async() => await this.TestCorsRulesAsync(client, context, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                context,
                "A maximum of two prefixed allowed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.AllowedHeaders.Remove("x-ms-meta-toomany*");
        }
Example #59
0
 internal Task <TableQuerySegment <TElement> > ExecuteQuerySegmentedAsync(TableContinuationToken token, CloudTableClient client, string tableName, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
Example #60
0
        internal IAsyncOperation <TableQuerySegment <TElement> > ExecuteQuerySegmentedAsync(TableContinuationToken token, CloudTableClient client, string tableName, TableRequestOptions requestOptions, OperationContext operationContext)
#endif
        {
            CommonUtility.AssertNotNullOrEmpty("tableName", tableName);
            TableRequestOptions modifiedOptions = TableRequestOptions.ApplyDefaults(requestOptions, client);

            operationContext = operationContext ?? new OperationContext();

            RESTCommand <TableQuerySegment <TElement> > cmdToExecute = QueryImpl(this, token, client, tableName, EntityUtilities.ResolveEntityByType <TElement>, modifiedOptions);

#if ASPNET_K || PORTABLE
            return(Task.Run(async() => await Executor.ExecuteAsync(
                                cmdToExecute,
                                modifiedOptions.RetryPolicy,
                                operationContext,
                                cancellationToken), cancellationToken));
#else
            return(AsyncInfo.Run(async(cancellationToken) => await Executor.ExecuteAsync(
                                     cmdToExecute,
                                     modifiedOptions.RetryPolicy,
                                     operationContext,
                                     cancellationToken)));
#endif
        }