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();
        }
 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);
     }
 }
예제 #3
0
 protected override void OnLoad()
 {
     base.OnLoad();
     var accountName = RouteVariables["account"];
     var tableName = RouteVariables["table"];
     var accountInfo = (from account in StorageAccountInfo.Load() where account.AccountName == accountName select account).FirstOrDefault();
     currentStorageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accountInfo.Key), accountInfo.UseHttps);
     table = currentStorageAccount.CreateCloudTableClient().GetTableReference(tableName);
     Grid.DataSource = new TableEntityDataSource(currentStorageAccount.CreateCloudTableClient().GetTableReference(tableName), Application);
     Grid.DataSource.DataChanged += OnDataLoad;
 }
예제 #4
0
파일: Crawler.cs 프로젝트: ngokchau/pa4
        public Crawler()
        {
            storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            urlQueue = storageAccount.CreateCloudQueueClient().GetQueueReference("krawlerurl");
            cmdQueue = storageAccount.CreateCloudQueueClient().GetQueueReference("krawlercmd");
            index = storageAccount.CreateCloudTableClient().GetTableReference("krawlerindex");
            errorQueue = storageAccount.CreateCloudQueueClient().GetQueueReference("krawlererror");
            lastTenUrlQueue = storageAccount.CreateCloudQueueClient().GetQueueReference("lasttenurlcrawled");
            crawlStatTable = storageAccount.CreateCloudTableClient().GetTableReference("krawlerstattable");
            disallowedPaths = new List<string>();
            visited = new HashSet<string>();

            crawlStatTable.CreateIfNotExists();
            crawlCounter = (NumberOfUrlCrawled() != 0) ? NumberOfUrlCrawled() : 0;
        }
예제 #5
0
        void RemoveFromTable()
        {
            try
            {
                //Setup connection to the azure table
                Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["TableConnectionString"].ConnectionString);
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                CloudTable       entryTable  = tableClient.GetTableReference(tableName);

                //Query all rows then calls them to be deleted
                var entities = entryTable.ExecuteQuery(new TableQuery <DynamicTableEntity>()).ToList();
                foreach (var row in entities)
                {
                    TableOperation deleteOP = TableOperation.Delete(row);
                    entryTable.ExecuteAsync(deleteOP);
                }

                //Print update status to user
                Results1.Text += "<br />Removed from Azure Table";
            }
            catch (Exception ex)
            {
                Error1.Text = "Failed to remove from table";
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["stockName"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.stockName;

            if (string.IsNullOrEmpty(name))
            {
                return(new BadRequestResult());
            }

            var connectionString = "DefaultEndpointsProtocol=https;AccountName=storageaccount4471b6a6;AccountKey=dX2VUCuxC0EcRnyZ7Srg+XIKLLagAO30kkpcBcsv9bq91rG+h2FomX6EHP/IByNzKSxVdRIqq6phUYDQ3PAPnw==;EndpointSuffix=core.windows.net";

            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("stocksinfo");

            var summary = GetSummary(table, name);

            if (summary == null)
            {
                return(new NotFoundResult());;
            }

            return(new OkObjectResult(JsonConvert.SerializeObject(summary)));
        }
 public TableStorageJobEventContext(CloudStorageAccount storageAccount, string jobsTableName = "Jobs", string jobInstancesTableName = "JobInstances", string jobInstanceEventsTableName = "JobInstanceEvents")
 {
     var tableClient = storageAccount.CreateCloudTableClient();
     _jobsWriter = new TableWriter(tableClient, jobsTableName);
     _jobInstancesWriter = new TableWriter(tableClient, jobInstancesTableName);
     _jobInstanceEventsWriter = new TableWriter(tableClient, jobInstanceEventsTableName);
 }
예제 #8
0
        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();
        }
예제 #9
0
 public BuildUtil(CloudStorageAccount account)
 {
     var client = account.CreateCloudTableClient();
     _buildResultDateTable = client.GetTableReference(AzureConstants.TableNames.BuildResultDate);
     _buildFailureDateTable = client.GetTableReference(AzureConstants.TableNames.BuildFailureDate);
     _viewNameDateTable = client.GetTableReference(AzureConstants.TableNames.ViewNameDate);
 }
예제 #10
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 async static void Log(
     string storageAccountName, 
     string storageAccountKey, 
     string exceptionsTableName, 
     string exceptionSource, 
     string exceptionDescription, 
     ILogger logger = null)
 {
     DateTime dt = DateTime.UtcNow;
     try
     {
         StorageCredentials storageCredentials = new StorageCredentials(storageAccountName, storageAccountKey);
         CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
         CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
         tableClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 10);
         CloudTable table_AppExceptions = tableClient.GetTableReference(exceptionsTableName);
         await table_AppExceptions.CreateIfNotExistsAsync();
         ExceptionLog entity = new ExceptionLog((DateTime.MaxValue - dt).ToString());
         entity.DT = dt;
         entity.MachineName = Environment.MachineName;
         entity.Application = Assembly.GetEntryAssembly().GetName().Name;
         entity.Source = exceptionSource;
         entity.Description = exceptionDescription;
         await table_AppExceptions.ExecuteAsync(TableOperation.Insert(entity));
     } 
     catch (System.Exception ex)
     {
         if (logger != null)
         {
             logger.Error(exceptionSource + ":" + exceptionDescription + ": " + ex.ToString());
         }
         Console.WriteLine(dt.ToString() + " " + Environment.MachineName + ":" + Assembly.GetEntryAssembly().GetName().Name + ":" + exceptionSource + ":" + exceptionDescription + ": " + ex.ToString());
     } 
 }
예제 #12
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string          requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            StockNamesModel data        = JsonConvert.DeserializeObject <StockNamesModel>(requestBody);


            if (data.stockNames == null || data.stockNames.Count <= 0)
            {
                return(new BadRequestResult());
            }

            var connectionString = "DefaultEndpointsProtocol=https;AccountName=storageaccount4471b6a6;AccountKey=dX2VUCuxC0EcRnyZ7Srg+XIKLLagAO30kkpcBcsv9bq91rG+h2FomX6EHP/IByNzKSxVdRIqq6phUYDQ3PAPnw==;EndpointSuffix=core.windows.net";

            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("stocksinfo");


            var comparisonList = new StockComparisonInfo();

            foreach (var s in data.stockNames)
            {
                var info = StockSummary.GetSummary(table, s);
                comparisonList.StockSummaries.Add(info);
            }

            return(new OkObjectResult(JsonConvert.SerializeObject(comparisonList)));
        }
 protected override void Initialize(HttpControllerContext controllerContext)
 {
     base.Initialize(controllerContext);
     storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
     var tableClient = storageAccount.CreateCloudTableClient();
     table = tableClient.GetTableReference("people");
 }
예제 #14
0
        public static void CreateClassRooms(int number, int building, int floor, int capacity, string description)
        {
            StorageCredentials creds = new StorageCredentials(accountName, accountKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(creds, useHttps: true);

            // Create the table client.
            CloudTableClient classRoomClient = storageAccount.CreateCloudTableClient();

            // Create the table if it doesn't exist.
            CloudTable table = classRoomClient.GetTableReference("ClassRoom");
            table.CreateIfNotExists();

            // Create the entity.
            ClassRoomEntity foo = new ClassRoomEntity(number, building);

            foo.Floor = floor;
            foo.Capacity = capacity;
            foo.Description = description;

            // Create the TableOperation that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(foo);

            // Execute the insert operation.
            table.Execute(insertOperation);
        }
예제 #15
0
 public SensorAccess()
 {
     credentials = new StorageCredentials(_accountName, _key);
     storageAccount = new CloudStorageAccount(credentials, true);
     tableClient = storageAccount.CreateCloudTableClient();
     table = tableClient.GetTableReference("AccelerometerTable");
 }
 static NDIAzureTableController()
 {
     _storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
     _tableClient = _storageAccount.CreateCloudTableClient();
     _table = _tableClient.GetTableReference("ndiparams");
     _retrieveOperation = TableOperation.Retrieve("VidParams", "LastVideo");
 }
예제 #17
0
 public TestDataController()
 {
     _storageAccount = ControllerUtil.CreateStorageAccount();
     _storage = new TestResultStorage(_storageAccount);
     _stats = new TestCacheStats(_storage, _storageAccount.CreateCloudTableClient());
     _statsUtil = ControllerUtil.GetOrCreateCounterStatsUtil(_storageAccount);
 }
 public ProcessTrackInfoHelper(string strConn)
 {
     storageAccount = CloudStorageAccount.Parse(strConn);
     CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
     // Create the table if it doesn't exist.
     table = tableClient.GetTableReference("wamsbutlerprocesstrack");
     table.CreateIfNotExists();
 }
예제 #19
0
        public AzureEventStore(CloudStorageAccount account, string tableName)
        {
            this.account = account;
            this.client = account.CreateCloudTableClient();
            this.tableName = tableName;

            this.created = false;
        }
예제 #20
0
        public static void Initialize(string storageConnectionString)
        {
            // Get storage account
            _storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            // Create the clients
            _tableClient = _storageAccount.CreateCloudTableClient();
        }
예제 #21
0
    static GuestBookDataSource()
    {
      storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("DataConnectionString"));

      CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient();
      CloudTable table = cloudTableClient.GetTableReference("GuestBookEntry");
      table.CreateIfNotExists();
    }
예제 #22
0
파일: ChatBackup.cs 프로젝트: tzkwizard/ELS
 public ChatBackup(CloudStorageAccount storageAccount)
 {
     var client = storageAccount.CreateCloudTableClient();
     _table = client.GetTableReference("Chat");
     _table.CreateIfNotExists();
     _iDbService = new DbService();
     _retryPolicy = _iDbService.GetRetryPolicy();
 }
예제 #23
0
파일: PostBackup.cs 프로젝트: tzkwizard/ELS
 public PostBackup(CloudStorageAccount storageAccount, string endpointUrl, string authorizationKey)
 {
     _iDbService = new DbService(endpointUrl,authorizationKey);
     CloudTableClient c = storageAccount.CreateCloudTableClient();
     _table = c.GetTableReference("Post");
     _table.CreateIfNotExists();
     _retryPolicy = _iDbService.GetRetryPolicy();
 }
예제 #24
0
 public PostBackup(CloudStorageAccount storageAccount)
 {
     _iDbService = new DbService();
     CloudTableClient c = storageAccount.CreateCloudTableClient();
     _table = c.GetTableReference("Post");
     _table.CreateIfNotExists();
     _retryPolicy = RetryService.GetRetryPolicy();
 }
예제 #25
0
 public async Task<CloudTable> GetTable(string tablename)
 {
     var account = new CloudStorageAccount(new StorageCredentials("slavapp", WebConfigurationManager.AppSettings["AzureStorageKey"]), true);
     var client = account.CreateCloudTableClient();
     var table = client.GetTableReference(tablename);
     await table.CreateIfNotExistsAsync();
     return table;
 }
        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 TableUserIndexBuilder(CloudStorageAccount storageAccount, string userTableName, string userIndexTableName)
        {
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            _userTable = tableClient.GetTableReference(userTableName);
            _userIndexTable = tableClient.GetTableReference(userIndexTableName);

            _userIndexTable.CreateIfNotExists();
        }
예제 #28
0
      /// <summary>
      /// Creates class instance
      /// </summary>
      /// <param name="storageAccountName">Storage account name</param>
      /// <param name="storageAccountKey">Storage account key</param>
      /// <param name="tableName">Target table name</param>
      public AzureTableLogWriter(string storageAccountName, string storageAccountKey, string tableName)
      {
         var creds = new StorageCredentials(storageAccountName, storageAccountKey);
         var account = new CloudStorageAccount(creds, true);

         CloudTableClient tableClient = account.CreateCloudTableClient();
         _table = tableClient.GetTableReference(tableName);
         _table.CreateIfNotExists();
      }
        public override void ActivateOptions()
        {
            base.ActivateOptions();

            _account = CloudStorageAccount.Parse(ConnectionString);
            _client = _account.CreateCloudTableClient();
            _table = _client.GetTableReference(TableName);
            _table.CreateIfNotExists();
        }
        public UserRepository()
        {
            // Retrieve the storage account from the connection string.
            _storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.AppSettings["StorageConnectionString"]);

            var client = _storageAccount.CreateCloudTableClient();
            client.GetTableReference(TableStorageConstants.UserTableKey).CreateIfNotExists();
        }
예제 #31
0
 /// <summary>
 /// Returns the AZURE Storage Table to log the service calls in.
 /// Table Name : RedPillLog
 /// </summary>
 /// <returns></returns>
 static CloudTable GetCloudTable()
 {
     StorageCredentials creds = new StorageCredentials(AccountName, AccountKey);
     CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
     CloudTableClient client = account.CreateCloudTableClient();
     CloudTable table = client.GetTableReference("RedPillLog");
     table.CreateIfNotExists();
     return table;
 }
예제 #32
0
        public AzureClient()
        {
            var storageCredentials = new StorageCredentials("galileospslon15",
                "");
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

            CloudTableClient client = storageAccount.CreateCloudTableClient();
            roomTable = client.GetTableReference("roomstatus");
        }
예제 #33
0
      /// <summary>
        /// Construct a sink that saves logs to the specified storage account.
        /// </summary>
        /// <param name="storageAccount">The Cloud Storage Account to use to insert the log entries to.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="storageTableName">Table name that log entries will be written to. Note: Optional, setting this may impact performance</param>
        public AzureTableStorageSink(CloudStorageAccount storageAccount, IFormatProvider formatProvider, string storageTableName = null)
        {
            _formatProvider = formatProvider;
            var tableClient = storageAccount.CreateCloudTableClient();

            if (string.IsNullOrEmpty(storageTableName)) storageTableName = typeof(LogEventEntity).Name;

            _table = tableClient.GetTableReference(storageTableName);
            _table.CreateIfNotExists();
        }
예제 #34
0
파일: Program.cs 프로젝트: agholap/Azure532
 static Microsoft.WindowsAzure.Storage.Table.CloudTable GetAzureTable()
 {
     Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccount"));
     //create cloud table client
     Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
     //get cloud table
     Microsoft.WindowsAzure.Storage.Table.CloudTable table = tableClient.GetTableReference("customers");
     //cleanup
     table.DeleteIfExists();
     table.CreateIfNotExists();
     return(table);
 }
        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);
        }
예제 #36
0
        public static void ProcessFile(string file)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["StorageConnection"].ToString();

            Microsoft.WindowsAzure.Storage.CloudStorageAccount account = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString);
            StorageCredentialsAccountAndKey cre = new StorageCredentialsAccountAndKey(account.Credentials.AccountName, account.Credentials.ExportBase64EncodedKey());

            Microsoft.WindowsAzure.CloudStorageAccount ac = new Microsoft.WindowsAzure.CloudStorageAccount(cre, true);
            CloudTableClient client = account.CreateCloudTableClient();
            CloudTable       table  = client.GetTableReference("employe");

            table.CreateIfNotExists();
            var dt = DataAccess.DataTable.New.ReadAzureBlob(ac, "fileupload", file);

            foreach (var row in dt.Rows)
            {
                EmployeeTableEntity emp = new EmployeeTableEntity {
                    EmployeeId = Convert.ToInt16(row["EmployeeId"]), FirstName = row["FirstName"], LastName = row["LastName"], ContactNo = row["ContactNo"], EmailId = row["EmailId"], PartitionKey = row["EmployeeId"], RowKey = Guid.NewGuid().ToString()
                };
                TableOperation operation = TableOperation.InsertOrMerge(emp);
                table.Execute(operation);
            }
        }
예제 #37
0
        public static Microsoft.WindowsAzure.Storage.Table.TableResult GetRandomTableResult()
        {
            //try
            //{
            Microsoft.WindowsAzure.Storage.Table.TableResult retreiveResult = null;
            XmlDocument document = new XmlDocument();

            document.Load(@"C:\Users\Administrator\source\repos\ConsoleApp5\ConsoleApp5\bin\Debug\Test.xml");
            var appSettings = System.Configuration.ConfigurationManager.AppSettings;

            if (appSettings.Count == 0)
            {
                Console.WriteLine("The appsettings is empty\nEnter a valid ConnectionString in AppConfig file");
                Console.WriteLine("Press a key to exit..");
                Console.ReadLine();
            }
            else
            {
                foreach (var key in appSettings.AllKeys)
                {
                    Microsoft.WindowsAzure.Storage.CloudStorageAccount    storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(System.Configuration.ConfigurationManager.AppSettings[key]);
                    Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient    = storageAccount.CreateCloudTableClient();
                    Microsoft.WindowsAzure.Storage.Table.CloudTable       table          = tableClient.GetTableReference("CustomerInformation");
                    //table.CreateIfNotExists();

                    /*foreach (Json_File file in json_Files)
                     * {
                     *  Microsoft.WindowsAzure.Storage.Table.TableOperation insertOperation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Insert(file);
                     *  table.Execute(insertOperation);
                     * }
                     */
                    if (table.Exists())
                    {
                        Console.WriteLine("The table exists..");
                        //Microsoft.WindowsAzure.Storage.Table.EntityProperty.CreateEntityPropertyFromObject
                        Dictionary <int, string> Partition_Keys = new Dictionary <int, string>();
                        int num = 1;
                        Microsoft.WindowsAzure.Storage.Table.TableContinuationToken token = null;
                        var entities = new List <Json_File>();
                        do
                        {
                            var queryResult = table.ExecuteQuerySegmented(new Microsoft.WindowsAzure.Storage.Table.TableQuery <Json_File>(), token);
                            entities.AddRange(queryResult.Results);
                            token = queryResult.ContinuationToken;
                        } while (token != null);
                        foreach (var file in entities)
                        {
                            Partition_Keys.Add(num, file.PartitionKey);
                            num++;
                        }
                        int    size               = Partition_Keys.Count;
                        Random random             = new Random();
                        int    random_number      = random.Next(1, size + 1);
                        string RandomPartitionKey = Partition_Keys[random_number];

                        Microsoft.WindowsAzure.Storage.Table.TableContinuationToken continuationToken = null;
                        var Entities = new List <Json_File>();
                        do
                        {
                            var rangeQueryResult = table
                                                   .ExecuteQuerySegmented(new Microsoft.WindowsAzure.Storage.Table.TableQuery <Json_File>()
                                                                          .Where(Microsoft.WindowsAzure.Storage.Table.TableQuery
                                                                                 .GenerateFilterCondition("PartitionKey",
                                                                                                          Microsoft.WindowsAzure.Storage.Table.QueryComparisons.Equal, RandomPartitionKey)),
                                                                          continuationToken);
                            Entities.AddRange(rangeQueryResult.Results);
                            continuationToken = rangeQueryResult.ContinuationToken;
                        } while (continuationToken != null);

                        Dictionary <int, string> Row_Keys = new Dictionary <int, string>();
                        int number = 1;
                        foreach (var file in Entities)
                        {
                            Row_Keys.Add(number, file.RowKey);
                            number++;
                        }
                        int sub_size = Row_Keys.Count;

                        Random rand        = new Random();
                        int    rand_number = rand.Next(1, sub_size + 1);

                        string RandomRowKey = Row_Keys[rand_number];

                        Microsoft.WindowsAzure.Storage.Table.TableOperation retreiveOperation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Retrieve <Json_File>(RandomPartitionKey, RandomRowKey);

                        retreiveResult = table.Execute(retreiveOperation);
                    }
                    else
                    {
                        Console.WriteLine("Table doesn't exists\nPress a key to exit....");
                        Console.ReadLine();
                    }
                }
            }
            return(retreiveResult);

            /*catch (Exception ex)
             * {
             * Console.WriteLine(ex.Message);
             * Console.WriteLine(ex.StackTrace);
             * Console.WriteLine(ex.InnerException);
             * Console.WriteLine(ex.Source);
             * Console.WriteLine("Press a key to exit...");
             * Console.ReadLine();
             * }
             */
        }
예제 #38
0
        void ProcessQuery()
        {
            ResultTitle.Text = "Query Results";
            string firstName = TextBox_firstname.Text;
            string lastName  = TextBox_lastname.Text;

            //Setup connection to the azure table
            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["TableConnectionString"].ConnectionString);
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable       entryTable  = tableClient.GetTableReference(tableName);

            //Only partition key
            if (firstName == string.Empty && lastName != string.Empty)
            {
                TableQuery <DynamicTableEntity> query = new TableQuery <DynamicTableEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, lastName));
                TableContinuationToken          token = null;

                do
                {
                    TableQuerySegment <DynamicTableEntity> resultSegment = entryTable.ExecuteQuerySegmented(query, token);
                    token = resultSegment.ContinuationToken;
                    foreach (DynamicTableEntity entity in resultSegment.Results)
                    {
                        IDictionary <string, EntityProperty> properties = entity.Properties;

                        Results1.Text += entity.PartitionKey + ", " + entity.RowKey + ": ";
                        foreach (KeyValuePair <string, EntityProperty> entry in properties)
                        {
                            Results1.Text += entry.Key + " = " + entry.Value.StringValue + "; ";
                        }
                        Results1.Text += "<br />";
                    }
                } while (token != null);
            }

            //Only row key
            else if (firstName != string.Empty && lastName == string.Empty)
            {
                TableQuery <DynamicTableEntity> query = new TableQuery <DynamicTableEntity>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, firstName));
                TableContinuationToken          token = null;

                do
                {
                    TableQuerySegment <DynamicTableEntity> resultSegment = entryTable.ExecuteQuerySegmented(query, token);
                    token = resultSegment.ContinuationToken;
                    foreach (DynamicTableEntity entity in resultSegment.Results)
                    {
                        IDictionary <string, EntityProperty> properties = entity.Properties;

                        Results1.Text += entity.PartitionKey + ", " + entity.RowKey + ": ";
                        foreach (KeyValuePair <string, EntityProperty> entry in properties)
                        {
                            Results1.Text += entry.Key + " = " + entry.Value.StringValue + "; ";
                        }
                        Results1.Text += "<br />";
                    }
                } while (token != null);
            }

            //Using both keys
            else if (firstName != string.Empty && lastName != string.Empty)
            {
                TableOperation retrieveOp = TableOperation.Retrieve <DynamicTableEntity>(lastName, firstName);
                TableResult    retrieved  = entryTable.Execute(retrieveOp);

                if (retrieved.Result != null)
                {
                    IDictionary <string, EntityProperty> properties = ((DynamicTableEntity)retrieved.Result).Properties;

                    Results1.Text = ((DynamicTableEntity)retrieved.Result).PartitionKey + ", " + ((DynamicTableEntity)retrieved.Result).RowKey + ": ";
                    foreach (KeyValuePair <string, EntityProperty> entry in properties)
                    {
                        Results1.Text += entry.Key + " = " + entry.Value.StringValue + "; ";
                    }
                }
            }
            if (Results1.Text == string.Empty)
            {
                Results1.Text = "No results found. <br />Needs exact spelling.";
            }
        }
예제 #39
0
        void UploadToTable(List <string> entries)
        {
            try
            {
                Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["TableConnectionString"].ConnectionString);
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                CloudTable       entryTable  = tableClient.GetTableReference(tableName);
                entryTable.CreateIfNotExistsAsync().Wait();

                ResultTitle.Text = "";
                Results1.Text    = "";
                Error1.Text      = "";
                foreach (string entry in entries)
                {
                    //Parse the string..
                    //Attempts to remove tabs and white spaces, doesnt fix the Robert williams case.
                    char   tab      = '\u0009';
                    string newEntry = entry.Replace(tab.ToString(), " ");
                    newEntry.Trim();
                    string[] arr = newEntry.Split();

                    //Jerry rigged to fix the robert williams case where the first substring is empty
                    int counter = 0;
                    if (arr[0] == string.Empty)
                    {
                        //Error1.Text += "String[0] is empty";
                        counter++;
                    }

                    string firstName = arr[counter];
                    string lastName  = arr[counter + 1];

                    var entity = new DynamicTableEntity(lastName, firstName);

                    string valuesToPrint = "";
                    if (arr.Length > 2)
                    {
                        for (int i = 2; i < arr.Length; i++)
                        {
                            int index = arr[i].IndexOf('=');
                            if (index == -1)
                            {
                                continue;
                            }
                            string key   = arr[i].Substring(0, index);
                            string value = arr[i].Substring(index + 1);

                            entity.Properties.Add(key, new EntityProperty(value));

                            valuesToPrint += key + "=" + value + " ";
                        }
                    }

                    var mergeOperation = TableOperation.InsertOrMerge(entity);
                    entryTable.ExecuteAsync(mergeOperation);

                    ResultTitle.Text = "Merged into table:";
                    Results1.Text   += "Name: " + lastName + ", " + firstName + "    " + valuesToPrint + "<br />";
                }
            }
            catch (Exception ex)
            {
                Error1.Text = "Failed to upload to table. <br />If you just cleared the table, wait for it to finish deletion.";
            }
        }