internal static Tuple<HttpWebRequest, Stream> BuildRequestForTableOperation(Uri uri, UriQueryBuilder builder, IBufferManager bufferManager, int? timeout, TableOperation operation, OperationContext ctx)
        {
            HttpWebRequest msg = BuildRequestCore(uri, builder, operation.HttpMethod, timeout, ctx);

            if (operation.OperationType == TableOperationType.InsertOrMerge || operation.OperationType == TableOperationType.Merge)
            {
                // post tunnelling
                msg.Headers.Add("X-HTTP-Method", "MERGE");
            }

            // etag
            if (operation.OperationType == TableOperationType.Delete ||
                operation.OperationType == TableOperationType.Replace ||
                operation.OperationType == TableOperationType.Merge)
            {
                if (operation.Entity.ETag != null)
                {
                    msg.Headers.Add("If-Match", operation.Entity.ETag);
                }
            }

            if (operation.OperationType == TableOperationType.Insert ||
                operation.OperationType == TableOperationType.Merge ||
                operation.OperationType == TableOperationType.InsertOrMerge ||
                operation.OperationType == TableOperationType.InsertOrReplace ||
                operation.OperationType == TableOperationType.Replace)
            {
                // create the writer, indent for readability of the examples.  
                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    CheckCharacters = false,   // sets this flag on the XmlWriter for ATOM  
                    Version = ODataVersion.V2 // set the Odata version to use when writing the entry 
                };

                HttpWebRequestAdapterMessage adapterMsg = new HttpWebRequestAdapterMessage(msg, bufferManager);
                ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings);
                ODataWriter writer = odataWriter.CreateODataEntryWriter();
                WriteOdataEntity(operation.Entity, operation.OperationType, ctx, writer);

                return new Tuple<HttpWebRequest, Stream>(adapterMsg.GetPopulatedMessage(), adapterMsg.GetStream());
            }

            return new Tuple<HttpWebRequest, Stream>(msg, null);
        }
Exemplo n.º 2
0
        private async Task <List <TableOperation> > BuildTableOperationDelete(T entity)
        {
            var entityIdValues = EntityDefinition.GetIdValues(entity);
            var idString       = string.Join(StorageQueryBuilder.PARTITION_FIELD_SEPARATOR,
                                             entityIdValues.Select(StorageQueryBuilder.NormalizeStringValue));

            var record = GenerateRecordMainPartition(entity, null, null);

            List <TableOperation> operations = new List <TableOperation>
            {
                TableOperation.Delete(record)
            };

            var old = await GetById(idString).ConfigureAwait(false);

            if (old != null)
            {
                var oldFields = GetEntityFilterableFields(old);
                operations.AddRange(GeneratePersistPartitionData(old, null, oldFields).Select(TableOperation.Delete));
            }
            return(operations);
        }
Exemplo n.º 3
0
        public async Task Assert()
        {
            const int           delayIncrement = 750;
            const int           maximumDelay   = delayIncrement * 120;
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AbstractIntegrationTest.Settings.StorageConnectionString);
            CloudTableClient    tableClient    = storageAccount.CreateCloudTableClient();
            CloudTable          markerTable    = tableClient.GetTableReference("markers");

            int totalDelay           = 0;
            MarkerTableEntity marker = null;

            do
            {
                await Task.Delay(delayIncrement);

                totalDelay += delayIncrement;
                marker      = (MarkerTableEntity)(await markerTable.ExecuteAsync(TableOperation.Retrieve <MarkerTableEntity>(MarkerId.ToString(), string.Empty)))?.Result;
            } while (totalDelay < maximumDelay && marker == null);

            Xunit.Assert.NotNull(marker);
            Xunit.Assert.Equal(Value, marker.Value);
        }
Exemplo n.º 4
0
        private void SaveEditSurvey(IDialogContext context, dynamic resultValue, EventEntity oneEventEntity)
        {
            // Get card from result
            Dictionary <string, string> editedQuestionList = resultValue.ToObject <Dictionary <string, string> >();

            for (int i = 0; i < questionList.Count; i++)
            {
                if (editedQuestionList.ContainsKey("q" + i))
                {
                    if (!(string.IsNullOrEmpty(editedQuestionList["q" + i]) || string.IsNullOrWhiteSpace(editedQuestionList["q" + i])))
                    {
                        questionList[i] = editedQuestionList["q" + i];
                    }
                }
            }

            //Serialize the object back and save it
            var survey   = new List <QuestionEntity>();
            var question = new QuestionEntity();

            for (int i = 0; i < questionList.Count; i++)
            {
                question = new QuestionEntity();
                question.PartitionKey = oneEventEntity.SurveyCode;
                question.RowKey       = (i + 1).ToString();
                question.AnswerList   = JsonConvert.SerializeObject(answerList[i]);
                question.QuestionText = questionList[i];
                survey.Add(question);
            }

            oneEventEntity.Survey = JsonConvert.SerializeObject(survey);

            var        storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]);
            var        tableClient    = storageAccount.CreateCloudTableClient();
            CloudTable cloudTable     = tableClient.GetTableReference("Event");

            cloudTable.CreateIfNotExists();
            cloudTable.Execute(TableOperation.InsertOrMerge(oneEventEntity));
        }
Exemplo n.º 5
0
        public int GetConfigValueByKey(string key)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

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

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("config");

            // Create a retrieve operation that takes a customer entity.
            TableOperation retrieveOperation = TableOperation.Retrieve <ConfigEntity>(PARTITION_KEY, key);

            // Execute the retrieve operation.
            TableResult retrievedResult = table.Execute(retrieveOperation);

            var    config = (ConfigEntity)retrievedResult.Result;
            string value  = config.Value;

            return(Convert.ToInt32(value));
        }
        /// <summary>
        /// Creates several Table Storage entities.
        /// </summary>
        /// <param name="count"></param>
        public void CreateEntities(int count)
        {
            // Create several entities.
            for (int i = 1; i <= count; i++)
            {
                // Create a new entity.
                Random       rnd    = new Random();
                SampleEntity entity = new SampleEntity(Guid.NewGuid())
                {
                    CreatedAt = DateTime.UtcNow.ToString("o"),
                    Number    = rnd.Next(0, int.MaxValue)
                };

                // Create the TableOperation that inserts the entity.
                Console.WriteLine(String.Format("Inserting entity {0}.", i));
                TableOperation insertOperation = TableOperation.Insert(entity);

                // Execute the insert operation.
                table.Execute(insertOperation);
                Console.WriteLine(String.Format("Entity '{0}' inserted.", entity.RowKey));
            }
        }
Exemplo n.º 7
0
        public static void WriteLine(string line)
        {
            Console.WriteLine(
                $"[{DateTime.Now.ToString("hh:mm:ss.fff", CultureInfo.InvariantCulture)}] - {line}");

#if DEBUG
            Debug.WriteLine($"{line}");
            return;
#endif

            var storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.AppSettings["Azure.Storage.ConnectionString"]);

            var tableClient = storageAccount.CreateCloudTableClient();
            var table       = tableClient.GetTableReference("CloudConsole");
            table.CreateIfNotExists();

            var operation = TableOperation.Insert(
                new TableEntity((long.MaxValue - DateTime.Now.Ticks).ToString(), line));

            table.Execute(operation);
        }
Exemplo n.º 8
0
        public static async Task <IActionResult> DeleteTodoAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "todo/{id}")] HttpRequest req,
            [Table("todos", Connection = "AzureWebJobsStorage")] CloudTable todoTable,
            ILogger log, string id)
        {
            log.LogInformation("Deleting todo list by Id");

            var deleteOperation = TableOperation.Delete(new TableEntity()
            {
                PartitionKey = "TODO", RowKey = id, ETag = "*"
            });

            try
            {
                var deleteResult = await todoTable.ExecuteAsync(deleteOperation);
            }
            catch (StorageException e) when(e.RequestInformation.HttpStatusCode == 404)
            {
                return(new NotFoundResult());
            }
            return(new OkResult());
        }
Exemplo n.º 9
0
        public async Task<T> ReplaceAsync(string partitionKey, string rowKey, Func<T, T> replaceAction)
        {
            object itm = "Not read";
            try
            {
                while (true)
                {
                    try
                    {
                        var entity = await GetDataAsync(partitionKey, rowKey);
                        if (entity != null)
                        {
                            var result = replaceAction(entity);
                            itm = result;
                            if (result != null)
                                await GetTable().ExecuteAsync(TableOperation.Replace(result));

                            return result;
                        }

                        return null;

                    }
                    catch (StorageException e)
                    {
                        // Если поймали precondition fall = 412, значит в другом потоке данную сущность успели поменять
                        // - нужно повторить операцию, пока не исполнится без ошибок
                        if (e.RequestInformation.HttpStatusCode != 412)
                            throw;
                    }
                }

            }
            catch (Exception ex)
            {
                _log?.WriteFatalError("Table storage: " + _tableName, "Replace item", TableStorageUtils.PrintItem(itm), ex).Wait();
                throw;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Store the given LogMessage object an Azure Table Storage table called "SystemLogs" in the Azure Storage account pointed to by the "AzureStorageConnectionString"
        /// </summary>
        /// <param name="logMessage">Message object to log</param>
        public static void LogMessageToTableStorage(LogMessage logMessage)
        {
            try
            {
                // Convert message to Azure Table Entity
                var logAzureTableEntity = new LogAzureTableEntity(logMessage);

                var connectionString = CloudConfigurationManager.GetSetting(telemetryStorageConnectionStringSettingName);
                var table            = AzureTablesHelper.GetAzureTablesTableObject(connectionString, AzureTableStorageTableName);
                table.CreateIfNotExists();

                // Create the TableOperation object that inserts the entity.
                var insertOperation = TableOperation.Insert(logAzureTableEntity);

                // Execute the insert operation.
                table.Execute(insertOperation);
            }
            catch (Exception e)
            {
                // ignored
            }
        }
Exemplo n.º 11
0
        internal static async Task <bool> DeleteRow(CloudTable todoTable, string id, string partitionKey)
        {
            var entity = new TableEntity()
            {
                PartitionKey = partitionKey, RowKey = id, ETag = "*"
            };
            var deleteOperation = TableOperation.Delete(entity);

            try
            {
                var deleteResult = await todoTable.ExecuteAsync(deleteOperation);
            }
            catch (StorageException e) when(e.RequestInformation.HttpStatusCode == 404)
            {
                return(false);
            }
            catch (System.Exception ex)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 12
0
        private static async Task AddNewStudent()
        {
            System.Console.WriteLine("University:");
            string university = Console.ReadLine();

            System.Console.WriteLine("CNP:");
            string cnp = Console.ReadLine();

            System.Console.WriteLine("FirstName:");
            string firstName = Console.ReadLine();

            System.Console.WriteLine("LastName:");
            string lastName = Console.ReadLine();

            System.Console.WriteLine("Faculty:");
            string faculty = Console.ReadLine();

            System.Console.WriteLine("Year:");
            string year = Console.ReadLine();

            StudentEntity stud = await RetrieveRecordAsync(studentsTable, university, cnp);

            if (stud == null)
            {
                var student = new StudentEntity(university, cnp);
                student.FirstName = firstName;
                student.LastName  = lastName;
                student.Faculty   = faculty;
                student.Year      = Convert.ToInt32(year);
                var insertOperation = TableOperation.Insert(student);
                await studentsTable.ExecuteAsync(insertOperation);

                System.Console.WriteLine("Inserted!");
            }
            else
            {
                System.Console.WriteLine("Entries exists!");
            }
        }
Exemplo n.º 13
0
        private Person CheckStorage(string email, string password)
        {
            string tableName = "Registrerade";

            try
            {
                CloudStorageAccount account = CloudStorageAccount.Parse(tableConnectionString);

                CloudTableClient client = account.CreateCloudTableClient();
                CloudTable       table  = client.GetTableReference(tableName);

                TableOperation retrieveOperation = TableOperation.Retrieve <Person>("signups", email);

                TableResult user = table.Execute(retrieveOperation);

                Person person = new Person();
                person = (Person)user.Result;

                if (person.Email == email)
                {
                    Trace.WriteLine(person.Email);

                    Console.WriteLine(person.Email);
                    return(person);
                }
                else
                {
                    Trace.WriteLine("The f*g was not found.");
                    Console.WriteLine("FAGGITY");
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                Console.WriteLine(ex);
            }
            return(null);
        }
Exemplo n.º 14
0
        public async Task <bool> StoreAllAnalysedMailAsync(List <AnalysedMailMessageEntity> analysedMail)
        {
            if (analysedMail == null || analysedMail.Count == 0)
            {
                Dependencies.DiagnosticLogging.Verbose("MailProcessor: No analysed email to store, exiting.");
                return(true);
            }
            var numMsgs = analysedMail.Count;

            try
            {
                Dependencies.DiagnosticLogging.Verbose("MailProcessor: {numMsgs} mail messages to store.", numMsgs);
                var tblRef = CreateClientTableReference(DataStores.Tables.TableNameProcessedMail);

                foreach (var m in analysedMail)
                {
                    var op     = TableOperation.Insert(m);
                    var result = await tblRef.ExecuteAsync(op);

                    var resultCode = result.HttpStatusCode;
                    if (resultCode >= 300)
                    {
                        Dependencies.DiagnosticLogging.Error("MailProcessor: Unable to write analysed messages to table storage status code: {resultCode}", resultCode);
                    }
                }
                Dependencies.DiagnosticLogging.Info("MailProcessor: Analysed messages stored: #{numMsgs}", numMsgs);
                return(true);
            }
            catch (Exception ex)
            {
                Dependencies.DiagnosticLogging.Error(ex, "MailProcessor: Error storing analysed mail list");
                var baseEx = ex.GetBaseException();
                if (baseEx != null)
                {
                    Dependencies.DiagnosticLogging.Error(baseEx, "MailProcessor: Error storing analysed mail list (Inner/base error)");
                }
            }
            return(false);
        }
Exemplo n.º 15
0
        public static async Task InsertRecordToTableAsync(CloudTable table, string time, string nickname, string value)
        {
            MessageTable message = new MessageTable();

            message.Time           = time;
            message.AuthorNickName = nickname;
            message.Body           = value;

            Message mess = await RetrieveRecordAsync(table, time, nickname);

            if (mess == null)
            {
                TableOperation tableOperation = TableOperation.Insert(message);
                await table.ExecuteAsync(tableOperation);

                //Console.WriteLine("Record inserted");
            }
            else
            {
                //Console.WriteLine("Record exists");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Demonstrate the most efficient storage query - the point query - where both partition key and row key are specified.
        /// </summary>
        /// <param name="table">Sample table name</param>
        /// <param name="partitionKey">Partition key - i.e., last name</param>
        /// <param name="rowKey">Row key - i.e., first name</param>
        /// <returns>A Task object</returns>
        private static async Task <CustomerEntity> RetrieveEntityUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
        {
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <CustomerEntity>(partitionKey, rowKey);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                CustomerEntity customer = result.Result as CustomerEntity;
                if (customer != null)
                {
                    Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customer.PartitionKey, customer.RowKey, customer.Email, customer.PhoneNumber);
                }

                return(customer);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
Exemplo n.º 17
0
        public async Task UpsertAsync(T t)
        {
            var tcw = t as IConcurrencyAware;
            OperationContext ctx = null;

            if (tcw != null)
            {
                ctx = new OperationContext()
                {
                    UserHeaders =
                    {
                        { "If-Match", tcw.ETag }
                    }
                }
            }
            ;

            var table = await GetTable();

            await table.ExecuteAsync(TableOperation.InsertOrReplace(GetEntity(t, true)),
                                     null, ctx);
        }
Exemplo n.º 18
0
        private static async Task AddNewStudent()
        {
            System.Console.WriteLine("Adauga universitatea:");
            string university = Console.ReadLine();

            System.Console.WriteLine("Adauga CNP:");
            string cnp = Console.ReadLine();

            System.Console.WriteLine("Adauga nume:");
            string nume = Console.ReadLine();

            System.Console.WriteLine("Adauga prenume:");
            string prenume = Console.ReadLine();

            System.Console.WriteLine("Adauga facultate:");
            string facultate = Console.ReadLine();

            System.Console.WriteLine("Adauga an studiu:");
            string an = Console.ReadLine();

            Studententity stud = await RetrieveRecordAsync(studentsTable, university, cnp);

            if (stud == null)
            {
                var student = new Studententity(university, cnp);
                student.Nume      = nume;
                student.Prenume   = prenume;
                student.Facultate = facultate;
                student.An        = Convert.ToInt32(an);
                var insertOperation = TableOperation.Insert(student);
                await studentsTable.ExecuteAsync(insertOperation);

                System.Console.WriteLine("S-a adaugat!");
            }
            else
            {
                System.Console.WriteLine("S-a gasit!");
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Inserts a data entry in the Azure table: creates a new one if does not exists or overwrites (without eTag) an already existing version (the "update in place" semantincs).
        /// </summary>
        /// <param name="data">Data to be inserted or replaced in the table.</param>
        /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
        public async Task <string> UpsertTableEntryAsync(T data)
        {
            const string operation = "UpsertTableEntry";
            var          startTime = DateTime.UtcNow;

            if (Logger.IsVerbose2)
            {
                Logger.Verbose2("{0} entry {1} into table {2}", operation, data, TableName);
            }

            try
            {
                try
                {
                    // WAS:
                    // svc.AttachTo(TableName, data, null);
                    // svc.UpdateObject(data);
                    // SaveChangesOptions.ReplaceOnUpdate,

                    var opResult = await Task <TableResult> .Factory.FromAsync(
                        tableReference.BeginExecute,
                        tableReference.EndExecute,
                        TableOperation.InsertOrReplace(data),
                        null);

                    return(opResult.Etag);
                }
                catch (Exception exc)
                {
                    Logger.Warn(ErrorCode.AzureTable_06, String.Format("Intermediate error upserting entry {0} to the table {1}",
                                                                       (data == null ? "null" : data.ToString()), TableName), exc);
                    throw;
                }
            }
            finally
            {
                CheckAlertSlowAccess(startTime, operation);
            }
        }
        /// <summary>
        /// Method to delete user mapping.
        /// </summary>
        /// <param name="partitionKey">The partition key.</param>
        /// <param name="rowKey">The row key.</param>
        /// <returns>boolean value that indicates delete success.</returns>
        public async Task <bool> DeleteMappedUserDetailsAsync(string partitionKey, string rowKey)
        {
            await this.EnsureInitializedAsync().ConfigureAwait(false);

            // Table query
            TableQuery <AllUserMappingEntity> deleteQuery = new TableQuery <AllUserMappingEntity>();

            deleteQuery
            .Where(TableQuery.CombineFilters(
                       TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey),
                       TableOperators.And,
                       TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey)));

            // Results list
            List <AllUserMappingEntity> results           = new List <AllUserMappingEntity>();
            TableContinuationToken      continuationToken = null;

            if (await this.userMappingCloudTable.ExistsAsync().ConfigureAwait(false))
            {
                TableQuerySegment <AllUserMappingEntity> queryResults = await this.userMappingCloudTable.ExecuteQuerySegmentedAsync(
                    deleteQuery,
                    continuationToken).ConfigureAwait(false);

                continuationToken = queryResults.ContinuationToken;
                results           = queryResults.Results;
            }

            var            row    = results.FirstOrDefault();
            TableOperation delete = TableOperation.Delete(row);

            var result = await this.userMappingCloudTable.ExecuteAsync(delete).ConfigureAwait(false);

            if (result.HttpStatusCode == (int)HttpStatusCode.NoContent)
            {
                return(true);
            }

            return(false);
        }
        public async Task <TContext> LoadContextAsync <TContext>(long botId, long userOrChatId)
            where TContext : class, new()
        {
            var table = await GetTable(options.MainTableName);

            var key = BotUserOrChatContext.GetKey(botId, userOrChatId);
            var obj = await table.ExecuteAsync(TableOperation.Retrieve <BotUserOrChatContext>(key.PartitionKey, key.RowKey));

            if (obj.Result == null)
            {
                return(null);
            }

            var context = (BotUserOrChatContext)obj.Result;

            if (string.IsNullOrEmpty(context.Value))
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <TContext>(context.Value, EntityPropertyExtensions.JsonSettings));
        }
Exemplo n.º 22
0
        private static void ReplaceEntity()
        {
            // Retrieve the storage account from the connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

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

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("people");

            // Create a retrieve operation that takes a customer entity.
            TableOperation retrieveOperation = TableOperation.Retrieve <CustomerEntity>("Smith", "Ben");

            // Execute the operation.
            TableResult retrievedResult = table.Execute(retrieveOperation);

            // Assign the result to a CustomerEntity object.
            CustomerEntity updateEntity = (CustomerEntity)retrievedResult.Result;

            if (updateEntity != null)
            {
                // Change the phone number.
                updateEntity.PhoneNumber = "425-555-0105";

                // Create the Replace TableOperation.
                TableOperation updateOperation = TableOperation.Replace(updateEntity);

                // Execute the operation.
                table.Execute(updateOperation);

                Console.WriteLine("Entity updated.");
            }
            else
            {
                Console.WriteLine("Entity could not be retrieved.");
            }
        }
Exemplo n.º 23
0
        static string deleteEntry(string tableName, string csvArg)
        {
            string returnString = "[done] Added entity. ";

            try
            {
                string[] argArray  = csvArg.Split(',');
                string   firstName = argArray[0];
                string   lastName  = argArray[1];

                // Create the CloudTable object that represents the "people" table.
                CloudTable table = tableClient.GetTableReference(tableName);

                // Create a retrieve operation that takes a customer entity.
                TableOperation retrieveOperation = TableOperation.Retrieve <CustomerEntity>(firstName, lastName);

                // Execute the retrieve operation.
                TableResult retrievedResult = table.Execute(retrieveOperation);
                // Assign the result to a CustomerEntity.
                CustomerEntity deleteEntity = (CustomerEntity)retrievedResult.Result;

                // Create the Delete TableOperation.
                if (deleteEntity != null)
                {
                    TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
                    // Execute the operation.
                    table.Execute(deleteOperation);
                }
                else
                {
                    returnString = "Could not retrieve the entity.";
                }
            }
            catch (Exception Err)
            {
                returnString = Err.Message;
            }
            return(returnString);
        }
Exemplo n.º 24
0
        private static PictureEntity RunTableCode(CloudBlockBlob blob)
        {
            Console.WriteLine("\n\nStarting Table Demo...");
            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

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

            // Get or create the table
            CloudTable table = tableClient.GetTableReference("pictures");

            table.CreateIfNotExists();

            PictureEntity picture = new PictureEntity(blob.Name);

            picture.FileSize = blob.Properties.Length;
            picture.BlobUri  = blob.Uri.ToString();

            TableOperation insert = TableOperation.Insert(picture);

            table.Execute(insert);

            Console.WriteLine("'Picture' TableEntity properties: ");
            foreach (var prop in picture.GetType().GetProperties())
            {
                Console.WriteLine("   " + prop.Name + ": " + prop.GetValue(picture, null));
            }

            Console.WriteLine("\nWrote metadata entity into " + table.Name + " table.");
            TableQuery <PictureEntity> query = new TableQuery <PictureEntity>()
                                               .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, picture.PartitionKey));


            Console.WriteLine("Entries for this picture: " + table.ExecuteQuery(query).Count());

            return(picture);
        }
Exemplo n.º 25
0
        public static SnapmailRowData Update(string key, SnapmailRowData snapmail)
        {
            try
            {
                CloudTable      tblSnapmails = GetAzureTable(SNAPMAIL_TABLE_NAME);
                SnapmailRowData old          = Get(key);
                SnapmailRowData mail         = new SnapmailRowData()
                {
                    RowKey       = key,
                    PartitionKey = snapmail.PartitionKey,
                    ETag         = snapmail.ETag,
                    Timestamp    = snapmail.Timestamp,
                    Cameras      = snapmail.Cameras,
                    CameraNames  = snapmail.CameraNames,
                    Message      = old.Message,
                    NotifyDays   = snapmail.NotifyDays,
                    NotifyTime   = snapmail.NotifyTime,
                    TimeZone     = snapmail.TimeZone,
                    Recipients   = snapmail.Recipients,
                    Subject      = old.Subject,
                    UserId       = snapmail.UserId,
                    UserName     = snapmail.UserName,
                    IsActive     = old.IsActive,
                    IsScheduled  = old.IsScheduled,
                    AccessToken  = snapmail.AccessToken,
                    RefreshToken = snapmail.RefreshToken,
                    TokenExpires = snapmail.TokenExpires,
                    TokenCreated = snapmail.TokenCreated
                };

                TableOperation updateEmail = TableOperation.Replace(mail);
                var            result      = tblSnapmails.Execute(updateEmail);
                return(Get(key));
            }
            catch (Exception x)
            {
                return(snapmail);
            }
        }
Exemplo n.º 26
0
        public void Write(string partitionKey, string rowKey, IDictionary <string, EntityProperty> values)
        {
            try
            {
                // Make sure the table exists.
                if (!_tableCreated)
                {
                    Diagnostics.TableStorageEventSource.Log.Info("Ensuring table '{0}' exists.", _table.Name);

                    // Create.
                    _table.CreateIfNotExists();
                    _tableCreated = true;
                }

                // Write.
                _table.Execute(TableOperation.InsertOrMerge(new DynamicTableEntity(partitionKey, rowKey, "*", values)));
            }
            catch (Exception ex)
            {
                Diagnostics.TableStorageEventSource.Log.ErrorDetails(ex, "Error writing to table '{0}'.", _table.Name);
            }
        }
Exemplo n.º 27
0
        public async Task Upsert(string organisation, PullRequest pullRequest)
        {
            var entity = new PullRequestDao
            {
                PartitionKey   = organisation.ToLowerInvariant(),
                RowKey         = pullRequest.Id.ToString(),
                Number         = pullRequest.Number,
                Title          = pullRequest.Title,
                Timestamp      = DateTimeOffset.Now,
                Url            = pullRequest.Url.ToString(),
                CreatedAt      = pullRequest.CreatedAt,
                UpdatedAt      = pullRequest.UpdatedAt,
                ClosedAt       = pullRequest.ClosedAt,
                Status         = pullRequest.Status.ToString(),
                RepositoryName = pullRequest.RepositoryName,
                RepositoryUrl  = pullRequest.RepositoryUrl.ToString()
            };

            var table = await _azureStorage.GetTable(PullRequestsTable);

            await table.ExecuteAsync(TableOperation.InsertOrReplace(entity));
        }
        public SubmissionTableEntity IncrementVote(ItemNumber whichItem, string key)
        {
            var submission = GetSubmission(key);

            if (submission != null)
            {
                if (whichItem == ItemNumber.Item1)
                {
                    submission.Item1Votes++;
                }
                else if (whichItem == ItemNumber.Item2)
                {
                    submission.Item2Votes++;
                }

                var update = TableOperation.Replace(submission);

                _table.Execute(update);
            }

            return(submission);
        }
Exemplo n.º 29
0
        public static async Task <IActionResult> UpdateUser(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = Route + "/{id}")] HttpRequest req,
            [Table(TableName, Connection = "AzureWebJobsStorage")] CloudTable userTable,
            ILogger log, string id)
        {
            string requestBody   = await new StreamReader(req.Body).ReadToEndAsync();
            var    updated       = JsonConvert.DeserializeObject <UserUpdateModel>(requestBody);
            var    findOperation = TableOperation.Retrieve <UserTableEntity>("signup", id);
            var    findResult    = await userTable.ExecuteAsync(findOperation);

            if (findResult.Result == null)
            {
                return(new NotFoundResult());
            }
            var existingRow = (UserTableEntity)findResult.Result;

            existingRow.IsActive = updated.IsActive;
            var replaceOperation = TableOperation.Replace(existingRow);
            await userTable.ExecuteAsync(replaceOperation);

            return(new OkObjectResult(existingRow.ToUser()));
        }
Exemplo n.º 30
0
        //AUTHENTIFICATION

        //ADD NEW USER IN DB
        public async Task <string> DBStoreUser(string login, string hash, string nickname, string level)
        {
            CloudTable cloudTable = tableClient.GetTableReference("users");
            //await CreateNewTableAsync(cloudTable);

            UserTable userTable = new UserTable();

            userTable.Login    = login;
            userTable.Hash     = hash;
            userTable.Nickname = nickname;
            userTable.Level    = level;
            userTable.Photo    = "";

            userTable.AssignPartitionKey();
            userTable.AssignRowKey();


            TableOperation tableOperation = TableOperation.Insert(userTable);
            await cloudTable.ExecuteAsync(tableOperation);

            return("Record inserted");
        }
Exemplo n.º 31
0
        public async Task <bool> SaveEntryAsync(GeoTaggerEntry entity)
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureConnectionString);

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

                // Define the insert operation
                var operation = TableOperation.InsertOrReplace(entity);

                // Execute the insert against the table
                var result = await table.ExecuteAsync(operation);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemplo n.º 32
0
        private RowCollection CompareTables(Output targetOutput, Table targetTable, Table updatedTable, out TableOperation operation)
        {
            RowCollection rows = new RowCollection();
            operation = TableOperation.None;

            // dropped tables
            if (null == updatedTable ^ null == targetTable)
            {
                if (null == targetTable)
                {
                    operation = TableOperation.Add;
                    rows.AddRange(updatedTable.Rows);
                }
                else if (null == updatedTable)
                {
                    operation = TableOperation.Drop;
                }
            }
            else // possibly modified tables
            {
                SortedList updatedPrimaryKeys = new SortedList();
                SortedList targetPrimaryKeys = new SortedList();

                // compare the table definitions
                if (0 != targetTable.Definition.CompareTo(updatedTable.Definition))
                {
                    // continue to the next table; may be more mismatches
                    this.OnMessage(WixErrors.DatabaseSchemaMismatch(targetOutput.SourceLineNumbers, targetTable.Name));
                }
                else
                {
                    this.IndexPrimaryKeys(targetTable, targetPrimaryKeys, updatedTable, updatedPrimaryKeys);

                    // diff the target and updated rows
                    foreach (DictionaryEntry targetPrimaryKeyEntry in targetPrimaryKeys)
                    {
                        string targetPrimaryKey = (string)targetPrimaryKeyEntry.Key;
                        bool keepRow = false;
                        RowOperation rowOperation = RowOperation.None;

                        Row compared = this.CompareRows(targetTable, targetPrimaryKeyEntry.Value as Row, updatedPrimaryKeys[targetPrimaryKey] as Row, out rowOperation, out keepRow);

                        if (keepRow)
                        {
                            rows.Add(compared);
                        }
                    }

                    // find the inserted rows
                    foreach (DictionaryEntry updatedPrimaryKeyEntry in updatedPrimaryKeys)
                    {
                        string updatedPrimaryKey = (string)updatedPrimaryKeyEntry.Key;

                        if (!targetPrimaryKeys.Contains(updatedPrimaryKey))
                        {
                            Row updatedRow = (Row)updatedPrimaryKeyEntry.Value;

                            updatedRow.Operation = RowOperation.Add;
                            updatedRow.SectionId = sectionDelimiter + updatedRow.SectionId;
                            rows.Add(updatedRow);
                        }
                    }
                }
            }

            return rows;
        }
        internal static Tuple<HttpWebRequest, Stream> BuildRequestForTableOperation(Uri uri, UriQueryBuilder builder, IBufferManager bufferManager, int? timeout, TableOperation operation, bool useVersionHeader, OperationContext ctx, TableRequestOptions options, string accountName)
        {
            HttpWebRequest msg = BuildRequestCore(uri, builder, operation.HttpMethod, timeout, useVersionHeader, ctx);

            TablePayloadFormat payloadFormat = options.PayloadFormat.Value;

            // Set Accept and Content-Type based on the payload format.
            SetAcceptHeaderForHttpWebRequest(msg, payloadFormat);
            Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat);

            if (operation.HttpMethod != "HEAD" && operation.HttpMethod != "GET")
            {
                SetContentTypeForHttpWebRequest(msg, payloadFormat);
            }

            if (operation.OperationType == TableOperationType.InsertOrMerge || operation.OperationType == TableOperationType.Merge)
            {
                options.AssertNoEncryptionPolicyOrStrictMode();

                // post tunnelling
                msg.Headers.Add("X-HTTP-Method", "MERGE");
            }

            // etag
            if (operation.OperationType == TableOperationType.Delete ||
                operation.OperationType == TableOperationType.Replace ||
                operation.OperationType == TableOperationType.Merge)
            {
                if (operation.Entity.ETag != null)
                {
                    msg.Headers.Add("If-Match", operation.Entity.ETag);
                }
            }

            // prefer header
            if (operation.OperationType == TableOperationType.Insert)
            {
                msg.Headers.Add("Prefer", operation.EchoContent ? "return-content" : "return-no-content");
            }
            
            if (operation.OperationType == TableOperationType.Insert ||
                operation.OperationType == TableOperationType.Merge ||
                operation.OperationType == TableOperationType.InsertOrMerge ||
                operation.OperationType == TableOperationType.InsertOrReplace ||
                operation.OperationType == TableOperationType.Replace)
            {
                // create the writer, indent for readability of the examples.  
                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    CheckCharacters = false,   // sets this flag on the XmlWriter for ATOM  
                    Version = TableConstants.ODataProtocolVersion // set the Odata version to use when writing the entry 
                };

                HttpWebRequestAdapterMessage adapterMsg = new HttpWebRequestAdapterMessage(msg, bufferManager);

                if (operation.HttpMethod != "HEAD" && operation.HttpMethod != "GET")
                {
                    SetContentTypeForAdapterMessage(adapterMsg, payloadFormat);
                }
                
                ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings, new TableStorageModel(accountName));
                ODataWriter writer = odataWriter.CreateODataEntryWriter();
                WriteOdataEntity(operation.Entity, operation.OperationType, ctx, writer, options);

                return new Tuple<HttpWebRequest, Stream>(adapterMsg.GetPopulatedMessage(), adapterMsg.GetStream());
            }

            return new Tuple<HttpWebRequest, Stream>(msg, null);
        }
Exemplo n.º 34
0
Arquivo: Table.cs Projeto: zooba/wix3
        /// <summary>
        /// Parse a table from the xml.
        /// </summary>
        /// <param name="reader">XmlReader where the intermediate is persisted.</param>
        /// <param name="section">Section to populate with persisted data.</param>
        /// <param name="tableDefinitions">TableDefinitions to use in the intermediate.</param>
        /// <returns>The parsed table.</returns>
        internal static Table Parse(XmlReader reader, Section section, TableDefinitionCollection tableDefinitions)
        {
            Debug.Assert("table" == reader.LocalName);

            bool empty = reader.IsEmptyElement;
            TableOperation operation = TableOperation.None;
            string name = null;

            while (reader.MoveToNextAttribute())
            {
                switch (reader.LocalName)
                {
                    case "name":
                        name = reader.Value;
                        break;
                    case "op":
                        switch (reader.Value)
                        {
                            case "add":
                                operation = TableOperation.Add;
                                break;
                            case "drop":
                                operation = TableOperation.Drop;
                                break;
                            default:
                                throw new WixException(WixErrors.IllegalAttributeValue(SourceLineNumberCollection.FromUri(reader.BaseURI), "table", reader.Name, reader.Value, "Add", "Drop"));
                        }
                        break;
                    default:
                        if (!reader.NamespaceURI.StartsWith("http://www.w3.org/", StringComparison.Ordinal))
                        {
                            throw new WixException(WixErrors.UnexpectedAttribute(SourceLineNumberCollection.FromUri(reader.BaseURI), "table", reader.Name));
                        }
                        break;
                }
            }

            if (null == name)
            {
                throw new WixException(WixErrors.ExpectedAttribute(SourceLineNumberCollection.FromUri(reader.BaseURI), "table", "name"));
            }

            TableDefinition tableDefinition = tableDefinitions[name];
            Table table = new Table(section, tableDefinition);
            table.Operation = operation;

            if (!empty)
            {
                bool done = false;

                // loop through all the rows in a table
                while (!done && reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            switch (reader.LocalName)
                            {
                                case "row":
                                    Row.Parse(reader, table);
                                    break;
                                default:
                                    throw new WixException(WixErrors.UnexpectedElement(SourceLineNumberCollection.FromUri(reader.BaseURI), "table", reader.Name));
                            }
                            break;
                        case XmlNodeType.EndElement:
                            done = true;
                            break;
                    }
                }

                if (!done)
                {
                    throw new WixException(WixErrors.ExpectedEndElement(SourceLineNumberCollection.FromUri(reader.BaseURI), "table"));
                }
            }

            return table;
        }