Example #1
0
        /// <summary>
        /// Removes a User.
        /// </summary>
        /// <param name="user">The User to remove.</param>
        /// <returns>True if the User has been removed successfully.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="user"/> is <c>null</c>.</exception>
        public bool RemoveUser(UserInfo user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            try {
                UserEntity userEntity = GetUserEntity(_wiki, user.Username);
                // If the user does not exists return false;
                if (userEntity == null)
                {
                    return(false);
                }

                IList <UserDataEntity> userDataEntities = GetUserDataEntities(_wiki, user.Username);
                foreach (UserDataEntity userDataEntity in userDataEntities)
                {
                    _context.DeleteObject(userDataEntity);
                }
                _context.SaveChangesStandard();

                _context.DeleteObject(userEntity);
                _context.SaveChangesStandard();

                _users = null;

                return(true);
            }
            catch (Exception ex) {
                throw ex;
            }
        }
        /// <summary>
        /// Stores the outgoing links of a page, overwriting existing data.
        /// </summary>
        /// <param name="page">The full name of the page.</param>
        /// <param name="outgoingLinks">The full names of the pages that <b>page</b> links to.</param>
        /// <returns><c>true</c> if the outgoing links are stored, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="page"/> or <paramref name="outgoingLinks"/> are <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="page"/> or <paramref name="outgoingLinks"/> are empty.</exception>
        public bool StoreOutgoingLinks(string page, string[] outgoingLinks)
        {
            if (page == null)
            {
                throw new ArgumentNullException("page");
            }
            if (outgoingLinks == null)
            {
                throw new ArgumentNullException("outgoingLinks");
            }
            if (page.Length == 0)
            {
                throw new ArgumentException("page");
            }

            try {
                var query = (from e in _context.CreateQuery <OutgoingLinkEntity>(OutgoingLinksTable).AsTableServiceQuery()
                             where e.PartitionKey.Equals(_wiki) && e.SourcePage.Equals(page)
                             select e).AsTableServiceQuery();
                var entities = QueryHelper <OutgoingLinkEntity> .All(query);

                foreach (var entity in entities)
                {
                    _context.DeleteObject(entity);
                }
                _context.SaveChangesStandard();

                foreach (string outgoingLink in outgoingLinks)
                {
                    if (outgoingLink == null)
                    {
                        throw new ArgumentNullException("outgoingLinks", "Null element in outgoing links array");
                    }
                    if (outgoingLink.Length == 0)
                    {
                        throw new ArgumentException("Elements in outgoing links cannot be empty", "outgoingLinks");
                    }

                    OutgoingLinkEntity outgoingLinksEntity = new OutgoingLinkEntity()
                    {
                        PartitionKey    = _wiki,
                        RowKey          = Guid.NewGuid().ToString("N"),
                        SourcePage      = page,
                        DestinationPage = outgoingLink
                    };
                    _context.AddObject(OutgoingLinksTable, outgoingLinksEntity);
                }
                _context.SaveChangesStandard();
                return(true);
            }
            catch (Exception ex) {
                throw ex;
            }
        }
        /// <summary>
        /// Test deleting entities inside and outside the given range.
        /// </summary>
        /// <param name="testClient">The table client to test.</param>
        /// <param name="tableName">The name of the table to test.</param>
        /// <param name="accessPermissions">The access permissions of the table client.</param>
        /// <param name="startPk">The start partition key range.</param>
        /// <param name="startRk">The start row key range.</param>
        /// <param name="endPk">The end partition key range.</param>
        /// <param name="endRk">The end row key range.</param>
        private void TestDelete(
            CloudTableClient testClient,
            string tableName,
            SharedAccessTablePermissions accessPermissions,
            string startPk,
            string startRk,
            string endPk,
            string endRk)
        {
            TableServiceContext referenceContext = testClient.GetTableServiceContext();

            Action <BaseEntity> deleteDelegate = (tableEntity) =>
            {
                TableServiceContext context = testClient.GetTableServiceContext();

                context.AttachTo(tableName, tableEntity, "*");
                context.DeleteObject(tableEntity);
                context.SaveChangesWithRetries();
                context.Detach(tableEntity);
            };

            bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Delete) != 0;

            // Perform test
            TestOperationWithRange(
                tableName,
                startPk,
                startRk,
                endPk,
                endRk,
                deleteDelegate,
                "delete",
                expectSuccess,
                expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.NotFound);
        }
Example #4
0
        private void MovePageRecursively(Models.Site site, string pageFullName, string newParent, TableServiceContext serviceContext)
        {
            var oldPage = Get(new Page(site, pageFullName));
            var entity  = PageEntityHelper.ToPageEntity(oldPage);

            if (!string.IsNullOrEmpty(newParent))
            {
                var newPage = new Page(new Page(site, newParent), oldPage.Name);
                entity.FullName   = newPage.FullName;
                entity.ParentPage = newPage.Parent.FullName;
            }
            else
            {
                entity.FullName   = oldPage.Name;
                entity.ParentPage = "";
            }

            foreach (var item in ChildPages(oldPage))
            {
                MovePageRecursively(site, item.FullName, entity.FullName, serviceContext);
            }

            serviceContext.AddObject(PageTable, entity);
            var oldEntity = PageEntityHelper.ToPageEntity(oldPage);

            serviceContext.AttachTo(PageTable, oldEntity, "*");
            serviceContext.DeleteObject(oldEntity);
        }
Example #5
0
        public void Remove(string url)
        {
            var o = _tableContext.CreateQuery <StoredSiteUrl>(_tableName).ToList().First(x => x.Url == url);

            _tableContext.DeleteObject(o);
            _tableContext.SaveChanges();
        }
Example #6
0
        private void DeleteBook()
        {
            if (bookTree.SelectedNode == null)
            {
                return;
            }

            var bookNode = bookTree.SelectedNode as BookTreeNode;

            // Delete the book...

            CloudTableClient    tableClient  = storageAccount.CreateCloudTableClient();
            TableServiceContext tableContext = tableClient.GetDataServiceContext();

            Book book = tableContext.CreateQuery <Book>("Book").Where(b =>
                                                                      b.PartitionKey == bookNode.Book.PartitionKey &&
                                                                      b.RowKey == bookNode.Book.RowKey).FirstOrDefault();

            if (book == null)
            {
                throw new InvalidOperationException("The requested book was not found.");
            }

            tableContext.DeleteObject(book);
            tableContext.SaveChangesWithRetries();

            CreateNewBook();
            LoadAllBooks();
        }
        public void DeleteEntity(IEnumerable <T> objs)
        {
            TableServiceContext context = this.CreateContext();

            foreach (var obj in objs)
            {
                context.AttachTo(this.tableName, obj, "*");
                context.DeleteObject(obj);
            }

            try
            {
                context.SaveChanges();
            }
            catch (DataServiceRequestException ex)
            {
                var dataServiceClientException = ex.InnerException as DataServiceClientException;
                if (dataServiceClientException != null)
                {
                    if (dataServiceClientException.StatusCode == 404)
                    {
                        return;
                    }
                }

                throw;
            }
        }
Example #8
0
        public void Delete(IEnumerable <T> objs)
        {
            TableServiceContext context = this.CreateContext();

            foreach (var obj in objs)
            {
                context.AttachTo(this.tableName, obj, "*");
                context.DeleteObject(obj);
            }

            this.StorageRetryPolicy.ExecuteAction(() =>
            {
                try
                {
                    context.SaveChanges();
                }
                catch (DataServiceRequestException ex)
                {
                    var dataServiceClientException = ex.InnerException as DataServiceClientException;
                    if (dataServiceClientException != null)
                    {
                        if (dataServiceClientException.StatusCode == 404)
                        {
                            TraceHelper.TraceWarning(ex.TraceInformation());
                            return;
                        }
                    }

                    TraceHelper.TraceError(ex.TraceInformation());

                    throw;
                }
            });
        }
        public void Delete(T item)
        {
            int  trycount = 0;
            bool success  = false;

            while (trycount++ < 1)
            {
                try
                {
                    TableServiceContext tableServiceContext = TableContext();
                    tableServiceContext.AttachTo(tableName, item, "*");
                    tableServiceContext.DeleteObject(item);
                    tableServiceContext.SaveChangesWithRetries();
                    success = true;
                    break;
                }
                catch
                {
                    Connect();
                }
            }
            if (!success)
            {
                throw new Exception("Could not delete " + typeof(T).Name);
            }
        }
        private static void InitializeTableSchemaFromEntity(CloudTableClient tableStorage, string entityName, TableServiceEntity entity)
        {
            TableServiceContext context = tableStorage.GetDataServiceContext();
            DateTime            now     = DateTime.UtcNow;

            entity.PartitionKey = Guid.NewGuid().ToString();
            entity.RowKey       = Guid.NewGuid().ToString();
            Array.ForEach(
                entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance),
                p =>
            {
                if ((p.Name != "PartitionKey") && (p.Name != "RowKey") && (p.Name != "Timestamp"))
                {
                    if (p.PropertyType == typeof(string))
                    {
                        p.SetValue(entity, Guid.NewGuid().ToString(), null);
                    }
                    else if (p.PropertyType == typeof(DateTime))
                    {
                        p.SetValue(entity, now, null);
                    }
                }
            });

            context.AddObject(entityName, entity);
            context.SaveChangesWithRetries();
            context.DeleteObject(entity);
            context.SaveChangesWithRetries();
        }
        public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
        {
            Debug.Assert(context != null);
            Debug.Assert(lockId != null);
            Debug.Assert(_blobProvider != null);
            SecUtility.CheckParameter(ref id, true, true, false, Configuration.MaxStringPropertySizeInChars, "id");

            try
            {
                TableServiceContext svc     = CreateDataServiceContext();
                SessionRow          session = GetSession(id, svc);
                if (session == null)
                {
                    Debug.Assert(false);
                    return;
                }
                if (session.Lock != (int)lockId)
                {
                    Debug.Assert(false);
                    return;
                }
                svc.DeleteObject(session);
                svc.SaveChangesWithRetries();
            }
            catch (InvalidOperationException e)
            {
                throw new ProviderException("Error accessing the data store!", e);
            }

            // delete associated blobs
            try
            {
                IEnumerable <IListBlobItem> e = _blobProvider.ListBlobs(GetBlobNamePrefix(id));
                if (e == null)
                {
                    return;
                }
                IEnumerator <IListBlobItem> props = e.GetEnumerator();
                if (props == null)
                {
                    return;
                }
                while (props.MoveNext())
                {
                    if (props.Current != null)
                    {
                        if (!_blobProvider.DeleteBlob(props.Current.Uri.ToString()))
                        {
                            // ignore this; it is possible that another thread could try to delete the blob
                            // at the same time
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new ProviderException("Error accessing blob storage.", e);
            }
        }
Example #12
0
        public static void UnregisterRoute(string routeName)
        {
            TableServiceContext tableContext = GetTableContext();
            RouteEntity         entity       = new RouteEntity(routeName, null);

            tableContext.AttachTo(_tableName, entity, "*");
            tableContext.DeleteObject(entity);
            tableContext.SaveChanges();
            _configCache.Remove(_partitionKey);
        }
        /// <summary>
        /// Removes the request device details from the table, and then removes
        /// from memory once the table has been updated.
        /// </summary>
        /// <param name="record">Request record of the entity being removed.</param>
        private void Remove(RequestRecord record)
        {
            lock (_serviceContext)
            {
                // Get the entity matching the record held in the context.
                RequestEntity entity = GetEntityFromContext(record);
                if (entity == null)
                {
                    // Get the entity from the table if it exists.
                    entity = GetEntityFromTable(record);
                }

                // If the entity has been found remove it from the context and the table.
                if (entity != null)
                {
                    _serviceContext.DeleteObject(entity);
                    _serviceContext.SaveChanges();
                }
            }
        }
Example #14
0
        public async Task Delete(IEnumerable <T> entities)
        {
            TableServiceContext context = this.CreateContext();

            foreach (var entity in entities)
            {
                context.AttachTo(this._tableName, entity, "*");
                context.DeleteObject(entity);
            }

            await this.SaveChangesAsync(context, context.SaveChangesDefaultOptions);
        }
Example #15
0
        private void RemovePageWithChildPages(TableServiceContext serviceContext, PageEntity entity)
        {
            serviceContext.DeleteObject(entity);

            var children = serviceContext.CreateQuery <PageEntity>(PageTable)
                           .Where(it => it.PartitionKey == entity.SiteName && it.ParentPage == entity.FullName)
                           .ToArray();

            foreach (var item in children)
            {
                RemovePageWithChildPages(serviceContext, item);
            }
        }
        /// <summary>
        /// Reduces the size of the Log to the specified size (or less).
        /// </summary>
        /// <param name="size">The size to shrink the log to (in bytes).</param>
        private void CutLog(int size)
        {
            size = size * 1024;
            var query = (from e in _context.CreateQuery <LogEntity>(LogsTable).AsTableServiceQuery()
                         where e.PartitionKey.Equals("0")
                         select e).AsTableServiceQuery();

            LogEntity[] logEntities = QueryHelper <LogEntity> .All(query).ToArray();

            int estimatedSize = logEntities.Length * EstimatedLogEntrySize;

            if (size < estimatedSize)
            {
                int difference      = estimatedSize - size;
                int entriesToDelete = difference / EstimatedLogEntrySize;
                // Add 10% to avoid 1-by-1 deletion when adding new entries
                entriesToDelete += entriesToDelete / 10;

                if (entriesToDelete > 0)
                {
                    int count = 0;
                    for (int i = 0; i < entriesToDelete; i++)
                    {
                        _context.DeleteObject(logEntities[i]);
                        if (count > 98)
                        {
                            _context.SaveChangesStandard();
                            count = 0;
                        }
                        else
                        {
                            count++;
                        }
                    }
                    _context.SaveChangesStandard();
                }
            }
        }
Example #17
0
        // Delete a contact.
        public static void DeleteContact(string rowKey)
        {
            // Get data context.
            TableServiceContext context = tableClient.GetDataServiceContext();

            // Retrieve contact.
            ContactEntity entity = GetContact(rowKey, context);

            // Delete the entity.
            context.DeleteObject(entity);

            // Save changes to the service.
            context.SaveChanges();
        }
Example #18
0
        public static void DeleteEntity(string account, string key, string table, string partitionKey, string rowKey)
        {
            CloudTableClient    tableClient = Client.GetTableClient(account, key);
            TableServiceContext context     = tableClient.GetDataServiceContext();

            TableEntity entity = new TableEntity()
            {
                PartitionKey = partitionKey, RowKey = rowKey
            };

            context.AttachTo(table, entity, "*");
            context.DeleteObject(entity);
            context.SaveChangesWithRetries(SaveChangesOptions.None);
        }
Example #19
0
        // remember that there is no is no rollback functionality for the table storage service right now
        // be cautious when using this function
        // if a role does not exist, we stop deleting roles, if a user in a role does not exist, we continue deleting
        // in case of error conditions, the behavior of this function is different than the SQL role provider
        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            SecUtility.CheckArrayParameter(ref roleNames, true, true, true, MaxTableRoleNameLength, "roleNames");
            SecUtility.CheckArrayParameter(ref usernames, true, true, true, Constants.MaxTableUsernameLength, "usernames");

            RoleRow row;

            try
            {
                TableServiceContext svc = CreateDataServiceContext();
                foreach (string role in roleNames)
                {
                    if (!RoleExists(role))
                    {
                        throw new ProviderException(string.Format(CultureInfo.InstalledUICulture, "The role {0} does not exist!", role));
                    }
                    foreach (string user in usernames)
                    {
                        row = GetUserInRole(svc, role, user);
                        if (row == null)
                        {
                            Log.Write(EventKind.Warning, string.Format(CultureInfo.InstalledUICulture, "The user {0} does not exist in the role {1}.", user, role));
                            continue;
                        }
                        try
                        {
                            svc.DeleteObject(row);
                            svc.SaveChangesWithRetries();
                        }
                        catch (Exception e)
                        {
                            var dsce = e.InnerException as DataServiceClientException;
                            if (dsce != null && (dsce.StatusCode == (int)HttpStatusCode.NoContent || dsce.StatusCode == (int)HttpStatusCode.NotFound))
                            {
                                Log.Write(EventKind.Warning, string.Format(CultureInfo.InstalledUICulture, "The user {0} does not exist in the role {1}.", user, role));
                                svc.Detach(row);
                            }
                            else
                            {
                                throw new ProviderException(string.Format(CultureInfo.InstalledUICulture, "Error deleting user {0} from role {1}.", user, role));
                            }
                        }
                    }
                }
            }
            catch (InvalidOperationException e)
            {
                throw new ProviderException("Error while accessing the data store.", e);
            }
        }
        protected void DelAllBut_Click(object sender, EventArgs e)
        {
#if AZURE
            var storageAccount = CloudStorageAccount.Parse(Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue("fiftyonedegrees"));
            var serviceContext = new TableServiceContext(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials);
            storageAccount.CreateCloudTableClient().CreateTableIfNotExist("log");

            foreach (var row in serviceContext.CreateQuery <LogMessageEntity>("log"))
            {
                serviceContext.DeleteObject(row);
            }
            serviceContext.SaveChanges();

            Page.Response.Redirect(Page.Request.Url.ToString(), true);
#endif
        }
Example #21
0
        public void DeleteCounter(string counter, string instance)
        {
            var x = GetCounters(false);

            x.ForEach((i) => {
                if (i.CounterName == counter && i.InstanceName == instance)
                {
                    _tableContext.DeleteObject(i);
                }
            });

            try {
                _tableContext.SaveChanges(SaveChangesOptions.Batch);
            }
            catch {
                // this happens when the records have already been deleted and a second worker tries to delete them
            }
        }
        private static void CreateUserPrivilegeTable(CloudTableClient cloudTableClient)
        {
            cloudTableClient.CreateTableIfNotExist(PrivilegesTableServiceContext.UserPrivilegeTableName);

            // Execute conditionally for development storage only.
            if (cloudTableClient.BaseUri.IsLoopback)
            {
                TableServiceContext context = cloudTableClient.GetDataServiceContext();
                var entity = new UserPrivilege {
                    UserId = "UserId", Privilege = "Privilege"
                };

                context.AddObject(PrivilegesTableServiceContext.UserPrivilegeTableName, entity);
                context.SaveChangesWithRetries();
                context.DeleteObject(entity);
                context.SaveChangesWithRetries();
            }
        }
Example #23
0
        public bool DeleteBtsAssemblyFilesMetadata(BtsAssemblyFilesMetadata btsAssemblyFilesMetadata)
        {
            this.tableClient = account.CreateCloudTableClient();
            this.tableClient.CreateTableIfNotExist(MapFilesTableName);
            this.tableContext = tableClient.GetDataServiceContext();

            btsAssemblyFilesMetadata.PartitionKey = btsAssemblyFilesMetadata.FileName;
            btsAssemblyFilesMetadata.RowKey       = btsAssemblyFilesMetadata.FileName;
            btsAssemblyFilesMetadata.Timestamp    = DateTime.UtcNow;

            MapFiles.Remove(btsAssemblyFilesMetadata);

            tableContext.AttachTo(MapFilesTableName, btsAssemblyFilesMetadata, "*");
            tableContext.DeleteObject(btsAssemblyFilesMetadata);

            DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch | SaveChangesOptions.ReplaceOnUpdate);

            return(response.BatchStatusCode == Http200 || response.BatchStatusCode == Http201 || response.BatchStatusCode == Http202);
        }
Example #24
0
        public bool DeleteTradingPartnerSpecCertMetadata(TradingPartnerSpecCertMetadata tradingPartnerSpecCert)
        {
            this.tableClient = account.CreateCloudTableClient();
            this.tableClient.CreateTableIfNotExist(TradingPartnerSpecCertTableName);
            this.tableContext = tableClient.GetDataServiceContext();

            tradingPartnerSpecCert.PartitionKey = tradingPartnerSpecCert.TradingPartnerName;
            tradingPartnerSpecCert.RowKey       = string.Format("{0}_{1}", tradingPartnerSpecCert.DocumentType, tradingPartnerSpecCert.Direction);
            tradingPartnerSpecCert.Timestamp    = DateTime.UtcNow;

            TradingPartnerSpecCerts.Remove(tradingPartnerSpecCert);

            tableContext.AttachTo(TradingPartnerSpecCertTableName, tradingPartnerSpecCert, "*");
            tableContext.DeleteObject(tradingPartnerSpecCert);

            DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch | SaveChangesOptions.ReplaceOnUpdate);

            return(response.BatchStatusCode == Http200 || response.BatchStatusCode == Http201 || response.BatchStatusCode == Http202);
        }
        public bool DeleteBizRuleCertMetadata(BizRuleCertMetadata bizRuleCertMetadata)
        {
            this.tableClient = account.CreateCloudTableClient();
            this.tableClient.CreateTableIfNotExist(BizRuleCertTableName);
            this.tableContext = tableClient.GetDataServiceContext();

            bizRuleCertMetadata.PartitionKey = bizRuleCertMetadata.TradingPartnerName;
            bizRuleCertMetadata.RowKey       = bizRuleCertMetadata.RuleCertFileName;
            bizRuleCertMetadata.Timestamp    = DateTime.UtcNow;

            BizRuleCerts.Remove(bizRuleCertMetadata);

            tableContext.AttachTo(BizRuleCertTableName, bizRuleCertMetadata, "*");
            tableContext.DeleteObject(bizRuleCertMetadata);

            DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch | SaveChangesOptions.ReplaceOnUpdate);

            return(response.BatchStatusCode == Http200 || response.BatchStatusCode == Http201 || response.BatchStatusCode == Http202);
        }
Example #26
0
        /// <summary>
        /// Deletes a set of already existing data entries in the table, by using eTag.
        /// Fails if the data does not already exist or if eTag does not match.
        /// </summary>
        /// <param name="list">List of data entries and their corresponding etags to be deleted from the table.</param>
        /// <returns>Completion promise for this storage operation.</returns>
        internal async Task DeleteTableEntriesAsync(IReadOnlyCollection <Tuple <T, string> > list)
        {
            const string operation = "DeleteTableEntries";
            var          startTime = DateTime.UtcNow;

            if (Logger.IsVerbose2)
            {
                Logger.Verbose2("Deleting {0} table entries: {1}", TableName, Utils.EnumerableToString(list));
            }

            try
            {
                TableServiceContext svc = tableOperationsClient.GetDataServiceContext();
                foreach (var tuple in list)
                {
                    svc.AttachTo(TableName, tuple.Item1, tuple.Item2);
                    svc.DeleteObject(tuple.Item1);
                }
                try
                {
                    await Task <DataServiceResponse> .Factory.FromAsync(
                        svc.BeginSaveChangesWithRetries,
                        svc.EndSaveChangesWithRetries,
                        SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch,
                        null);
                }
                catch (Exception exc)
                {
                    Logger.Warn(ErrorCode.AzureTable_08,
                                String.Format("Intermediate error deleting entries {0} from the table {1}.",
                                              Utils.EnumerableToString(list), TableName), exc);
                    throw;
                }
            }
            finally
            {
                CheckAlertSlowAccess(startTime, operation);
            }
        }
Example #27
0
        private bool CreateIfNotExist <T>(string tableName) where T : ITableServiceEntity
        {
            var  cloudTableClient = new CloudTableClient(this.StorageAccount.TableEndpoint.ToString(), this.StorageAccount.Credentials);
            bool result           = cloudTableClient.CreateTableIfNotExist(tableName);

            if (cloudTableClient.BaseUri.IsLoopback)
            {
                TableServiceContext context = cloudTableClient.GetDataServiceContext();
                DateTime            now     = DateTime.UtcNow;
                ITableServiceEntity entity  = Activator.CreateInstance(typeof(T)) as ITableServiceEntity;
                entity.PartitionKey = Guid.NewGuid().ToString();
                entity.RowKey       = Guid.NewGuid().ToString();
                Array.ForEach(
                    entity.GetType().GetProperties(
                        BindingFlags.Public | BindingFlags.Instance),
                    p =>
                {
                    if ((p.Name != "PartitionKey") && (p.Name != "RowKey") && (p.Name != "Timestamp"))
                    {
                        if (p.PropertyType == typeof(string))
                        {
                            p.SetValue(entity, Guid.NewGuid().ToString(), null);
                        }
                        else if (p.PropertyType == typeof(DateTime))
                        {
                            p.SetValue(entity, now, null);
                        }
                    }
                });

                context.AddObject(tableName, entity);
                context.SaveChangesWithRetries();
                context.DeleteObject(entity);
                context.SaveChangesWithRetries();
            }

            return(result);
        }
Example #28
0
        // Delete entity.
        // Return true on success, false if not found, throw exception on error.

        public bool DeleteEntity <T>(string tableName, string partitionKey, string rowKey) where T : TableServiceEntity
        {
            try
            {
                TableServiceContext tableServiceContext = TableClient.GetDataServiceContext();
                IQueryable <T>      entities            = (from e in tableServiceContext.CreateQuery <T>(tableName)
                                                           where e.PartitionKey == partitionKey && e.RowKey == rowKey
                                                           select e);

                T entity = entities.FirstOrDefault();

                if (entities != null)
                {
                    tableServiceContext.DeleteObject(entity);
                    tableServiceContext.SaveChanges();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (DataServiceRequestException)
            {
                return(false);
            }
            catch (StorageClientException ex)
            {
                if ((int)ex.StatusCode == 404)
                {
                    return(false);
                }

                throw;
            }
        }
Example #29
0
        // Based on: http://blogs.msdn.com/b/cesardelatorre/archive/2011/03/12/typical-issue-one-of-the-request-inputs-is-not-valid-when-working-with-the-wa-development-storage.aspx
        private async Task InitializeTableSchemaFromEntity(CloudTableClient tableClient)
        {
            const string operation = "InitializeTableSchemaFromEntity";
            var          startTime = DateTime.UtcNow;

            TableServiceEntity entity = new T();

            entity.PartitionKey = Guid.NewGuid().ToString();
            entity.RowKey       = Guid.NewGuid().ToString();
            Array.ForEach(
                entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance),
                p =>
            {
                if ((p.Name == "PartitionKey") || (p.Name == "RowKey") || (p.Name == "Timestamp"))
                {
                    return;
                }

                if (p.PropertyType == typeof(string))
                {
                    p.SetValue(entity, Guid.NewGuid().ToString(),
                               null);
                }
                else if (p.PropertyType == typeof(DateTime))
                {
                    p.SetValue(entity, startTime, null);
                }
            });

            try
            {
                TableServiceContext svc = tableClient.GetDataServiceContext();
                svc.AddObject(TableName, entity);

                try
                {
                    await Task <DataServiceResponse> .Factory.FromAsync(
                        svc.BeginSaveChangesWithRetries,
                        svc.EndSaveChangesWithRetries,
                        SaveChangesOptions.None,
                        null);
                }
                catch (Exception exc)
                {
                    CheckAlertWriteError(operation + "-Create", entity, null, exc);
                    throw;
                }

                try
                {
                    svc.DeleteObject(entity);
                    await Task <DataServiceResponse> .Factory.FromAsync(
                        svc.BeginSaveChangesWithRetries,
                        svc.EndSaveChangesWithRetries,
                        SaveChangesOptions.None,
                        null);
                }
                catch (Exception exc)
                {
                    CheckAlertWriteError(operation + "-Delete", entity, null, exc);
                    throw;
                }
            }
            finally
            {
                CheckAlertSlowAccess(startTime, operation);
            }
        }
Example #30
0
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, MaxTableRoleNameLength, "rolename");

            try
            {
                TableServiceContext        svc      = CreateDataServiceContext();
                DataServiceQuery <RoleRow> queryObj = svc.CreateQuery <RoleRow>(_tableName);

                var query = (from userRole in queryObj
                             where userRole.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) >= 0 &&
                             userRole.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 &&
                             userRole.RowKey == SecUtility.Escape(roleName)
                             select userRole).AsTableServiceQuery();
                IEnumerable <RoleRow> userRows = query.Execute();

                if (userRows == null)
                {
                    return(false);
                }
                List <RoleRow> l = new List <RoleRow>(userRows);
                if (l.Count == 0)
                {
                    // the role does not exist
                    return(false);
                }
                RoleRow role;
                if (IsStaleRole(l, out role))
                {
                    return(false);
                }
                if (l.Count > 1 && throwOnPopulatedRole)
                {
                    throw new ProviderException("Cannot delete populated role.");
                }
                svc.DeleteObject(role);
                svc.SaveChangesWithRetries();
                // lets try to remove all remaining elements in the role
                foreach (RoleRow row in l)
                {
                    if (row != role)
                    {
                        try
                        {
                            svc.DeleteObject(row);
                            svc.SaveChangesWithRetries();
                        }
                        catch (InvalidOperationException ex)
                        {
                            var dsce = ex.InnerException as DataServiceClientException;

                            if (ex.InnerException is DataServiceClientException && (dsce.StatusCode == (int)HttpStatusCode.NoContent || dsce.StatusCode == (int)HttpStatusCode.NotFound))
                            {
                                // this element already was already deleted by another process or during a failed retry
                                // this is not a fatal error; continue deleting elements
                                Log.Write(EventKind.Warning, string.Format(CultureInfo.InstalledUICulture, "The user {0} does not exist in the role {1}.", row.UserName, row.RoleName));
                            }
                            else
                            {
                                throw new ProviderException(string.Format(CultureInfo.InstalledUICulture, "Error deleting user {0} from role {1}.", row.UserName, row.RoleName));
                            }
                        }
                    }
                }
                return(true);
            }
            catch (InvalidOperationException e)
            {
                throw new ProviderException("Error while accessing the data store.", e);
            }
        }